<commit_before>/*
* GLOW Context
*/

GLOW.Context = (function() {

	"use strict"; "use restrict";

    // constructor
    function Context( parameters ) {
    	if( parameters === undefined ) parameters = {};

    	this.id                     = parameters.id                    !== undefined ? parameters.id                    : GLOW.uniqueId();
    	this.alpha                  = parameters.alpha                 !== undefined ? parameters.alpha                 : true;
    	this.depth                  = parameters.depth                 !== undefined ? parameters.depth                 : true;
    	this.antialias              = parameters.antialias             !== undefined ? parameters.antialias             : true;
    	this.stencil                = parameters.stencil               !== undefined ? parameters.stencil               : false;
    	this.premultipliedAlpha     = parameters.premultipliedAlpha    !== undefined ? parameters.premultipliedAlpha    : true;
    	this.preserveDrawingBuffer  = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
    	this.width                  = parameters.width                 !== undefined ? parameters.width                 : window.innerWidth;
    	this.height                 = parameters.height                !== undefined ? parmaeters.height                : window.innerHeight;
    	this.cache                  = new GLOW.Cache();

    	if( parameters.context ) {
    	    this.GL = parameters.context;
        	GLOW.registerContext( this );
    	} else {
        	try {
        		this.domElement = document.createElement( 'canvas' );
        		this.GL         = this.domElement.getContext( 'experimental-webgl', { alpha:                 this.alpha,
                                                                                depth:                 this.depth,
                                                                                antialias:             this.antialias,
                                                                                stencil:               this.stencil,
                                                                                premultipliedAlpha:    this.premultipliedAlpha,
                                                                                preserveDrawingBuffer: this.preserveDrawingBuffer } );
        		this.domElement.width  = this.width;
        		this.domElement.height = this.height;
        	} catch( error ) {
        		console.error( "GLOW.Context.construct: " + error );
        	}

        	GLOW.registerContext( this );

        	this.enableCulling( true, { frontFace: GL.CCW, cullFace: GL.BACK } );
        	this.enableDepthTest( true, { func: GL.LEQUAL, write: true, zNear: 0, zFar: 1 } );
        	this.enableBlend( false );
        	this.setupClear( { clearBits: GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT } );
        	this.setupViewport( { x: 0, y: 0, width: this.width, height: this.height } );
        	this.clear();
    	}
    }

	// methods
    Context.prototype.setupClear = function( setup ) {
    	var r = setup.red   !== undefined ? Math.min( 1, Math.max( 0, setup.red   )) : 0;
    	var g = setup.green !== undefined ? Math.min( 1, Math.max( 0, setup.green )) : 0;
    	var b = setup.blue  !== undefined ? Math.min( 1, Math.max( 0, setup.blue  )) : 0;
    	var a = setup.alpha !== undefined ? Math.min( 1, Math.max( 0, setup.alpha )) : 1;
    	var d = setup.depth !== undefined ? Math.min( 1, Math.max( 0, setup.depth )) : 1;

    	GL.clearColor( r, g, b, a );
    	GL.clearDepth( d );
    	this.clearBits = setup.clearBits !== undefined ? setup.clearBits : this.clearBits;
    	return this;
    };

    Context.prototype.clear = function( bits ) {
    	if( bits === undefined ) { bits = this.clearBits };
    	GL.clear( bits );
    	return this;
    };

    Context.prototype.enableBlend = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.BLEND );
    		if( setup ) this.setupBlend( setup );
    	} else GL.disable( GL.BLEND );
    	return this;
    };

    Context.prototype.setupBlend = function( setup ) {
    	if( setup.equationRGB ) {
    		try {
    			if( setup.equationAlpha ) GL.blendEquationSeparate( setup.equationRGB, setup.equationAlpha );
    			if( setup.srcRGB        ) GL.blendFuncSeparate( setup.srcRGB, setup.dstRGB, setup.srcAlpha, setup.dstAlpha );
    		} catch( error ) { console.error( "GLOW.Context.setupBlend: " + error ); }
    	} else {
    		try {
    			if( setup.equation ) GL.blendEquation( setup.equation );
    			if( setup.src      ) GL.blendFunc( setup.src, setup.dst );
    		} catch( error ) { console.error( "GLOW.Context.setupBlend: " + error ); }
    	}
    	return this;
    };

    Context.prototype.enableDepthTest = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.DEPTH_TEST );
    		if( setup ) this.setupDepthTest( setup );
    	} else GL.disable( GL.DEPTH_TEST );
    	return this;
    };

    Context.prototype.setupDepthTest = function( setup ) {
    	try {
    		if( setup.func  !== undefined ) GL.depthFunc( setup.func );
    		if( setup.write !== undefined ) GL.depthMask( setup.write );
    		if( setup.zNear !== undefined && setup.zFar !== undefined && setup.zNear <= setup.zFar ) {
    			GL.depthRange( Math.max( 0, Math.min( 1, setup.zNear )), Math.max( 0, Math.min( 1, setup.zFar )));
    		}
    	} catch( error ) { console.log( "GLOW.Context.setupDepthTest: " + error ); }
    	return this;
    };

    Context.prototype.enableStencilTest = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.STENCIL_TEST );
    		if( setup ) this.setupStencilTest( setup );
    	} else GL.disable( GL.STENCIL_TEST );
    	return this;
    };

    Context.prototype.setupStencilTest = function( setup ) {
    	try {
            if( setup.func && setup.funcFace ) {
                GL.stencilFuncSeparate( setup.funcFace, setup.func, setup.funcRef, setup.funcMask );
            } else if( setup.func ) {
                GL.stencilFunc( setup.func, setup.funcRef, setup.funcMask );
            }

            if( setup.mask && setup.maskFace ) {
                GL.stencilMaskSeparate( setup.maskFace, setup.mask );
            } else if( setup.mask ) {
                GL.stencilMask( setup.mask );
            }

            if( setup.opFail && setup.opFace ) {
                GL.stencilOpSeparate( setup.opFace, setup.opFail, setup.opZfail, setup.opZpass );
            } else if( setup.opFail ) {
                GL.stencilOp( setup.opFail, setup.opZfail, setup.opZpass );
            }
    	} catch( error ) {
    	    console.error( "GLOW.Context.setupStencilTest: " + error );
    	}
    	return this;
    };

    Context.prototype.enableCulling = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.CULL_FACE );
    		if( setup ) this.setupCulling( setup );
    	} else GL.disable( GL.CULL_FACE );
    	return this;
    };

    Context.prototype.setupCulling = function( setup ) {
    	try {
    		if( setup.frontFace ) GL.frontFace( setup.frontFace );
    		if( setup.cullFace  ) GL.cullFace ( setup.cullFace  );
    	} catch( error ) {
    		console.error( "GLOW.Context.setupCulling: " + error );
    	}
    	return this;
    };

    Context.prototype.enableScissor = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.SCISSOR_TEST );
    		if( setup ) this.setupScissor( setup );
    	} else {
    		GL.disable( GL.SCISSOR_TEST );
    	}
    	return this;
    };

    Context.prototype.setupScissor = function( setup ) {
        try {
            GL.scissor( setup.x, setup.y, setup.width, setup.height );
        } catch( error ) {
            console.error( "GLOW.Context.setupScissorTest: " + error );
        }
    	return this;
    };

    Context.prototype.setupViewport = function( setup ) {
        setup = setup !== undefined ? setup : {};
        var x = setup.x !== undefined ? setup.x : 0;
        var y = setup.y !== undefined ? setup.y : 0;
        var w = this.width = setup.width !== undefined ? setup.width : window.innerWidth;
        var h = this.height = setup.height !== undefined ? setup.height : window.innerHeight;
		this.GL.viewport( x, y, w, h );
    	return this;
    };

	return Context;
})();

<commit_msg>Added polygonOffset support<commit_after>/*
* GLOW Context
*/

