<commit_before>// ==UserScript==
// @name GeoFS Spoilers Arming
// @description This extension (by Harry Xue) allows the user to arm the spoilers before landing.
// @namespace GeoFS-Plugins
// @match http://*/geofs.php*
// @run-at document-end
// @version 0.4.0
// @grant none
// ==/UserScript==

(function (init) {
	// Checks if the game completes loading
	var timer = setInterval(function () {
		if (window.geofs && geofs.aircraft && geofs.aircraft.instance && geofs.aircraft.instance.object3d) {
			clearInterval(timer);
			init();
		}
	}, 100);
})(function () {
	var initialWheelAccel, aircraft = geofs.aircraft.instance;

	var _armed = false;
	var armed = function (bool) {
		if (arguments.length === 0) {
			if (aircraft.animationValue.airbrakesTarget !== 0) _armed = false;
			if (aircraft.animationValue.airbrakesPosition !== 0) return false;
			return _armed;
		}
		if (enabled()) _armed = !!bool;
	};

	var _enabled = true;
	var enabled = function (bool) {
		if (arguments.length === 0) return _enabled;
		if (!bool) armed(false);
		_enabled = !!bool;
	};

	// Adds callback after every frame to update spoilersArmed animation value and status
	geofs.api.addFrameCallback(function () {
		spoilersArming();
		geofs.aircraft.instance.animationValue.spoilersArmed = armed();
	}, 'spoilersArming');

	// Instrument overlay definition
	instruments.definitions.spoilersArming = {
		overlay: {
			url: 'https://dl.dropboxusercontent.com/s/pjji50e8ogwinmr/spoilers-arm.png',
			alignment: { x: 'right', y: 'bottom' },
			size: { x: 100, y: 21 },
			position: { x: 20, y: 195 },
			anchor: { x: 100, y: 0 },
			rescale: true,
			rescalePosition: true,
			animations: [{
				type: 'show',
				value: 'spoilersArmed',
				when: [ true ]
			}]
		}
	};

	// Sets <Shift> + airbrake toggle key for spoilers arming
	$(document)
		.off('keydown', controls.keyDown)
		.on('keydown', function (event) {
			if (event.shiftKey &&
				event.which === geofs.preferences.keyboard.keys['Airbrake toggle (on/off)'].keycode) {
				armed(enabled() ? !armed() : false);
			} else controls.keyDown(event);
		});

 	// Checks for spoilers arming status, called at every frame
	function spoilersArming () {
		if (!armed()) return;
		if (!aircraft.groundContact) {
			initialWheelAccel = undefined;
			return;
		}

		if (aircraft.animationValue.maxAngularVRatio !== 0 && !initialWheelAccel)
			initialWheelAccel = aircraft.animationValue.maxAngularVRatio;

		// Touched down and stablized
		var tdStable = aircraft.animationValue.maxAngularVRatio !== initialWheelAccel &&
			initialWheelAccel >= 300 && aircraft.animationValue.maxAngularVRatio >= 2 &&
			aircraft.animationValue.maxAngularVRatio < 10;

		if (tdStable) {
			if (controls.airbrakes.target !== 1) controls.setters.setAirbrakes.set();
			initialWheelAccel = undefined;
			armed(false);
		}
	}

	// Redefines instrument init to check if aircraft has spoilers to arm
	var oldInit = instruments.init;
	instruments.init = function (instrumentList) {
		if (typeof instrumentList.spoilers !== 'undefined') {
			armed(false);
			enabled(true);
			$.extend(instrumentList, { spoilersArming: instrumentList.spoilers });
		} else enabled(false);

		oldInit(instrumentList);
	};

	/**
	 * Checks for arming eligibility after page load
 	 */
	$(function () {
		instruments.init(aircraft.setup.instruments);
	});
});
<commit_msg>Revised image path<commit_after>// ==UserScript==
// @name GeoFS Spoilers Arming
// @description This extension (by Harry Xue) allows the user to arm the spoilers before landing.
// @namespace GeoFS-Plugins
// @match http://*/geofs.php*
// @run-at document-end
// @version 0.4.0
// @grant none
// ==/UserScript==

(function (init) {
	// Checks if the game completes loading
	var timer = setInterval(function () {
		if (window.geofs && geofs.aircraft && geofs.aircraft.instance && geofs.aircraft.instance.object3d) {
			clearInterval(timer);
			init();
		}
	}, 100);
})(function () {
	var initialWheelAccel, aircraft = geofs.aircraft.instance;

	var _armed = false;
	var armed = function (bool) {
		if (arguments.length === 0) {
			if (aircraft.animationValue.airbrakesTarget !== 0) _armed = false;
			if (aircraft.animationValue.airbrakesPosition !== 0) return false;
			return _armed;
		}
		if (enabled()) _armed = !!bool;
	};

	var _enabled = true;
	var enabled = function (bool) {
		if (arguments.length === 0) return _enabled;
		if (!bool) armed(false);
		_enabled = !!bool;
	};

	// Adds callback after every frame to update spoilersArmed animation value and status
	geofs.api.addFrameCallback(function () {
		spoilersArming();
		geofs.aircraft.instance.animationValue.spoilersArmed = armed();
	}, 'spoilersArming');

	// Instrument overlay definition
	instruments.definitions.spoilersArming = {
		overlay: {
			url: PAGE_PATH + 'images/hx/spoilers-arm.png',
			alignment: { x: 'right', y: 'bottom' },
			size: { x: 100, y: 21 },
			position: { x: 20, y: 195 },
			anchor: { x: 100, y: 0 },
			rescale: true,
			rescalePosition: true,
			animations: [{
				type: 'show',
				value: 'spoilersArmed',
				when: [ true ]
			}]
		}
	};

	// Sets <Shift> + airbrake toggle key for spoilers arming
	$(document)
		.off('keydown', controls.keyDown)
		.on('keydown', function (event) {
			if (event.shiftKey &&
				event.which === geofs.preferences.keyboard.keys['Airbrake toggle (on/off)'].keycode) {
				armed(enabled() ? !armed() : false);
			} else controls.keyDown(event);
		});

 	// Checks for spoilers arming status, called at every frame
	function spoilersArming () {
		if (!armed()) return;
		if (!aircraft.groundContact) {
			initialWheelAccel = undefined;
			return;
		}

		if (aircraft.animationValue.maxAngularVRatio !== 0 && !initialWheelAccel)
			initialWheelAccel = aircraft.animationValue.maxAngularVRatio;

		// Touched down and stablized
		var tdStable = aircraft.animationValue.maxAngularVRatio !== initialWheelAccel &&
			initialWheelAccel >= 300 && aircraft.animationValue.maxAngularVRatio >= 2 &&
			aircraft.animationValue.maxAngularVRatio < 10;

		if (tdStable) {
			if (controls.airbrakes.target !== 1) controls.setters.setAirbrakes.set();
			initialWheelAccel = undefined;
			armed(false);
		}
	}

	// Redefines instrument init to check if aircraft has spoilers to arm
	var oldInit = instruments.init;
	instruments.init = function (instrumentList) {
		if (typeof instrumentList.spoilers !== 'undefined') {
			armed(false);
			enabled(true);
			$.extend(instrumentList, { spoilersArming: instrumentList.spoilers });
		} else enabled(false);

		oldInit(instrumentList);
	};

	/**
	 * Checks for arming eligibility after page load
 	 */
	$(function () {
		instruments.init(aircraft.setup.instruments);
	});
});
<|endoftext|>


<commit_before>/**
 * conjoon
 * (c) 2002-2012 siteartwork.de/conjoon.org
 * licensing@conjoon.org
 *
 * $Author$
 * $Id$
 * $Date$
 * $Revision$
 * $LastChangedDate$
 * $LastChangedBy$
 * $URL$
 */

Ext.namespace('com.conjoon.groupware.workbench');

/**
 *
 * @class com.conjoon.groupware.workbench.Menubar
 * @singleton
 */
