<commit_before>var creep_work5 = {

    /** @param {Creep} creep **/
    run: function(creep, thisSpawn) {

        //wew lad
        /*if (!creep.room.controller.sign) {
            if(creep.pos.isNearTo(creep.room.controller)) {
                creep.signController(creep.room.controller, 'This is, by far, the most kupo room I\'ve ever seen!');
            }
        }*/

        if (creep.memory.priority == 'miner' || creep.memory.priority == 'minerNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'minerNearDeath';
                creep.memory.jobSpecific = creep.memory.jobSpecific + 'NearDeath';
            }
            //Creep will immediately harvest and store mined materials
            var storageTarget = Game.getObjectById(creep.memory.linkSource);
            var mineTarget = Game.getObjectById(creep.memory.mineSource);
            if (mineTarget && storageTarget) {
                if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(mineTarget, {
                        reusePath: 20
                    });
                } else {
                    creep.transfer(storageTarget RESOURCE_ENERGY)
                }
            }

            /*if (_.sum(creep.carry) < 144) {
                var savedTarget = Game.getObjectById(creep.memory.mineSource);
                if (savedTarget) {
                    if (creep.harvest(savedTarget) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget, {
                            reusePath: 20
                        });
                    } else if (creep.harvest(savedTarget, RESOURCE_ENERGY) == ERR_NOT_ENOUGH_RESOURCES && _.sum(creep.carry) > 0) {
                        //Source is dry, store what you have.
                        var savedTarget2 = Game.getObjectById(creep.memory.linkSource);
                        if (savedTarget2) {
                            if (creep.transfer(savedTarget2, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (_.sum(creep.carry) >= 144) {
                var savedTarget = Game.getObjectById(creep.memory.linkSource);
                if (savedTarget) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        //This should never actually fire, if ideal.
                        creep.moveTo(savedTarget);
                    }
                }
            }*/
        } else if (creep.memory.priority == 'upgrader' || creep.memory.priority == 'upgraderNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'upgraderNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                var linkTarget = Game.getObjectById(creep.memory.linkSource);
                if (linkTarget) {
                    if (linkTarget.energy > 0) {
                        if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(linkTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        //Get from storage instead
                        var storageTarget = Game.getObjectById(creep.memory.storageSource);
                        if (storageTarget) {
                            if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                                if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                    creep.moveTo(storageTarget, {
                                        reusePath: 20
                                    });
                                }
                            }
                        }
                    }
                } else {
                    var storageTarget = Game.getObjectById(creep.memory.storageSource);
                    if (storageTarget) {
                        if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                            if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(storageTarget, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(creep.room.controller, {
                        reusePath: 20
                    });
                }
            }
        } else if (creep.memory.priority == 'mule' || creep.memory.priority == 'muleNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'muleNearDeath';
            }
            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] > 0) {
                        //Get from container
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }

                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                var savedTarget = Game.getObjectById(creep.memory.structureTarget)

                if (savedTarget) {
                    if (creep.build(savedTarget) == ERR_INVALID_TARGET) {
                        if (savedTarget.structureType != STRUCTURE_CONTAINER && savedTarget.structureType != STRUCTURE_STORAGE && savedTarget.structureType != STRUCTURE_CONTROLLER) {
                            //Storing in spawn/extension/tower
                            if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(savedTarget, {
                                    reusePath: 20
                                });
                            }
                            if (savedTarget.energy == savedTarget.energyCapacity) {
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Upgrading controller
                            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(creep.room.controller, {
                                    reusePath: 20
                                });
                            }
                        }
                    } else {
                        if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget, {
                                reusePath: 20
                            });
                        }
                    }
                } else {
                    var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_EXTENSION ||
                                structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                        }
                    });
                    if (targets) {
                        creep.memory.structureTarget = targets.id;
                        if (creep.transfer(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(targets);
                        }
                        if (targets.energy == targets.energyCapacity) {
                            //If container fills up on this tick, forget it.
                            creep.memory.structureTarget = undefined;
                        }
                    } else {
                        targets3 = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_TOWER) && ((structure.energyCapacity - structure.energy) >= 300);
                            }
                        });
                        if (targets3) {
                            creep.memory.structureTarget = targets3.id;
                            if (creep.transfer(targets3, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets3);
                            }
                            if (targets3.energy == targets3.energyCapacity) {
                                //If container fills up on this tick, forget it.
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Store in terminal
                            terminalTarget = Game.getObjectById(creep.memory.terminalID)
                            if (terminalTarget) {
                                if (terminalTarget.store[RESOURCE_ENERGY] < 50000) {
                                    creep.memory.structureTarget = terminalTarget;
                                    if (creep.transfer(terminalTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(terminalTarget, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    terminalTarget = undefined;
                                }
                            }
                            if (!terminalTarget) {
                                //Build
                                var targets2 = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
                                if (targets2) {
                                    creep.memory.structureTarget = targets2.id;
                                    if (creep.build(targets2) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(targets2, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    //Upgrade
                                    creep.memory.structureTarget = creep.room.controller.id;
                                    if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(creep.room.controller, {
                                            reusePath: 20
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (creep.memory.priority == 'repair' || creep.memory.priority == 'repairNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'repairNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                //Get from storage
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 120) {
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else if (creep.memory.structureTarget) {
                var thisStructure = Game.getObjectById(creep.memory.structureTarget);
                if (thisStructure) {
                    if (thisStructure.hits == thisStructure.hitsMax) {
                        creep.memory.structureTarget = undefined;
                    } else {
                        if (creep.repair(thisStructure) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(thisStructure, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else {
                var closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hitsMax - structure.hits >= 200)
                });
                if (closestDamagedStructure.length > 0) {
                    closestDamagedStructure.sort(repairCompare);
                    creep.memory.structureTarget = closestDamagedStructure[0].id;
                    if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(closestDamagedStructure[0], {
                            reusePath: 20
                        });
                    }
                }
            }

        } else if (creep.memory.priority == 'mineralMiner') {
            var thisMineral = Game.getObjectById(creep.memory.mineralID);
            if (thisMineral.mineralAmount == 0) {
                //Nothing left to do
                creep.suicide();
            } else if (_.sum(creep.carry) >= 40) {
                //Store in terminal
                var savedTarget = Game.getObjectById(creep.memory.terminalID);
                if (savedTarget) {
                    if (creep.transfer(savedTarget, thisMineral.mineralType) == ERR_NOT_IN_RANGE) {
                        //This should never actually fire, if ideal.
                        creep.moveTo(savedTarget);
                    }
                }
            } else {
                //Mine
                var thisExtractor = Game.getObjectById(creep.memory.extractorID);
                if (thisExtractor.cooldown == 0) {
                    if (creep.harvest(thisMineral) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(thisMineral, {
                            reusePath: 20
                        });
                    }
                }
            }
        }
    }
};

module.exports = creep_work5;

function repairCompare(a, b) {
    if (a.hits < b.hits)
        return -1;
    if (a.hits > b.hits)
        return 1;
    return 0;
}<commit_msg>I swear to god<commit_after>var creep_work5 = {

    /** @param {Creep} creep **/
    run: function(creep, thisSpawn) {

        //wew lad
        /*if (!creep.room.controller.sign) {
            if(creep.pos.isNearTo(creep.room.controller)) {
                creep.signController(creep.room.controller, 'This is, by far, the most kupo room I\'ve ever seen!');
            }
        }*/

        if (creep.memory.priority == 'miner' || creep.memory.priority == 'minerNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'minerNearDeath';
                creep.memory.jobSpecific = creep.memory.jobSpecific + 'NearDeath';
            }
            //Creep will immediately harvest and store mined materials
            var storageTarget = Game.getObjectById(creep.memory.linkSource);
            var mineTarget = Game.getObjectById(creep.memory.mineSource);
            if (mineTarget && storageTarget) {
                if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(mineTarget, {
                        reusePath: 20
                    });
                } else {
                    creep.transfer(storageTarget, RESOURCE_ENERGY)
                }
            }

            /*if (_.sum(creep.carry) < 144) {
                var savedTarget = Game.getObjectById(creep.memory.mineSource);
                if (savedTarget) {
                    if (creep.harvest(savedTarget) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(savedTarget, {
                            reusePath: 20
                        });
                    } else if (creep.harvest(savedTarget, RESOURCE_ENERGY) == ERR_NOT_ENOUGH_RESOURCES && _.sum(creep.carry) > 0) {
                        //Source is dry, store what you have.
                        var savedTarget2 = Game.getObjectById(creep.memory.linkSource);
                        if (savedTarget2) {
                            if (creep.transfer(savedTarget2, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (_.sum(creep.carry) >= 144) {
                var savedTarget = Game.getObjectById(creep.memory.linkSource);
                if (savedTarget) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        //This should never actually fire, if ideal.
                        creep.moveTo(savedTarget);
                    }
                }
            }*/
        } else if (creep.memory.priority == 'upgrader' || creep.memory.priority == 'upgraderNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'upgraderNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                var linkTarget = Game.getObjectById(creep.memory.linkSource);
                if (linkTarget) {
                    if (linkTarget.energy > 0) {
                        if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(linkTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        //Get from storage instead
                        var storageTarget = Game.getObjectById(creep.memory.storageSource);
                        if (storageTarget) {
                            if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                                if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                    creep.moveTo(storageTarget, {
                                        reusePath: 20
                                    });
                                }
                            }
                        }
                    }
                } else {
                    var storageTarget = Game.getObjectById(creep.memory.storageSource);
                    if (storageTarget) {
                        if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                            if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(storageTarget, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(creep.room.controller, {
                        reusePath: 20
                    });
                }
            }
        } else if (creep.memory.priority == 'mule' || creep.memory.priority == 'muleNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'muleNearDeath';
            }
            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] > 0) {
                        //Get from container
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }

                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                var savedTarget = Game.getObjectById(creep.memory.structureTarget)

                if (savedTarget) {
                    if (creep.build(savedTarget) == ERR_INVALID_TARGET) {
                        if (savedTarget.structureType != STRUCTURE_CONTAINER && savedTarget.structureType != STRUCTURE_STORAGE && savedTarget.structureType != STRUCTURE_CONTROLLER) {
                            //Storing in spawn/extension/tower
                            if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(savedTarget, {
                                    reusePath: 20
                                });
                            }
                            if (savedTarget.energy == savedTarget.energyCapacity) {
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Upgrading controller
                            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(creep.room.controller, {
                                    reusePath: 20
                                });
                            }
                        }
                    } else {
                        if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget, {
                                reusePath: 20
                            });
                        }
                    }
                } else {
                    var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_EXTENSION ||
                                structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                        }
                    });
                    if (targets) {
                        creep.memory.structureTarget = targets.id;
                        if (creep.transfer(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(targets);
                        }
                        if (targets.energy == targets.energyCapacity) {
                            //If container fills up on this tick, forget it.
                            creep.memory.structureTarget = undefined;
                        }
                    } else {
                        targets3 = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_TOWER) && ((structure.energyCapacity - structure.energy) >= 300);
                            }
                        });
                        if (targets3) {
                            creep.memory.structureTarget = targets3.id;
                            if (creep.transfer(targets3, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets3);
                            }
                            if (targets3.energy == targets3.energyCapacity) {
                                //If container fills up on this tick, forget it.
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Store in terminal
                            terminalTarget = Game.getObjectById(creep.memory.terminalID)
                            if (terminalTarget) {
                                if (terminalTarget.store[RESOURCE_ENERGY] < 50000) {
                                    creep.memory.structureTarget = terminalTarget;
                                    if (creep.transfer(terminalTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(terminalTarget, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    terminalTarget = undefined;
                                }
                            }
                            if (!terminalTarget) {
                                //Build
                                var targets2 = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
                                if (targets2) {
                                    creep.memory.structureTarget = targets2.id;
                                    if (creep.build(targets2) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(targets2, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    //Upgrade
                                    creep.memory.structureTarget = creep.room.controller.id;
                                    if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(creep.room.controller, {
                                            reusePath: 20
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (creep.memory.priority == 'repair' || creep.memory.priority == 'repairNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'repairNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                //Get from storage
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 120) {
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else if (creep.memory.structureTarget) {
                var thisStructure = Game.getObjectById(creep.memory.structureTarget);
                if (thisStructure) {
                    if (thisStructure.hits == thisStructure.hitsMax) {
                        creep.memory.structureTarget = undefined;
                    } else {
                        if (creep.repair(thisStructure) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(thisStructure, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else {
                var closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hitsMax - structure.hits >= 200)
                });
                if (closestDamagedStructure.length > 0) {
                    closestDamagedStructure.sort(repairCompare);
                    creep.memory.structureTarget = closestDamagedStructure[0].id;
                    if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(closestDamagedStructure[0], {
                            reusePath: 20
                        });
                    }
                }
            }

        } else if (creep.memory.priority == 'mineralMiner') {
            var thisMineral = Game.getObjectById(creep.memory.mineralID);
            if (thisMineral.mineralAmount == 0) {
                //Nothing left to do
                creep.suicide();
            } else if (_.sum(creep.carry) >= 40) {
                //Store in terminal
                var savedTarget = Game.getObjectById(creep.memory.terminalID);
                if (savedTarget) {
                    if (creep.transfer(savedTarget, thisMineral.mineralType) == ERR_NOT_IN_RANGE) {
                        //This should never actually fire, if ideal.
                        creep.moveTo(savedTarget);
                    }
                }
            } else {
                //Mine
                var thisExtractor = Game.getObjectById(creep.memory.extractorID);
                if (thisExtractor.cooldown == 0) {
                    if (creep.harvest(thisMineral) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(thisMineral, {
                            reusePath: 20
                        });
                    }
                }
            }
        }
    }
};

module.exports = creep_work5;

function repairCompare(a, b) {
    if (a.hits < b.hits)
        return -1;
    if (a.hits > b.hits)
        return 1;
    return 0;
}<|endoftext|>


<commit_before>glimpse.util = (function($) {
    var connectionNotice = function(scope) {
            var that = (this === window) ? {} : this;
            that.scope = scope;
            that.text = scope.find('span');
            return that;
        };

    connectionNotice.prototype = {
        connected : false,
        prePoll : function () {
            var that = this;
            if (!that.connected) {
                that.text.text('Connecting...');
                that.scope.removeClass('gconnect').addClass('gdisconnect');
            }
        },
        complete : function (textStatus) {
            var that = this;
            if (textStatus != "success") {
                that.connected = false;
                that.text.text('Disconnected...');
                that.scope.removeClass('gconnect').addClass('gdisconnect');
            }
            else {
                that.connected = true;
                that.text.text('Connected...');
                that.scope.removeClass('gdisconnect').addClass('gconnect');
            }
        }
    };

    return {
        cookie : function (key, value, days) {
            if (arguments.length > 1) {
                value = $.isPlainObject(value) ? JSON.stringify(value) : String(value);

		        var date = new Date();
                date.setDate(date.getDate() + days || 1000);

	            document.cookie = key + "=" + encodeURIComponent(value) + "; expires=" + date.toGMTString() + "; path=/";
                return;
            }

	        key += "=";
	        var ca = document.cookie.split(';');
	        for (var i = 0; i < ca.length; i++) {
		        var c = ca[i];
		        while (c.charAt(0) == ' ')
		            c = c.substring(1, c.length);
		        if (c.indexOf(key) == 0)
		            return JSON.parse(decodeURIComponent(c.substring(key.length, c.length)));
	        }
        },
        localStorage: function (key, value) {
            if (arguments.length == 1)
                return JSON.parse(localStorage.getItem(key));
            localStorage.setItem(key, JSON.stringify(value));
        },
        htmlEncode: function (value) {
            return !(value == undefined || value == null) ? value.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>') : '';
        },
        preserveWhitespace: function (value) {
            return value.replace(/\r\n/g, '
').replace(/\n/g, '
').replace(/\t/g, '    ').replace(/  /g, '  ');
        },
        lengthJson: function (data) {
            var count = 0;
            if ($.isPlainObject(data))
                $.each(data, function (k, v) { count++; });
            return count;
        },
        uriTemplate: function (uri, data) {
            return UriTemplate.parse(uri).expand(data || {});
        },
        getDomain: function (uri) {
            if (uri.indexOf('://') > -1)
                uri = uri.split('://')[1];
            return uri.split('/')[0];
        },
        sortTabs: function (data) {
            var sorted = {},
                i, temp = [];

            for (i in data)
                temp.push({ id: i, name: data[i].name });
            temp.sort(function(a, b) {
                return a.name  b.name ? 1 : 0;
            });
            for (i = 0; i < temp.length; i++)
                sorted[temp[i].id] = data[temp[i].id];
            return sorted;
        },
        getTokens: function(formatString) {
            var count = 0, working = '', result = [];
            for (var i = 0; i < formatString.length; i++) {
                var x = formatString[i];

                if (count <= 2) {
                    if (x == '{')
                        count++;
                    else if (x == '}' && count > 0)
                        count--;
                    else if (count == 2) {
                        if (!$.isNumeric(x)) {
                            count = 0;
                            working = '';
                        }
                        else
                            working += '' + x;
                    }
                    else {
                        count = 0;
                        working = '';
                    }

                    if (count == 0 && working != '') {
                        result.push(working);
                        working = '';
                    }
                }
            }
            return result;
        },
        connectionNotice: function(scope) {
            return new connectionNotice(scope);
        },
        timeConvert : function(value) {
            if (value < 1000)
                return value + 'ms';
            return Math.round(value / 10) / 100 + 's';
        },
    };
})(jQueryGlimpse);<commit_msg>Change until function to also have space between time value and "ms"<commit_after>glimpse.util = (function($) {
    var connectionNotice = function(scope) {
            var that = (this === window) ? {} : this;
            that.scope = scope;
            that.text = scope.find('span');
            return that;
        };

    connectionNotice.prototype = {
        connected : false,
        prePoll : function () {
            var that = this;
            if (!that.connected) {
                that.text.text('Connecting...');
                that.scope.removeClass('gconnect').addClass('gdisconnect');
            }
        },
        complete : function (textStatus) {
            var that = this;
            if (textStatus != "success") {
                that.connected = false;
                that.text.text('Disconnected...');
                that.scope.removeClass('gconnect').addClass('gdisconnect');
            }
            else {
                that.connected = true;
                that.text.text('Connected...');
                that.scope.removeClass('gdisconnect').addClass('gconnect');
            }
        }
    };

    return {
        cookie : function (key, value, days) {
            if (arguments.length > 1) {
                value = $.isPlainObject(value) ? JSON.stringify(value) : String(value);

		        var date = new Date();
                date.setDate(date.getDate() + days || 1000);

	            document.cookie = key + "=" + encodeURIComponent(value) + "; expires=" + date.toGMTString() + "; path=/";
                return;
            }

	        key += "=";
	        var ca = document.cookie.split(';');
	        for (var i = 0; i < ca.length; i++) {
		        var c = ca[i];
		        while (c.charAt(0) == ' ')
		            c = c.substring(1, c.length);
		        if (c.indexOf(key) == 0)
		            return JSON.parse(decodeURIComponent(c.substring(key.length, c.length)));
	        }
        },
        localStorage: function (key, value) {
            if (arguments.length == 1)
                return JSON.parse(localStorage.getItem(key));
            localStorage.setItem(key, JSON.stringify(value));
        },
        htmlEncode: function (value) {
            return !(value == undefined || value == null) ? value.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>') : '';
        },
        preserveWhitespace: function (value) {
            return value.replace(/\r\n/g, '
').replace(/\n/g, '
').replace(/\t/g, '    ').replace(/  /g, '  ');
        },
        lengthJson: function (data) {
            var count = 0;
            if ($.isPlainObject(data))
                $.each(data, function (k, v) { count++; });
            return count;
        },
        uriTemplate: function (uri, data) {
            return UriTemplate.parse(uri).expand(data || {});
        },
        getDomain: function (uri) {
            if (uri.indexOf('://') > -1)
                uri = uri.split('://')[1];
            return uri.split('/')[0];
        },
        sortTabs: function (data) {
            var sorted = {},
                i, temp = [];

            for (i in data)
                temp.push({ id: i, name: data[i].name });
            temp.sort(function(a, b) {
                return a.name  b.name ? 1 : 0;
            });
            for (i = 0; i < temp.length; i++)
                sorted[temp[i].id] = data[temp[i].id];
            return sorted;
        },
        getTokens: function(formatString) {
            var count = 0, working = '', result = [];
            for (var i = 0; i < formatString.length; i++) {
                var x = formatString[i];

                if (count <= 2) {
                    if (x == '{')
                        count++;
                    else if (x == '}' && count > 0)
                        count--;
                    else if (count == 2) {
                        if (!$.isNumeric(x)) {
                            count = 0;
                            working = '';
                        }
                        else
                            working += '' + x;
                    }
                    else {
                        count = 0;
                        working = '';
                    }

                    if (count == 0 && working != '') {
                        result.push(working);
                        working = '';
                    }
                }
            }
            return result;
        },
        connectionNotice: function(scope) {
            return new connectionNotice(scope);
        },
        timeConvert : function(value) {
            if (value < 1000)
                return value + ' ms';
            return Math.round(value / 10) / 100 + ' s';
        },
    };
})(jQueryGlimpse);<|endoftext|>


<commit_before>import React from 'react';
import classNames from 'classnames/bind';
import {connectToStores} from 'fluxible-addons-react';
import DeckPageStore from '../../stores/DeckPageStore';
import ServiceErrorStore from '../../stores/ServiceErrorStore';
import hideLeftColumn from '../../actions/deckpagelayout/hideLeftColumn';
import restoreDeckPageLayout from '../../actions/deckpagelayout/restoreDeckPageLayout';
import TreePanel from './TreePanel/TreePanel';
import SlideEditPanel from './SlideEditPanel/SlideEditPanel';
import ContentPanel from './ContentPanel/ContentPanel';
import ContentModulesPanel from './ContentModulesPanel/ContentModulesPanel';
//import ActivityFeedPanel from './ActivityFeedPanel/ActivityFeedPanel';
import ServiceUnavailable from '../Error/ServiceUnavailable';
import InfoPanel from './InfoPanel/InfoPanel';

class Deck extends React.Component {
    handleExpandClick(){
        this.context.executeAction(hideLeftColumn, {});
        return false;
    }
    handleCollapseClick(){
        this.context.executeAction(restoreDeckPageLayout, {});
        return false;
    }
    render() {
        const error = this.props.ServiceErrorStore.error;
        let status = this.props.DeckPageStore.componentsStatus;
        let navigationPanelClass = classNames({
            'twelve': status.NavigationPanel.columnSize===12,
            'sixteen': status.NavigationPanel.columnSize===16,
            'wide column': status.NavigationPanel.visible,
            'hide-element': !status.NavigationPanel.visible
        });
        let leftColClass = classNames({
            'three':  status.TreePanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.TreePanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.TreePanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.TreePanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.TreePanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.TreePanel.visible && !status.ActivityFeedPanel.visible
        });
        let treePanelClass = classNames({
            'hide-element': !status.TreePanel.visible
        });
        let leftColClassSlideEdit = classNames({
            'three':  status.SlideEditPanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.SlideEditPanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.SlideEditPanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.SlideEditPanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.SlideEditPanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.SlideEditPanel.visible && !status.ActivityFeedPanel.visible
        });
        let SlideEditPanelClass = classNames({
            'hide-element': !status.SlideEditPanel.visible
        });
        /*
        let ActivityFeedPanelClass = classNames({
            'hide-element': !status.ActivityFeedPanel.visible
        });
        */
        let centerColClass = classNames({
            'four':  status.ContentPanel.columnSize===4 || status.ContentModulesPanel.columnSize===4,
            'ten':  status.ContentPanel.columnSize===10 || status.ContentModulesPanel.columnSize===10,
            'twelve':  status.ContentPanel.columnSize===12 || status.ContentModulesPanel.columnSize===12,
            'sixteen':  status.ContentPanel.columnSize===16 || status.ContentModulesPanel.columnSize===16,
            'wide column': status.ContentPanel.visible || status.ContentModulesPanel.visible
        });
        let contentPanelClass = classNames({
            'ten':  status.ContentPanel.columnSize===10,
            'twelve':  status.ContentPanel.columnSize===12,
            'sixteen':  status.ContentPanel.columnSize===16,
            'wide column': status.ContentPanel.visible,
            'hide-element': !status.ContentPanel.visible
        });
        let contentModulesPanelClass = classNames({
            'ten':  status.ContentModulesPanel.columnSize===10,
            'twelve':  status.ContentModulesPanel.columnSize===12,
            'sixteen':  status.ContentModulesPanel.columnSize===16,
            'wide column': status.ContentModulesPanel.visible,
            'hide-element': !status.ContentModulesPanel.visible
        });
        let rightColClass = classNames({
            'three':  status.TreePanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.TreePanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.TreePanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.TreePanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.TreePanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.TreePanel.visible && !status.ActivityFeedPanel.visible,
            'ui container': true
        });
        let oneColumnMode = 0;
        if(!status.TreePanel.visible && !status.ActivityFeedPanel.visible){
            oneColumnMode = 1;
        }
        let dividerDIV = '';
        if(oneColumnMode){
            if(status.ContentModulesPanel.visible){
                dividerDIV =

;
            }
        }else{
            dividerDIV =

;
        }
        let leftPanel;
        if(this.props.DeckPageStore.mode === 'edit' && this.props.DeckPageStore.selector.stype === 'slide' && this.props.DeckPageStore.selector.spath !== '')
        {
            //if we view a slide in edit mode - show slide edit panel
            leftPanel =

                                        <SlideEditPanel mode={this.props.DeckPageStore.mode} page={this.props.DeckPageStore.page}/>

;
        }
        else {
            //if we view something else - show decktree
            leftPanel =

                                        <TreePanel mode={this.props.DeckPageStore.mode} page={this.props.DeckPageStore.page}/>

                                    {/*

                                            <ActivityFeedPanel />

*/}

;
        }
        return (

                    {/*}

                      <NavigationPanel />

*/}

                {leftPanel}

                {dividerDIV}

                            <ContentPanel />

                                {this.props.DeckPageStore.mode !== 'view'? '' : <ContentModulesPanel mode='deck' />}

                        <InfoPanel />

                {error.hasOwnProperty('statusCode') ? <ServiceUnavailable error={this.props.ServiceErrorStore.error} /> : ''}

        );
    }
}

Deck.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
Deck = connectToStores(Deck, [DeckPageStore, ServiceErrorStore], (context, props) => {
    return {
        DeckPageStore: context.getStore(DeckPageStore).getState(),
        ServiceErrorStore: context.getStore(ServiceErrorStore).getState(),
    };
});
export default Deck;
<commit_msg>remove extra rom in old breadcrumb<commit_after>import React from 'react';
import classNames from 'classnames/bind';
import {connectToStores} from 'fluxible-addons-react';
import DeckPageStore from '../../stores/DeckPageStore';
import ServiceErrorStore from '../../stores/ServiceErrorStore';
import hideLeftColumn from '../../actions/deckpagelayout/hideLeftColumn';
import restoreDeckPageLayout from '../../actions/deckpagelayout/restoreDeckPageLayout';
import TreePanel from './TreePanel/TreePanel';
import SlideEditPanel from './SlideEditPanel/SlideEditPanel';
import ContentPanel from './ContentPanel/ContentPanel';
import ContentModulesPanel from './ContentModulesPanel/ContentModulesPanel';
//import ActivityFeedPanel from './ActivityFeedPanel/ActivityFeedPanel';
import ServiceUnavailable from '../Error/ServiceUnavailable';
import InfoPanel from './InfoPanel/InfoPanel';

class Deck extends React.Component {
    handleExpandClick(){
        this.context.executeAction(hideLeftColumn, {});
        return false;
    }
    handleCollapseClick(){
        this.context.executeAction(restoreDeckPageLayout, {});
        return false;
    }
    render() {
        const error = this.props.ServiceErrorStore.error;
        let status = this.props.DeckPageStore.componentsStatus;
        let navigationPanelClass = classNames({
            'twelve': status.NavigationPanel.columnSize===12,
            'sixteen': status.NavigationPanel.columnSize===16,
            'wide column': status.NavigationPanel.visible,
            'hide-element': !status.NavigationPanel.visible
        });
        let leftColClass = classNames({
            'three':  status.TreePanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.TreePanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.TreePanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.TreePanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.TreePanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.TreePanel.visible && !status.ActivityFeedPanel.visible
        });
        let treePanelClass = classNames({
            'hide-element': !status.TreePanel.visible
        });
        let leftColClassSlideEdit = classNames({
            'three':  status.SlideEditPanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.SlideEditPanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.SlideEditPanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.SlideEditPanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.SlideEditPanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.SlideEditPanel.visible && !status.ActivityFeedPanel.visible
        });
        let SlideEditPanelClass = classNames({
            'hide-element': !status.SlideEditPanel.visible
        });
        /*
        let ActivityFeedPanelClass = classNames({
            'hide-element': !status.ActivityFeedPanel.visible
        });
        */
        let centerColClass = classNames({
            'four':  status.ContentPanel.columnSize===4 || status.ContentModulesPanel.columnSize===4,
            'ten':  status.ContentPanel.columnSize===10 || status.ContentModulesPanel.columnSize===10,
            'twelve':  status.ContentPanel.columnSize===12 || status.ContentModulesPanel.columnSize===12,
            'sixteen':  status.ContentPanel.columnSize===16 || status.ContentModulesPanel.columnSize===16,
            'wide column': status.ContentPanel.visible || status.ContentModulesPanel.visible
        });
        let contentPanelClass = classNames({
            'ten':  status.ContentPanel.columnSize===10,
            'twelve':  status.ContentPanel.columnSize===12,
            'sixteen':  status.ContentPanel.columnSize===16,
            'wide column': status.ContentPanel.visible,
            'hide-element': !status.ContentPanel.visible
        });
        let contentModulesPanelClass = classNames({
            'ten':  status.ContentModulesPanel.columnSize===10,
            'twelve':  status.ContentModulesPanel.columnSize===12,
            'sixteen':  status.ContentModulesPanel.columnSize===16,
            'wide column': status.ContentModulesPanel.visible,
            'hide-element': !status.ContentModulesPanel.visible
        });
        let rightColClass = classNames({
            'three':  status.TreePanel.columnSize===3 || status.ActivityFeedPanel.columnSize===3,
            'four':  status.TreePanel.columnSize===4 || status.ActivityFeedPanel.columnSize===4,
            'twelve':  status.TreePanel.columnSize===12 || status.ActivityFeedPanel.columnSize===12,
            'sixteen':  status.TreePanel.columnSize===16 || status.ActivityFeedPanel.columnSize===16,
            'wide column': status.TreePanel.visible || status.ActivityFeedPanel.visible,
            'hide-element': !status.TreePanel.visible && !status.ActivityFeedPanel.visible,
            'ui container': true
        });
        let oneColumnMode = 0;
        if(!status.TreePanel.visible && !status.ActivityFeedPanel.visible){
            oneColumnMode = 1;
        }
        let dividerDIV = '';
        if(oneColumnMode){
            if(status.ContentModulesPanel.visible){
                dividerDIV =

;
            }
        }else{
            dividerDIV =

;
        }
        let leftPanel;
        if(this.props.DeckPageStore.mode === 'edit' && this.props.DeckPageStore.selector.stype === 'slide' && this.props.DeckPageStore.selector.spath !== '')
        {
            //if we view a slide in edit mode - show slide edit panel
            leftPanel =

                                        <SlideEditPanel mode={this.props.DeckPageStore.mode} page={this.props.DeckPageStore.page}/>

;
        }
        else {
            //if we view something else - show decktree
            leftPanel =

                                        <TreePanel mode={this.props.DeckPageStore.mode} page={this.props.DeckPageStore.page}/>

                                    {/*

                                            <ActivityFeedPanel />

*/}

;
        }
        return (

                {/*}

                      <NavigationPanel />

*/}

                {leftPanel}

                {dividerDIV}

                            <ContentPanel />

                                {this.props.DeckPageStore.mode !== 'view'? '' : <ContentModulesPanel mode='deck' />}

                        <InfoPanel />

                {error.hasOwnProperty('statusCode') ? <ServiceUnavailable error={this.props.ServiceErrorStore.error} /> : ''}

        );
    }
}

Deck.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
Deck = connectToStores(Deck, [DeckPageStore, ServiceErrorStore], (context, props) => {
    return {
        DeckPageStore: context.getStore(DeckPageStore).getState(),
        ServiceErrorStore: context.getStore(ServiceErrorStore).getState(),
    };
});
export default Deck;
<|endoftext|>


<commit_before>'use strict';

module.exports = class Race {
  constructor(id, VehicleType, player, NumberofPlayer, StartingPoint, RaceCheckpoint, times, weatherr, defaultvehicle, alldefaultvehicle, addingyatspawn, checkpointhash, checkpointtype, poitype, nitrobool, ghostpoi, cameraview, types) {
    this.id = id;
    this.vehicletype = VehicleType;
    this.players = player;
    this.notfinish = NumberofPlayer;
    this.startingpoint = StartingPoint;
    this.raceCheckpoint = RaceCheckpoint;
    this.time = times;
    this.weather = weatherr;
    this.defaultvehicle = defaultvehicle;
    this.alldefaultvehicle = alldefaultvehicle;
    this.AddingYatrespawn = addingyatspawn;
    this.checkpointhash = checkpointhash;
    this.ChekpointType = checkpointtype;
    this.PoiType = poitype;
    this.ghostpoi = ghostpoi;
    this.nitro = nitrobool;
    this.leaderboard = [];
    this.playersname = [];
    this.wingsuitrace = false;
    this.cameraview = cameraview;
    this.type = types;
    this.mctime = 15000; // time in seconds before changing player on mc
    this.intervalswitch = setInterval(function() {jcmp.events.Call('MCChangePlayerDrive');}, this.mctime);

  }

  Start() {
    console.log("Id of the race: " + this.id);

    if (this.type == undefined || this.type == "classic") {
      console.log("ClassicRace!!!");
      this.ClassicRace();
    } else if (this.type == "multicrew") {
      console.log("Multicrew!!!");
      this.Multicrew();
    }

  }

  broadcast(msg, color) {
    for (let player of this.players) {
      race.chat.send(player, msg, color);
    }
  }

  AddPlayerOnLeaderboard(player) {
    jcmp.events.CallRemote('Add_Player_On_Leaderboard', player, JSON.stringify(this.playersname));
  }

  UpdateEndLeaderboard(playername, leaderboardplace, minute, seconds) {
    for (let player of this.players) {
      jcmp.events.CallRemote('Update_leaderboard_all', player, playername, leaderboardplace, minute, seconds);
      // Don't update on people that have finish the race before you maybe because they are remove from the Race constructor
    }

  }

//////////////////////////////////////////////// CLASSIC RACE ///////////////////////////////////////////////////////
  ClassicRace() {
    for (var i = 0; i < this.players.length; i++) {
      const player = this.players[i];
      let rotation = new Vector3f(this.startingpoint[i].rotx, this.startingpoint[i].roty, this.startingpoint[i].rotz);
      player.race.playerrotationspawn = rotation;
      player.position = new Vector3f(this.startingpoint[i].x, this.startingpoint[i].y, this.startingpoint[i].z);
      player.rotation = new Vector3f(this.startingpoint[i].rotx, this.startingpoint[i].roty, this.startingpoint[i].rotz);
      player.respawnPosition = new Vector3f(this.startingpoint[i].x, this.startingpoint[i].y, this.startingpoint[i].z);
      player.race.game = this;
      player.race.ingame = true;
      player.dimension = this.id;
      player.race.time = 0;
      player.race.hasfinish = false;
      this.playersname.push(player.name);

      if (player.race.vehicle == 0) {
        // wingsuit race
        console.log("true wingsuit");
        this.wingsuitrace = true;
      }
      if (this.alldefaultvehicle) {
        player.race.vehicle = this.defaultvehicle;
        //jcmp.events.Call('race_player_checkpoint_respawn', player);
        setTimeout(function() {
          if (player.race.vehicle != 0) {
            const vehicle = new Vehicle(player.race.vehicle, player.position, rotation);
            vehicle.nitroEnabled = this.nitro;
            vehicle.dimension = player.race.game.id;
            vehicle.SetOccupant(0, player);

          }

        }, 4000);

      } else {
        //  jcmp.events.CallRemote('race_vehicle_choice_menu',player);
      }
      let firstcheckpoint = this.raceCheckpoint[player.race.checkpoints];
      let ghostcheckpoint = this.raceCheckpoint[player.race.checkpoints + 1];
      if (this.wingsuitrace) {
        jcmp.events.CallRemote('race_checkpoint_client', player, JSON.stringify(firstcheckpoint), this.id, this.PoiType, this.checkpointhash, this.ChekpointType, JSON.stringify(ghostcheckpoint), true);

      } else {
        jcmp.events.CallRemote('race_checkpoint_client', player, JSON.stringify(firstcheckpoint), this.id, this.PoiType, this.checkpointhash, this.ChekpointType, JSON.stringify(ghostcheckpoint));

      }

      jcmp.events.CallRemote('race_Freeze_player', player);
      jcmp.events.CallRemote('race_set_time', player, this.time.hour, this.time.minute);
      jcmp.events.CallRemote('race_set_weather', player, this.weather);
      //spawning the first checkpoint

      jcmp.events.CallRemote('Checkpoint_length_client', player, this.raceCheckpoint.length);
      jcmp.events.CallRemote('Checkpoint_current_client', player, player.race.checkpoints);
      jcmp.events.CallRemote('race_Start_client', player,this.type);
    }
  }

  CRRespawnCar(player) {
    if (player.race.vehicle != 0) {
      const vehicle = new Vehicle(player.race.vehicle, player.position, player.race.playerrotationspawn);
      vehicle.nitroEnabled = player.race.nitro;
      console.log("Vehicle spawning");
      vehicle.dimension = player.race.game.id;
      setTimeout(function() {
        vehicle.SetOccupant(0, player); // sometime the player don't go inside or vehicle is destroy to early
        //  race.game.RacePeopleDie.removePlayer(player);
        player.race.spawningdouble = false;
      }, race.game.respawntimer + 1000);
    } else {
      //Wingsuit race
    }
  }

  /////////////////////////////////// MULTICREW ////////////////////////////////////////////////////////////////////

  Multicrew() {

    for (var i = 0; i < this.players.length; i++) {
      const player = this.players[i];
      let rotation = new Vector3f(this.startingpoint[i].rotx, this.startingpoint[i].roty, this.startingpoint[i].rotz);
      player.race.playerrotationspawn = rotation;
      player.position = new Vector3f(this.startingpoint[i].x, this.startingpoint[i].y, this.startingpoint[i].z);
      player.rotation = new Vector3f(this.startingpoint[i].rotx, this.startingpoint[i].roty, this.startingpoint[i].rotz);
      player.respawnPosition = new Vector3f(this.startingpoint[i].x, this.startingpoint[i].y, this.startingpoint[i].z);
      player.race.game = this;
      player.race.ingame = true;
      player.dimension = this.id;
      player.race.time = 0;
      player.race.hasfinish = false;
      this.playersname.push(player.name);
      if (i % 2 === 0) {
        const secondplayer = this.players[i +1];
        player.race.partnerplayer.push(player);
        player.race.partnerplayer.push(secondplayer);
        secondplayer.race.partnerplayer = player.race.partnerplayer;
        jcmp.events.CallRemote('PlayerPassager',secondplayer,true);
        jcmp.events.CallRemote('PlayerPassager',player,false);
      }

      if (this.alldefaultvehicle) { // need to replace all this if to not spawn a vehicle per player but a vehicle per team
        player.race.vehicle = this.defaultvehicle;

        setTimeout(function() {
          if (player.race.vehicle != 0 && player.race.partnerplayer[0].name == player.name) {
            const vehicle = new Vehicle(player.race.vehicle, player.position, rotation);
            vehicle.nitroEnabled = this.nitro;
            vehicle.dimension = player.race.game.id;
            vehicle.SetOccupant(0, player);
            vehicle.SetOccupant(1, player.race.partnerplayer[1]);

          }

        }, 4000);
      }
      let firstcheckpoint = this.raceCheckpoint[player.race.checkpoints];
      let ghostcheckpoint = this.raceCheckpoint[player.race.checkpoints + 1];
      //TODO: Only the passager can see the checkpoint
      if(player.race.partnerplayer[1].name == player.name){
        jcmp.events.CallRemote('race_checkpoint_client', player, JSON.stringify(firstcheckpoint), this.id, this.PoiType, this.checkpointhash, this.ChekpointType, JSON.stringify(ghostcheckpoint));
      }
      jcmp.events.CallRemote('race_Freeze_player', player);
      jcmp.events.CallRemote('race_set_time', player, this.time.hour, this.time.minute);
      jcmp.events.CallRemote('race_set_weather', player, this.weather);
      //spawning the first checkpoint

      jcmp.events.CallRemote('Checkpoint_length_client', player, this.raceCheckpoint.length);
      jcmp.events.CallRemote('Checkpoint_current_client', player, player.race.checkpoints);
      jcmp.events.CallRemote('race_Start_client', player,this.type);

    }

    setInterval(function() { // Not working
    //  jcmp.events.Call('MCChangePlayerDrive');
    }, this.mctime);
  }

  MCVehicleReset(player,vehicleold) {

    if (player.race.partnerplayer[0].name == player.name) {
      if (vehicleold != undefined) {
        vehicleold.Destroy();
      }
      const vehicle = new Vehicle(player.race.vehicle, player.position, player.race.playerrotationspawn);
      vehicle.nitroEnabled = this.nitro;
      vehicle.dimension = player.race.game.id;
      vehicle.SetOccupant(0, player);
      vehicle.SetOccupant(1, player.race.partnerplayer[1]);
      return;
    }
     if (player.race.partnerplayer[1].name == player.name) {
      if(player.race.partnerplayer[0].vehicle != undefined){
        console.log("passager!!!");
        player.race.partnerplayer[0].vehicle.SetOccupant(1,player);
        return;
      }
    }
  }

///////////////////////////////// OTHER TYPE OF RACE ////////////////////////////////////////////////////

}
<commit_msg>UpdateLeaderBoard<commit_after>'use strict';

module.exports = class Race {
  constructor(id, VehicleType, player, NumberofPlayer, StartingPoint, RaceCheckpoint, times, weatherr, defaultvehicle, alldefaultvehicle, addingyatspawn, checkpointhash, checkpointtype, poitype, nitrobool, ghostpoi, cameraview, types) {
    this.id = id;
    this.vehicletype = VehicleType;
    this.players = player;
    this.notfinish = NumberofPlayer;
    this.startingpoint = StartingPoint;
    this.raceCheckpoint = RaceCheckpoint;
    this.time = times;
    this.weather = weatherr;
    this.defaultvehicle = defaultvehicle;
    this.alldefaultvehicle = alldefaultvehicle;
    this.AddingYatrespawn = addingyatspawn;
    this.checkpointhash = checkpointhash;
    this.ChekpointType = checkpointtype;
    this.PoiType = poitype;
    this.ghostpoi = ghostpoi;
    this.nitro = nitrobool;
    this.leaderboard = [];
    this.playersname = [];
    this.wingsuitrace = false;
    this.cameraview = cameraview;
    this.type = types;
    this.mctime = 15000; // time in seconds before changing player on mc
    this.intervalswitch = setInterval(function() {jcmp.events.Call('MCChangePlayerDrive');}, this.mctime);

  }

  Start() {
    console.log("Id of the race: " + this.id);

    if (this.type == undefined || this.type == "classic") {
      console.log("ClassicRace!!!");
      this.ClassicRace();
    } else if (this.type == "multicrew") {
      console.log("Multicrew!!!");
      this.Multicrew();
    }

  }

  broadcast(msg, color) {
    for (let player of this.players) {
      race.chat.send(player, msg, color);
    }
  }

  AddPlayerOnLeaderboard(player) {
    jcmp.events.CallRemote('Add_Player_On_Leaderboard', player, JSON.stringify(this.playersname));
  }

  UpdateEndLeaderboard(playername, leaderboardplace, minute, seconds) {
    for (let player of this.players) {
      jcmp.events.CallRemote('Update_leaderboard_all', player, playername, leaderboardplace, minute, seconds);
      // Don't update on people that have finish the race before you maybe because they are remove from the Race constructor
    }

  }

//////////////////////////////////////////////// CLASSIC RACE ///////////////////////////////////////////////////////
  ClassicRace() {
    for (var i = 0; i < this.players.length; i++) {
      const player = this.players[i];
      let rotation = new Vector3f(this.startingpoint[i].rotx, this.startingpoint[i].roty, this.startingpoint[i].rotz);
      player.race.playerrotationspawn = rotation;
      player.position = new Vector3f(this.startingpoint[i].x, this.startingpoint[i].y, this.startingpoint[i].z);
      player.rotation = new Vector3f(this.startingpoint[i].rotx, this.startingpoint[i].roty, this.startingpoint[i].rotz);
      player.respawnPosition = new Vector3f(this.startingpoint[i].x, this.startingpoint[i].y, this.startingpoint[i].z);
      player.race.game = this;
      player.race.ingame = true;
      player.dimension = this.id;
      player.race.time = 0;
      player.race.hasfinish = false;
      this.playersname.push(player.name);

      if (player.race.vehicle == 0) {
        // wingsuit race
        console.log("true wingsuit");
        this.wingsuitrace = true;
      }
      if (this.alldefaultvehicle) {
        player.race.vehicle = this.defaultvehicle;
        //jcmp.events.Call('race_player_checkpoint_respawn', player);
        setTimeout(function() {
          if (player.race.vehicle != 0) {
            const vehicle = new Vehicle(player.race.vehicle, player.position, rotation);
            vehicle.nitroEnabled = this.nitro;
            vehicle.dimension = player.race.game.id;
            vehicle.SetOccupant(0, player);

          }

        }, 4000);

      } else {
        //  jcmp.events.CallRemote('race_vehicle_choice_menu',player);
      }
      let firstcheckpoint = this.raceCheckpoint[player.race.checkpoints];
      let ghostcheckpoint = this.raceCheckpoint[player.race.checkpoints + 1];
      if (this.wingsuitrace) {
        jcmp.events.CallRemote('race_checkpoint_client', player, JSON.stringify(firstcheckpoint), this.id, this.PoiType, this.checkpointhash, this.ChekpointType, JSON.stringify(ghostcheckpoint), true);

      } else {
        jcmp.events.CallRemote('race_checkpoint_client', player, JSON.stringify(firstcheckpoint), this.id, this.PoiType, this.checkpointhash, this.ChekpointType, JSON.stringify(ghostcheckpoint));

      }

      jcmp.events.CallRemote('race_Freeze_player', player);
      jcmp.events.CallRemote('race_set_time', player, this.time.hour, this.time.minute);
      jcmp.events.CallRemote('race_set_weather', player, this.weather);
      //spawning the first checkpoint

      jcmp.events.CallRemote('Checkpoint_length_client', player, this.raceCheckpoint.length);
      jcmp.events.CallRemote('Checkpoint_current_client', player, player.race.checkpoints);
      jcmp.events.CallRemote('race_Start_client', player,this.type);
    }
  }

  CRRespawnCar(player) {
    if (player.race.vehicle != 0) {
      const vehicle = new Vehicle(player.race.vehicle, player.position, player.race.playerrotationspawn);
      vehicle.nitroEnabled = player.race.nitro;
      console.log("Vehicle spawning");
      vehicle.dimension = player.race.game.id;
      setTimeout(function() {
        vehicle.SetOccupant(0, player); // sometime the player don't go inside or vehicle is destroy to early
        //  race.game.RacePeopleDie.removePlayer(player);
        player.race.spawningdouble = false;
      }, race.game.respawntimer + 1000);
    } else {
      //Wingsuit race
    }
  }

  /////////////////////////////////// MULTICREW ////////////////////////////////////////////////////////////////////

  Multicrew() {

    for (var i = 0; i < this.players.length; i++) {
      const player = this.players[i];
      let rotation = new Vector3f(this.startingpoint[i].rotx, this.startingpoint[i].roty, this.startingpoint[i].rotz);
      player.race.playerrotationspawn = rotation;
      player.position = new Vector3f(this.startingpoint[i].x, this.startingpoint[i].y, this.startingpoint[i].z);
      player.rotation = new Vector3f(this.startingpoint[i].rotx, this.startingpoint[i].roty, this.startingpoint[i].rotz);
      player.respawnPosition = new Vector3f(this.startingpoint[i].x, this.startingpoint[i].y, this.startingpoint[i].z);
      player.race.game = this;
      player.race.ingame = true;
      player.dimension = this.id;
      player.race.time = 0;
      player.race.hasfinish = false;

      if (i % 2 === 0) {
        const secondplayer = this.players[i +1];
        player.race.partnerplayer.push(player);
        player.race.partnerplayer.push(secondplayer);
        secondplayer.race.partnerplayer = player.race.partnerplayer;
        jcmp.events.CallRemote('PlayerPassager',secondplayer,true);
        jcmp.events.CallRemote('PlayerPassager',player,false);
        this.playersname.push(player.name + " " + secondplayer.name);
      }

      if (this.alldefaultvehicle) { // need to replace all this if to not spawn a vehicle per player but a vehicle per team
        player.race.vehicle = this.defaultvehicle;

        setTimeout(function() {
          if (player.race.vehicle != 0 && player.race.partnerplayer[0].name == player.name) {
            const vehicle = new Vehicle(player.race.vehicle, player.position, rotation);
            vehicle.nitroEnabled = this.nitro;
            vehicle.dimension = player.race.game.id;
            vehicle.SetOccupant(0, player);
            vehicle.SetOccupant(1, player.race.partnerplayer[1]);

          }

        }, 4000);
      }
      let firstcheckpoint = this.raceCheckpoint[player.race.checkpoints];
      let ghostcheckpoint = this.raceCheckpoint[player.race.checkpoints + 1];
      //TODO: Only the passager can see the checkpoint
      if(player.race.partnerplayer[1].name == player.name){
        jcmp.events.CallRemote('race_checkpoint_client', player, JSON.stringify(firstcheckpoint), this.id, this.PoiType, this.checkpointhash, this.ChekpointType, JSON.stringify(ghostcheckpoint));
      }
      jcmp.events.CallRemote('race_Freeze_player', player);
      jcmp.events.CallRemote('race_set_time', player, this.time.hour, this.time.minute);
      jcmp.events.CallRemote('race_set_weather', player, this.weather);
      //spawning the first checkpoint

      jcmp.events.CallRemote('Checkpoint_length_client', player, this.raceCheckpoint.length);
      jcmp.events.CallRemote('Checkpoint_current_client', player, player.race.checkpoints);
      jcmp.events.CallRemote('race_Start_client', player,this.type);

    }

    setInterval(function() { // Not working
    //  jcmp.events.Call('MCChangePlayerDrive');
    }, this.mctime);
  }

  MCVehicleReset(player,vehicleold) {

    if (player.race.partnerplayer[0].name == player.name) {
      if (vehicleold != undefined) {
        vehicleold.Destroy();
      }
      const vehicle = new Vehicle(player.race.vehicle, player.position, player.race.playerrotationspawn);
      vehicle.nitroEnabled = this.nitro;
      vehicle.dimension = player.race.game.id;
      vehicle.SetOccupant(0, player);
      vehicle.SetOccupant(1, player.race.partnerplayer[1]);
      return;
    }
     if (player.race.partnerplayer[1].name == player.name) {
      if(player.race.partnerplayer[0].vehicle != undefined){
        console.log("passager!!!");
        player.race.partnerplayer[0].vehicle.SetOccupant(1,player);
        return;
      }
    }
  }

///////////////////////////////// OTHER TYPE OF RACE ////////////////////////////////////////////////////

}
<|endoftext|>


<commit_before>function ParetoFrontVisualizer (element)
{
	this.element = element;
//    google.setOnLoadCallback(loadCallback);
//        function loadCallback()
//        {
//        }
}

ParetoFrontVisualizer.prototype.draw = function(processor, args, labels)
{
	if ((args.length < 2) || args.length != labels.length)
	{
		alert("Should have exactly 2 values in each argument");
		return;
	}

    var hasThird = (args.length >= 3); // has third dimension
    var hasForth = (args.length >= 4); // has forth dimension

    var sizeTLimit = 20; // bubbles cannot be bigger than this

//    alert(args[3]);

	var instanceCount = processor.getInstanceCount();

    var data = new google.visualization.DataTable();
    data.addColumn({type:'string', label: 'PID'});
    data.addColumn({type:'number', label: labels[0], role:'domain'});
    data.addColumn({type:'number', label: labels[1], role:'data'});

    if (hasThird)
        data.addColumn({type:'number', label: labels[2], role:'data'});

    if (hasForth)
        data.addColumn({type:'number', label: labels[3], role:'data'});

    var rows = new Array();

    var maxX = 0;
    var minX = 10000000000;

    var maxY = 0;
    var minY = 10000000000;

    var maxZ = 0;
    var minZ = 10000000000;

    var maxT = 0;
    var minT = 10000000000;

    var minTSize = 12;
    var maxTSize;

    if (hasForth)
    {
        maxTSize = sizeTLimit;
    }
    else
    {
        maxTSize = minTSize;
        maxT = 0;
        minT = 0;
    }

	for (var i = 1; i <= instanceCount; i++)
	{

		var first = processor.getFeatureValue(i, args[0], true); // get only numeric
		var second = processor.getFeatureValue(i, args[1], true); // get only numeric

		point = new Array();
		point.push("V" + i);
		point.push(first);
		point.push(second);

        var delta = 1;

        if (first < minX)
            minX = first - delta;

        if (first >= maxX)
            maxX = first + delta;

        if (second < minY)
            minY = second - delta;

        if (second >= maxY)
            maxY = second + delta;

        if (hasThird)
        {
            var third = processor.getFeatureValue(i, args[2], true); // get only numeric
            point.push(third);
        }

        if (hasForth)
        {
            var forth = processor.getFeatureValue(i, args[3], true); // get only numeric

            if (forth < minT)
                minT = forth;

            if (forth >= maxT)
                maxT = forth;

//            alert(forth);
            point.push(forth);
        }

		rows.push(point);
	}

    if (hasForth){
        $("#MaxCircleLegend").text(maxT);
        $("#MinCircleLegend").text(minT);
        $("#svgcontT").show();
    } else {
        $("#svgcontT").hide();
    }

    //update goals placeholders
    for (var y = 0; y < args.length; y++){
        var maxG = 0;
        var minG = 10000000000;
        for (var i = 1; i <= instanceCount; i++){
            var test = processor.getFeatureValue(i, args[y], true);
            if (test < minG)
                minG = test;

            if (test >= maxG)
                maxG = test;
        }
        this.showGoal(labels[y], minG, maxG);
    }

    if (minY > 0)
        minY = 0;

    if (minX > 0)
        minX = 0;

    if (maxX > maxY)
        maxY = maxX;

    var chartWidth;
    var chartHeight;

    if (hasThird)
    {
        colorAxisLegendPosition = "top";
        chartTop = 26;
        chartHeight = "88%";
        chartWidth = "88%";
    }
    else
    {
        colorAxisLegendPosition = "none";
        chartTop = 10;
        chartHeight = "91%";
        chartWidth = "91%";
    }

    if ($('[name~="' + labels[2] + '"]').attr("id") == "operation_min"){
        var colorList = ['green', 'yellow', 'red'];
    } else {
        var colorList = ['red', 'yellow', 'green'];
    }

    data.addRows(rows);

	var options = {
//	  theme: 'maximized',
	  title: '',
      chartArea: {left:"20", top:chartTop, width: chartWidth, height: chartHeight},
      titleTextStyle: {color: "black", fontName: "Arial", fontSize: 12},
	  hAxis: {maxValue: maxX, minValue: minX},
	  vAxis: {maxValue: maxY, minValue: minY},
      axisTitlesPosition: 'in',
	  sizeAxis: {maxValue: maxT, maxSize: maxTSize, minValue: minT, minSize: minTSize},

//	  hAxis: {title: labels[0], viewWindowMode: "pretty"},
//	  vAxis: {title: labels[1], viewWindowMode: "pretty"},
	  animation: {duration:3000},
      colorAxis: {legend : {position : colorAxisLegendPosition}, colors: colorList},

      bubble: {textStyle: {fontSize: 12}, stroke: "black"},
//      sizeAxis: {maxSize: 12, minSize: 12},
      legend: 'bottom'
    };

	this.chart = new google.visualization.BubbleChart(document.getElementById(this.element));

    google.visualization.events.addListener(this.chart, 'select', this.myClickHandler);
    google.visualization.events.addListener(this.chart, 'onmouseover', function(data){

        $("#comparison #th0_" + (data.row+1)).css("background", "#ffffcc");

        var originalPoints = this.host.findModule("mdInput").originalPoints;
        $("#chart circle").each(function(){
            if (data.row >= originalPoints){
                if ($(this).attr("id") == null){
                    $(this).hide();
                }
            }
        });
    });
    google.visualization.events.addListener(this.chart, 'onmouseout', function(data){

        $("#comparison #th0_" + (data.row+1)).css("background", "");

        $("#chart circle").each(function(){
            if ($(this).attr("id") == null){
                $(this).attr("id", "V" + (data.row + 1) + "c");
            }
        });

        var originalPoints = this.host.findModule("mdInput").originalPoints;
        for (var i = 1; i <= ($("#chart circle").length); i++){
            if (i > originalPoints){
                $("#V" + i + "c").hide();
            }
        }
    });
    host.chart = this.chart;

	this.chart.draw(data, options);

}

ParetoFrontVisualizer.prototype.myClickHandler = function()
{
//    alert(this);
  var selection = host.chart.getSelection();
  host.chart.setSelection(null);
  var originalPoints = this.host.findModule("mdInput").originalPoints;
  var id = -1;

  for (var y = 0; y < selection.length; y++){
        $("#chart circle").each(function(){
            if (selection[y].row >= originalPoints){
                if ($(this).attr("id") == null){
                    $(this).hide()
                }
            }
        });
  }

  for (var i = 0; i < selection.length; i++)
  {
    var item = selection[i];
    if (item.row != null)
    {
        id = item.row;
    }

    if (id == -1)
        return;

    var pid = "V" + (id + 1);

    if (host.selector.isSelected(pid))
    {
        host.selector.onDeselected(pid);
    }
    else
    {
        host.selector.onSelected(pid);
    }
  }
}

ParetoFrontVisualizer.prototype.showGoal = function(goal, min, max){
    $("#"+goal+"min").attr("placeholder", min);
    $("#"+goal+"max").attr("placeholder", max);
}

<commit_msg>Added backwards highlighting to analysis<commit_after>function ParetoFrontVisualizer (element)
{
	this.element = element;
//    google.setOnLoadCallback(loadCallback);
//        function loadCallback()
//        {
//        }
}

ParetoFrontVisualizer.prototype.draw = function(processor, args, labels)
{
	if ((args.length < 2) || args.length != labels.length)
	{
		alert("Should have exactly 2 values in each argument");
		return;
	}

    var hasThird = (args.length >= 3); // has third dimension
    var hasForth = (args.length >= 4); // has forth dimension

    var sizeTLimit = 20; // bubbles cannot be bigger than this

//    alert(args[3]);

	var instanceCount = processor.getInstanceCount();

    var data = new google.visualization.DataTable();
    data.addColumn({type:'string', label: 'PID'});
    data.addColumn({type:'number', label: labels[0], role:'domain'});
    data.addColumn({type:'number', label: labels[1], role:'data'});

    if (hasThird)
        data.addColumn({type:'number', label: labels[2], role:'data'});

    if (hasForth)
        data.addColumn({type:'number', label: labels[3], role:'data'});

    var rows = new Array();

    var maxX = 0;
    var minX = 10000000000;

    var maxY = 0;
    var minY = 10000000000;

    var maxZ = 0;
    var minZ = 10000000000;

    var maxT = 0;
    var minT = 10000000000;

    var minTSize = 12;
    var maxTSize;

    if (hasForth)
    {
        maxTSize = sizeTLimit;
    }
    else
    {
        maxTSize = minTSize;
        maxT = 0;
        minT = 0;
    }

	for (var i = 1; i <= instanceCount; i++)
	{

		var first = processor.getFeatureValue(i, args[0], true); // get only numeric
		var second = processor.getFeatureValue(i, args[1], true); // get only numeric

		point = new Array();
		point.push("V" + i);
		point.push(first);
		point.push(second);

        var delta = 1;

        if (first < minX)
            minX = first - delta;

        if (first >= maxX)
            maxX = first + delta;

        if (second < minY)
            minY = second - delta;

        if (second >= maxY)
            maxY = second + delta;

        if (hasThird)
        {
            var third = processor.getFeatureValue(i, args[2], true); // get only numeric
            point.push(third);
        }

        if (hasForth)
        {
            var forth = processor.getFeatureValue(i, args[3], true); // get only numeric

            if (forth < minT)
                minT = forth;

            if (forth >= maxT)
                maxT = forth;

//            alert(forth);
            point.push(forth);
        }

		rows.push(point);
	}

    if (hasForth){
        $("#MaxCircleLegend").text(maxT);
        $("#MinCircleLegend").text(minT);
        $("#svgcontT").show();
    } else {
        $("#svgcontT").hide();
    }

    //update goals placeholders
    for (var y = 0; y < args.length; y++){
        var maxG = 0;
        var minG = 10000000000;
        for (var i = 1; i <= instanceCount; i++){
            var test = processor.getFeatureValue(i, args[y], true);
            if (test < minG)
                minG = test;

            if (test >= maxG)
                maxG = test;
        }
        this.showGoal(labels[y], minG, maxG);
    }

    if (minY > 0)
        minY = 0;

    if (minX > 0)
        minX = 0;

    if (maxX > maxY)
        maxY = maxX;

    var chartWidth;
    var chartHeight;

    if (hasThird)
    {
        colorAxisLegendPosition = "top";
        chartTop = 26;
        chartHeight = "88%";
        chartWidth = "88%";
    }
    else
    {
        colorAxisLegendPosition = "none";
        chartTop = 10;
        chartHeight = "91%";
        chartWidth = "91%";
    }

    if ($('[name~="' + labels[2] + '"]').attr("id") == "operation_min"){
        var colorList = ['green', 'yellow', 'red'];
    } else {
        var colorList = ['red', 'yellow', 'green'];
    }

    data.addRows(rows);

	var options = {
//	  theme: 'maximized',
	  title: '',
      chartArea: {left:"20", top:chartTop, width: chartWidth, height: chartHeight},
      titleTextStyle: {color: "black", fontName: "Arial", fontSize: 12},
	  hAxis: {maxValue: maxX, minValue: minX},
	  vAxis: {maxValue: maxY, minValue: minY},
      axisTitlesPosition: 'in',
	  sizeAxis: {maxValue: maxT, maxSize: maxTSize, minValue: minT, minSize: minTSize},

//	  hAxis: {title: labels[0], viewWindowMode: "pretty"},
//	  vAxis: {title: labels[1], viewWindowMode: "pretty"},
	  animation: {duration:3000},
      colorAxis: {legend : {position : colorAxisLegendPosition}, colors: colorList},

      bubble: {textStyle: {fontSize: 12}, stroke: "black"},
//      sizeAxis: {maxSize: 12, minSize: 12},
      legend: 'bottom'
    };

	this.chart = new google.visualization.BubbleChart(document.getElementById(this.element));

    google.visualization.events.addListener(this.chart, 'select', this.myClickHandler);
    google.visualization.events.addListener(this.chart, 'onmouseover', function(data){

        $("#comparison #th0_" + (data.row+1)).css("background", "#ffffcc");
        var tomodify = $("#analysis #unique th").has("text:contains('" + (data.row+1) +"')");
        var text = String((data.row+1)) + String((data.row+1)) + "--";
        tomodify.each(function(){
            var thistext = $(this).text();
            if (thistext == text)
                $(this).css("background", "#ffffcc");
        });

        var originalPoints = this.host.findModule("mdInput").originalPoints;
        $("#chart circle").each(function(){
            if (data.row >= originalPoints){
                if ($(this).attr("id") == null){
                    $(this).hide();
                }
            }
        });
    });
    google.visualization.events.addListener(this.chart, 'onmouseout', function(data){

        $("#comparison #th0_" + (data.row+1)).css("background", "");
        var tomodify = $("#analysis #unique th").has("text:contains('" + (data.row+1) +"')");
        var text = String((data.row+1)) + String((data.row+1)) + "--";
        tomodify.each(function(){
            var thistext = $(this).text();
            if (thistext == text)
                $(this).css("background", "");
        });

        $("#chart circle").each(function(){
            if ($(this).attr("id") == null){
                $(this).attr("id", "V" + (data.row + 1) + "c");
            }
        });

        var originalPoints = this.host.findModule("mdInput").originalPoints;
        for (var i = 1; i <= ($("#chart circle").length); i++){
            if (i > originalPoints){
                $("#V" + i + "c").hide();
            }
        }
    });
    host.chart = this.chart;

	this.chart.draw(data, options);

}

ParetoFrontVisualizer.prototype.myClickHandler = function()
{
//    alert(this);
  var selection = host.chart.getSelection();
  host.chart.setSelection(null);
  var originalPoints = this.host.findModule("mdInput").originalPoints;
  var id = -1;

  for (var y = 0; y < selection.length; y++){
        $("#chart circle").each(function(){
            if (selection[y].row >= originalPoints){
                if ($(this).attr("id") == null){
                    $(this).hide()
                }
            }
        });
  }

  for (var i = 0; i < selection.length; i++)
  {
    var item = selection[i];
    if (item.row != null)
    {
        id = item.row;
    }

    if (id == -1)
        return;

    var pid = "V" + (id + 1);

    if (host.selector.isSelected(pid))
    {
        host.selector.onDeselected(pid);
    }
    else
    {
        host.selector.onSelected(pid);
    }
  }
}

ParetoFrontVisualizer.prototype.showGoal = function(goal, min, max){
    $("#"+goal+"min").attr("placeholder", min);
    $("#"+goal+"max").attr("placeholder", max);
}

<|endoftext|>


<commit_before>/*
---
description: Extensions to the Function class that allow a more functional programming style
license: LGPL
authors: ['Michael Ficarra']
requires: [Core,Function,Class]
provides: [
	FunctionTools, Function._, Function.empty, Function.identity, Function.lambda,
	Function.combine, Function.compose, Function.overload, Function::wrap, Function::memoize,
	Function::partial, Function::curry, Function::not, Function::prepend, Function::append,
	Function::overload, Function::getArgs, Function::getArity, Array::toFunction, Hash::toFunction
]
... */

// class properties and globals
this._ = Function._ = function(_){
	if(!arguments.callee.caller) return;
	var args = arguments.callee.caller.arguments;
	if(_===undefined) args._ = (args._===undefined ? 0 : args._+1);
	return args[_||args._];
};

// class methods
Function.extend({

	empty: function(){},

	identity: function(_){ return _; },

	lambda: function(_){
		return function(){ return _; };
	},

	combine: function(){
		var args = Array.prototype.slice.call(arguments);
		return function(){
			var result;
			args.each(function(fn){
				result = fn.apply(this,arguments);
			});
			return result;
		};
	},

	compose: function(){
		var args = Array.prototype.slice.call(arguments);
		return function(){
			var lastReturn = Array.prototype.slice.call(arguments);
			args.reverse().each(function(fn){
				lastReturn = [fn.apply(this,lastReturn)]
			});
			return lastReturn[0];
		}
	},

	overload: function(funcTable){
		if(!funcTable || typeof funcTable === 'function'){
			var newTable = [];
			for(var i=0, l=arguments.length; i<l; i++){
				newTable[arguments[i].arity] = arguments[i];
			}
			funcTable = newTable;
		}
		return function(){
			var fn = funcTable[arguments.length];
			if(!fn || typeof fn !== 'function') return undefined;
			return fn.apply(this,arguments);
		};
	}
});

// instance methods
Function.implement({

	wrap: function(fn){
		var that = this;
		var ret = function(){
			var args = Array.prototype.slice.call(arguments);
			return fn.call(this,that.bind(this),args);
		};
		ret._origin = this;
		return ret;
	},

	memoize: function(memos){
		memos = memos || {};
		return this.wrap(function(original,args){
			var origin = this;
			while(origin._origin) origin = origin._origin;
			var key = [origin,args];
			if(memos[key] !== undefined) return memos[key];
			if(memos[args] !== undefined) return memos[args];
			return (memos[key] = original.apply(this,args));
		});
	},

	partial: function(){
		var partialArgs = Array.prototype.slice.call(arguments);
		return this.wrap(function(original,passedArgs){
			var collectedArgs = [];
			partialArgs.each(function(arg){
				collectedArgs.push([undefined,Function._].contains(arg) ? passedArgs.shift() : arg);
			});
			return original.apply(this,collectedArgs.concat(passedArgs));
		});
	},

	curry: function(){
		var curriedArgs = Array.prototype.slice.call(arguments);
		return this.wrap(function(original,passedArgs){
			return original.apply(this,curriedArgs.concat(passedArgs));
		});
	},

	not: function(){
		if(arguments.length) return this.not().apply(this,arguments);
		return this.wrap(function(fn,args){
			return !fn.apply(this,args);
		});
	},

	prepend: function(fn){
		return this.wrap(function(self,args){
			fn.apply(this,args);
			return self.apply(this,args);
		});
	},

	append: function(fn){
		return this.wrap(function(self,args){
			self.apply(this,args);
			return fn.apply(this,args);
		});
	},

	overload: function(funcTable){
		if(!funcTable || typeof funcTable === 'function') {
			var others = Array.prototype.slice.call(arguments);
			return Function.overload.apply(null,others.concat(this));
		} else {
			funcTable[this.arity] = this;
			return Function.overload(funcTable);
		}
	},

	getArgs: function(){
		var fn = this;
		while(fn._origin) fn = fn._origin;
		var args = fn.toString().match(/function\s*\S*?\((.*?)\)/)[1].split(/\s*,\s*/);
		return args.filter(function(_){ return _ !== ""; });
	},

	getArity: function(){
		return this.arity || this.getArgs().length;
	}

});

// cache arglists
(function(){
	var original = Function.prototype.getArgs;
	Function.prototype.getArgs = (function(){ return original.apply(this,arguments); }).memoize();
})();

// implement array methods
['forEach','each','every','some','filter','map','reduce','sort'].each(function(fnStr){
	var fn = function(){
		var args = Array.prototype.slice.call(arguments);
		var arr = args.shift();
		return arr[fnStr].apply(arr,[this].concat(args));
	};
	fn._origin = Array.prototype[fnStr];
	Function.implement(fnStr,fn);
});

// Array.toFunction, Hash.toFunction
(function(){
	var toFunction = function(){
		var self = this;
		return function(index){ return self[index]; };
	};
	Array.implement('toFunction',toFunction);
	if(Hash) Hash.implement('toFunction',toFunction);
})();

/* Copyright 2010 Michael Ficarra
This program is distributed under the (very open)
terms of the GNU Lesser General Public License */
<commit_msg>fixed error when first argument is accessed with _ function<commit_after>/*
---
description: Extensions to the Function class that allow a more functional programming style
license: LGPL
authors: ['Michael Ficarra']
requires: [Core,Function,Class]
provides: [
	FunctionTools, Function._, Function.empty, Function.identity, Function.lambda,
	Function.combine, Function.compose, Function.overload, Function::wrap, Function::memoize,
	Function::partial, Function::curry, Function::not, Function::prepend, Function::append,
	Function::overload, Function::getArgs, Function::getArity, Array::toFunction, Hash::toFunction
]
... */

// class properties and globals
this._ = Function._ = function(_){
	if(!arguments.callee.caller) return;
	var args = arguments.callee.caller.arguments;
	if(_===undefined) args._ = (args._===undefined ? 0 : args._+1);
	return args[_===undefined ? args._ : _];
};

// class methods
Function.extend({

	empty: function(){},

	identity: function(_){ return _; },

	lambda: function(_){
		return function(){ return _; };
	},

	combine: function(){
		var args = Array.prototype.slice.call(arguments);
		return function(){
			var result;
			args.each(function(fn){
				result = fn.apply(this,arguments);
			});
			return result;
		};
	},

	compose: function(){
		var args = Array.prototype.slice.call(arguments);
		return function(){
			var lastReturn = Array.prototype.slice.call(arguments);
			args.reverse().each(function(fn){
				lastReturn = [fn.apply(this,lastReturn)]
			});
			return lastReturn[0];
		}
	},

	overload: function(funcTable){
		if(!funcTable || typeof funcTable === 'function'){
			var newTable = [];
			for(var i=0, l=arguments.length; i<l; i++){
				newTable[arguments[i].arity] = arguments[i];
			}
			funcTable = newTable;
		}
		return function(){
			var fn = funcTable[arguments.length];
			if(!fn || typeof fn !== 'function') return undefined;
			return fn.apply(this,arguments);
		};
	}
});

// instance methods
Function.implement({

	wrap: function(fn){
		var that = this;
		var ret = function(){
			var args = Array.prototype.slice.call(arguments);
			return fn.call(this,that.bind(this),args);
		};
		ret._origin = this;
		return ret;
	},

	memoize: function(memos){
		memos = memos || {};
		return this.wrap(function(original,args){
			var origin = this;
			while(origin._origin) origin = origin._origin;
			var key = [origin,args];
			if(memos[key] !== undefined) return memos[key];
			if(memos[args] !== undefined) return memos[args];
			return (memos[key] = original.apply(this,args));
		});
	},

	partial: function(){
		var partialArgs = Array.prototype.slice.call(arguments);
		return this.wrap(function(original,passedArgs){
			var collectedArgs = [];
			partialArgs.each(function(arg){
				collectedArgs.push([undefined,Function._].contains(arg) ? passedArgs.shift() : arg);
			});
			return original.apply(this,collectedArgs.concat(passedArgs));
		});
	},

	curry: function(){
		var curriedArgs = Array.prototype.slice.call(arguments);
		return this.wrap(function(original,passedArgs){
			return original.apply(this,curriedArgs.concat(passedArgs));
		});
	},

	not: function(){
		if(arguments.length) return this.not().apply(this,arguments);
		return this.wrap(function(fn,args){
			return !fn.apply(this,args);
		});
	},

	prepend: function(fn){
		return this.wrap(function(self,args){
			fn.apply(this,args);
			return self.apply(this,args);
		});
	},

	append: function(fn){
		return this.wrap(function(self,args){
			self.apply(this,args);
			return fn.apply(this,args);
		});
	},

	overload: function(funcTable){
		if(!funcTable || typeof funcTable === 'function') {
			var others = Array.prototype.slice.call(arguments);
			return Function.overload.apply(null,others.concat(this));
		} else {
			funcTable[this.arity] = this;
			return Function.overload(funcTable);
		}
	},

	getArgs: function(){
		var fn = this;
		while(fn._origin) fn = fn._origin;
		var args = fn.toString().match(/function\s*\S*?\((.*?)\)/)[1].split(/\s*,\s*/);
		return args.filter(function(_){ return _ !== ""; });
	},

	getArity: function(){
		return this.arity || this.getArgs().length;
	}

});

// cache arglists
(function(){
	var original = Function.prototype.getArgs;
	Function.prototype.getArgs = (function(){ return original.apply(this,arguments); }).memoize();
})();

// implement array methods
['forEach','each','every','some','filter','map','reduce','sort'].each(function(fnStr){
	var fn = function(){
		var args = Array.prototype.slice.call(arguments);
		var arr = args.shift();
		return arr[fnStr].apply(arr,[this].concat(args));
	};
	fn._origin = Array.prototype[fnStr];
	Function.implement(fnStr,fn);
});

// Array.toFunction, Hash.toFunction
(function(){
	var toFunction = function(){
		var self = this;
		return function(index){ return self[index]; };
	};
	Array.implement('toFunction',toFunction);
	if(Hash) Hash.implement('toFunction',toFunction);
})();

/* Copyright 2010 Michael Ficarra
This program is distributed under the (very open)
terms of the GNU Lesser General Public License */
<|endoftext|>