GLOW.Context = (function() {

	"use strict"; "use restrict";

    // constructor
    function Context( parameters ) {
    	if( parameters === undefined ) parameters = {};

    	this.id                     = parameters.id                    !== undefined ? parameters.id                    : GLOW.uniqueId();
    	this.alpha                  = parameters.alpha                 !== undefined ? parameters.alpha                 : true;
    	this.depth                  = parameters.depth                 !== undefined ? parameters.depth                 : true;
    	this.antialias              = parameters.antialias             !== undefined ? parameters.antialias             : true;
    	this.stencil                = parameters.stencil               !== undefined ? parameters.stencil               : false;
    	this.premultipliedAlpha     = parameters.premultipliedAlpha    !== undefined ? parameters.premultipliedAlpha    : true;
    	this.preserveDrawingBuffer  = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
    	this.width                  = parameters.width                 !== undefined ? parameters.width                 : window.innerWidth;
    	this.height                 = parameters.height                !== undefined ? parmaeters.height                : window.innerHeight;
    	this.cache                  = new GLOW.Cache();

    	if( parameters.context ) {
    	    this.GL = parameters.context;
        	GLOW.registerContext( this );
    	} else {
        	try {
        		this.domElement = document.createElement( 'canvas' );
        		this.GL         = this.domElement.getContext( 'experimental-webgl', { alpha:                 this.alpha,
                                                                                depth:                 this.depth,
                                                                                antialias:             this.antialias,
                                                                                stencil:               this.stencil,
                                                                                premultipliedAlpha:    this.premultipliedAlpha,
                                                                                preserveDrawingBuffer: this.preserveDrawingBuffer } );
        		this.domElement.width  = this.width;
        		this.domElement.height = this.height;
        	} catch( error ) {
        		console.error( "GLOW.Context.construct: " + error );
        	}

        	GLOW.registerContext( this );

        	this.enableCulling( true, { frontFace: GL.CCW, cullFace: GL.BACK } );
        	this.enableDepthTest( true, { func: GL.LEQUAL, write: true, zNear: 0, zFar: 1 } );
        	this.enableBlend( false );
        	this.setupClear( { clearBits: GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT } );
        	this.setupViewport( { x: 0, y: 0, width: this.width, height: this.height } );
        	this.clear();
    	}
    }

	// methods
    Context.prototype.setupClear = function( setup ) {
    	var r = setup.red   !== undefined ? Math.min( 1, Math.max( 0, setup.red   )) : 0;
    	var g = setup.green !== undefined ? Math.min( 1, Math.max( 0, setup.green )) : 0;
    	var b = setup.blue  !== undefined ? Math.min( 1, Math.max( 0, setup.blue  )) : 0;
    	var a = setup.alpha !== undefined ? Math.min( 1, Math.max( 0, setup.alpha )) : 1;
    	var d = setup.depth !== undefined ? Math.min( 1, Math.max( 0, setup.depth )) : 1;

    	GL.clearColor( r, g, b, a );
    	GL.clearDepth( d );
    	this.clearBits = setup.clearBits !== undefined ? setup.clearBits : this.clearBits;
    	return this;
    };

    Context.prototype.clear = function( bits ) {
    	if( bits === undefined ) { bits = this.clearBits };
    	GL.clear( bits );
    	return this;
    };

    Context.prototype.enableBlend = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.BLEND );
    		if( setup ) this.setupBlend( setup );
    	} else GL.disable( GL.BLEND );
    	return this;
    };

    Context.prototype.setupBlend = function( setup ) {
    	if( setup.equationRGB ) {
			if( setup.equationAlpha ) GL.blendEquationSeparate( setup.equationRGB, setup.equationAlpha );
			if( setup.srcRGB        ) GL.blendFuncSeparate( setup.srcRGB, setup.dstRGB, setup.srcAlpha, setup.dstAlpha );
    	} else {
			if( setup.equation ) GL.blendEquation( setup.equation );
			if( setup.src      ) GL.blendFunc( setup.src, setup.dst );
    	}
    	return this;
    };

    Context.prototype.enableDepthTest = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.DEPTH_TEST );
    		if( setup ) this.setupDepthTest( setup );
    	} else GL.disable( GL.DEPTH_TEST );
    	return this;
    };

    Context.prototype.setupDepthTest = function( setup ) {
		if( setup.func  !== undefined ) GL.depthFunc( setup.func );
		if( setup.write !== undefined ) GL.depthMask( setup.write );
		if( setup.zNear !== undefined && setup.zFar !== undefined && setup.zNear <= setup.zFar ) {
			GL.depthRange( Math.max( 0, Math.min( 1, setup.zNear )), Math.max( 0, Math.min( 1, setup.zFar )));
		}
    	return this;
    };

    Context.prototype.enablePolygonOffset = function( flag, setup ) {
        if( flag ) {
            GL.enable( GL.POLYGON_OFFSET_FILL );
            if( setup ) this.setupPolygonOffset( setup );
        } else GL.disable( GL.POLYGON_OFFSET_FILL );
        return this;
    }

    Context.prototype.setupPolygonOffset = function( setup ) {
        if( setup.factor && setup.units ) GL.polygonOffset( setup.factor, setup.units );
    }

    Context.prototype.enableStencilTest = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.STENCIL_TEST );
    		if( setup ) this.setupStencilTest( setup );
    	} else GL.disable( GL.STENCIL_TEST );
    	return this;
    };

    Context.prototype.setupStencilTest = function( setup ) {
        if( setup.func && setup.funcFace ) {
            GL.stencilFuncSeparate( setup.funcFace, setup.func, setup.funcRef, setup.funcMask );
        } else if( setup.func ) {
            GL.stencilFunc( setup.func, setup.funcRef, setup.funcMask );
        }

        if( setup.mask && setup.maskFace ) {
            GL.stencilMaskSeparate( setup.maskFace, setup.mask );
        } else if( setup.mask ) {
            GL.stencilMask( setup.mask );
        }

        if( setup.opFail && setup.opFace ) {
            GL.stencilOpSeparate( setup.opFace, setup.opFail, setup.opZfail, setup.opZpass );
        } else if( setup.opFail ) {
            GL.stencilOp( setup.opFail, setup.opZfail, setup.opZpass );
        }
    	return this;
    };

    Context.prototype.enableCulling = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.CULL_FACE );
    		if( setup ) this.setupCulling( setup );
    	} else GL.disable( GL.CULL_FACE );
    	return this;
    };

    Context.prototype.setupCulling = function( setup ) {
    	try {
    		if( setup.frontFace ) GL.frontFace( setup.frontFace );
    		if( setup.cullFace  ) GL.cullFace ( setup.cullFace  );
    	} catch( error ) {
    		console.error( "GLOW.Context.setupCulling: " + error );
    	}
    	return this;
    };

    Context.prototype.enableScissor = function( flag, setup ) {
    	if( flag ) {
    		GL.enable( GL.SCISSOR_TEST );
    		if( setup ) this.setupScissor( setup );
    	} else {
    		GL.disable( GL.SCISSOR_TEST );
    	}
    	return this;
    };

    Context.prototype.setupScissor = function( setup ) {
        try {
            GL.scissor( setup.x, setup.y, setup.width, setup.height );
        } catch( error ) {
            console.error( "GLOW.Context.setupScissorTest: " + error );
        }
    	return this;
    };

    Context.prototype.setupViewport = function( setup ) {
        setup = setup !== undefined ? setup : {};
        var x = setup.x !== undefined ? setup.x : 0;
        var y = setup.y !== undefined ? setup.y : 0;
        var w = this.width = setup.width !== undefined ? setup.width : window.innerWidth;
        var h = this.height = setup.height !== undefined ? setup.height : window.innerHeight;
		this.GL.viewport( x, y, w, h );
    	return this;
    };

	return Context;
})();

<|endoftext|>


<commit_before>/**
 * # Chatter widget for nodeGame
 * Copyright(c) 2019 Stefano Balietti
 * MIT Licensed
 *
 * Manage chats with clients.
 *
 * www.nodegame.org
 * ---
 */
(function(node) {

    "use strict";

    node.widgets.register('Chatter', Chatter);

    var JSUS = node.JSUS;

    // ## Meta-data

    Chatter.version = '0.3.0';
    Chatter.description = 'Manage chats with the clients.';

    Chatter.title = 'Start a Chat';
    Chatter.className = 'chatter';

    // ## Dependencies
    Chatter.dependencies = {
        JSUS: {}
    };

    // Position 0 is default.
    Chatter.modes = [
        {
            id: 'one_to_many',
            name: 'One to many',
            description: 'Broadcast to all participants, replies ' +
                'visible to you only'
        },
        {
            id: 'many_to_many',
            name: 'Many to many',
            description: 'Broadcast to all participants, replies visible to all'
        },
        {
            id: 'receivers_only',
            name: 'Receivers only',
            description: 'Broadcast to all participants, replies not allowed'
        }
    ];
    // Index the modes by id.
    Chatter.modesIdx = {};
    (function(c) {
        var i;
        for (i = 0; i < c.modes.length; i++) {
            c.modesIdx[c.modes[i].id] = c.modes[i];
        }
    })(Chatter);

    function Chatter(options) {

        // Reference to the button to start a new chat.
        this.chatButton = null;

        // Reference to select menu for type of chat.
        // @see Chatter.modes
        this.chatMode = Chatter.modes[0].id;

        // Checkbox to include bots, etc.
        this.includeNonPlayers = null;

        // Checkbox to erase initial message for each new chat.
        this.eraseInitialMsg = null;

        // Textarea with initial msg, etc.
        this.initialMsg = null;

        // List of open chats.
        this.chats = {};

        // TODO.
        // List of visible chats.
        // this.visibleChats = [];

    }

    Chatter.prototype.append = function() {
        var that, label;
        that = this;

        // Initial msg.
        this.initialMsg = W.add('textarea', this.bodyDiv, {
            className: 'form-control initial-chat-msg',
            placeholder: 'Initial message (optional)'
        });

        this.bodyDiv.appendChild(document.createElement('br'));

        // Buttons.
        this.chatButton = W.get('button', {
            className: 'btn btn-primary',
            innerHTML: 'Chat'
        });

        // On click.
        this.chatButton.onclick = function() {
            var cl, chatEvent, allClients, msg, opts;
            var title, visibleTitle, selectedClients, recipients, w;

            // Collect recipients list.

            cl = node.game.clientList;
            selectedClients = cl.getSelectedClients();
            if (!selectedClients.length) return;

            allClients = that.includeNonPlayers.checked;
            recipients = [];
            selectedClients.forEach((id) => {
                if (allClients || cl.clientMap[id].clientType === 'player') {
                    recipients.push(id);
                    if (!title) title = cl.roomName + ': ' + id;
                    else title += ', ' + id;
                }
            });
            if (!recipients.length) return;

            // Creates a diplay title (might be same as title).
            if (title.length > 35) {
                visibleTitle = cl.roomName + ': ' + recipients.length +
                    ' participant';
                if (recipients.length > 1) visibleTitle += 's';
            }
            else {
                visibleTitle = title;
            }

            // Read msg.
            msg = that.readInitialMsg();

            // Open a chat window locally.

            if (that.chats[title]) {
                chatEvent = that.chats[title].chatEvent;
            }
            else {
                chatEvent = 'CHAT_' + Math.floor(Math.random() * 10000000);
                opts = {
                    chatEvent: chatEvent,
                    participants: recipients,
                    title: visibleTitle,
                    collapsible: true,
                    closable: true,
                    docked: true,
                    printNames: visibleTitle !== title,
                    printStartTime: true
                };
                if (msg) opts.initialMsg = { msg: msg };

                // Register the new Chat widget.
                w = node.widgets.append('Chat', document.body, opts);
                w.on('destroyed', function() {
                    that.chats[title] = null;
                });
                that.chats[title] = w;
            }

            // Open a chat window remotely.

            opts = {
                chatEvent: chatEvent,
                participants: [
                    {
                        recipient: 'MONITOR',
                        sender: node.game.channelInUse,
                        name: 'Monitor'
                    }
                ],
                collapsible: true,
                closable: true,
                docked: true,
                title: 'Chat with Monitor',
                printStartTime: true
            };
            // Add initialMsg.
            if (msg) opts.initialMsg = { id: node.game.channelInUse, msg: msg };
            // Send.
            node.remoteSetup('widgets', recipients, { append: {
                Chat: opts
            }});
        };

        // Make the buttons.

        var btnGroup = document.createElement('div');
        btnGroup.role = 'group';
        btnGroup['aria-label'] = 'Chat Buttons';
        btnGroup.className = 'btn-group';

        var btnGroupModes = document.createElement('div');
        btnGroupModes.role = 'group';
        btnGroupModes['aria-label'] = 'Select mode';
        btnGroupModes.className = 'btn-group';

        var btnMode = document.createElement('button');
        btnMode.className = 'btn btn-secondary dropdown-toggle';
        btnMode['data-toggle'] = 'dropdown';
        btnMode['aria-haspopup'] = 'true';
        btnMode['aria-expanded'] = 'false';
        btnMode.innerHTML = Chatter.modes[0].name + ' ';

        var span = document.createElement('span');
        span.className = 'caret';

        btnMode.appendChild(span);

        var li, a, i, tmp;
        var ul = document.createElement('ul');
        ul.className = 'dropdown-menu';
        ul.style = 'text-align: left';

        for (i = 0; i < Chatter.modes.length; i++) {
            tmp = Chatter.modes[i];
            li = document.createElement('li');
            li.id = tmp.id;
            a = document.createElement('a');
            a.href = '#';
            a.innerHTML = '' + tmp.name + ': ' +
                tmp.description;
            li.appendChild(a);
            ul.appendChild(li);
        }

        // Append
        btnGroupModes.appendChild(btnMode);
        btnGroupModes.appendChild(ul);

        btnGroup.appendChild(this.chatButton);
        btnGroup.appendChild(btnGroupModes);

        this.bodyDiv.appendChild(btnGroup);

        // TODO: Do we need this? We are actually including the .js files.
        // Variable toggled controls if the dropdown menu
        // is displayed (we are not using bootstrap js files)
        // and we redo the job manually here.
        var toggled = false;
        btnMode.onclick = function() {
            if (toggled) {
                ul.style = 'display: none';
                toggled = false;
            }
            else {
                ul.style = 'display: block; text-align: left';
                toggled = true;
            }
        };

        ul.onclick = function(eventData) {
            var id;
            ul.style = 'display: none';
            id = eventData.target.parentNode.id;
            if (!id) id = eventData.target.parentNode.parentNode.id;
            btnMode.innerHTML = Chatter.modesIdx[id].name + ' ';
            btnMode.appendChild(span);
            that.chatMode = id;
            toggled = false;
        };

        W.add('hr', this.bodyDiv);

        // Options.

        label = W.get('label');
        this.eraseInitialMsg = W.add('input', label, {
            type: 'checkbox',
            className: 'monitor-checkbox'
        });
        label.appendChild(document.createTextNode(' Erase initial msg'));
        this.bodyDiv.appendChild(label);

        this.bodyDiv.appendChild(document.createElement('br'));

        label = W.get('label');
        this.includeNonPlayers = W.add('input', label, {
            type: 'checkbox',
            className: 'monitor-checkbox'
        });
        label.appendChild(document.createTextNode(' Include non-players'));
        this.bodyDiv.appendChild(label);
    };

    Chatter.prototype.readInitialMsg = function() {
        var txt;
        txt = this.initialMsg.value;
        if (this.eraseInitialMsg.checked) this.initialMsg.value = '';
        return txt.trim();
    };

})(node);
<commit_msg>fix transparent chat background<commit_after>/**
 * # Chatter widget for nodeGame
 * Copyright(c) 2019 Stefano Balietti
 * MIT Licensed
 *
 * Manage chats with clients.
 *
 * www.nodegame.org
 * ---
 */