com.conjoon.groupware.workbench.Menubar = function(){

    var _menubar = null;

    var _viewMenu = null;

    var _emailMenu = null;

    var _accStore = null;

    /**
     * Listener for the "Email"-menu "beforeshow"-event.
     * Will either render the "Folder mappings..." menu item enabled or disabled
     * based on the availability of IMAP accounts.
     *
     */
    var _onEmailMenuBeforeShow = function()
    {
        if (!_accStore) {
            _accStore = com.conjoon.groupware.email.AccountStore.getInstance();
        }

        var recs = _accStore.getRange();

        var found = false;;
        for (var i = 0, len = recs.length; i < len; i++) {
            if (recs[i].get('protocol').toLowerCase() == 'imap') {
                found = true;
                break;
            }
        }

        _emailMenu.menu.items.get(3).setDisabled(!found);
    };

    /**
     *
     * @return {Ext.Toolbar.Button}
     */
    var _getEmailMenu = function()
    {
        if (_emailMenu) {
            return _emailMenu;
        }

        _emailMenu = new Ext.Toolbar.Button({
            text : com.conjoon.Gettext.gettext("Email"),
            menu : [{
                text    : com.conjoon.Gettext.gettext("Add account"),
                handler : function() {
                    var w = new com.conjoon.groupware.email.EmailAccountWizard();
                    w.show();
                }
            }, '-', {
                text    : com.conjoon.Gettext.gettext("Accounts..."),
                handler : function() {
                    var dialog = new com.conjoon.groupware.email.EmailAccountDialog();
                    dialog.show();
                }
            }, {
                text    : com.conjoon.Gettext.gettext("Folder mappings..."),
                handler : function() {
                    com.conjoon.groupware.email.options.FolderMappingBaton.showDialog();
                }
            }]
        });

        _emailMenu.menu.on('beforeshow', _onEmailMenuBeforeShow);

        return _emailMenu;
    };

    /**
     *
     * @param workbench {com.conjoon.groupware.Workbench}
     *
     * @return {Ext.Toolbar.Button}
     */
    var _getViewMenu = function(workbench)
    {
        if (_viewMenu) {
            return _viewMenu;
        }

        var westPanel = workbench.getWestPanel();
        var eastPanel = workbench.getEastPanel();

        var showWestPanelItem = new Ext.menu.CheckItem({
            text    : com.conjoon.Gettext.gettext("Left Quick Panel"),
            checked : !westPanel.hidden,
            listeners : {
                checkchange : function(item, checked) {
                    this.getWestPanel().setVisible(item.checked);
                },
                scope : workbench
            }
        });

        var showEastPanelItem = new Ext.menu.CheckItem({
            text    : com.conjoon.Gettext.gettext("Right Quick Panel"),
            checked : !eastPanel.hidden,
            listeners : {
                checkchange : function(item, checked) {
                    this.getEastPanel().setVisible(item.checked);
                },
                scope : workbench
            }
        });

        westPanel.on('add', function() {
            this.setDisabled(false);
        }, showWestPanelItem);

        eastPanel.on('add', function() {
            this.setDisabled(false);
        }, showEastPanelItem);

        eastPanel.on('remove', function(panel) {
            if (panel.items.items.length == 0) {
                this.setDisabled(true);
            }
        }, showEastPanelItem);

        westPanel.on('remove', function(panel) {
            if (panel.items.items.length == 0) {
                this.setDisabled(true);
            }
        }, showWestPanelItem);

        westPanel.on('show', function() {
            this.setChecked(true, true);
        }, showWestPanelItem);
        westPanel.on('hide', function() {
            this.setChecked(false, true);
        }, showWestPanelItem);

        eastPanel.on('show', function() {
            this.setChecked(true, true);
        }, showEastPanelItem);
        eastPanel.on('hide', function() {
            this.setChecked(false, true);
        }, showEastPanelItem);

        var itemMenu = new Ext.menu.Menu({
            items : [
                showWestPanelItem,
                showEastPanelItem,
                '-'
            ]
        });

        _viewMenu = new Ext.Toolbar.Button({
            text : com.conjoon.Gettext.gettext("View"),
            menu : [{
                text : com.conjoon.Gettext.gettext("Quick Panels"),
                menu : itemMenu
            }, '-', {
                text    : com.conjoon.Gettext.gettext("Statusbar"),
                checked : true,
                handler : function(item) {
                    this.getSouthPanel().setVisible(!item.checked);
                    this.doLayout();
                },
                scope : workbench
            }]
        });

        workbench.on('afterlayout', function() {

            var items = [];

            var w = this.getWestPanel();
            var e = this.getEastPanel();

            var wItems = w.items;
            var eItems = e.items;
            var item   = null;

            for (var i = 0, len = wItems.length; i < len; i++) {
                item = wItems.get(i);
                itemMenu.add({
                    text    : item.itemTitle ? item.itemTitle : item.title,
                    checked : !item.hidden,
                    handler : function(menuItem) {
                        if (this.ownerCt.hidden && !menuItem.checked) {
                            this.ownerCt.setVisible(true);
                        }
                        this.setVisible(!menuItem.checked);
                    },
                    scope : item
                });
            }
            if (len == 0) {
                showWestPanelItem.setDisabled(true);
            }

            for (var i = 0, len = eItems.length; i < len; i++) {
                item = eItems.get(i);
                var menuItem = new Ext.menu.CheckItem({
                    text    : item.itemTitle ? item.itemTitle : item.title,
                    checked : !item.hidden,
                    handler : function(menuItem) {
                        if (this.ownerCt.hidden && !menuItem.checked) {
                            this.ownerCt.setVisible(true);
                        }
                        this.setVisible(!menuItem.checked);
                    },
                    scope : item
                });
                itemMenu.add(menuItem);
            }
            if (len == 0) {
                showEastPanelItem.setDisabled(true);
            }

        }, workbench, {single : true});

        return _viewMenu;
    };

    return {

        /**
         *
         * @param workbench {com.conjoon.groupware.Workbench}
         *
         * @return {Ext.Toolbar}
         */
        getInstance : function(workbench)
        {
            if (!_menubar) {

                _menubar = new Ext.Toolbar({
                    cls   : 'com-conjoon-groupware-Menubar',
                    items : [{
                        text : com.conjoon.Gettext.gettext("File"),
                        menu : [{
                            text : com.conjoon.Gettext.gettext("New"),
                            menu : [com.conjoon.groupware.email.decorator.AccountActionComp.decorate(new Ext.menu.Item({
                                text    : com.conjoon.Gettext.gettext("Email..."),
                                handler : function() {
                                   com.conjoon.groupware.email.EmailEditorManager.createEditor();
                                }
                            }))]
                        }, '-', {
                            text    : com.conjoon.Gettext.gettext("Logout..."),
                            handler : function() {
                                com.conjoon.groupware.Reception.showLogout();
                            }
                        }]
                    }, _getViewMenu(workbench)
                    , _getEmailMenu(), {
                        text : com.conjoon.Gettext.gettext("Extras"),
                        menu : [{
                            text    : com.conjoon.Gettext.gettext("Feeds..."),
                            handler : function() {
                                var dialog = new com.conjoon.groupware.feeds.FeedOptionsDialog();
                                dialog.show();
                            }
                        }, '-', {
                            text : com.conjoon.Gettext.gettext("Local cache"),
                            handler : function() {
                                com.conjoon.groupware.localCache.options.Dialog.showDialog();
                            }
                        }]
                    }, {
                        text : com.conjoon.Gettext.gettext("Help"),
                        menu : [{
                            text     : com.conjoon.Gettext.gettext("Online User Guide"),
                            handler  : function() {
                                window.open("http://conjoon.org/wiki/display/DOC/conjoon+User%27s+Guide", 'conjoonResources');
                            }
                        }, {
                            text     : com.conjoon.Gettext.gettext("Make a Suggestion..."),
                            handler  : function() {
                                var sd = new com.conjoon.groupware.workbench.tools.SuggestionDialog();
                                sd.show();
                            }
                        }, {
                            text     : com.conjoon.Gettext.gettext("Report a Bug..."),
                            handler  : function() {
                                var brd = new com.conjoon.groupware.workbench.tools.BugReportDialog();
                                brd.show();
                            }
                        }, {
                            text     : com.conjoon.Gettext.gettext("Online Forums"),
                            handler  : function() {
                                window.open("http://conjoon.org/forum", 'conjoonResources');
                            }
                        }, '-', {
                            text     : com.conjoon.Gettext.gettext("Check for Updates"),
                            disabled : true
                        }, '-', {
                            text : com.conjoon.Gettext.gettext("About conjoon"),
                            handler : function() {
                                com.conjoon.groupware.workbench.AboutDialog.show();
                            }
                        }]
                    }]
                });

            }

            return _menubar;
        }
    };

}();<commit_msg>[Workbench] - enhancement: removed obsolete "check for updates" menu item (closes CN-425)<commit_after>/**
 * conjoon
 * (c) 2002-2012 siteartwork.de/conjoon.org
 * licensing@conjoon.org
 *
 * $Author$
 * $Id$
 * $Date$
 * $Revision$
 * $LastChangedDate$
 * $LastChangedBy$
 * $URL$
 */

Ext.namespace('com.conjoon.groupware.workbench');

/**
 *
 * @class com.conjoon.groupware.workbench.Menubar
 * @singleton
 */
com.conjoon.groupware.workbench.Menubar = function(){

    var _menubar = null;

    var _viewMenu = null;

    var _emailMenu = null;

    var _accStore = null;

    /**
     * Listener for the "Email"-menu "beforeshow"-event.
     * Will either render the "Folder mappings..." menu item enabled or disabled
     * based on the availability of IMAP accounts.
     *
     */
    var _onEmailMenuBeforeShow = function()
    {
        if (!_accStore) {
            _accStore = com.conjoon.groupware.email.AccountStore.getInstance();
        }

        var recs = _accStore.getRange();

        var found = false;;
        for (var i = 0, len = recs.length; i < len; i++) {
            if (recs[i].get('protocol').toLowerCase() == 'imap') {
                found = true;
                break;
            }
        }

        _emailMenu.menu.items.get(3).setDisabled(!found);
    };

    /**
     *
     * @return {Ext.Toolbar.Button}
     */
    var _getEmailMenu = function()
    {
        if (_emailMenu) {
            return _emailMenu;
        }

        _emailMenu = new Ext.Toolbar.Button({
            text : com.conjoon.Gettext.gettext("Email"),
            menu : [{
                text    : com.conjoon.Gettext.gettext("Add account"),
                handler : function() {
                    var w = new com.conjoon.groupware.email.EmailAccountWizard();
                    w.show();
                }
            }, '-', {
                text    : com.conjoon.Gettext.gettext("Accounts..."),
                handler : function() {
                    var dialog = new com.conjoon.groupware.email.EmailAccountDialog();
                    dialog.show();
                }
            }, {
                text    : com.conjoon.Gettext.gettext("Folder mappings..."),
                handler : function() {
                    com.conjoon.groupware.email.options.FolderMappingBaton.showDialog();
                }
            }]
        });

        _emailMenu.menu.on('beforeshow', _onEmailMenuBeforeShow);

        return _emailMenu;
    };

    /**
     *
     * @param workbench {com.conjoon.groupware.Workbench}
     *
     * @return {Ext.Toolbar.Button}
     */
    var _getViewMenu = function(workbench)
    {
        if (_viewMenu) {
            return _viewMenu;
        }

        var westPanel = workbench.getWestPanel();
        var eastPanel = workbench.getEastPanel();

        var showWestPanelItem = new Ext.menu.CheckItem({
            text    : com.conjoon.Gettext.gettext("Left Quick Panel"),
            checked : !westPanel.hidden,
            listeners : {
                checkchange : function(item, checked) {
                    this.getWestPanel().setVisible(item.checked);
                },
                scope : workbench
            }
        });

        var showEastPanelItem = new Ext.menu.CheckItem({
            text    : com.conjoon.Gettext.gettext("Right Quick Panel"),
            checked : !eastPanel.hidden,
            listeners : {
                checkchange : function(item, checked) {
                    this.getEastPanel().setVisible(item.checked);
                },
                scope : workbench
            }
        });

        westPanel.on('add', function() {
            this.setDisabled(false);
        }, showWestPanelItem);

        eastPanel.on('add', function() {
            this.setDisabled(false);
        }, showEastPanelItem);

        eastPanel.on('remove', function(panel) {
            if (panel.items.items.length == 0) {
                this.setDisabled(true);
            }
        }, showEastPanelItem);

        westPanel.on('remove', function(panel) {
            if (panel.items.items.length == 0) {
                this.setDisabled(true);
            }
        }, showWestPanelItem);

        westPanel.on('show', function() {
            this.setChecked(true, true);
        }, showWestPanelItem);
        westPanel.on('hide', function() {
            this.setChecked(false, true);
        }, showWestPanelItem);

        eastPanel.on('show', function() {
            this.setChecked(true, true);
        }, showEastPanelItem);
        eastPanel.on('hide', function() {
            this.setChecked(false, true);
        }, showEastPanelItem);

        var itemMenu = new Ext.menu.Menu({
            items : [
                showWestPanelItem,
                showEastPanelItem,
                '-'
            ]
        });

        _viewMenu = new Ext.Toolbar.Button({
            text : com.conjoon.Gettext.gettext("View"),
            menu : [{
                text : com.conjoon.Gettext.gettext("Quick Panels"),
                menu : itemMenu
            }, '-', {
                text    : com.conjoon.Gettext.gettext("Statusbar"),
                checked : true,
                handler : function(item) {
                    this.getSouthPanel().setVisible(!item.checked);
                    this.doLayout();
                },
                scope : workbench
            }]
        });

        workbench.on('afterlayout', function() {

            var items = [];

            var w = this.getWestPanel();
            var e = this.getEastPanel();

            var wItems = w.items;
            var eItems = e.items;
            var item   = null;

            for (var i = 0, len = wItems.length; i < len; i++) {
                item = wItems.get(i);
                itemMenu.add({
                    text    : item.itemTitle ? item.itemTitle : item.title,
                    checked : !item.hidden,
                    handler : function(menuItem) {
                        if (this.ownerCt.hidden && !menuItem.checked) {
                            this.ownerCt.setVisible(true);
                        }
                        this.setVisible(!menuItem.checked);
                    },
                    scope : item
                });
            }
            if (len == 0) {
                showWestPanelItem.setDisabled(true);
            }

            for (var i = 0, len = eItems.length; i < len; i++) {
                item = eItems.get(i);
                var menuItem = new Ext.menu.CheckItem({
                    text    : item.itemTitle ? item.itemTitle : item.title,
                    checked : !item.hidden,
                    handler : function(menuItem) {
                        if (this.ownerCt.hidden && !menuItem.checked) {
                            this.ownerCt.setVisible(true);
                        }
                        this.setVisible(!menuItem.checked);
                    },
                    scope : item
                });
                itemMenu.add(menuItem);
            }
            if (len == 0) {
                showEastPanelItem.setDisabled(true);
            }

        }, workbench, {single : true});

        return _viewMenu;
    };

    return {

        /**
         *
         * @param workbench {com.conjoon.groupware.Workbench}
         *
         * @return {Ext.Toolbar}
         */
        getInstance : function(workbench)
        {
            if (!_menubar) {

                _menubar = new Ext.Toolbar({
                    cls   : 'com-conjoon-groupware-Menubar',
                    items : [{
                        text : com.conjoon.Gettext.gettext("File"),
                        menu : [{
                            text : com.conjoon.Gettext.gettext("New"),
                            menu : [com.conjoon.groupware.email.decorator.AccountActionComp.decorate(new Ext.menu.Item({
                                text    : com.conjoon.Gettext.gettext("Email..."),
                                handler : function() {
                                   com.conjoon.groupware.email.EmailEditorManager.createEditor();
                                }
                            }))]
                        }, '-', {
                            text    : com.conjoon.Gettext.gettext("Logout..."),
                            handler : function() {
                                com.conjoon.groupware.Reception.showLogout();
                            }
                        }]
                    }, _getViewMenu(workbench)
                    , _getEmailMenu(), {
                        text : com.conjoon.Gettext.gettext("Extras"),
                        menu : [{
                            text    : com.conjoon.Gettext.gettext("Feeds..."),
                            handler : function() {
                                var dialog = new com.conjoon.groupware.feeds.FeedOptionsDialog();
                                dialog.show();
                            }
                        }, '-', {
                            text : com.conjoon.Gettext.gettext("Local cache"),
                            handler : function() {
                                com.conjoon.groupware.localCache.options.Dialog.showDialog();
                            }
                        }]
                    }, {
                        text : com.conjoon.Gettext.gettext("Help"),
                        menu : [{
                            text     : com.conjoon.Gettext.gettext("Online User Guide"),
                            handler  : function() {
                                window.open("http://conjoon.org/wiki/display/DOC/conjoon+User%27s+Guide", 'conjoonResources');
                            }
                        }, {
                            text     : com.conjoon.Gettext.gettext("Make a Suggestion..."),
                            handler  : function() {
                                var sd = new com.conjoon.groupware.workbench.tools.SuggestionDialog();
                                sd.show();
                            }
                        }, {
                            text     : com.conjoon.Gettext.gettext("Report a Bug..."),
                            handler  : function() {
                                var brd = new com.conjoon.groupware.workbench.tools.BugReportDialog();
                                brd.show();
                            }
                        }, {
                            text     : com.conjoon.Gettext.gettext("Online Forums"),
                            handler  : function() {
                                window.open("http://conjoon.org/forum", 'conjoonResources');
                            }
                        }, '-', {
                            text : com.conjoon.Gettext.gettext("About conjoon"),
                            handler : function() {
                                com.conjoon.groupware.workbench.AboutDialog.show();
                            }
                        }]
                    }]
                });

            }

            return _menubar;
        }
    };

}();<|endoftext|>


<commit_before>/* globals $ */
var toggleTheme = function() {
  $(function() {
    var toggleStuff = function(className) {
      $('body', $('iframe').contents()[0]).attr('class', className);
      localStorage.setItem('theme', className);
      $('body', '.ap-profile').attr('class', '');
    };
    $('#sg-switchtheme-blue', $('iframe').contents()[0]).off('change');
    $('#sg-switchtheme-grey', $('iframe').contents()[0]).off('change');
    $('#sg-switchtheme-white', $('iframe').contents()[0]).off('change');

    if (localStorage.getItem('theme') &&
      localStorage.getItem('theme') === 'business') {
      $('body', $('iframe').contents()[0]).attr('class', 'business');
      $('#sg-switchtheme-blue', $('iframe').contents()[0]).prop('checked', true);
    } else if (localStorage.getItem('theme') &&
      localStorage.getItem('theme') === 'private-person') {
      $('body', $('iframe').contents()[0]).attr('class', 'private-person');
      $('#sg-switchtheme-grey', $('iframe').contents()[0]).prop('checked', true);
    } else {
      $('body', $('iframe').contents()[0]).attr('class', 'neutral');
      $('#sg-switchtheme-white', $('iframe').contents()[0])
        .prop('checked', true);
    }
    $('#sg-switchtheme-blue', $('iframe').contents()[0]).on('change',
      function() {
        toggleStuff('business');
      });
    $('#sg-switchtheme-grey', $('iframe').contents()[0]).on('change',
      function() {
        toggleStuff('private-person');
      });
    $('#sg-switchtheme-white', $('iframe').contents()[0]).on('change',
      function() {
        toggleStuff('neutral');
      });
    $('body', '.ap-profile').attr('class', '');
  });
};
<commit_msg>Modified toggleTheme.js to allow for multiple classnames on body.<commit_after>/* globals $ */
var toggleTheme = function() {
  $(function() {
    var toggleStuff = function(className) {
      $('body', $('iframe').contents()[0]).removeClass('business');
      $('body', $('iframe').contents()[0]).removeClass('private-person');
      $('body', $('iframe').contents()[0]).removeClass('neutral');
      $('body', $('iframe').contents()[0]).addClass(className);
      // $('body', $('iframe').contents()[0]).attr('class', className);
      localStorage.setItem('theme', className);
      $('body', '.ap-profile').attr('class', '');
    };
    $('#sg-switchtheme-blue', $('iframe').contents()[0]).off('change');
    $('#sg-switchtheme-grey', $('iframe').contents()[0]).off('change');
    $('#sg-switchtheme-white', $('iframe').contents()[0]).off('change');

    if (localStorage.getItem('theme') &&
      localStorage.getItem('theme') === 'business') {
      $('body', $('iframe').contents()[0]).removeClass('private-person');
      $('body', $('iframe').contents()[0]).removeClass('neutral');
      $('body', $('iframe').contents()[0]).addClass('business');
      // $('body', $('iframe').contents()[0]).attr('class', 'business');
      $('#sg-switchtheme-blue', $('iframe').contents()[0]).prop('checked', true);
    } else if (localStorage.getItem('theme') &&
      localStorage.getItem('theme') === 'private-person') {
      $('body', $('iframe').contents()[0]).removeClass('business');
      $('body', $('iframe').contents()[0]).removeClass('neutral');
      $('body', $('iframe').contents()[0]).addClass('private-person');
      // $('body', $('iframe').contents()[0]).attr('class', 'private-person');
      $('#sg-switchtheme-grey', $('iframe').contents()[0]).prop('checked', true);
    } else {
      $('body', $('iframe').contents()[0]).removeClass('business');
      $('body', $('iframe').contents()[0]).removeClass('private-person');
      $('body', $('iframe').contents()[0]).addClass('neutral');
      // $('body', $('iframe').contents()[0]).attr('class', 'neutral');
      $('#sg-switchtheme-white', $('iframe').contents()[0])
        .prop('checked', true);
    }
    $('#sg-switchtheme-blue', $('iframe').contents()[0]).on('change',
      function() {
        toggleStuff('business');
      });
    $('#sg-switchtheme-grey', $('iframe').contents()[0]).on('change',
      function() {
        toggleStuff('private-person');
      });
    $('#sg-switchtheme-white', $('iframe').contents()[0]).on('change',
      function() {
        toggleStuff('neutral');
      });
    $('body', '.ap-profile').attr('class', '');
  });
};
<|endoftext|>


<commit_before>/** WebUI helper namespace
Acceptable input for dates:
'/', '.' or '-' are accepted as separators; for brevity only '/' formats will be listed below:

Acceptable input for times:
':', '-', are accepted as separators;

For date time, only ' ' can be used for separating dates from time.

===== DATE FORMATS =====
13/3/2012, 23/02/2012 -> dd/mm/yyyy format; adapted to 13-3-2012 and 23-2-2012 leading 0 may be omitted i.e. 02/03/2012 equals 2/3/2012
13/3/13 -> dd/mm/yy format; adapted to 13-3-2013, year is considered to be 19yy if yy>29 or 20yy otherwise; leading 0 may be omitted
13/3, 23/12 -> dd/mm format, adapted to 13-3-2012 and 23-12-2012, year is considered to be the current year; leading 0 may be omitted

05022013 -> ddmmyyyy format - adapted to 5-2-2013; leading 0 may NOT be omitted
050213 -> ddmmyy format, adapted to 5-2-2013, year is considered to be 19yy if yy>29 or 20yy otherwise; leading 0 may NOT be omitted
0502 -> ddmmyy format, adapted to 5-2-2012, year is considered to be the current year; leading 0 may NOT be omitted

===== TIME FORMATS =====
09:05	-> HH:MM format - standard time format. It'll not be adapted.
9:05	-> H:MM format, adapted to 09:05; you always have to specify 2 digit minutes, but leading 0-s for hours may be omitted

0905	-> HHMM format, adapted to 09:05.
905		-> HMM format, adapted to 09:05; you always have to specify 2 digit minutes, but leading 0-s for hours may be omitted
*/
var WebUI;
if(WebUI === undefined)
    WebUI = new Object();