(function(node) {

    "use strict";

    node.widgets.register('Chatter', Chatter);

    var JSUS = node.JSUS;

    // ## Meta-data

    Chatter.version = '0.3.0';
    Chatter.description = 'Manage chats with the clients.';

    Chatter.title = 'Start a Chat';
    Chatter.className = 'chatter';

    // ## Dependencies
    Chatter.dependencies = {
        JSUS: {}
    };

    // Position 0 is default.
    Chatter.modes = [
        {
            id: 'one_to_many',
            name: 'One to many',
            description: 'Broadcast to all participants, replies ' +
                'visible to you only'
        },
        {
            id: 'many_to_many',
            name: 'Many to many',
            description: 'Broadcast to all participants, replies visible to all'
        },
        {
            id: 'receivers_only',
            name: 'Receivers only',
            description: 'Broadcast to all participants, replies not allowed'
        }
    ];
    // Index the modes by id.
    Chatter.modesIdx = {};
    (function(c) {
        var i;
        for (i = 0; i < c.modes.length; i++) {
            c.modesIdx[c.modes[i].id] = c.modes[i];
        }
    })(Chatter);

    function Chatter(options) {

        // Reference to the button to start a new chat.
        this.chatButton = null;

        // Reference to select menu for type of chat.
        // @see Chatter.modes
        this.chatMode = Chatter.modes[0].id;

        // Checkbox to include bots, etc.
        this.includeNonPlayers = null;

        // Checkbox to erase initial message for each new chat.
        this.eraseInitialMsg = null;

        // Textarea with initial msg, etc.
        this.initialMsg = null;

        // List of open chats.
        this.chats = {};

        // TODO.
        // List of visible chats.
        // this.visibleChats = [];

    }

    Chatter.prototype.append = function() {
        var that, label;
        that = this;

        // Initial msg.
        this.initialMsg = W.add('textarea', this.bodyDiv, {
            className: 'form-control initial-chat-msg',
            placeholder: 'Initial message (optional)'
        });

        this.bodyDiv.appendChild(document.createElement('br'));

        // Buttons.
        this.chatButton = W.get('button', {
            className: 'btn btn-primary',
            innerHTML: 'Chat'
        });

        // On click.
        this.chatButton.onclick = function() {
            var cl, chatEvent, allClients, msg, opts;
            var title, visibleTitle, selectedClients, recipients, w;

            // Collect recipients list.

            cl = node.game.clientList;
            selectedClients = cl.getSelectedClients();
            if (!selectedClients.length) return;

            allClients = that.includeNonPlayers.checked;
            recipients = [];
            selectedClients.forEach((id) => {
                if (allClients || cl.clientMap[id].clientType === 'player') {
                    recipients.push(id);
                    if (!title) title = cl.roomName + ': ' + id;
                    else title += ', ' + id;
                }
            });
            if (!recipients.length) return;

            // Creates a diplay title (might be same as title).
            if (title.length > 35) {
                visibleTitle = cl.roomName + ': ' + recipients.length +
                    ' participant';
                if (recipients.length > 1) visibleTitle += 's';
            }
            else {
                visibleTitle = title;
            }

            // Read msg.
            msg = that.readInitialMsg();

            // Open a chat window locally.

            if (that.chats[title]) {
                chatEvent = that.chats[title].chatEvent;
            }
            else {
                chatEvent = 'CHAT_' + Math.floor(Math.random() * 10000000);
                opts = {
                    panel: true, // Otherwise chat background is transparent.
                    chatEvent: chatEvent,
                    participants: recipients,
                    title: visibleTitle,
                    collapsible: true,
                    closable: true,
                    docked: true,
                    printNames: visibleTitle !== title,
                    printStartTime: true
                };
                if (msg) opts.initialMsg = { msg: msg };

                // Register the new Chat widget.
                w = node.widgets.append('Chat', document.body, opts);
                w.on('destroyed', function() {
                    that.chats[title] = null;
                });
                that.chats[title] = w;
            }

            // Open a chat window remotely.

            opts = {
                chatEvent: chatEvent,
                participants: [
                    {
                        recipient: 'MONITOR',
                        sender: node.game.channelInUse,
                        name: 'Monitor'
                    }
                ],
                collapsible: true,
                closable: true,
                docked: true,
                title: 'Chat with Monitor',
                printStartTime: true
            };
            // Add initialMsg.
            if (msg) opts.initialMsg = { id: node.game.channelInUse, msg: msg };
            // Send.
            node.remoteSetup('widgets', recipients, { append: {
                Chat: opts
            }});
        };

        // Make the buttons.

        var btnGroup = document.createElement('div');
        btnGroup.role = 'group';
        btnGroup['aria-label'] = 'Chat Buttons';
        btnGroup.className = 'btn-group';

        var btnGroupModes = document.createElement('div');
        btnGroupModes.role = 'group';
        btnGroupModes['aria-label'] = 'Select mode';
        btnGroupModes.className = 'btn-group';

        var btnMode = document.createElement('button');
        btnMode.className = 'btn btn-secondary dropdown-toggle';
        btnMode['data-toggle'] = 'dropdown';
        btnMode['aria-haspopup'] = 'true';
        btnMode['aria-expanded'] = 'false';
        btnMode.innerHTML = Chatter.modes[0].name + ' ';

        var span = document.createElement('span');
        span.className = 'caret';

        btnMode.appendChild(span);

        var li, a, i, tmp;
        var ul = document.createElement('ul');
        ul.className = 'dropdown-menu';
        ul.style = 'text-align: left';

        for (i = 0; i < Chatter.modes.length; i++) {
            tmp = Chatter.modes[i];
            li = document.createElement('li');
            li.id = tmp.id;
            a = document.createElement('a');
            a.href = '#';
            a.innerHTML = '' + tmp.name + ': ' +
                tmp.description;
            li.appendChild(a);
            ul.appendChild(li);
        }

        // Append
        btnGroupModes.appendChild(btnMode);
        btnGroupModes.appendChild(ul);

        btnGroup.appendChild(this.chatButton);
        btnGroup.appendChild(btnGroupModes);

        this.bodyDiv.appendChild(btnGroup);

        // TODO: Do we need this? We are actually including the .js files.
        // Variable toggled controls if the dropdown menu
        // is displayed (we are not using bootstrap js files)
        // and we redo the job manually here.
        var toggled = false;
        btnMode.onclick = function() {
            if (toggled) {
                ul.style = 'display: none';
                toggled = false;
            }
            else {
                ul.style = 'display: block; text-align: left';
                toggled = true;
            }
        };

        ul.onclick = function(eventData) {
            var id;
            ul.style = 'display: none';
            id = eventData.target.parentNode.id;
            if (!id) id = eventData.target.parentNode.parentNode.id;
            btnMode.innerHTML = Chatter.modesIdx[id].name + ' ';
            btnMode.appendChild(span);
            that.chatMode = id;
            toggled = false;
        };

        W.add('hr', this.bodyDiv);

        // Options.

        label = W.get('label');
        this.eraseInitialMsg = W.add('input', label, {
            type: 'checkbox',
            className: 'monitor-checkbox'
        });
        label.appendChild(document.createTextNode(' Erase initial msg'));
        this.bodyDiv.appendChild(label);

        this.bodyDiv.appendChild(document.createElement('br'));

        label = W.get('label');
        this.includeNonPlayers = W.add('input', label, {
            type: 'checkbox',
            className: 'monitor-checkbox'
        });
        label.appendChild(document.createTextNode(' Include non-players'));
        this.bodyDiv.appendChild(label);
    };

    Chatter.prototype.readInitialMsg = function() {
        var txt;
        txt = this.initialMsg.value;
        if (this.eraseInitialMsg.checked) this.initialMsg.value = '';
        return txt.trim();
    };

})(node);
<|endoftext|>


<commit_before>define(["jquery", "text!html/ui-fragments.html"], function ($, _fragments) {
  "use strict";

  var UI = {},
    $fragments = $(document.createElement("div")).html(_fragments);

  UI.select = function (select, fn) {

    $(".filter").removeClass("hide");

    var $el = $(".ui-select", $fragments).clone(true),
      $toggleBtn = $el.find(".icon"),
      $selectedEl = $el.find(".ui-selected"),
      $menuContainer = $el.find(".ui-select-menu"),
      $menu = $menuContainer.find("ul"),
      $li = $menu.find("li");

    var $select = $(select),
      $options = $("option", select),
      id = $select.attr("id");

    fn = fn || function () {};

    $options.each(function (i, option) {
      var val = $(option).val(),
	html = $(option).text(),
        $newLi = $li.clone();
      $newLi.attr("data-value", val);
      $newLi.html(html);
      if ($(option).attr("selected")) {
        $newLi.attr("data-selected", true);
        $selectedEl.html(html);
      }
      $newLi.click(function () {
        var $this = $(this);

        $menu.find("[data-selected]").removeAttr("data-selected");
        $(this).attr("data-selected", true);
        $selectedEl.text(html);
        $menuContainer.hide();
        fn(val);
        $select.val(val);

      });
      $menu.append($newLi);
    });

    $selectedEl.click(function (e) {
      $menuContainer.toggle();
    });
    $toggleBtn.click(function (e) {
      $menuContainer.toggle();
    });

    $el.attr("id", id);
    $select.removeAttr("id");

    $li.remove();
    $el.insertAfter($select);
    $select.hide();
  };

  UI.pagination = function (page, total, limit, callback) {
    var $pagination = $(".pagination"),
      $ul = $pagination.find("ul"),
      $_li = $("

"),
      $li,
      MAX_NUMS = 4,
      totalPages = total ? Math.ceil(total / limit) : 0,
      set = Math.floor((page - 1) / MAX_NUMS),
      startPage = set * MAX_NUMS + 1,
      endPage = Math.min((set * MAX_NUMS) + MAX_NUMS, totalPages);

    if (totalPages > 1) {
      $pagination.show();
    } else {
      $pagination.hide();
    }

    var $prevBtn = $_li.clone().html(""),
      $nextBtn = $_li.clone().html("");

    function pageSearch(page) {
      return function () {
        callback(page);
      };
    }

    $ul.empty();

    // Show previous?
    if (page > 1) {
      $ul.append($prevBtn);
      $prevBtn.click(pageSearch(page - 1));
    }
    // Iterate over all pages;
    for (var i = startPage; i <= endPage; i++) {
      $li = $_li.clone();
      $li.text(i);
      if (i === page) {
        $li.addClass("active");
      }
      $li.click(pageSearch(i));
      $ul.append($li);
    }
    if (totalPages > endPage) {
      $li = $_li.clone();
      $li.text(totalPages);
      $li.click(pageSearch(totalPages));
      $ul.append("

");
      $ul.append($li);
    }
    if (page < totalPages) {
      $ul.append($nextBtn);
      $nextBtn.click(pageSearch(page + 1));
    }
  };

  return UI;

});
<commit_msg>un-break build<commit_after>define(["jquery", "text!html/ui-fragments.html"], function ($, _fragments) {
  "use strict";

  var UI = {},
    $fragments = $(document.createElement("div")).html(_fragments);

  UI.select = function (select, fn) {

    $(".filter").removeClass("hide");

    var $el = $(".ui-select", $fragments).clone(true),
      $toggleBtn = $el.find(".icon"),
      $selectedEl = $el.find(".ui-selected"),
      $menuContainer = $el.find(".ui-select-menu"),
      $menu = $menuContainer.find("ul"),
      $li = $menu.find("li");

    var $select = $(select),
      $options = $("option", select),
      id = $select.attr("id");

    fn = fn || function () {};

    $options.each(function (i, option) {
      var val = $(option).val(),
        html = $(option).text(),
        $newLi = $li.clone();
      $newLi.attr("data-value", val);
      $newLi.html(html);
      if ($(option).attr("selected")) {
        $newLi.attr("data-selected", true);
        $selectedEl.html(html);
      }
      $newLi.click(function () {
        var $this = $(this);

        $menu.find("[data-selected]").removeAttr("data-selected");
        $(this).attr("data-selected", true);
        $selectedEl.text(html);
        $menuContainer.hide();
        fn(val);
        $select.val(val);

      });
      $menu.append($newLi);
    });

    $selectedEl.click(function (e) {
      $menuContainer.toggle();
    });
    $toggleBtn.click(function (e) {
      $menuContainer.toggle();
    });

    $el.attr("id", id);
    $select.removeAttr("id");

    $li.remove();
    $el.insertAfter($select);
    $select.hide();
  };

  UI.pagination = function (page, total, limit, callback) {
    var $pagination = $(".pagination"),
      $ul = $pagination.find("ul"),
      $_li = $("

"),
      $li,
      MAX_NUMS = 4,
      totalPages = total ? Math.ceil(total / limit) : 0,
      set = Math.floor((page - 1) / MAX_NUMS),
      startPage = set * MAX_NUMS + 1,
      endPage = Math.min((set * MAX_NUMS) + MAX_NUMS, totalPages);

    if (totalPages > 1) {
      $pagination.show();
    } else {
      $pagination.hide();
    }

    var $prevBtn = $_li.clone().html(""),
      $nextBtn = $_li.clone().html("");

    function pageSearch(page) {
      return function () {
        callback(page);
      };
    }

    $ul.empty();

    // Show previous?
    if (page > 1) {
      $ul.append($prevBtn);
      $prevBtn.click(pageSearch(page - 1));
    }
    // Iterate over all pages;
    for (var i = startPage; i <= endPage; i++) {
      $li = $_li.clone();
      $li.text(i);
      if (i === page) {
        $li.addClass("active");
      }
      $li.click(pageSearch(i));
      $ul.append($li);
    }
    if (totalPages > endPage) {
      $li = $_li.clone();
      $li.text(totalPages);
      $li.click(pageSearch(totalPages));
      $ul.append("

");
      $ul.append($li);
    }
    if (page < totalPages) {
      $ul.append($nextBtn);
      $nextBtn.click(pageSearch(page + 1));
    }
  };

  return UI;

});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular.module('RkyApp.directives')
    .directive('d3Bars', ['d3', function(d3) {
      return {
        restrict: 'EA',
        scope: {
          data: "=",
          label: "@",
          onClick: "&"
        },
        link: function(scope, iElement, iAttrs) {
          var svg = d3.select(iElement[0])
              .append("svg")
              .attr("width", "100%");

          // on window resize, re-render d3 canvas
          window.onresize = function() {
            return scope.$apply();
          };
          scope.$watch(function(){
              return angular.element(window)[0].innerWidth;
            }, function(){
              return scope.render(scope.data);
            }
          );

          // watch for data changes and re-render
          scope.$watch('data', function(newVals, oldVals) {
            return scope.render(newVals);
          }, true);

          // define render function
          scope.render = function(data){
            // remove all previous items before render
            svg.selectAll("*").remove();

            // setup variables
            var width, height, max;
            width = d3.select(iElement[0])[0][0].offsetWidth - 20;
              // 20 is for margins and can be changed
            height = scope.data.length * 35;
              // 35 = 30(bar height) + 5(margin between bars)
            max = 98;
              // this can also be found dynamically when the data is not static
              // max = Math.max.apply(Math, _.map(data, ((val)-> val.count)))

            // set the height based on the calculations above
            svg.attr('height', height);

            //create the rectangles for the bar chart
            svg.selectAll("rect")
              .data(data)
              .enter()
                .append("rect")
                .on("click", function(d, i){return scope.onClick({item: d});})
                .attr("height", 30) // height of each bar
                .attr("width", 0) // initial width of 0 for transition
                .attr("x", 10) // half of the 20 side margin specified above
                .attr("y", function(d, i){
                  return i * 35;
                }) // height + margin between bars
                .transition()
                  .duration(1000) // time of duration
                  .attr("width", function(d){
                    return d.value/(max/width);
                  }); // width based on scale

            svg.selectAll("text")
              .data(data)
              .enter()
                .append("text")
                .attr("fill", "#fff")
                .attr("y", function(d, i){return i * 35 + 22;})
                .attr("x", 15)
                .text(function(d){return d[scope.label];});

          };
        }
      };
    }]);

}());

// -- by e-Coucou

(function () {
  'use strict';

  angular.module('RkyApp.directives')
    .directive('d3Lines', ['d3', function(d3) {
      return {
        restrict: 'EA',
        scope: {
          data: "=",
          label: "@",
          moyn: "=",
          onClick: "&"
        },
        link: function(scope, iElement, iAttrs) {
          var svg = d3.select(iElement[0])
              .append("svg")
              .attr("width", "90%");

          // on window resize, re-render d3 canvas
          window.onresize = function() {
            return scope.$apply();
          };
          scope.$watch(function(){
              return angular.element(window)[0].innerWidth;
            }, function(){
              return scope.render(scope.data);
            }
          );

          // watch for data changes and re-render
          scope.$watch('data', function(newVals, oldVals) {
            return scope.render(newVals);
          }, true);
          // define render function
          scope.render = function(data,moyn){

            // setup variables
            var width, height, max,maxi, min,mini;
            var padding = 1;

            // accessor
            function x(d,i) { return i * (width / data.length);}
            function y(d) { return (height - (d.value-min)/((max-min)/height)); }
            function h(d) { return ((d.value-min)/((max-min)/height));}

            // fonction
            function info(d,i) {
              label.text(Math.round(d.value*100)/100) ;
              var datac = [ { "x" : x(d,i), "y" : 0 }, { "x" : x(d,i), "y" : height } ];
              d3.selectAll(".curseur").remove();
              svg.append("path")
                .datum(datac)
                .attr("class", "curseur")
                .attr("d", curseur);
              }
            // remove all previous items before render
            svg.selectAll("*").remove();

            height = d3.select(iElement[0])[0][0].offsetHeight - 100;
            width = d3.select(iElement[0])[0][0].offsetWidth;
            console.log(height,width);
              // 20 is for margins and can be changed
//            width = 1160 ;//scope.data.length * 35;
            height = 450 ;
            if (data.length > 500 ) { padding = 0; } // no padding si trop de data
            maxi = Math.max.apply(Math, data.map(function(x) {return x.value; }));
            mini = Math.min.apply(Math, data.map(function(x) {return x.value; }));
//            console.log("max: ",maxi,"min: ",mini, "moyenne: ",scope.moyn);

            max = maxi + 0.07 * (maxi-mini);
            min = mini - 0.15 * (maxi-mini);

            // set the height based on the calculations above
            svg.attr('height', height)
               .attr('width',  width);

// Add the year label; the value is set on transition.
var label = svg.append("text")
    .attr("class", "year label")
    .attr("text-anchor", "end")
    .attr("y",  55)
    .attr("x", width)
    .text('VALEUR');

var curseur = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_min = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_max = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_moy = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

// Add a y-axis label.
var yScale = d3.scale.linear().domain([max, min]).range([0,height]),
    yAxis = d3.svg.axis().scale(yScale).orient("left");

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("mesure");

            //create the rectangles for the bar chart
            svg.selectAll("rect")
              .data(data)
              .enter()
                .append("rect")
                .on("click", function(d, i){return scope.onClick({item: d});})
                .on("mouseover",function (d,i) { return info(d,i);})
                .attr("height", 0) // height of each bar
                .attr("width", width / data.length - padding)
                .attr("x", function(d,i) { return x(d, i);})  // height + margin between bars
                .attr("fill","yellow")
                .transition()
                  .duration(3000) // time of duration
                  .attr("stroke-width",0)
                  .attr("fill", function(d) {
                    var val = ((d.value -min)/((max-min)/16));
                    return "rgb(100, 160, " + val*16 + ")";
                    })
                  .attr("height", function (d) { return h(d); }) // half of the 20 side margin specified above
                  .attr("y", function (d) { return y(d);}); // width based on scale

            // position des repères
            var ordonne = height - (mini-min)/((max-min)/height);
            var datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_min").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_min);
            ordonne = height - (maxi-min)/((max-min)/height);
            datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_max").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_max);
            ordonne = height - (scope.moyn-min)/((max-min)/height);
            datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_moy").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_moy);

            svg.selectAll("text")
              .data(data)
              .enter()
                .append("text")
                .attr("fill", "#fff")
                .attr("y", function(d, i){return i * 35 + 22;})
                .attr("x", 15)
                .text(function(d){return d[scope.label];});

          };
        }
      };
    }]);

}());<commit_msg>adjust<commit_after>(function () {
  'use strict';

  angular.module('RkyApp.directives')
    .directive('d3Bars', ['d3', function(d3) {
      return {
        restrict: 'EA',
        scope: {
          data: "=",
          label: "@",
          onClick: "&"
        },
        link: function(scope, iElement, iAttrs) {
          var svg = d3.select(iElement[0])
              .append("svg")
              .attr("width", "100%");

          // on window resize, re-render d3 canvas
          window.onresize = function() {
            return scope.$apply();
          };
          scope.$watch(function(){
              return angular.element(window)[0].innerWidth;
            }, function(){
              return scope.render(scope.data);
            }
          );

          // watch for data changes and re-render
          scope.$watch('data', function(newVals, oldVals) {
            return scope.render(newVals);
          }, true);

          // define render function
          scope.render = function(data){
            // remove all previous items before render
            svg.selectAll("*").remove();

            // setup variables
            var width, height, max;
            width = d3.select(iElement[0])[0][0].offsetWidth - 20;
              // 20 is for margins and can be changed
            height = scope.data.length * 35;
              // 35 = 30(bar height) + 5(margin between bars)
            max = 98;
              // this can also be found dynamically when the data is not static
              // max = Math.max.apply(Math, _.map(data, ((val)-> val.count)))

            // set the height based on the calculations above
            svg.attr('height', height);

            //create the rectangles for the bar chart
            svg.selectAll("rect")
              .data(data)
              .enter()
                .append("rect")
                .on("click", function(d, i){return scope.onClick({item: d});})
                .attr("height", 30) // height of each bar
                .attr("width", 0) // initial width of 0 for transition
                .attr("x", 10) // half of the 20 side margin specified above
                .attr("y", function(d, i){
                  return i * 35;
                }) // height + margin between bars
                .transition()
                  .duration(1000) // time of duration
                  .attr("width", function(d){
                    return d.value/(max/width);
                  }); // width based on scale

            svg.selectAll("text")
              .data(data)
              .enter()
                .append("text")
                .attr("fill", "#fff")
                .attr("y", function(d, i){return i * 35 + 22;})
                .attr("x", 15)
                .text(function(d){return d[scope.label];});

          };
        }
      };
    }]);

}());

// -- by e-Coucou

(function () {
  'use strict';

  angular.module('RkyApp.directives')
    .directive('d3Lines', ['d3', function(d3) {
      return {
        restrict: 'EA',
        scope: {
          data: "=",
          label: "@",
          moyn: "=",
          onClick: "&"
        },
        link: function(scope, iElement, iAttrs) {
          var svg = d3.select(iElement[0])
              .append("svg")
              .attr("width", "100%");

          // on window resize, re-render d3 canvas
          window.onresize = function() {
            return scope.$apply();
          };
          scope.$watch(function(){
              return angular.element(window)[0].innerWidth;
            }, function(){
              return scope.render(scope.data);
            }
          );

          // watch for data changes and re-render
          scope.$watch('data', function(newVals, oldVals) {
            return scope.render(newVals);
          }, true);
          // define render function
          scope.render = function(data,moyn){

            // setup variables
            var width, height, max,maxi, min,mini;
            var padding = 1;

            // accessor
            function x(d,i) { return i * (width / data.length);}
            function y(d) { return (height - (d.value-min)/((max-min)/height)); }
            function h(d) { return ((d.value-min)/((max-min)/height));}

            // fonction
            function info(d,i) {
              label.text(Math.round(d.value*100)/100) ;
              var datac = [ { "x" : x(d,i), "y" : 0 }, { "x" : x(d,i), "y" : height } ];
              d3.selectAll(".curseur").remove();
              svg.append("path")
                .datum(datac)
                .attr("class", "curseur")
                .attr("d", curseur);
              }
            // remove all previous items before render
            svg.selectAll("*").remove();

            height = d3.select(iElement[0])[0][0].offsetHeight - 100;
            width = d3.select(iElement[0])[0][0].offsetWidth;
            console.log(height,width);
              // 20 is for margins and can be changed
//            width = 1160 ;//scope.data.length * 35;
            height = 450 ;
            if (data.length > 500 ) { padding = 0; } // no padding si trop de data
            maxi = Math.max.apply(Math, data.map(function(x) {return x.value; }));
            mini = Math.min.apply(Math, data.map(function(x) {return x.value; }));
//            console.log("max: ",maxi,"min: ",mini, "moyenne: ",scope.moyn);

            max = maxi + 0.07 * (maxi-mini);
            min = mini - 0.15 * (maxi-mini);

            // set the height based on the calculations above
            svg.attr('height', height)
               .attr('width',  width);

// Add the year label; the value is set on transition.
var label = svg.append("text")
    .attr("class", "year label")
    .attr("text-anchor", "end")
    .attr("y",  55)
    .attr("x", width)
    .text('VALEUR');

var curseur = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_min = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_max = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var repere_moy = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

// Add a y-axis label.
var yScale = d3.scale.linear().domain([max, min]).range([0,height]),
    yAxis = d3.svg.axis().scale(yScale).orient("right");

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("mesure");

            //create the rectangles for the bar chart
            svg.selectAll("rect")
              .data(data)
              .enter()
                .append("rect")
                .on("click", function(d, i){return scope.onClick({item: d});})
                .on("mouseover",function (d,i) { return info(d,i);})
                .attr("height", 0) // height of each bar
                .attr("width", width / data.length - padding)
                .attr("x", function(d,i) { return x(d, i);})  // height + margin between bars
                .attr("fill","yellow")
                .transition()
                  .duration(3000) // time of duration
                  .attr("stroke-width",0)
                  .attr("fill", function(d) {
                    var val = ((d.value -min)/((max-min)/16));
                    return "rgb(100, 160, " + val*16 + ")";
                    })
                  .attr("height", function (d) { return h(d); }) // half of the 20 side margin specified above
                  .attr("y", function (d) { return y(d);}); // width based on scale

            // position des repères
            var ordonne = height - (mini-min)/((max-min)/height);
            var datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_min").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_min);
            ordonne = height - (maxi-min)/((max-min)/height);
            datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_max").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_max);
            ordonne = height - (scope.moyn-min)/((max-min)/height);
            datac = [ { "x" : 0, "y" : ordonne }, { "x" : width, "y" : ordonne } ];
            d3.selectAll(".repere_moy").remove();
            svg.append("path")
              .datum(datac)
              .attr("class", "repere")
              .style("stroke-dasharray", ("10,5,2,5"))
              .attr("d", repere_moy);

            svg.selectAll("text")
              .data(data)
              .enter()
                .append("text")
                .attr("fill", "#fff")
                .attr("y", function(d, i){return i * 35 + 22;})
                .attr("x", 15)
                .text(function(d){return d[scope.label];});

          };
        }
      };
    }]);

}());<|endoftext|>


<commit_before>var lang = $('html').attr('lang'),
	langues = ['fr', 'nl', 'en'],
	content = [];

function translate(string) {
	// alert(string);
	// alert('content[string]' + content[string]);
	// return string; // BUG
	// if (content[string]) {
	// 	return content[string];
	// } else {
	// 	return string;
	// }
		return string;
}

function showMessage(responsetext, responsetype) {
	var errorClass;
	if (responsetype == 'error') {
		errorClass = ' alert-error';
	} else {
		errorClass = '';
	}
	$('.alert').remove();
	var alerte = '
'+responsetext+'
';
	$('#container').prepend(alerte);
	$('.alert').hide().fadeIn('fast');
}

!function( $ ){

	"use strict";

	$(function () {

		function javascriptError(data, statusText) {
			showMessage(translate('Unknown error'), 1);
			console.log(statusText);
			console.log(data);
		}

		function checkAndShowMessageDiv() {
			var messageDiv, error;
			messageDiv = $('#message');
			if (messageDiv.length) {
				messageDiv.hide().children('li').each(function () {
					if ($(this).hasClass('error')) {
						error = 'error';
					}
					showMessage($(this).text(), error);
				});
			}
		}

		checkAndShowMessageDiv();

		var dropZoneTemplate = '
\

\
					\

\
						\

\

\

\

\

\

';

		$('#uploaderAddButtonContainer').click(function(event) {
			return false;
		});
		$( "#uploaderAddButton" ).on( "click", function() {
			$('#dropzone').trigger('click');
		});

		Dropzone.options.dropzone = {
			clickable: true,
			maxFilesize: 2, // MB
			acceptedFiles: 'image/jpeg,image/gif,image/png',
			previewTemplate: dropZoneTemplate,
			previewsContainer: '.dropzone-previews',
			thumbnailWidth: 130,
			thumbnailHeight: 130,
			init: function () {
				var totalFiles = 0,
					completeFiles = 0;
				this.on("complete", function (file) {
					completeFiles += 1;
					if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
						// Mettre à jour les position
						var files = this.getAcceptedFiles();
						var done = 0;
						for (var key in files){
							var object = jQuery.parseJSON( files[key].xhr.responseText );
							object.position = parseInt($('#nb_elements').text()) + parseInt(key);
							$.ajax({
								type: 'PATCH',
								url: cleanUrl() + '/' + object.id,
								data: object
							}).done(function(){
								done += 1;
								if (done === files.length) {
									location.reload();
								}
							}).fail(function () {
								alertify.error(translate('An error occurred while sorting files.'));
							});
						}
					}
				});
			}
		};

	});

}( window.jQuery || window.ender );
<commit_msg>indentation<commit_after>var lang = $('html').attr('lang'),
	langues = ['fr', 'nl', 'en'],
	content = [];

function translate(string) {
	// alert(string);
	// alert('content[string]' + content[string]);
	// return string; // BUG
	// if (content[string]) {
	// 	return content[string];
	// } else {
	// 	return string;
	// }
	return string;
}

function showMessage(responsetext, responsetype) {
	var errorClass;
	if (responsetype == 'error') {
		errorClass = ' alert-error';
	} else {
		errorClass = '';
	}
	$('.alert').remove();
	var alerte = '
'+responsetext+'
';
	$('#container').prepend(alerte);
	$('.alert').hide().fadeIn('fast');
}

!function( $ ){

	"use strict";

	$(function () {

		function javascriptError(data, statusText) {
			showMessage(translate('Unknown error'), 1);
			console.log(statusText);
			console.log(data);
		}

		function checkAndShowMessageDiv() {
			var messageDiv, error;
			messageDiv = $('#message');
			if (messageDiv.length) {
				messageDiv.hide().children('li').each(function () {
					if ($(this).hasClass('error')) {
						error = 'error';
					}
					showMessage($(this).text(), error);
				});
			}
		}

		checkAndShowMessageDiv();

		var dropZoneTemplate = '
\

\
					\

\
						\

\

\

\

\

\

';

		$('#uploaderAddButtonContainer').click(function(event) {
			return false;
		});
		$( "#uploaderAddButton" ).on( "click", function() {
			$('#dropzone').trigger('click');
		});

		Dropzone.options.dropzone = {
			clickable: true,
			maxFilesize: 2, // MB
			acceptedFiles: 'image/jpeg,image/gif,image/png',
			previewTemplate: dropZoneTemplate,
			previewsContainer: '.dropzone-previews',
			thumbnailWidth: 130,
			thumbnailHeight: 130,
			init: function () {
				var totalFiles = 0,
					completeFiles = 0;
				this.on("complete", function (file) {
					completeFiles += 1;
					if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
						// Mettre à jour les position
						var files = this.getAcceptedFiles();
						var done = 0;
						for (var key in files){
							var object = jQuery.parseJSON( files[key].xhr.responseText );
							object.position = parseInt($('#nb_elements').text()) + parseInt(key);
							$.ajax({
								type: 'PATCH',
								url: cleanUrl() + '/' + object.id,
								data: object
							}).done(function(){
								done += 1;
								if (done === files.length) {
									location.reload();
								}
							}).fail(function () {
								alertify.error(translate('An error occurred while sorting files.'));
							});
						}
					}
				});
			}
		};

	});

}( window.jQuery || window.ender );
<|endoftext|>