$.extend(WebUI, {

	/** *** DateInput control code *** */
	dateInputCheck : function(evt) {
		if (!evt) {
			evt = window.event;
			if (!evt) {
				return;
			}
		}
		var c = evt.target || evt.srcElement;
		WebUI.dateInputRepairValueIn(c);
	},

	dateInputRepairValueIn : function(c) {
		if (!c)
			return;
		var val = c.value;

		if (!val || val.length == 0) // Nothing to see here, please move on.
			return;
		Calendar.__init();

		// -- Try to decode then reformat the date input
		try {
			//Remove multiple separators
			val = val.replace(new RegExp("\\" +  Calendar._TT["DATE_TIME_SEPARATOR"] + "+"), Calendar._TT["DATE_TIME_SEPARATOR"]);
			var numbereOfSpaces = val.split(Calendar._TT["DATE_TIME_SEPARATOR"]).length - 1;
			var res;
			if(numbereOfSpaces == 0){
				res = WebUI.dateInputRepairDateValue(val);
			} else if(numbereOfSpaces == 1){
				res = WebUI.dateInputRepairDateTimeValue(val);
			} else {
				throw "date invalid";
			}
			c.value = res;
		} catch (x) {
			alert(Calendar._TT["INVALID"]);
		}
	},

	dateInputRepairDateValue : function(val) {
		var fmt = Calendar._TT["DEF_DATE_FORMAT"];
		var separatorsCount = WebUI.countSeparators(val);
		if (separatorsCount < 2) {
			val = WebUI.insertDateSeparators(val, fmt, separatorsCount);
		}
		var res = Date.parseDate(val, fmt);
		return res.print(fmt);
	},

	dateInputRepairTimeValue : function(val) {
		var fmt = Calendar._TT["DEF_TIME_FORMAT"];
		var timeSeparator = Calendar._TT["TIME_SEPARATOR"];
		if(val.indexOf(timeSeparator) < 0){
			//add time separator before specified minutes
			var placeForSeparator = val.length - 2;
			val = [val.slice(0, placeForSeparator), timeSeparator, val.slice(placeForSeparator)].join('');
		}
		var dummyDate = new Date();
		dummyDate.setHours(val.split(timeSeparator)[0], val.split(timeSeparator)[1], 0, 0);
		return dummyDate.print(fmt);
	},

	dateInputRepairDateTimeValue : function(val) {
		var fmt = Calendar._TT["DEF_DATETIME_FORMAT"];

		var parts = val.split(Calendar._TT["DATE_TIME_SEPARATOR"]);
		var datePart = WebUI.dateInputRepairDateValue(parts[0]);
		var timePart = WebUI.dateInputRepairTimeValue(parts[1]);
		val = datePart + Calendar._TT["DATE_TIME_SEPARATOR"] + timePart;

		var res = Date.parseDate(val, fmt);
		return res.print(fmt);
	},

	/**
	 * Count of separator chars (anything else than letters and/or digits).
	 */
	countSeparators : function(str) {
		var count = 0;
		for ( var i = str.length; --i >= 0;) {
			if (WebUI.isDateSeparator(str.charAt(i)))
				count++;
		}
		return count;
	},

	/**
	 * Returns T if char is anything else than letters and/or digits.
	 */
	isDateSeparator : function(c) {
		return Calendar._TT["DATE_SEPARATOR"].indexOf(c) > -1;
	},

	insertDateSeparators : function(str, fmt, separatorsCount) {
		var b = fmt.match(/%./g); // Split format items
		var len = str.length;
		var ylen;
		if (len == 8)
			ylen = 4;
		else if (len == 6)
			ylen = 2;
		else if (len >= 3 && len <= 5)
			ylen = 0;
		else
			throw "date invalid";
		// dd-mm dd/mm case - ignore existing separator
		if (separatorsCount == 1) {
			var index = 0;
			while (!WebUI.isDateSeparator(str.charAt(index))) {
				index++;
				if (index > len - 1) {
					throw "invalid state";
				}
			}
			str = str.substring(0, index) + '-' + str.substring(index + 1);
		}
		// -- Edit the string according to the pattern,
		var res = "";
		for ( var fix = 0; fix < b.length; fix++) {
			if (res.length != 0 && str.length != 0)
				res = res + '-'; // Just a random separator.
			switch (b[fix]) {
			default:
				throw "date invalid";
			case "%d":
			case "%e":
			case "%m":
				// Pre-existing dash separator or 2-digit day or month. Copy.
				var dashIndex = str.indexOf('-');
				var index = dashIndex == -1 ? 2 : dashIndex;
				var indexNext = dashIndex == -1 ? 2 : dashIndex + 1;
				res += str.substring(0, index);
				str = str.substring(indexNext);
				break;
			case '%y':
			case '%Y':
				// -- 2- or 4 digit year,
				res += str.substring(0, ylen);
				str = str.substring(ylen);
				break;
			}
		}
		return res;
	}

});
<commit_msg>Trimming date input before the check.<commit_after>/** WebUI helper namespace
Acceptable input for dates:
'/', '.' or '-' are accepted as separators; for brevity only '/' formats will be listed below:

Acceptable input for times:
':', '-', are accepted as separators;

For date time, only ' ' can be used for separating dates from time.

===== DATE FORMATS =====
13/3/2012, 23/02/2012 -> dd/mm/yyyy format; adapted to 13-3-2012 and 23-2-2012 leading 0 may be omitted i.e. 02/03/2012 equals 2/3/2012
13/3/13 -> dd/mm/yy format; adapted to 13-3-2013, year is considered to be 19yy if yy>29 or 20yy otherwise; leading 0 may be omitted
13/3, 23/12 -> dd/mm format, adapted to 13-3-2012 and 23-12-2012, year is considered to be the current year; leading 0 may be omitted

05022013 -> ddmmyyyy format - adapted to 5-2-2013; leading 0 may NOT be omitted
050213 -> ddmmyy format, adapted to 5-2-2013, year is considered to be 19yy if yy>29 or 20yy otherwise; leading 0 may NOT be omitted
0502 -> ddmmyy format, adapted to 5-2-2012, year is considered to be the current year; leading 0 may NOT be omitted

===== TIME FORMATS =====
09:05	-> HH:MM format - standard time format. It'll not be adapted.
9:05	-> H:MM format, adapted to 09:05; you always have to specify 2 digit minutes, but leading 0-s for hours may be omitted

0905	-> HHMM format, adapted to 09:05.
905		-> HMM format, adapted to 09:05; you always have to specify 2 digit minutes, but leading 0-s for hours may be omitted
*/
var WebUI;
if(WebUI === undefined)
    WebUI = new Object();

$.extend(WebUI, {

	/** *** DateInput control code *** */
	dateInputCheck : function(evt) {
		if (!evt) {
			evt = window.event;
			if (!evt) {
				return;
			}
		}
		var c = evt.target || evt.srcElement;
		WebUI.dateInputRepairValueIn(c);
	},

	dateInputRepairValueIn : function(c) {
		if (!c)
			return;
		var val = c.value;

		if (!val || val.length == 0) // Nothing to see here, please move on.
			return;
		Calendar.__init();

		// -- Try to decode then reformat the date input
		try {
			val = val.trim();
			//Remove multiple separators
			val = val.replace(new RegExp("\\" +  Calendar._TT["DATE_TIME_SEPARATOR"] + "+"), Calendar._TT["DATE_TIME_SEPARATOR"]);
			var numbereOfSpaces = val.split(Calendar._TT["DATE_TIME_SEPARATOR"]).length - 1;
			var res;
			if(numbereOfSpaces == 0){
				res = WebUI.dateInputRepairDateValue(val);
			} else if(numbereOfSpaces == 1){
				res = WebUI.dateInputRepairDateTimeValue(val);
			} else {
				throw "date invalid";
			}
			c.value = res;
		} catch (x) {
			alert(Calendar._TT["INVALID"]);
		}
	},

	dateInputRepairDateValue : function(val) {
		var fmt = Calendar._TT["DEF_DATE_FORMAT"];
		var separatorsCount = WebUI.countSeparators(val);
		if (separatorsCount < 2) {
			val = WebUI.insertDateSeparators(val, fmt, separatorsCount);
		}
		var res = Date.parseDate(val, fmt);
		return res.print(fmt);
	},

	dateInputRepairTimeValue : function(val) {
		var fmt = Calendar._TT["DEF_TIME_FORMAT"];
		var timeSeparator = Calendar._TT["TIME_SEPARATOR"];
		if(val.indexOf(timeSeparator) < 0){
			//add time separator before specified minutes
			var placeForSeparator = val.length - 2;
			val = [val.slice(0, placeForSeparator), timeSeparator, val.slice(placeForSeparator)].join('');
		}
		var dummyDate = new Date();
		dummyDate.setHours(val.split(timeSeparator)[0], val.split(timeSeparator)[1], 0, 0);
		return dummyDate.print(fmt);
	},

	dateInputRepairDateTimeValue : function(val) {
		var fmt = Calendar._TT["DEF_DATETIME_FORMAT"];

		var parts = val.split(Calendar._TT["DATE_TIME_SEPARATOR"]);
		var datePart = WebUI.dateInputRepairDateValue(parts[0]);
		var timePart = WebUI.dateInputRepairTimeValue(parts[1]);
		val = datePart + Calendar._TT["DATE_TIME_SEPARATOR"] + timePart;

		var res = Date.parseDate(val, fmt);
		return res.print(fmt);
	},

	/**
	 * Count of separator chars (anything else than letters and/or digits).
	 */
	countSeparators : function(str) {
		var count = 0;
		for ( var i = str.length; --i >= 0;) {
			if (WebUI.isDateSeparator(str.charAt(i)))
				count++;
		}
		return count;
	},

	/**
	 * Returns T if char is anything else than letters and/or digits.
	 */
	isDateSeparator : function(c) {
		return Calendar._TT["DATE_SEPARATOR"].indexOf(c) > -1;
	},

	insertDateSeparators : function(str, fmt, separatorsCount) {
		var b = fmt.match(/%./g); // Split format items
		var len = str.length;
		var ylen;
		if (len == 8)
			ylen = 4;
		else if (len == 6)
			ylen = 2;
		else if (len >= 3 && len <= 5)
			ylen = 0;
		else
			throw "date invalid";
		// dd-mm dd/mm case - ignore existing separator
		if (separatorsCount == 1) {
			var index = 0;
			while (!WebUI.isDateSeparator(str.charAt(index))) {
				index++;
				if (index > len - 1) {
					throw "invalid state";
				}
			}
			str = str.substring(0, index) + '-' + str.substring(index + 1);
		}
		// -- Edit the string according to the pattern,
		var res = "";
		for ( var fix = 0; fix < b.length; fix++) {
			if (res.length != 0 && str.length != 0)
				res = res + '-'; // Just a random separator.
			switch (b[fix]) {
			default:
				throw "date invalid";
			case "%d":
			case "%e":
			case "%m":
				// Pre-existing dash separator or 2-digit day or month. Copy.
				var dashIndex = str.indexOf('-');
				var index = dashIndex == -1 ? 2 : dashIndex;
				var indexNext = dashIndex == -1 ? 2 : dashIndex + 1;
				res += str.substring(0, index);
				str = str.substring(indexNext);
				break;
			case '%y':
			case '%Y':
				// -- 2- or 4 digit year,
				res += str.substring(0, ylen);
				str = str.substring(ylen);
				break;
			}
		}
		return res;
	}

});
<|endoftext|>


<commit_before>'use strict';

/* Written by Carl, used to test the IPannel of item.js. Statically uses a library
and a json of all schemas (such as is called by <fetched.Param name="schemas" url="/profiles/")>*/

jest.autoMockOff();

// Fixes https://github.com/facebook/jest/issues/78
jest.dontMock('react');
jest.dontMock('underscore');

describe('Testing item-view.js', function() {
    var React, ItemView, testItem, TestUtils, FetchContext, context, schemas, _, Wrapper, sinon, server;

    beforeAll(function(){

        sinon = require('sinon');
        server = sinon.fakeServer.create();

        server.respondWith(
            "GET",
            '/profiles/?format=json',
            [
                200,
                { "Content-Type" : "application/json" },
                '' // Don't actually need content JSON here for test. Just to silence loadSchemas XHR request error (no XHR avail in test)
            ]
        );

        server.respondWith(
            "GET",
            '/profiles/?format=json',
            [
                200,
                { "Content-Type" : "application/json" },
                '' // Don't actually need content JSON here for test. Just to silence loadSchemas XHR request error (no XHR avail in test)
            ]
        );
    });

    afterAll(function(){
        server.restore();
    });

    beforeEach(function() {
        React = require('react');
        TestUtils = require('react-dom/lib/ReactTestUtils');
        _ = require('underscore');
        ItemView = require('./../item-pages/item-view');
        var { Item } = require('./../item-pages/item');
        context = require('../testdata/library/sid38806');
        schemas = require('../testdata/schemas');
        Wrapper = React.createClass({
            render: function() {
                return (

{this.props.children}

                );
            }
        });
        testItem = TestUtils.renderIntoDocument(
            <Wrapper>
                <Item schemas={schemas} context={context} />
            </Wrapper>
        );

        jest.runAllTimers();

    });

    /** TODO: IMPROVE */
    it('has the correct number of def terms and def descriptions', function() {
        var defTerms = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'item-label');
        var defDescs = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'item-value');
        expect(defTerms.length).toBeLessThan(19);
        expect(defDescs.length).toBeLessThan(19);
    });

    it('has a good title', function() {
        var titleLine = TestUtils.findRenderedDOMComponentWithClass(testItem, 'subtitle');
        var exptHeading = titleLine;
        expect(exptHeading.textContent).toEqual('ENCLB055ZZZ');
    });

    /** TODO: FIX TEST */
    it('expands object views properly', function() {
        server.respond();
        var objToggles = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'item-page-detail-toggle-button');
        var detailPanel = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'item-page-detail-panel');
        jest.runAllTimers();
        var collapse = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'collapse');

        return;

        // TODO:: FIX BELOW
        expect(detailPanel.length).toEqual(1);
        expect(objToggles.length).toEqual(1);
        expect(collapse.length).toEqual(1);
        expect(collapse[0].className.indexOf('in') > -1).toBe(false);
        var objDefDesc = objToggles[0];
        // this is the biosamples link
        TestUtils.Simulate.click(objDefDesc);
        jest.runAllTimers();

        expect(collapse[0].className.indexOf('in') > -1).toBe(true);
        var defTerms = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'item-label');
        var defDescs = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'item-value');
        expect(defTerms.length).toEqual(19);
        expect(defDescs.length).toEqual(19);

        //var objDefinitions = TestUtils.findRenderedDOMComponentWithClass(testItem, 'sub-descriptions');
        //var objEntries = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'sub-entry');
        // there should be 25 entries within the biosample object subview
        //expect(objEntries.length).toEqual(25);
    });

    it('opens and closes tooltips correctly', function(){
        var objTriggers = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'tooltip-trigger');
        TestUtils.SimulateNative.mouseOver(objTriggers[0]);
        var openTooltips = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'tooltip-open');
        expect(openTooltips.length > 0).toBeTruthy();
        TestUtils.SimulateNative.mouseOut(objTriggers[0]);
        var openTooltips = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'tooltip-open');
        expect(openTooltips.length).toEqual(0);
    });
});
<commit_msg>Disable deprecated tooltips test.<commit_after>'use strict';

/* Written by Carl, used to test the IPannel of item.js. Statically uses a library
and a json of all schemas (such as is called by <fetched.Param name="schemas" url="/profiles/")>*/

jest.autoMockOff();

// Fixes https://github.com/facebook/jest/issues/78
jest.dontMock('react');
jest.dontMock('underscore');

describe('Testing item-view.js', function() {
    var React, ItemView, testItem, TestUtils, FetchContext, context, schemas, _, Wrapper, sinon, server;

    beforeAll(function(){

        sinon = require('sinon');
        server = sinon.fakeServer.create();

        server.respondWith(
            "GET",
            '/profiles/?format=json',
            [
                200,
                { "Content-Type" : "application/json" },
                '' // Don't actually need content JSON here for test. Just to silence loadSchemas XHR request error (no XHR avail in test)
            ]
        );

        server.respondWith(
            "GET",
            '/profiles/?format=json',
            [
                200,
                { "Content-Type" : "application/json" },
                '' // Don't actually need content JSON here for test. Just to silence loadSchemas XHR request error (no XHR avail in test)
            ]
        );
    });

    afterAll(function(){
        server.restore();
    });

    beforeEach(function() {
        React = require('react');
        TestUtils = require('react-dom/lib/ReactTestUtils');
        _ = require('underscore');
        ItemView = require('./../item-pages/item-view');
        var { Item } = require('./../item-pages/item');
        context = require('../testdata/library/sid38806');
        schemas = require('../testdata/schemas');
        Wrapper = React.createClass({
            render: function() {
                return (

{this.props.children}

                );
            }
        });
        testItem = TestUtils.renderIntoDocument(
            <Wrapper>
                <Item schemas={schemas} context={context} />
            </Wrapper>
        );

        jest.runAllTimers();

    });

    /** TODO: IMPROVE */
    it('has the correct number of def terms and def descriptions', function() {
        var defTerms = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'item-label');
        var defDescs = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'item-value');
        expect(defTerms.length).toBeLessThan(19);
        expect(defDescs.length).toBeLessThan(19);
    });

    it('has a good title', function() {
        var titleLine = TestUtils.findRenderedDOMComponentWithClass(testItem, 'subtitle');
        var exptHeading = titleLine;
        expect(exptHeading.textContent).toEqual('ENCLB055ZZZ');
    });

    /** TODO: FIX TEST */
    it('expands object views properly', function() {
        server.respond();
        var objToggles = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'item-page-detail-toggle-button');
        var detailPanel = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'item-page-detail-panel');
        jest.runAllTimers();
        var collapse = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'collapse');

        return;

        // TODO:: FIX BELOW
        expect(detailPanel.length).toEqual(1);
        expect(objToggles.length).toEqual(1);
        expect(collapse.length).toEqual(1);
        expect(collapse[0].className.indexOf('in') > -1).toBe(false);
        var objDefDesc = objToggles[0];
        // this is the biosamples link
        TestUtils.Simulate.click(objDefDesc);
        jest.runAllTimers();

        expect(collapse[0].className.indexOf('in') > -1).toBe(true);
        var defTerms = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'item-label');
        var defDescs = TestUtils.scryRenderedDOMComponentsWithTag(testItem, 'item-value');
        expect(defTerms.length).toEqual(19);
        expect(defDescs.length).toEqual(19);

        //var objDefinitions = TestUtils.findRenderedDOMComponentWithClass(testItem, 'sub-descriptions');
        //var objEntries = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'sub-entry');
        // there should be 25 entries within the biosample object subview
        //expect(objEntries.length).toEqual(25);
    });

    /*
    DEPRECATED. TODO: Create new version for new tooltips.
    it('opens and closes tooltips correctly', function(){
        var objTriggers = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'tooltip-trigger');
        TestUtils.SimulateNative.mouseOver(objTriggers[0]);
        var openTooltips = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'tooltip-open');
        expect(openTooltips.length > 0).toBeTruthy();
        TestUtils.SimulateNative.mouseOut(objTriggers[0]);
        var openTooltips = TestUtils.scryRenderedDOMComponentsWithClass(testItem, 'tooltip-open');
        expect(openTooltips.length).toEqual(0);
    });
    */
});
<|endoftext|>