<commit_before>$(document).ready(function(){

  var Log = Backbone.Model.extend({});
  var LogStore = Backbone.Collection.extend({
   model: Log,
     url: '/logs'
  });

  var LogTableView = Backbone.View.extend({

    offset: 0,

    howManyShown: 15,

    events: {
      "click .arrow-left  img": "swapLeft",
      "click .arrow-right img": "swapRight"
    },

    swapLeft: function(){
      this.offset = Math.max(this.offset - this.howManyShown, 0);
      this.render();
    },

    swapRight: function(){
      this.offset = Math.min(this.offset + this.howManyShown, logs.size()-1);
      this.render();
    },

    logsToShow: function(){
      var l = logs.map(function(x){ return x.toJSON(); });
      return l.slice(this.offset, this.offset + this.howManyShown);
    },

    render: function() {
      view = this;
      $.get('views/log-table.mustache', function(tpl){
        var shownlogs = view.logsToShow();
        var htmlText = Mustache.render(tpl, {logs: shownlogs});
        view.$el.html(htmlText);
      })
    }

  });

  var logs = new LogStore;
  var logTableView = new LogTableView({el: '#log-table'});

  logs.fetch({success: function(){ logTableView.render(); }});
})
<commit_msg>Internal Model/View inside the table view itself.<commit_after>var LogBook = (typeof module !== "undefined" && module.exports) || {};