<commit_before>describe('CollapsibleCollection', function(){
  var collectionsFromHRMCHTML, collectionsFromBlobHTML, collectionBlob, collection;

  beforeEach(function(){

    // Content comes as a single blob of markdown from the GDSAPI in the "body" field.
    collectionsFromBlobString =
      '
'+
        '
'+
          '
'+
            // Some content not in a collapsible subsection
            '
Where the tax gets paid to the man about the thing for the other thing
'+
            '
Where the tax gets paid to the man about the thing for the other thing
'+
            '
Where the tax gets paid to the man about the thing for the other thing
'+
            // Three collapsible subsections
            '
A section title!
'+
            '
Where an employer meets the tax payable on a non-cash incentive award given to a direct
'+
            '
A second section title!
'+
            '
Where an employer meets the tax payable on a non-cash incentive award given to a direct
'+
            '
Where an employer meets the tax payable on a non-cash incentive award given to a direct
'+
            '
A third section title!
'+
            '
Where an employer meets the tax payable on a non-cash incentive award given to a direct
'+
          '
'+
        '
'+
      '
';

      collectionsFromBlobHTML = $(collectionsFromBlobString);

      $('body').append(collectionsFromBlobHTML);
      collection = new GOVUK.CollapsibleCollection({$el:collectionsFromBlobHTML});
  });

  afterEach(function(){
    collectionsFromBlobHTML.remove();
  });

  describe('CollapsibleCollection', function(){
    it('should close all sections by default', function(){
      spyOn(GOVUK, 'getCurrentLocation').and.returnValue({
        hash: ''
      });

      var collection = new GOVUK.CollapsibleCollection({
        $el: collectionsFromBlobHTML
      });

      var sections = $.map(
        collection.collapsibles,
        function(section, index) { return section; }
      );

      var openSections = sections.filter(
        function(section) { return !section.isClosed(); }
      );

      expect(openSections.length).toBe(0);
    });

    it('should open the section linked to by the anchor in the URL', function(){
      spyOn(GOVUK, 'getCurrentLocation').and.returnValue({
        hash: '#a-second-section-title'
      });

      var collection = new GOVUK.CollapsibleCollection({
        $el: collectionsFromBlobHTML
      });

      var sections = $.map(
        collection.collapsibles,
        function(section, index) { return section; }
      );

      var openSections = sections.filter(
        function(section) { return !section.isClosed(); }
      );

      expect(openSections.length).toBe(1);
      expect(openSections[0]).toBe(collection.collapsibles['a-second-section-title']);
    });
  });

  describe('initCollapsible', function(){
    it ('should add control links to HTML generated from a blob', function(){
      var html = $(collectionsFromBlobString);
      expect(html.find('a.collection-control').length).toBe(0);
      var newCollection = new GOVUK.CollapsibleCollection({$el:html});
      expect(newCollection.$container.find('.js-collection-controls a').length).toBe(2);
    });

    it('should add a new object to collapsibles hash with the id from the section for blobs', function(){
      var collection = new GOVUK.CollapsibleCollection({
        $el: collectionsFromBlobHTML
      });
      var collectionSize = Object.keys(collection.collapsibles).length;
      collection.initCollapsible(collection.$sections[0]);
      expect(Object.keys(collection.collapsibles).length).toBe(collectionSize+1);
    });
  });

  describe('markupSections', function(){
    it('should add the a js-subsection-title class to any h2s that are not excluded by js-exclude-h2s or have the link-out class for blobs', function(){
      var html = $(collectionsFromBlobString);
      var h2Count = html.find('h2').length;
      var excludedH2Count = html.find('.js-ignore-h2s h2, h2.linked-title').length
      var sectionHeaderCount = h2Count - excludedH2Count;

      expect(html.find('h2.js-subsection-title').length).toBe(0);
      var newCollection = new GOVUK.CollapsibleCollection({$el:html});
      expect(html.find('h2.js-subsection-title').length).toBe(sectionHeaderCount);
    });

    it('should wrap h2 and section in a div with the classes js-openable for blobs', function(){
      collectionsFromBlobHTML.find('h2.js-subsection-title').each(function(index){
        expect($(this).parents('.js-openable').length).toBe(1);
      });
    });

    it('should wrap all tags following a js-subsection-title h2 up to the next js-subsection-title h2 in a div with the class js-subsection-body', function(){

      collectionsFromBlobHTML.find('h2.js-subsection-title').each(function(index){
        expect($(this).next().hasClass('js-subsection-body')).toBe(true);
      });

    });
  });

  describe('calculateSuperiorsSelector', function(){
    it ('should return all the headings of that depth level or of greater priority', function(){
     expect(collection.calculateSuperiorsSelector(1)).toBe('h2,h1');
     expect(collection.calculateSuperiorsSelector(2)).toBe('h3,h2,h1');
   });
  });

  describe('closeAll', function(){
    it('should close all collapsibles in this collection', function(){
      collection.openAll();

      for (var collapsible_id in this.collapsibles) {
        expect($(this.collapsible[collapsible.id]).isClosed()).toBe(false)
      }
      collection.closeAll();

      for (var collapsible_id in this.collapsibles) {
        expect($(this.collapsible[collapsible.id]).isClosed()).toBe(true)
      }
    });

    it('should call disable with the closeAll control', function(){
      spyOn(collection, "disableControl");
      collection.closeAll();
      expect(collection.disableControl).toHaveBeenCalledWith(collection.$closeAll);
    });

    it('should call enable with the openAll control', function(){
      spyOn(collection, "enableControl");
      collection.closeAll();
      expect(collection.enableControl).toHaveBeenCalledWith(collection.$openAll);
    });
  });

  describe('openAll', function(){
    it('should open all collapsibles in this collection', function(){
      collection.closeAll();

      for (var collapsible_id in this.collapsibles) {
        expect($(this.collapsible[collapsible.id]).isOpen()).toBe(false)
      }
      collection.openAll();

      for (var collapsible_id in this.collapsibles) {
        expect($(this.collapsible[collapsible.id]).isClosed()).toBe(true)
      }
    });

    it('should call disable with the openAll control', function(){
      spyOn(collection, "disableControl");
      collection.openAll();
      expect(collection.disableControl).toHaveBeenCalledWith(collection.$openAll);
    });

    it('should call enable with the closeAll control', function(){
      spyOn(collection, "enableControl");
      collection.openAll();
      expect(collection.enableControl).toHaveBeenCalledWith(collection.$closeAll);
    });
  });

  describe('updateControls', function(){
    it ('should call enableControl with openAll if any of the collapsible sections are closed', function(){
      spyOn(collection, "enableControl");
      collection.collapsibles[Object.keys(collection.collapsibles)[0]].close();
      collection.collapsibles[Object.keys(collection.collapsibles)[1]].open();
      collection.updateControls();

      expect(collection.enableControl).toHaveBeenCalledWith(collection.$openAll);
    });

    it ('should call enableControl with closeAll if any of the collapsible sections are open', function(){
      spyOn(collection, "enableControl");
      collection.collapsibles[Object.keys(collection.collapsibles)[0]].close();
      collection.collapsibles[Object.keys(collection.collapsibles)[1]].open();
      collection.updateControls();

      expect(collection.enableControl).toHaveBeenCalledWith(collection.$closeAll);
    });

    it ('should call disableControl with closeAll if all of the collapsible sections are closed', function(){
      spyOn(collection, "disableControl");
      collection.closeAll();

      collection.updateControls();

      expect(collection.disableControl).toHaveBeenCalledWith(collection.$closeAll);
    });

    it ('should call disableControl with openAll if all of the collapsible sections are open', function(){
      spyOn(collection, "disableControl");
      collection.openAll();

      collection.updateControls();

      expect(collection.disableControl).toHaveBeenCalledWith(collection.$openAll);
    });

  });
});

<commit_msg>Reset body content for tests that need to initialise CollapsibleCollection<commit_after>describe('CollapsibleCollection', function(){
  var collectionsFromHRMCHTML, collectionsFromBlobHTML, collectionBlob, collection;

  beforeEach(function(){

    // Content comes as a single blob of markdown from the GDSAPI in the "body" field.
    collectionsFromBlobString =
      '
'+
        '
'+
          '
'+
            // Some content not in a collapsible subsection
            '
Where the tax gets paid to the man about the thing for the other thing
'+
            '
Where the tax gets paid to the man about the thing for the other thing
'+
            '
Where the tax gets paid to the man about the thing for the other thing
'+
            // Three collapsible subsections
            '
A section title!
'+
            '
Where an employer meets the tax payable on a non-cash incentive award given to a direct
'+
            '
A second section title!
'+
            '
Where an employer meets the tax payable on a non-cash incentive award given to a direct
'+
            '
Where an employer meets the tax payable on a non-cash incentive award given to a direct
'+
            '
A third section title!
'+
            '
Where an employer meets the tax payable on a non-cash incentive award given to a direct
'+
          '
'+
        '
'+
      '
';

      collectionsFromBlobHTML = $(collectionsFromBlobString);

      $('body').append(collectionsFromBlobHTML);
      collection = new GOVUK.CollapsibleCollection({$el: collectionsFromBlobHTML});
  });

  afterEach(function(){
    collectionsFromBlobHTML.remove();
  });

  var resetBody = function resetBody() {
    collectionsFromBlobHTML.remove();
    collectionsFromBlobHTML = $(collectionsFromBlobString);
    $('body').append(collectionsFromBlobHTML);
  };

  describe('CollapsibleCollection', function(){
    beforeEach(function(){
      resetBody();
    });

    it('should close all sections by default', function(){
      spyOn(GOVUK, 'getCurrentLocation').and.returnValue({
        hash: ''
      });

      var collection = new GOVUK.CollapsibleCollection({$el: collectionsFromBlobHTML});

      var sections = $.map(
        collection.collapsibles,
        function(section, index) { return section; }
      );

      var openSections = sections.filter(
        function(section) { return !section.isClosed(); }
      );

      expect(openSections.length).toBe(0);
    });

    it('should open the section linked to by the anchor in the URL', function(){
      spyOn(GOVUK, 'getCurrentLocation').and.returnValue({
        hash: '#a-second-section-title'
      });

      var collection = new GOVUK.CollapsibleCollection({$el: collectionsFromBlobHTML});

      var sections = $.map(
        collection.collapsibles,
        function(section, index) { return section; }
      );

      var openSections = sections.filter(
        function(section) { return !section.isClosed(); }
      );

      expect(openSections.length).toBe(1);
      expect(openSections[0]).toBe(collection.collapsibles['a-second-section-title']);
    });
  });

  describe('initCollapsible', function(){
    it ('should add control links to HTML generated from a blob', function(){
      var html = $(collectionsFromBlobString);
      expect(html.find('a.collection-control').length).toBe(0);
      var collection = new GOVUK.CollapsibleCollection({$el:html});
      expect(collection.$container.find('.js-collection-controls a').length).toBe(2);
    });

    it('should add a new object to collapsibles hash with the id from the section for blobs', function(){
      var collectionSize = Object.keys(collection.collapsibles).length;
      collection.initCollapsible(collection.$sections[0]);
      expect(Object.keys(collection.collapsibles).length).toBe(collectionSize+1);
    });
  });

  describe('markupSections', function(){
    it('should add the a js-subsection-title class to any h2s that are not excluded by js-exclude-h2s or have the link-out class for blobs', function(){
      var html = $(collectionsFromBlobString);
      var h2Count = html.find('h2').length;
      var excludedH2Count = html.find('.js-ignore-h2s h2, h2.linked-title').length
      var sectionHeaderCount = h2Count - excludedH2Count;

      expect(html.find('h2.js-subsection-title').length).toBe(0);
      var newCollection = new GOVUK.CollapsibleCollection({$el:html});
      expect(html.find('h2.js-subsection-title').length).toBe(sectionHeaderCount);
    });

    it('should wrap h2 and section in a div with the classes js-openable for blobs', function(){
      collectionsFromBlobHTML.find('h2.js-subsection-title').each(function(index){
        expect($(this).parents('.js-openable').length).toBe(1);
      });
    });

    it('should wrap all tags following a js-subsection-title h2 up to the next js-subsection-title h2 in a div with the class js-subsection-body', function(){
      collectionsFromBlobHTML.find('h2.js-subsection-title').each(function(index){
        expect($(this).next().hasClass('js-subsection-body')).toBe(true);
      });
    });
  });

  describe('calculateSuperiorsSelector', function(){
    it ('should return all the headings of that depth level or of greater priority', function(){
     expect(collection.calculateSuperiorsSelector(1)).toBe('h2,h1');
     expect(collection.calculateSuperiorsSelector(2)).toBe('h3,h2,h1');
   });
  });

  describe('closeAll', function(){
    it('should close all collapsibles in this collection', function(){
      collection.openAll();

      for (var collapsible_id in this.collapsibles) {
        expect($(this.collapsible[collapsible.id]).isClosed()).toBe(false)
      }
      collection.closeAll();

      for (var collapsible_id in this.collapsibles) {
        expect($(this.collapsible[collapsible.id]).isClosed()).toBe(true)
      }
    });

    it('should call disable with the closeAll control', function(){
      spyOn(collection, "disableControl");
      collection.closeAll();
      expect(collection.disableControl).toHaveBeenCalledWith(collection.$closeAll);
    });

    it('should call enable with the openAll control', function(){
      spyOn(collection, "enableControl");
      collection.closeAll();
      expect(collection.enableControl).toHaveBeenCalledWith(collection.$openAll);
    });
  });

  describe('openAll', function(){
    it('should open all collapsibles in this collection', function(){
      collection.closeAll();

      for (var collapsible_id in this.collapsibles) {
        expect($(this.collapsible[collapsible.id]).isOpen()).toBe(false)
      }
      collection.openAll();

      for (var collapsible_id in this.collapsibles) {
        expect($(this.collapsible[collapsible.id]).isClosed()).toBe(true)
      }
    });

    it('should call disable with the openAll control', function(){
      spyOn(collection, "disableControl");
      collection.openAll();
      expect(collection.disableControl).toHaveBeenCalledWith(collection.$openAll);
    });

    it('should call enable with the closeAll control', function(){
      spyOn(collection, "enableControl");
      collection.openAll();
      expect(collection.enableControl).toHaveBeenCalledWith(collection.$closeAll);
    });
  });

  describe('updateControls', function(){
    it ('should call enableControl with openAll if any of the collapsible sections are closed', function(){
      spyOn(collection, "enableControl");
      collection.collapsibles[Object.keys(collection.collapsibles)[0]].close();
      collection.collapsibles[Object.keys(collection.collapsibles)[1]].open();
      collection.updateControls();

      expect(collection.enableControl).toHaveBeenCalledWith(collection.$openAll);
    });

    it ('should call enableControl with closeAll if any of the collapsible sections are open', function(){
      spyOn(collection, "enableControl");
      collection.collapsibles[Object.keys(collection.collapsibles)[0]].close();
      collection.collapsibles[Object.keys(collection.collapsibles)[1]].open();
      collection.updateControls();

      expect(collection.enableControl).toHaveBeenCalledWith(collection.$closeAll);
    });

    it ('should call disableControl with closeAll if all of the collapsible sections are closed', function(){
      spyOn(collection, "disableControl");
      collection.closeAll();

      collection.updateControls();

      expect(collection.disableControl).toHaveBeenCalledWith(collection.$closeAll);
    });

    it ('should call disableControl with openAll if all of the collapsible sections are open', function(){
      spyOn(collection, "disableControl");
      collection.openAll();

      collection.updateControls();

      expect(collection.disableControl).toHaveBeenCalledWith(collection.$openAll);
    });
  });
});