(function (exports) {

  // One single log tuple as a Backbone model
  exports.Log  = Backbone.Model.extend({});

  // All log tuples (as seen by the client) as a Backbone collection
  exports.Logs = Backbone.Collection.extend({
   model: exports.Log,
     url: '/logs'
  });

  // The table view
  exports.LogTableView = Backbone.View.extend({

    events: {
      "click .arrow-left  img": "swapLeft",
      "click .arrow-right img": "swapRight"
    },

    initialize: function(options) {
      this.model.on('all', this.render, this);
      this.State = Backbone.Model.extend({});
      this.state = new this.State({
        offset: 0,
        limit: 15
      });
      this.state.on('all', this.render, this);
    },

    offset: function(){ return this.state.get('offset'); },
    limit:  function(){ return this.state.get('limit');  },

    getLogs: function() {
      offset = this.offset();
      limit  = this.limit();
      return this.model
                 .map(function(x){ return x.toJSON(); })
                 .slice(offset, offset + limit);
    },

    swapLeft: function(){
      this.state.set({offset: Math.max(this.offset() - this.limit(), 0)});
    },

    swapRight: function(){
      this.state.set({offset: Math.min(this.offset() + this.limit(), this.model.size()-1)});
    },

    render: function() {
      var view = this;
      $.get('views/log-table.mustache', function(tpl){
        var shownlogs = view.getLogs(view.state);
        var htmlText = Mustache.render(tpl, {logs: shownlogs});
        view.$el.html(htmlText);
      })
    }

  });

})(LogBook);

$(document).ready(function(){
  var logs = new LogBook.Logs;
  var logTableView = new LogBook.LogTableView({model: logs, el: '#log-table'});
  logs.fetch();
})
<|endoftext|>


<commit_before>$(document).ready(function() {
  app.hookupMap();
  app.hookupSteps();
});

var app = app || {};
app.state = {
  channel: 'sms',
  geom: undefined,
  publisher_id: undefined,
};

app.eventMarkers = new L.FeatureGroup();

app.hookupMap = function() {
  var options = {
    zoom: 13,
    center: [47.604432, -122.336014],
    tileLayer: { detectRetina: true },
    scrollWheelZoom: false,
  };
  var mapId = $('meta[name=mapId]').attr('content');
  var map = app.map = L.mapbox.map('map', mapId, options);
};

app.hookupSteps = function() {
  $('.startButton').on('click', function() {
    app.scrollToElement($('#step1'));
  });

  $('.publisher:not(.soon)').on('click', function(event) {
    $('.publisher').removeClass('selected');

    var $publisher = $(event.currentTarget);
    app.state.publisher_id = $publisher.data('publisher-id');
    $publisher.addClass('selected');

    // Update the confirmation section with the name
    $('.confirmationType').html($publisher.data('publisher-title'));

    app.scrollToElement($('#step2'));

    // update events for the new publisher
    app.updateEvents();
  });

  $('.mapButton').on('click', function() {
    app.scrollToElement($('#step3'));
  });

  $('.smsButton').on('click', function(event) {
    $(event.target).addClass('selected');
    $('.extraInfo').slideDown();
  });

  var finishSubscribe = function(e) {
    // TODO: animate the done checkmark at the same time
    e.preventDefault();

    // TODO: handle email and webhooks also
    app.state.phone_number = $('.phoneNumber').val();

    app.submitSubscription(function() {
      $('#confirmation').slideDown();
      app.scrollToElement($('#confirmation'));
    });
  };
  $('.subscribeButton').on('click', finishSubscribe);
  $('#subscribeForm').on('submit', finishSubscribe);

  $('.resetButton').on('click', function(event) {
    app.resetState();
    app.scrollToElement($('#step1'));

    // Hide after we've scrolled up.
    setTimeout(function() {
      $('#confirmation').hide();
    }, 800);
  });

  var prevMarker, prevCircle;
  var geolocate = function(e) {
    e.preventDefault();
    var city = $('.publisher.selected').data('publisher-city');
    var address = $('#geolocate').val();
    app.geocode(address+' '+city, function(latlng) {
      app.map.setView(latlng, 15);
      app.updateEvents();
      updateGeometry(latlng);

      if (prevMarker) app.map.removeLayer(prevMarker);
      if (prevCircle) app.map.removeLayer(prevCircle);

      prevMarker = L.marker(latlng).addTo(app.map);
      prevCircle = L.circle(latlng, 500).addTo(app.map);
    });
  };

  var BOUNDING_DISTANCE_IN_KM = 0.5;
  var updateGeometry = function(latlng) {
    var center = new LatLon(latlng[0], latlng[1]);
    var bbox = center.boundingBox(BOUNDING_DISTANCE_IN_KM);
    app.state.geom = JSON.stringify({
      type: 'Polygon',
      coordinates: [bbox],
    });
  };

  $('#geolocateForm').on('submit', geolocate);
  $('.geolocateButton').on('click', geolocate);
};

app.updateEvents = function() {
  var mapBounds = app.map.getBounds();
  var mapGeometry = {
    type: 'Polygon',
    coordinates: [[
      [mapBounds._southWest.lng, mapBounds._northEast.lat],
      [mapBounds._northEast.lng, mapBounds._northEast.lat],
      [mapBounds._northEast.lng, mapBounds._southWest.lat],
      [mapBounds._southWest.lng, mapBounds._southWest.lat],
      [mapBounds._southWest.lng, mapBounds._northEast.lat]
    ]]
  }

  app.getEventsForGeometry(JSON.stringify(mapGeometry), function(events) {
    app.eventMarkers.eachLayer(function(layer) {
      app.map.removeLayer(layer);
    });
    events.forEach(app.displayEventMarker);
  });
};

app.displayEventMarker = function(event) {
  var geometry = JSON.parse(event.geom);
  var html = "
"+event.title+"
"
  var marker = L.circleMarker([geometry.coordinates[1], geometry.coordinates[0]], { radius: 4 })
                 .addTo(app.map)
                 .bindPopup(html);

  app.eventMarkers.addLayer(marker);
  return marker;
}

app.getEventsForGeometry = function(geometry, callback){
  if (!app.state.publisher_id) return;
  $.getJSON('/publishers/'+app.state.publisher_id+'/events', { geometry: geometry }, callback);
};

app.scrollToElement = function(el) {
  $('html,body').animate({
    scrollTop: el.offset().top
  }, 800);
};

app.geocode = function(city, callback, context) {
  var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(city);

  $.getJSON(url, function(response) {
    if (response.error || response.results.length === 0) {
      console.log('Unable to geocode city. Womp Womp.', response.error);
    }

    // Get the coordinates for the center of the city
    var location = response.results[0].geometry.location;
    var latlng = [location.lat, location.lng];
    callback.call(context || this, latlng);
  });
};

app.resetState = function() {
  app.state.publisher_id = undefined;
  $('.publisher').removeClass('selected');

  // Let's leave the location and phone number in place, for easy re-subscribe
};

app.submitSubscription = function(callback) {
  $.post('/subscriptions', { subscription: app.state }, callback);
};
<commit_msg>Geolocate when the address field changes<commit_after>$(document).ready(function() {
  app.hookupMap();
  app.hookupSteps();
});

var app = app || {};
app.state = {
  channel: 'sms',
  geom: undefined,
  publisher_id: undefined,
};

app.eventMarkers = new L.FeatureGroup();

app.hookupMap = function() {
  var options = {
    zoom: 13,
    center: [47.604432, -122.336014],
    tileLayer: { detectRetina: true },
    scrollWheelZoom: false,
  };
  var mapId = $('meta[name=mapId]').attr('content');
  var map = app.map = L.mapbox.map('map', mapId, options);
};

app.hookupSteps = function() {
  $('.startButton').on('click', function() {
    app.scrollToElement($('#step1'));
  });

  $('.publisher:not(.soon)').on('click', function(event) {
    $('.publisher').removeClass('selected');

    var $publisher = $(event.currentTarget);
    app.state.publisher_id = $publisher.data('publisher-id');
    $publisher.addClass('selected');

    // Update the confirmation section with the name
    $('.confirmationType').html($publisher.data('publisher-title'));

    app.scrollToElement($('#step2'));

    // update events for the new publisher
    app.updateEvents();
  });

  $('.mapButton').on('click', function() {
    app.scrollToElement($('#step3'));
  });

  $('.smsButton').on('click', function(event) {
    $(event.target).addClass('selected');
    $('.extraInfo').slideDown();
  });

  var finishSubscribe = function(e) {
    // TODO: animate the done checkmark at the same time
    e.preventDefault();

    // TODO: handle email and webhooks also
    app.state.phone_number = $('.phoneNumber').val();

    app.submitSubscription(function() {
      $('#confirmation').slideDown();
      app.scrollToElement($('#confirmation'));
    });
  };
  $('.subscribeButton').on('click', finishSubscribe);
  $('#subscribeForm').on('submit', finishSubscribe);

  $('.resetButton').on('click', function(event) {
    app.resetState();
    app.scrollToElement($('#step1'));

    // Hide after we've scrolled up.
    setTimeout(function() {
      $('#confirmation').hide();
    }, 800);
  });

  var prevMarker, prevCircle;
  var geolocate = function(e) {
    e.preventDefault();
    var city = $('.publisher.selected').data('publisher-city');
    var address = $('#geolocate').val();
    app.geocode(address+' '+city, function(latlng) {
      app.map.setView(latlng, 15);
      app.updateEvents();
      updateGeometry(latlng);

      if (prevMarker) app.map.removeLayer(prevMarker);
      if (prevCircle) app.map.removeLayer(prevCircle);

      prevMarker = L.marker(latlng).addTo(app.map);
      prevCircle = L.circle(latlng, 500).addTo(app.map);
    });
  };

  var BOUNDING_DISTANCE_IN_KM = 0.5;
  var updateGeometry = function(latlng) {
    var center = new LatLon(latlng[0], latlng[1]);
    var bbox = center.boundingBox(BOUNDING_DISTANCE_IN_KM);
    app.state.geom = JSON.stringify({
      type: 'Polygon',
      coordinates: [bbox],
    });
  };

  $('#geolocateForm').on('submit', geolocate);
  $('.geolocateButton').on('click', geolocate);
  $('#geolocate').on('change', geolocate);
};

app.updateEvents = function() {
  var mapBounds = app.map.getBounds();
  var mapGeometry = {
    type: 'Polygon',
    coordinates: [[
      [mapBounds._southWest.lng, mapBounds._northEast.lat],
      [mapBounds._northEast.lng, mapBounds._northEast.lat],
      [mapBounds._northEast.lng, mapBounds._southWest.lat],
      [mapBounds._southWest.lng, mapBounds._southWest.lat],
      [mapBounds._southWest.lng, mapBounds._northEast.lat]
    ]]
  }

  app.getEventsForGeometry(JSON.stringify(mapGeometry), function(events) {
    app.eventMarkers.eachLayer(function(layer) {
      app.map.removeLayer(layer);
    });
    events.forEach(app.displayEventMarker);
  });
};

app.displayEventMarker = function(event) {
  var geometry = JSON.parse(event.geom);
  var html = "
"+event.title+"
"
  var marker = L.circleMarker([geometry.coordinates[1], geometry.coordinates[0]], { radius: 4 })
                 .addTo(app.map)
                 .bindPopup(html);

  app.eventMarkers.addLayer(marker);
  return marker;
}

app.getEventsForGeometry = function(geometry, callback){
  if (!app.state.publisher_id) return;
  $.getJSON('/publishers/'+app.state.publisher_id+'/events', { geometry: geometry }, callback);
};

app.scrollToElement = function(el) {
  $('html,body').animate({
    scrollTop: el.offset().top
  }, 800);
};

app.geocode = function(city, callback, context) {
  var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(city);

  $.getJSON(url, function(response) {
    if (response.error || response.results.length === 0) {
      console.log('Unable to geocode city. Womp Womp.', response.error);
    }

    // Get the coordinates for the center of the city
    var location = response.results[0].geometry.location;
    var latlng = [location.lat, location.lng];
    callback.call(context || this, latlng);
  });
};

app.resetState = function() {
  app.state.publisher_id = undefined;
  $('.publisher').removeClass('selected');

  // Let's leave the location and phone number in place, for easy re-subscribe
};

app.submitSubscription = function(callback) {
  $.post('/subscriptions', { subscription: app.state }, callback);
};
<|endoftext|>