<|endoftext|>


<commit_before>describe("jquery.passwordStrengthIndicator", function() {
	var fixtureHtml = '
<input type="password" id="password" />
';

	beforeEach(function() {
		jasmine.getFixtures().set(fixtureHtml);
	});

	describe("Methods", function() {

		var defaults = {
			secureStrength: 25,

			indicatorClassName: "password-strength-indicator",

			indicatorDisplayType: "inline-block",

			points: {
				forEachCharacter: 1,
				forEachSpace: 1,
				containsLowercaseLetter: 2,
				containsUppercaseLetter: 2,
				containsNumber: 4,
				containsSymbol: 5
			},

			strengthClassNames: ["very-weak", "weak", "mediocre", "strong", "very-strong"]
		};

		it("should initialize the plugin calling it with no arguments", function () {
			var html = $("#root");
			var results = $("#password").passwordStrengthIndicator();
			expect(html.find(".password-strength-indicator").length).toEqual(1);
		});

		it("should get the defaults calling the plugin with 'defaults' as the first argument", function () {
			var results = $("#password").passwordStrengthIndicator("defaults");
			expect(results).toEqual(defaults);
		});

		it("should get the score calling the plugin with 'calculate' as the first argument and a string as the second argument", function () {
			var results = $("#password").passwordStrengthIndicator("calculate", "abc");
			expect(results).toBeGreaterThan(0);
		});

	});

	describe("PasswordStrengthCalculator", function() {
		var input;
		var result;

		beforeEach(function() {
			input = $("#password");
		});

		it("should give 0 points for empty string", function() {
			result = input.passwordStrengthIndicator("calculate", "");
			expect(result).toEqual(0);
		});

		it("should give 3 points for 1 lowercase character", function() {
			result = input.passwordStrengthIndicator("calculate", "a");
			expect(result).toEqual(3);
		});

		it("should give 4 points for 2 lowercase characters", function() {
			result = input.passwordStrengthIndicator("calculate", "ab");
			expect(result).toEqual(4);
		});

		it("should give 3 points for 1 uppercase character", function() {
			result = input.passwordStrengthIndicator("calculate", "A");
			expect(result).toEqual(3);
		});

		it("should give 4 points for 2 uppercase characters", function() {
			result = input.passwordStrengthIndicator("calculate", "AB");
			expect(result).toEqual(4);
		});

		it("should give 4 points extra when password contains a number", function() {
			result = input.passwordStrengthIndicator("calculate", "1");
			expect(result).toEqual(5);
		});

		it("should give 5 points extra when password contains a symbol", function() {
			result = input.passwordStrengthIndicator("calculate", "!");
			expect(result).toEqual(6);
		});

		it("should give 6 points for 1 lowercase, 1 uppercase characters", function() {
			result = input.passwordStrengthIndicator("calculate", "aB");
			expect(result).toEqual(6);
		});

		it("should give 8 points for 2 lowercase, 2 uppercase characters", function() {
			result = input.passwordStrengthIndicator("calculate", "aBcD");
			expect(result).toEqual(8);
		});

		it("should give 17 points for 1 lowercase, 1 uppercase characters, 1 number and 1 symbol", function() {
			result = input.passwordStrengthIndicator("calculate", "aB1?");
			expect(result).toEqual(17);
		});

		it("should give lots of points for a really strong password", function() {
			result = input.passwordStrengthIndicator("calculate", "This 1 is a really? strong password");
			expect(result).toEqual(48);
		});

	});

	describe("Indicator", function() {
		var html;
		var input;
		var defaults;

		beforeEach(function() {
			html = $("#root");
			input = $("#password").passwordStrengthIndicator();
			defaults = input.passwordStrengthIndicator("defaults");
		});

		function getIndicator() {
			return html.find("." + defaults.indicatorClassName);
		};

		it("should have default indicator class name", function() {
			expect(getIndicator().attr("class")).toEqual("password-strength-indicator");
		});

		it("should be hidden before typing", function() {
			expect(getIndicator().css("display")).toEqual("none");
		});

		it("should be displayed when it contains 1 ore more characters", function() {
			input.val("a").trigger("keyup");
			expect(getIndicator().css("display")).toEqual("inline-block");
		});

		it("should be hidden when it becomes emtpy", function() {
			input.val("a").trigger("keyup");
			expect(getIndicator().css("display")).toEqual("inline-block");
			input.val("").trigger("keyup");
			expect(getIndicator().css("display")).toEqual("none");
		});

		describe("Strength class names", function() {
			var html;
			var input;
			var options;

			beforeEach(function() {
				options = { indicatorClassName: "indicator" };

				html = $("#root");
				input = $("#password").passwordStrengthIndicator(options);
			});

			function setInputValueTo(value) {
				input.val(value).trigger("keyup");
			};

			function getIndicator() {
				return html.find("." + options.indicatorClassName);
			};

			it("should have very-week class for password with 0 points", function() {
				setInputValueTo("");
				expect(getIndicator().hasClass("very-weak")).toEqual(true);
			});

			it("should have week class for password with 7 points", function() {
				setInputValueTo("abcde");
				expect(getIndicator().hasClass("weak")).toEqual(true);
			});

			it("should have mediocre class for password with 13 points", function() {
				setInputValueTo("abcdefghijk");
				expect(getIndicator().hasClass("mediocre")).toEqual(true);
			});

			it("should have strong class for password with 19 points", function() {
				setInputValueTo("abcdefghijklmnopq");
				expect(getIndicator().hasClass("strong")).toEqual(true);
			});

			it("should have very-strong class for password with 25 points", function() {
				setInputValueTo("abcdefghijklmnopqrstuvwxz");
				expect(getIndicator().hasClass("very-strong")).toEqual(true);
			});

		});

	});

});<commit_msg>- Added specs for giving extra points for each space character. - Fixed spec failing after feature was introduced.<commit_after>describe("jquery.passwordStrengthIndicator", function() {
	var fixtureHtml = '
<input type="password" id="password" />
';

	beforeEach(function() {
		jasmine.getFixtures().set(fixtureHtml);
	});

	describe("Methods", function() {

		var defaults = {
			secureStrength: 25,

			indicatorClassName: "password-strength-indicator",

			indicatorDisplayType: "inline-block",

			points: {
				forEachCharacter: 1,
				forEachSpace: 1,
				containsLowercaseLetter: 2,
				containsUppercaseLetter: 2,
				containsNumber: 4,
				containsSymbol: 5
			},

			strengthClassNames: ["very-weak", "weak", "mediocre", "strong", "very-strong"]
		};

		it("should initialize the plugin calling it with no arguments", function () {
			var html = $("#root");
			var results = $("#password").passwordStrengthIndicator();
			expect(html.find(".password-strength-indicator").length).toEqual(1);
		});

		it("should get the defaults calling the plugin with 'defaults' as the first argument", function () {
			var results = $("#password").passwordStrengthIndicator("defaults");
			expect(results).toEqual(defaults);
		});

		it("should get the score calling the plugin with 'calculate' as the first argument and a string as the second argument", function () {
			var results = $("#password").passwordStrengthIndicator("calculate", "abc");
			expect(results).toBeGreaterThan(0);
		});

	});

	describe("PasswordStrengthCalculator", function() {
		var input;
		var result;

		beforeEach(function() {
			input = $("#password");
		});

		it("should give 0 points for empty string", function() {
			result = input.passwordStrengthIndicator("calculate", "");
			expect(result).toEqual(0);
		});

		it("should give 3 points for 1 lowercase character", function() {
			result = input.passwordStrengthIndicator("calculate", "a");
			expect(result).toEqual(3);
		});

		it("should give 4 points for 2 lowercase characters", function() {
			result = input.passwordStrengthIndicator("calculate", "ab");
			expect(result).toEqual(4);
		});

		it("should give 3 points for 1 uppercase character", function() {
			result = input.passwordStrengthIndicator("calculate", "A");
			expect(result).toEqual(3);
		});

		it("should give 1 point extra for 1 space", function() {
			result = input.passwordStrengthIndicator("calculate", "a b");
			expect(result).toEqual(6);
		});

		it("should give 2 points extra for 2 spaces", function() {
			result = input.passwordStrengthIndicator("calculate", "a b ");
			expect(result).toEqual(8);
		});

		it("should give 4 points for 2 uppercase characters", function() {
			result = input.passwordStrengthIndicator("calculate", "AB");
			expect(result).toEqual(4);
		});

		it("should give 4 points extra when password contains a number", function() {
			result = input.passwordStrengthIndicator("calculate", "1");
			expect(result).toEqual(5);
		});

		it("should give 5 points extra when password contains a symbol", function() {
			result = input.passwordStrengthIndicator("calculate", "!");
			expect(result).toEqual(6);
		});

		it("should give 6 points for 1 lowercase, 1 uppercase characters", function() {
			result = input.passwordStrengthIndicator("calculate", "aB");
			expect(result).toEqual(6);
		});

		it("should give 8 points for 2 lowercase, 2 uppercase characters", function() {
			result = input.passwordStrengthIndicator("calculate", "aBcD");
			expect(result).toEqual(8);
		});

		it("should give 17 points for 1 lowercase, 1 uppercase characters, 1 number and 1 symbol", function() {
			result = input.passwordStrengthIndicator("calculate", "aB1?");
			expect(result).toEqual(17);
		});

		it("should give lots of points for a really strong password", function() {
			result = input.passwordStrengthIndicator("calculate", "This 1 is a really? strong password");
			expect(result).toEqual(54);
		});

	});

	describe("Indicator", function() {
		var html;
		var input;
		var defaults;

		beforeEach(function() {
			html = $("#root");
			input = $("#password").passwordStrengthIndicator();
			defaults = input.passwordStrengthIndicator("defaults");
		});

		function getIndicator() {
			return html.find("." + defaults.indicatorClassName);
		};

		it("should have default indicator class name", function() {
			expect(getIndicator().attr("class")).toEqual("password-strength-indicator");
		});

		it("should be hidden before typing", function() {
			expect(getIndicator().css("display")).toEqual("none");
		});

		it("should be displayed when it contains 1 ore more characters", function() {
			input.val("a").trigger("keyup");
			expect(getIndicator().css("display")).toEqual("inline-block");
		});

		it("should be hidden when it becomes emtpy", function() {
			input.val("a").trigger("keyup");
			expect(getIndicator().css("display")).toEqual("inline-block");
			input.val("").trigger("keyup");
			expect(getIndicator().css("display")).toEqual("none");
		});

		describe("Strength class names", function() {
			var html;
			var input;
			var options;

			beforeEach(function() {
				options = { indicatorClassName: "indicator" };

				html = $("#root");
				input = $("#password").passwordStrengthIndicator(options);
			});

			function setInputValueTo(value) {
				input.val(value).trigger("keyup");
			};

			function getIndicator() {
				return html.find("." + options.indicatorClassName);
			};

			it("should have very-week class for password with 0 points", function() {
				setInputValueTo("");
				expect(getIndicator().hasClass("very-weak")).toEqual(true);
			});

			it("should have week class for password with 7 points", function() {
				setInputValueTo("abcde");
				expect(getIndicator().hasClass("weak")).toEqual(true);
			});

			it("should have mediocre class for password with 13 points", function() {
				setInputValueTo("abcdefghijk");
				expect(getIndicator().hasClass("mediocre")).toEqual(true);
			});

			it("should have strong class for password with 19 points", function() {
				setInputValueTo("abcdefghijklmnopq");
				expect(getIndicator().hasClass("strong")).toEqual(true);
			});

			it("should have very-strong class for password with 25 points", function() {
				setInputValueTo("abcdefghijklmnopqrstuvwxz");
				expect(getIndicator().hasClass("very-strong")).toEqual(true);
			});

		});

	});

});<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
 * Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
 * Created By:
 * Maintained By:
 */