<commit_before>(function() {
  $(function() {
    var socket = io();
    var user = "anonymous";
    $('#msg').focus();
    $('#messages').append($('
').text("Type \'\/nick new-user-name\' to change your username"));
    $('body').click(function() {
      $('#msg').focus();
    });
    $('form').submit(function(){
      var arr = $('#msg').val().split(" ");
      if (arr[0] == '/nick') {
        var olduser = user;
        user = arr.slice(1).join(" ");
        $('#msg').val('');
        socket.emit('namechange', olduser, user);
        return false;
      } else {
        socket.emit('msg', user + ":  " + $('#msg').val());
        $('#msg').val('');
        return false;
      }
    });
    socket.on('msg', function(msg){
        $('#messages').append($('
').text(msg));
      });
      socket.on('alert', function(msg) {
        $('#messages').append($('
').text(msg));
      });
  });
}());
<commit_msg>change body.click(...) to html.click(...) for select input logic<commit_after>(function() {
  $(function() {
    var socket = io();
    var user = "anonymous";
    $('#msg').focus();
    $('#messages').append($('
').text("Type \'\/nick new-user-name\' to change your username"));
    $('html').click(function() {
      $('#msg').focus();
    });
    $('form').submit(function(){
      var arr = $('#msg').val().split(" ");
      if (arr[0] == '/nick') {
        var olduser = user;
        user = arr.slice(1).join(" ");
        $('#msg').val('');
        socket.emit('namechange', olduser, user);
        return false;
      } else {
        socket.emit('msg', user + ":  " + $('#msg').val());
        $('#msg').val('');
        return false;
      }
    });
    socket.on('msg', function(msg){
        $('#messages').append($('
').text(msg));
      });
      socket.on('alert', function(msg) {
        $('#messages').append($('
').text(msg));
      });
  });
}());
<|endoftext|>


<commit_before>/* global addDocumentService,
 addWindowService,
 addAsyncService,
 addTimeoutService,
 addSignalService,
 addEventEmitterService,
 addCacheService,
 addLogService,
 addLogConsoleService,
 addErrorHandlerService,
 addUncaughtErrorHandlerService,
 addPerformanceService,
 addCookiesService,
 addStorageServices,
 addPromiseService,
 addHttpXhrService,
 addHttpJsonpService,
 addHttpDeferredService,
 addHttpProviderService,
 addHttpService,
 addRouterService
 */
"use strict";

function createApi(recurve, version) {
    var versionSplit = version.split(".");
    recurve.version = {
        full: version,
        major: versionSplit[0],
        minor: versionSplit[1],
        patch: versionSplit[2],
    }

    extend(recurve, {
        forEach: forEach,
        extend: extend,
        clone: clone,
        format: format,
        contains: contains,
        addEvent: addEvent,
        removeEvent: removeEvent,
        areEqual: areEqual,
        isNaN: isNaN,
        isSameType: isSameType,
        isString: isString,
        isUndefined: isUndefined,
        isError: isError,
        isObject: isObject,
        isArray: isArray,
        isFunction: isFunction,
        isDate: isDate,
        isNumber: isNumber,
        isRegExp: isRegExp,
        toJson: toJson,
        fromJson: fromJson,
        assert: assert
    });

    var recurveModule = recurve.$module = module();

    addDocumentService(recurveModule);
    addWindowService(recurveModule);
    addAsyncService(recurveModule);
    addTimeoutService(recurveModule);
    addSignalService(recurveModule);
    addEventEmitterService(recurveModule);
    addCacheService(recurveModule);
    addLogService(recurveModule);
    addLogConsoleService(recurveModule);
    addErrorHandlerService(recurveModule);
    addUncaughtErrorHandlerService(recurveModule);
    addPerformanceService(recurveModule);
    addCookiesService(recurveModule);
    addStorageServices(recurveModule);
    addPromiseService(recurveModule);
    addHttpXhrService(recurveModule);
    addHttpJsonpService(recurveModule);
    addHttpDeferredService(recurveModule);
    addHttpProviderService(recurveModule);
    addHttpService(recurveModule);
    addRouterService(recurveModule);

    recurveModule.exports([
        "$document", "$window", "$timeout", "$signal",
        "$eventEmitter", "$cache", "$log", "$logConsole",
        "$errorHandler", "$uncaughtErrorHandler", "$performance",
        "$cookies", "$promise", "$http"
    ]);

    recurve.module = function(dependentModules) {
        // TODO TBD core module is always include, but does not need to be explicitly specified
        // maybe require to be specified
        dependentModules = dependentModules || [];

        if (-1 === dependentModules.indexOf(recurveModule)) {
            dependentModules.unshift(recurveModule);
        }

        return module(dependentModules);
    };

    recurve.container = container;
}
<commit_msg>fix jshint warnings<commit_after>/* global addDocumentService,
 addWindowService,
 addAsyncService,
 addTimeoutService,
 addSignalService,
 addEventEmitterService,
 addCacheService,
 addLogService,
 addLogConsoleService,
 addErrorHandlerService,
 addUncaughtErrorHandlerService,
 addPerformanceService,
 addCookiesService,
 addStorageServices,
 addPromiseService,
 addHttpXhrService,
 addHttpJsonpService,
 addHttpDeferredService,
 addHttpProviderService,
 addHttpService,
 addRouterService
 */
"use strict";

function createApi(recurve, version) {
    var versionSplit = version.split(".");
    recurve.version = {
        full: version,
        major: versionSplit[0],
        minor: versionSplit[1],
        patch: versionSplit[2]
    };

    extend(recurve, {
        forEach: forEach,
        extend: extend,
        clone: clone,
        format: format,
        contains: contains,
        addEvent: addEvent,
        removeEvent: removeEvent,
        areEqual: areEqual,
        isNaN: isNaN,
        isSameType: isSameType,
        isString: isString,
        isUndefined: isUndefined,
        isError: isError,
        isObject: isObject,
        isArray: isArray,
        isFunction: isFunction,
        isDate: isDate,
        isNumber: isNumber,
        isRegExp: isRegExp,
        toJson: toJson,
        fromJson: fromJson,
        assert: assert
    });

    var recurveModule = recurve.$module = module();

    addDocumentService(recurveModule);
    addWindowService(recurveModule);
    addAsyncService(recurveModule);
    addTimeoutService(recurveModule);
    addSignalService(recurveModule);
    addEventEmitterService(recurveModule);
    addCacheService(recurveModule);
    addLogService(recurveModule);
    addLogConsoleService(recurveModule);
    addErrorHandlerService(recurveModule);
    addUncaughtErrorHandlerService(recurveModule);
    addPerformanceService(recurveModule);
    addCookiesService(recurveModule);
    addStorageServices(recurveModule);
    addPromiseService(recurveModule);
    addHttpXhrService(recurveModule);
    addHttpJsonpService(recurveModule);
    addHttpDeferredService(recurveModule);
    addHttpProviderService(recurveModule);
    addHttpService(recurveModule);
    addRouterService(recurveModule);

    recurveModule.exports([
        "$document", "$window", "$timeout", "$signal",
        "$eventEmitter", "$cache", "$log", "$logConsole",
        "$errorHandler", "$uncaughtErrorHandler", "$performance",
        "$cookies", "$promise", "$http"
    ]);

    recurve.module = function(dependentModules) {
        // TODO TBD core module is always include, but does not need to be explicitly specified
        // maybe require to be specified
        dependentModules = dependentModules || [];

        if (-1 === dependentModules.indexOf(recurveModule)) {
            dependentModules.unshift(recurveModule);
        }

        return module(dependentModules);
    };

    recurve.container = container;
}
<|endoftext|>


<commit_before>function	sync_sv()
{
	socket.emit("get seated players");
	socket.on("need sbbb", function(sb, bb) {
		console.log('Salut ca va ou pas');
		console.log(sb, bb);
	})
	socket.on("seated players info", function(seat, seat_idx)
	{
		$("#qr" + seat_idx).css("visibility", "hidden");
		$("#qr_spot" + seat_idx).css("visibility", "hidden");
		$("#scan_msg" + seat_idx).css("visibility", "hidden");
		$("#player_name" + seat_idx).css("visibility", "visible");
		$("#player_name" + seat_idx).text(seat.player.nickname);
		$("#player_bankroll" + seat_idx).css("visibility", "visible");
		$("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ seat_idx).css("visibility", "visible");
	});
	socket.on("new player", function(player)
	{
		$("#qr" + player.seat_nb).css("visibility", "hidden");
		$("#qr_spot" + player.seat_nb).css("visibility", "hidden");
		$("#scan_msg" + player.seat_nb).css("visibility", "hidden");
		$("#player_name" + player.seat_nb).css("visibility", "visible");
		$("#player_name" + player.seat_nb).text(player.nickname);
		$("#player_bankroll" + player.seat_nb).css("visibility", "visible");
		$("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ player.seat_nb).css("visibility", "visible");
	});
	socket.on("kick player", function(seat_nb)
	{
		$("#qr" + seat_nb).css("visibility", "visible");
		$("#qr_spot" + seat_nb).css("visibility", "visible");
		$("#scan_msg" + seat_nb).css("visibility", "visible");
		$("#player_name" + seat_nb).css("visibility", "hidden");
		$("#player_name" + seat_nb).text("");
		$("#player_bankroll" + seat_nb).css("visibility", "hidden");
		$("#player_bankroll" + seat_nb).text("");
		$("#player_cards"+ seat_nb).css("visibility", "hidden");
		$("#btn" + seat_nb).attr("src", "");
		$("#btn" + seat_nb).css("visibility", "hidden");
	});
	socket.emit("ask buttons");
	socket.on("place button", function(type, seat_nb)
	{
		if (seat_nb <= 0 || seat_nb >= 7)
			return ;
		if (type == "dealer")
		{
			$("#btn" + seat_nb).attr("src", "../img/Dealer.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "sb")
		{
			$("#btn" + seat_nb).attr("src", "../img/sb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "bb")
		{
			$("#btn" + seat_nb).attr("src", "../img/bb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("give cards", function(seat_nb)
	{
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("highlights", function(seat_idx, new_state)
	{
		if (new_state == "off")
			$("#seat" + seat_idx).css("background-color", "#006F60");
		else if (new_state == "on")
			$("#seat" + seat_idx).css("background-color", "#FE554C");
	});
	socket.on("bankroll modification", function(seat_idx, player)
	{
		if (player.bankroll == "ALL IN")
			$("#player_bankroll" + seat_idx).text("ALL IN");
		else
			$("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
	});
	socket.on("pot modification", function(pot_amount)
	{
		$("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
	});
	socket.on("bet", function(seat_idx, amount)
	{
		if (!amount)
			$("#bet_val" + seat_idx).text('');
		else {
			$("#bet_val" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
		}
	});

	socket.on("last action", function(decision, seat_nb)
	{
		$("#last_action" + seat_nb).text(decision);
	});
	socket.on("fold", function(seat_nb)
	{
		$("#btn" + seat_nb).css("visibility", "hidden");
		$("#bet_val" + seat_nb).text('');
		$("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
		$("#last_action" + seat_nb).text('');
	});
	socket.emit("get board");
	socket.on("send flop", function(card1, card2, card3)
	{
		$("#b1").attr("src", "img/cards/" + card1 + ".png");
		$("#b2").attr("src", "img/cards/" + card2 + ".png");
		$("#b3").attr("src", "img/cards/" + card3 + ".png");
		$("#b1, #b2, #b3").css("visibility", "visible");
	});
	socket.on("send turn", function(card4)
	{
		$("#b4").attr("src", "img/cards/" + card4 + ".png");
		$("#b4").css("visibility", "visible");
	});
	socket.on("send river", function(card5)
	{
		$("#b5").attr("src", "img/cards/" + card5 + ".png");
		$("#b5").css("visibility", "visible");
	});
	socket.on("remove last actions", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#last_action" + idx).remove();
	});
	socket.on("remove board", function()
	{
		$("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
		for (var idx = 1; idx <= 6; ++idx)
			$("#player_cards" + idx).attr("src", "../img/avatar.png");
	});
	socket.on("remove emplacements", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#btn" + idx).css("visibility", "hidden");
	});
	socket.on("show down", function(card1, card2, seat_nb)
	{
		if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
			$("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
			$("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
			$("#card1_" + seat_nb).css("visibility", "visible");
			$("#card2_" + seat_nb).css("visibility", "visible");
		}
	});
	socket.on("show down off", function(seat_nb)
	{
		$("#card1_" + seat_nb).css("visibility", "hidden");
		$("#card2_" + seat_nb).css("visibility", "hidden");
	});
	socket.on("winner", function(seat_nb, rank_name)
	{
		var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
		var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

		if (rank_name == 'disconnected') {
			//$("#winner_msg").text($("#player_name" + seat_nb).text());
			$('#histoContent').empty();
			$('#histoContent').append(disconnect);
		}
		else if (seat_nb == 42 && rank_name == 'null') {
			//$("#winner_msg").text("Split!");
			$('#histoContent').empty();
			$('#histoContent').append('
Split !
');
		}
		else {
			$('#histoContent').empty();
			$('#histoContent').append(won);
		}
		//$("#winner").css("visibility", "visible");
	});
	socket.on("win off", function()
	{
		$("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
	});
}
<commit_msg>Sb func<commit_after>function	sync_sv()
{
	socket.emit("get seated players");
	socket.on("need sbbb", function(sb, bb) {
		console.log('Salut ca va ou pas');
		setInterval(function() {
			sb = sb * 2;
			console.log(sb);
		}, 10000);
		console.log(sb);
	})
	socket.on("seated players info", function(seat, seat_idx)
	{
		$("#qr" + seat_idx).css("visibility", "hidden");
		$("#qr_spot" + seat_idx).css("visibility", "hidden");
		$("#scan_msg" + seat_idx).css("visibility", "hidden");
		$("#player_name" + seat_idx).css("visibility", "visible");
		$("#player_name" + seat_idx).text(seat.player.nickname);
		$("#player_bankroll" + seat_idx).css("visibility", "visible");
		$("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ seat_idx).css("visibility", "visible");
	});
	socket.on("new player", function(player)
	{
		$("#qr" + player.seat_nb).css("visibility", "hidden");
		$("#qr_spot" + player.seat_nb).css("visibility", "hidden");
		$("#scan_msg" + player.seat_nb).css("visibility", "hidden");
		$("#player_name" + player.seat_nb).css("visibility", "visible");
		$("#player_name" + player.seat_nb).text(player.nickname);
		$("#player_bankroll" + player.seat_nb).css("visibility", "visible");
		$("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ player.seat_nb).css("visibility", "visible");
	});
	socket.on("kick player", function(seat_nb)
	{
		$("#qr" + seat_nb).css("visibility", "visible");
		$("#qr_spot" + seat_nb).css("visibility", "visible");
		$("#scan_msg" + seat_nb).css("visibility", "visible");
		$("#player_name" + seat_nb).css("visibility", "hidden");
		$("#player_name" + seat_nb).text("");
		$("#player_bankroll" + seat_nb).css("visibility", "hidden");
		$("#player_bankroll" + seat_nb).text("");
		$("#player_cards"+ seat_nb).css("visibility", "hidden");
		$("#btn" + seat_nb).attr("src", "");
		$("#btn" + seat_nb).css("visibility", "hidden");
	});
	socket.emit("ask buttons");
	socket.on("place button", function(type, seat_nb)
	{
		if (seat_nb <= 0 || seat_nb >= 7)
			return ;
		if (type == "dealer")
		{
			$("#btn" + seat_nb).attr("src", "../img/Dealer.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "sb")
		{
			$("#btn" + seat_nb).attr("src", "../img/sb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "bb")
		{
			$("#btn" + seat_nb).attr("src", "../img/bb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("give cards", function(seat_nb)
	{
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("highlights", function(seat_idx, new_state)
	{
		if (new_state == "off")
			$("#seat" + seat_idx).css("background-color", "#006F60");
		else if (new_state == "on")
			$("#seat" + seat_idx).css("background-color", "#FE554C");
	});
	socket.on("bankroll modification", function(seat_idx, player)
	{
		if (player.bankroll == "ALL IN")
			$("#player_bankroll" + seat_idx).text("ALL IN");
		else
			$("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
	});
	socket.on("pot modification", function(pot_amount)
	{
		$("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
	});
	socket.on("bet", function(seat_idx, amount)
	{
		if (!amount)
			$("#bet_val" + seat_idx).text('');
		else {
			$("#bet_val" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
		}
	});

	socket.on("last action", function(decision, seat_nb)
	{
		$("#last_action" + seat_nb).text(decision);
	});
	socket.on("fold", function(seat_nb)
	{
		$("#btn" + seat_nb).css("visibility", "hidden");
		$("#bet_val" + seat_nb).text('');
		$("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
		$("#last_action" + seat_nb).text('');
	});
	socket.emit("get board");
	socket.on("send flop", function(card1, card2, card3)
	{
		$("#b1").attr("src", "img/cards/" + card1 + ".png");
		$("#b2").attr("src", "img/cards/" + card2 + ".png");
		$("#b3").attr("src", "img/cards/" + card3 + ".png");
		$("#b1, #b2, #b3").css("visibility", "visible");
	});
	socket.on("send turn", function(card4)
	{
		$("#b4").attr("src", "img/cards/" + card4 + ".png");
		$("#b4").css("visibility", "visible");
	});
	socket.on("send river", function(card5)
	{
		$("#b5").attr("src", "img/cards/" + card5 + ".png");
		$("#b5").css("visibility", "visible");
	});
	socket.on("remove last actions", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#last_action" + idx).remove();
	});
	socket.on("remove board", function()
	{
		$("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
		for (var idx = 1; idx <= 6; ++idx)
			$("#player_cards" + idx).attr("src", "../img/avatar.png");
	});
	socket.on("remove emplacements", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#btn" + idx).css("visibility", "hidden");
	});
	socket.on("show down", function(card1, card2, seat_nb)
	{
		if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
			$("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
			$("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
			$("#card1_" + seat_nb).css("visibility", "visible");
			$("#card2_" + seat_nb).css("visibility", "visible");
		}
	});
	socket.on("show down off", function(seat_nb)
	{
		$("#card1_" + seat_nb).css("visibility", "hidden");
		$("#card2_" + seat_nb).css("visibility", "hidden");
	});
	socket.on("winner", function(seat_nb, rank_name)
	{
		var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
		var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

		if (rank_name == 'disconnected') {
			//$("#winner_msg").text($("#player_name" + seat_nb).text());
			$('#histoContent').empty();
			$('#histoContent').append(disconnect);
		}
		else if (seat_nb == 42 && rank_name == 'null') {
			//$("#winner_msg").text("Split!");
			$('#histoContent').empty();
			$('#histoContent').append('
Split !
');
		}
		else {
			$('#histoContent').empty();
			$('#histoContent').append(won);
		}
		//$("#winner").css("visibility", "visible");
	});
	socket.on("win off", function()
	{
		$("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
	});
}
<|endoftext|>


<commit_before>crayon.version = '0.0.5';<commit_msg>versioning fix<commit_after>crayon.version = '0.0.6';<|endoftext|>