//= require can.jquery-all

(function(can, $) {

$(function() {
  if (!GGRC.page_object)
    return;

  var object_class = GGRC.infer_object_type(GGRC.page_object);
  var object = GGRC.make_model_instance(GGRC.page_object);
  var queue = new RefreshQueue();

  can.each(object.object_people, can.proxy(queue, "enqueue"));
  can.each(object.object_documents, can.proxy(queue, "enqueue"));
  queue.trigger();

  // var c = $('.cms_controllers_page_object').control(CMS.Controllers.PageObject);
  // if (c) {
  //   c.add_dashboard_widget_from_name("person");
  //   c.add_dashboard_widget_from_name("document");
  // }

  $("#people_widget").find("section.content").ggrc_controllers_list_view({
    model : CMS.Models.ObjectPerson
    , list : object.object_people
    , list_view : GGRC.mustache_path + "/people/list.mustache"
    , parent_instance : object
    , list_loader : function() {
      return $.when(object.object_people);
    }
  });
  object.object_people.bind("add remove", function() {
    $("#people_widget header .item-count").text("(" + this.length + ")").trigger("widgets_updated");
  });

  $("#documents_widget").find("section.content").ggrc_controllers_list_view({
    model : CMS.Models.ObjectDocument
    , list : object.object_documents
    , list_view : GGRC.mustache_path + "/documents/list.mustache"
    , parent_instance : object
    , list_loader : function() {
      return $.when(object.object_documents);
    }
  });
  object.object_documents.bind("add remove", function() {
    $("#documents_widget header .item-count").text("(" + this.length + ")").trigger("widgets_updated");
  });

  if(!~can.inArray(
    object_class
    , [CMS.Models.OrgGroup
      , CMS.Models.Project
      , CMS.Models.Product
      , CMS.Models.DataAsset
      , CMS.Models.Facility
      , CMS.Models.Market
      , CMS.Models.Risk]))
    return;

  var $top_tree = $("#" + object_class.root_object + "_widget .tree-structure").cms_controllers_tree_view({
    model : object_class
    , single_object : true
    , list : [object]
  }).on("modal:relationshipcreated modal:relationshipdestroyed", "li", function(ev, data) {
    var tree_obj = $(this).find(".item-main:first").data("model")
    , other_obj;

    if((other_obj = data.getOtherSide(tree_obj)) != null) {
      $(this)
      .find([".tree-structure[data-object-sub-type="
        , other_obj.constructor.table_singular
        , "], .tree-structure[data-object-type="
        , other_obj.constructor.shortName + "], .tree-structure[data-object-meta-type="
        , other_obj.constructor.root_object
        , "]"].join(""))
      .first()
      .trigger(ev.type === "modal:relationshipcreated" ? "newChild" : "removeChild", other_obj);
    }
  });

  var $risk_tree = $("#" + object_class.root_object + "_risk_widget .tree-structure").cms_controllers_tree_view({
    model : object_class
    , single_object : true
    , list : [object]
    , options_property : "risk_tree_options"
  });

  $(document.body).on("modal:success", ".link-objects", function(ev, data) {
    $top_tree.trigger("linkObject", $.extend($(this).data(), {
      parentId : object.id
      , data : data
    }));

  });

});

})(window.can, window.can.$);
<commit_msg>Story 55198902: delaying display of people and references widgets until linkage objects are refreshed to have full data<commit_after>/*
 * Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
 * Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
 * Created By:
 * Maintained By:
 */

//= require can.jquery-all

(function(can, $) {

$(function() {
  if (!GGRC.page_object)
    return;

  var object_class = GGRC.infer_object_type(GGRC.page_object)
  , object = GGRC.make_model_instance(GGRC.page_object)
  , queue = new RefreshQueue()
  , queue_dfd;

  can.each(object.object_people, can.proxy(queue, "enqueue"));
  can.each(object.object_documents, can.proxy(queue, "enqueue"));
  queue_dfd = queue.trigger();

  // var c = $('.cms_controllers_page_object').control(CMS.Controllers.PageObject);
  // if (c) {
  //   c.add_dashboard_widget_from_name("person");
  //   c.add_dashboard_widget_from_name("document");
  // }

  queue_dfd.done(function() {
    $("#people_widget").find("section.content").ggrc_controllers_list_view({
      model : CMS.Models.ObjectPerson
      , list : object.object_people
      , list_view : GGRC.mustache_path + "/people/list.mustache"
      , parent_instance : object
      , list_loader : function() {
        return $.when(object.object_people);
      }
    });
    object.object_people.bind("add remove", function() {
      $("#people_widget header .item-count").text("(" + this.length + ")").trigger("widgets_updated");
    });

    $("#documents_widget").find("section.content").ggrc_controllers_list_view({
      model : CMS.Models.ObjectDocument
      , list : object.object_documents
      , list_view : GGRC.mustache_path + "/documents/list.mustache"
      , parent_instance : object
      , list_loader : function() {
        return $.when(object.object_documents);
      }
    });
    object.object_documents.bind("add remove", function() {
      $("#documents_widget header .item-count").text("(" + this.length + ")").trigger("widgets_updated");
    });
  });

  if(!~can.inArray(
    object_class
    , [CMS.Models.OrgGroup
      , CMS.Models.Project
      , CMS.Models.Product
      , CMS.Models.DataAsset
      , CMS.Models.Facility
      , CMS.Models.Market
      , CMS.Models.Risk]))
    return;

  var $top_tree = $("#" + object_class.root_object + "_widget .tree-structure").cms_controllers_tree_view({
    model : object_class
    , single_object : true
    , list : [object]
  }).on("modal:relationshipcreated modal:relationshipdestroyed", "li", function(ev, data) {
    var tree_obj = $(this).find(".item-main:first").data("model")
    , other_obj;

    if((other_obj = data.getOtherSide(tree_obj)) != null) {
      $(this)
      .find([".tree-structure[data-object-sub-type="
        , other_obj.constructor.table_singular
        , "], .tree-structure[data-object-type="
        , other_obj.constructor.shortName + "], .tree-structure[data-object-meta-type="
        , other_obj.constructor.root_object
        , "]"].join(""))
      .first()
      .trigger(ev.type === "modal:relationshipcreated" ? "newChild" : "removeChild", other_obj);
    }
  });

  var $risk_tree = $("#" + object_class.root_object + "_risk_widget .tree-structure").cms_controllers_tree_view({
    model : object_class
    , single_object : true
    , list : [object]
    , options_property : "risk_tree_options"
  });

  $(document.body).on("modal:success", ".link-objects", function(ev, data) {
    $top_tree.trigger("linkObject", $.extend($(this).data(), {
      parentId : object.id
      , data : data
    }));

  });

});

})(window.can, window.can.$);
<|endoftext|>