<commit_before>/*
 * Dynamic Network of Speakers
 *
 * A dynamic network of Speakers
 * With MQTT
 *
 */

function include(filename) {
    if (document.querySelectorAll('[src="' + filename + '"]').length > 0 > 0) {
        return;
    }
	var head = document.getElementsByTagName('head')[0];
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	head.appendChild(script);
}

include('./gui.js');
include('./devices.js');
include('./objects.js');

DNS = (function (global) {
    /* Broker settings */
    // Check broker CONFIG
    if (CONFIG.use_broker < 1 || CONFIG.use_broker > Object.keys(CONFIG.broker).length) {
        console.log("Config error, bad USE_BROKER parameter. Using default broker instead");
        CONFIG.use_broker = 1;
    }
    var broker_mqtt = {
        url: CONFIG.broker[CONFIG.use_broker].uri,
        port: CONFIG.broker[CONFIG.use_broker].port_ws,
        client_name: ''
    };
    /* Random name generator */
    function rand(min,max) {return Math.floor(Math.random()*(max-min+1)+min);};
    var generate_name = function () {
        return CONFIG.name_website+parseInt(rand(1, 999));
    };
    broker_mqtt.client_name=generate_name(); // Set site name
    var connected = false; // Connection status
    var connect_options = {
        timeout: 3,
        onSuccess: function () {
            console.log("MQTT Connected as: "+client._getClientId());
            console.log("MQTT Connected with: "+CONFIG.broker[CONFIG.use_broker].broker);
            connected = true;
            subscribe_list();// Connection succeeded; subscribe to our topics
            DNS.send(DNS.topic("request_online"), '1');    //get initial devices
            DNS.send(DNS.topic("request_client_data"), topic("answer_site"));    //get initial devices parameters
            //update device info
        },
        onFailure: function (message) {
            connected = false;
            console.log("MQTT Connection failed: " + message.errorMessage);
        }
    };
    /* MQTT Topics (See: topic spec sheet and config file)*/
    var topic = function (topic_name) {
        var topic_root = "root";
        if(isEmpty(topic_name)){
            console.log("Topic request was empty");
            throw "Topic request was empty";
            return 0;
        }
        if(isEmpty(CONFIG.topics[topic_root])){
            console.log("The root topic: \""+topic_root+"\" was not found in the config");
            throw "The root topic: \""+topic_root+"\" was not found in the config";
            return 0;
        }
        if (topic_name == topic_root) {
            return CONFIG.topics[topic_root];
        }
        if(isEmpty(CONFIG.topics[topic_name])){
            console.log("Topic \""+topic_name+"\" was not found in the config");
            throw "Topic \""+topic_name+"\" was not found in the config";
            return 0;
        }
        return (CONFIG.topics[topic_root]+CONFIG.topics[topic_name]);
    }
    var client; // MQTT Client
    /* Init the DNS */
    var init = function () {
        welcome();      // Say hello!
        connect_MQTT(); // Connect to the broker
        GUI.init();     // initialize the GUI
        return 0;
    };
    /* stops the DNS */
    var deinit = function () {
        disconnect_MQTT();
    };
    /* Connect MQTT */
    var connect_MQTT = function () {
        if(connected) {
            console.log("Already connected");
            return;
        };
        client = new Paho.MQTT.Client(broker_mqtt.url,
                                      broker_mqtt.port,
                                      broker_mqtt.client_name);
        client.onMessageArrived = message_recieve;
        client.onConnectionLost = conn_lost_MQTT;
        client.connect(connect_options);
    };
    /* Disconnect MQTT */
    var disconnect_MQTT = function () {
        client.disconnect();
        connected = false;
    };
    /* Connection lost MQTT */
    var conn_lost_MQTT = function (responseObject) {
        console.log("connection lost: " + responseObject.errorMessage);
        /* Todo: add a reconnect system/proper disconnect */
    };
    /* Welcome message */
    var welcome = function () {
        console.log(CONFIG.name_short+" v"+
                    CONFIG.version.major+"."+
                    CONFIG.version.minor+"."+
                    CONFIG.version.revision);
    };
    /* Call when message is recieved */
    var message_recieve = function (message) {
        switch (message.destinationName) {
            case topic("online"):
                CLIENT.online(message.payloadString);
                GUI.draw_speakers_from_data();
                //console.log("Client online: "+message.payloadString);
                break;
            case topic("offline"):
                CLIENT.offline(message.payloadString);
                GUI.draw_speakers_from_data();
                //console.log("Client offline: "+message.payloadString);
                break;
            case topic("music_volume"):
                $("#volume_slider").val(message.payloadString);//set slider value
                //console.log("Volume: "+message.payloadString);
                break;
            case topic("clients_data")+'/'+broker_mqtt.client_name: // Filter own data message
                break;
            case topic("clients_data_first_object")+'/'+broker_mqtt.client_name: // Filter own data message
                break;
            case topic("music_sources"):
                var info_music_sources = JSON.parse(message.payloadString);
                console.log("Music Sources: ");console.log(info_music_sources);
                OBJECT.set_all(info_music_sources);
                GUI.draw_available_objects();
                break;
            default:
                if(message.destinationName.indexOf(topic("request"))>-1){ // Request topic
                    console.log("Request: "+message.destinationName+" | "+message.payloadString);
                    return;
                } else if(message.destinationName.indexOf(topic("answer_site"))>-1){ // Got answer
                    var device_date=message.payloadString;
                    if (!device_date) {
                        console.log("Empty device string!");
                        return;
                    }
                    try {
                        device_date=JSON.parse(device_date); // Produces a SyntaxError
                    } catch (error) {
                        console.log("Answer to object error:");
                        console.log(error.message);
                        return;
                    }
                    if (isEmpty(device_date)) {
                        console.log("Empty device data!");
                        return;
                    }
                    for (var client_name in device_date) {
                        if (!isEmpty(device_date[client_name])) { // Check if object is empty
                            CLIENT.set_objects(client_name, device_date[client_name]); // Set data of object
                            GUI.draw_speakers_from_data(); // Redraw
                        }
                    }
                    return;
                } else if (message.destinationName.indexOf(topic("clients_data")+'/')>-1) { // Got new clients data
                    var info_clients = JSON.parse(message.payloadString);
                    CLIENT.set_all(info_clients); // Set date
                    console.log(info_clients);
                    //GUI.draw_speakers_from_data(); // Redraw
                    return;
                } else if (message.destinationName.indexOf(topic("clients_data_first_object")+'/')>-1) { // Got first object pos
                    var object = JSON.parse(message.payloadString);
                    GUI.first_object_location.left = object.object_offset_left;
                    GUI.first_object_location.top = object.object_offset_top;
                    GUI.draw_speakers_from_data(); // Redraw
                    return;
                }
                console.log("Got unfiltred message from: "+message.destinationName+" | "+message.payloadString);
        }
    };
    /* Send message over MQTT */
    var send = function (topic, payload, retain = false) {
        message = new Paho.MQTT.Message(String(payload));
        message.destinationName = String(topic);
        message.retained = !!retain;
        client.send(message);
    };
    /* Send all clients data */
    var send_clients_data = function (data) {
        send(DNS.topic("clients_data")+'/'+broker_mqtt.client_name, data);
    };
    /* Send first position of first object */
    var send_first_position = function (left, top) {
        first_object = {
            object_offset_left: 0,
            object_offset_top: 0
        };
        first_object.object_offset_left = left;
        first_object.object_offset_top = top;
        send(DNS.topic("clients_data_first_object")+'/'+broker_mqtt.client_name, JSON.stringify(first_object), true);
    };
    /* Subscribe to a topic */
    var subscribe = function (topic) {
        client.subscribe(topic, {qos: 1});//qos Quality of Service
    };
    /* Unsubscribe from a topic */
    var unsubscribe = function (topic) {
        client.unsubscribe(topic, {});
    };
    /* Get the client ID */
    var clientid = function () {
        return broker.client_name;
    };
    /* Initial subscribed topics */
    var subscribe_list = function () {
        subscribe(topic("online"));
        subscribe(topic("offline"));
        subscribe(topic("music_volume"));
        subscribe(topic("music_sources"));
        subscribe(topic("clients_data")+'/+');
        subscribe(topic("clients_data_first_object")+'/+');

        subscribe(topic("answer_site")+'/#');
        //subscribe(topic("root")+'#'); // Debug for message check
    };

    return { // Bind functions to the outside world
        init                : init,
        deinit              : deinit,
        topic               : topic,
        subscribe           : subscribe,
        send                : send,
        send_clients_data   : send_clients_data,
        send_first_position : send_first_position,
        clientid            : clientid
    };
})(window);
<commit_msg>disable a debug statement<commit_after>/*
 * Dynamic Network of Speakers
 *
 * A dynamic network of Speakers
 * With MQTT
 *
 */

function include(filename) {
    if (document.querySelectorAll('[src="' + filename + '"]').length > 0 > 0) {
        return;
    }
	var head = document.getElementsByTagName('head')[0];
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	head.appendChild(script);
}

include('./gui.js');
include('./devices.js');
include('./objects.js');

DNS = (function (global) {
    /* Broker settings */
    // Check broker CONFIG
    if (CONFIG.use_broker < 1 || CONFIG.use_broker > Object.keys(CONFIG.broker).length) {
        console.log("Config error, bad USE_BROKER parameter. Using default broker instead");
        CONFIG.use_broker = 1;
    }
    var broker_mqtt = {
        url: CONFIG.broker[CONFIG.use_broker].uri,
        port: CONFIG.broker[CONFIG.use_broker].port_ws,
        client_name: ''
    };
    /* Random name generator */
    function rand(min,max) {return Math.floor(Math.random()*(max-min+1)+min);};
    var generate_name = function () {
        return CONFIG.name_website+parseInt(rand(1, 999));
    };
    broker_mqtt.client_name=generate_name(); // Set site name
    var connected = false; // Connection status
    var connect_options = {
        timeout: 3,
        onSuccess: function () {
            console.log("MQTT Connected as: "+client._getClientId());
            console.log("MQTT Connected with: "+CONFIG.broker[CONFIG.use_broker].broker);
            connected = true;
            subscribe_list();// Connection succeeded; subscribe to our topics
            DNS.send(DNS.topic("request_online"), '1');    //get initial devices
            DNS.send(DNS.topic("request_client_data"), topic("answer_site"));    //get initial devices parameters
            //update device info
        },
        onFailure: function (message) {
            connected = false;
            console.log("MQTT Connection failed: " + message.errorMessage);
        }
    };
    /* MQTT Topics (See: topic spec sheet and config file)*/
    var topic = function (topic_name) {
        var topic_root = "root";
        if(isEmpty(topic_name)){
            console.log("Topic request was empty");
            throw "Topic request was empty";
            return 0;
        }
        if(isEmpty(CONFIG.topics[topic_root])){
            console.log("The root topic: \""+topic_root+"\" was not found in the config");
            throw "The root topic: \""+topic_root+"\" was not found in the config";
            return 0;
        }
        if (topic_name == topic_root) {
            return CONFIG.topics[topic_root];
        }
        if(isEmpty(CONFIG.topics[topic_name])){
            console.log("Topic \""+topic_name+"\" was not found in the config");
            throw "Topic \""+topic_name+"\" was not found in the config";
            return 0;
        }
        return (CONFIG.topics[topic_root]+CONFIG.topics[topic_name]);
    }
    var client; // MQTT Client
    /* Init the DNS */
    var init = function () {
        welcome();      // Say hello!
        connect_MQTT(); // Connect to the broker
        GUI.init();     // initialize the GUI
        return 0;
    };
    /* stops the DNS */
    var deinit = function () {
        disconnect_MQTT();
    };
    /* Connect MQTT */
    var connect_MQTT = function () {
        if(connected) {
            console.log("Already connected");
            return;
        };
        client = new Paho.MQTT.Client(broker_mqtt.url,
                                      broker_mqtt.port,
                                      broker_mqtt.client_name);
        client.onMessageArrived = message_recieve;
        client.onConnectionLost = conn_lost_MQTT;
        client.connect(connect_options);
    };
    /* Disconnect MQTT */
    var disconnect_MQTT = function () {
        client.disconnect();
        connected = false;
    };
    /* Connection lost MQTT */
    var conn_lost_MQTT = function (responseObject) {
        console.log("connection lost: " + responseObject.errorMessage);
        /* Todo: add a reconnect system/proper disconnect */
    };
    /* Welcome message */
    var welcome = function () {
        console.log(CONFIG.name_short+" v"+
                    CONFIG.version.major+"."+
                    CONFIG.version.minor+"."+
                    CONFIG.version.revision);
    };
    /* Call when message is recieved */
    var message_recieve = function (message) {
        switch (message.destinationName) {
            case topic("online"):
                CLIENT.online(message.payloadString);
                GUI.draw_speakers_from_data();
                //console.log("Client online: "+message.payloadString);
                break;
            case topic("offline"):
                CLIENT.offline(message.payloadString);
                GUI.draw_speakers_from_data();
                //console.log("Client offline: "+message.payloadString);
                break;
            case topic("music_volume"):
                $("#volume_slider").val(message.payloadString);//set slider value
                //console.log("Volume: "+message.payloadString);
                break;
            case topic("clients_data")+'/'+broker_mqtt.client_name: // Filter own data message
                break;
            case topic("clients_data_first_object")+'/'+broker_mqtt.client_name: // Filter own data message
                break;
            case topic("music_sources"):
                var info_music_sources = JSON.parse(message.payloadString);
                console.log("Music Sources: ");console.log(info_music_sources);
                OBJECT.set_all(info_music_sources);
                GUI.draw_available_objects();
                break;
            default:
                if(message.destinationName.indexOf(topic("request"))>-1){ // Request topic
                    console.log("Request: "+message.destinationName+" | "+message.payloadString);
                    return;
                } else if(message.destinationName.indexOf(topic("answer_site"))>-1){ // Got answer
                    var device_date=message.payloadString;
                    if (!device_date) {
                        console.log("Empty device string!");
                        return;
                    }
                    try {
                        device_date=JSON.parse(device_date); // Produces a SyntaxError
                    } catch (error) {
                        console.log("Answer to object error:");
                        console.log(error.message);
                        return;
                    }
                    if (isEmpty(device_date)) {
                        console.log("Empty device data!");
                        return;
                    }
                    for (var client_name in device_date) {
                        if (!isEmpty(device_date[client_name])) { // Check if object is empty
                            CLIENT.set_objects(client_name, device_date[client_name]); // Set data of object
                            GUI.draw_speakers_from_data(); // Redraw
                        }
                    }
                    return;
                } else if (message.destinationName.indexOf(topic("clients_data")+'/')>-1) { // Got new clients data
                    var info_clients = JSON.parse(message.payloadString);
                    CLIENT.set_all(info_clients); // Set date
                    //console.log(info_clients);
                    //GUI.draw_speakers_from_data(); // Redraw
                    return;
                } else if (message.destinationName.indexOf(topic("clients_data_first_object")+'/')>-1) { // Got first object pos
                    var object = JSON.parse(message.payloadString);
                    GUI.first_object_location.left = object.object_offset_left;
                    GUI.first_object_location.top = object.object_offset_top;
                    GUI.draw_speakers_from_data(); // Redraw
                    return;
                }
                console.log("Got unfiltred message from: "+message.destinationName+" | "+message.payloadString);
        }
    };
    /* Send message over MQTT */
    var send = function (topic, payload, retain = false) {
        message = new Paho.MQTT.Message(String(payload));
        message.destinationName = String(topic);
        message.retained = !!retain;
        client.send(message);
    };
    /* Send all clients data */
    var send_clients_data = function (data) {
        send(DNS.topic("clients_data")+'/'+broker_mqtt.client_name, data);
    };
    /* Send first position of first object */
    var send_first_position = function (left, top) {
        first_object = {
            object_offset_left: 0,
            object_offset_top: 0
        };
        first_object.object_offset_left = left;
        first_object.object_offset_top = top;
        send(DNS.topic("clients_data_first_object")+'/'+broker_mqtt.client_name, JSON.stringify(first_object), true);
    };
    /* Subscribe to a topic */
    var subscribe = function (topic) {
        client.subscribe(topic, {qos: 1});//qos Quality of Service
    };
    /* Unsubscribe from a topic */
    var unsubscribe = function (topic) {
        client.unsubscribe(topic, {});
    };
    /* Get the client ID */
    var clientid = function () {
        return broker.client_name;
    };
    /* Initial subscribed topics */
    var subscribe_list = function () {
        subscribe(topic("online"));
        subscribe(topic("offline"));
        subscribe(topic("music_volume"));
        subscribe(topic("music_sources"));
        subscribe(topic("clients_data")+'/+');
        subscribe(topic("clients_data_first_object")+'/+');

        subscribe(topic("answer_site")+'/#');
        //subscribe(topic("root")+'#'); // Debug for message check
    };

    return { // Bind functions to the outside world
        init                : init,
        deinit              : deinit,
        topic               : topic,
        subscribe           : subscribe,
        send                : send,
        send_clients_data   : send_clients_data,
        send_first_position : send_first_position,
        clientid            : clientid
    };
})(window);
<|endoftext|>


<commit_before>/*
Design Basic Game Solo Challenge

This is a solo challenge

Your mission description:
Game name:
	FORAGE
Overall mission:
	To survive

Goals:
	To forage for enough food for the week
	To avoid eating poisonous plants
	To avoid starving

Characters:
	Player, Plants
Objects:
	A player with properties of name and nourishment level
	Several different plants (an array of objects) with properties of name, plants left, a fun fact, poisonous or not, availability (true or false)
Functions:
	mysteryPlant: randomly chooses a plant from an array of plant objects.  If none remain of a certain plant, that plant is removed from the array (or randomly choose until one is chosen)
	choicePoint: (modifies Player object) user chooses to eat or skip a plant.  This will result in changed nourishment level or dying of poison
	checkSurvival: evaluates whether the nourishment level has reached starving or survival and returns a statement if so.
	remainingPlants: (modifies plant object) if player chooses to eat a plant, there is one less plant.  If there's none left, availability is false.  Tells the player how many of that plant are left, if any.

Pseudocode
Create an ARRAY called "Flora" of at least 8 plant objects with their plant properties: name, number of plants left, whether its poisonous or not, whether there are any left in the forest, and a fun fact.

Create a function called "Begin" with a welcome message and instructions.
	Create a prompt equal to playerName asking for the players name and add this to a new object called "player"
	Set the player's nourishment level to base level 5.
	Create a function called "mysteryPlant".
		Randomly choose an object (plant) from the ARRAY.
		Create a function called "remaining" that alters the plant property "plantsLeft" by subtracting 1.
			IF there are no remaining individuals of this plant type, remove them from the ARRAY (and put into a new array).  If the ARRAY is empty, game is over, person starves.
		Create a function called choicePoint.
			Tell the user they have encountered a plant.  They have two options: to eat it or to skip it.
			Set a variable that prompts the user for their choice.
			Create a conditional statement:
				IF the player chooses to eat the plant AND it is poisonous:
					Tell the player what they ate, a fun fact, and that it's poisonous and they are dead. Game over.
				ELSE IF they choose to eat (and survive), raise the nourishment level 2 points.
					Adjust the number of plants of that type remaining (see function below).
					Tell the user what they ate, a fun fact,  how many of that plant remains, and their new nourishment level.
				ELSE IF they choose "skip" subtract 1 from the nourishment level.
			Check for survival: Create a checkSurvival function.
				IF nourishment level is >= 10, return a winning statement to the user. Game over.
				ELSE IF nourishment level is <=0, return a starvation statement to the user.  Game over.
			Send the user back to find another mysteryPlant.

*/
// Initial Code
//Creates an array of plants and their properties
var flora = [
{name: "poison hemlock",
plantsLeft: 3,
available: true,
poisonous: true,
funFact: "This plant is related to the carrot.  Socrates was died of this plant."},
{name: "soaproot",
plantsLeft: 3,
available: true,
poisonous: false,
funFact: "The root of this plant can be used as a brush, soap, stunning fish, or food."},
{name: "poison oak",
plantsLeft: 3,
available: true,
poisonous: true,
funFact: "Deer like to nibble on the leaves and eat the red berries.  If you eat it, it will make your throat itch and swell."},
{name: "miner's lettuce",
plantsLeft: 3,
available: true,
poisonous: false,
funFact: "The young leaves look like hearts and the older leaves are circles.  The stems, leaves, and flowers are edible."},
{name: "manzanita",
plantsLeft: 3,
available: true,
poisonous: false,
funFact:"This native CA plant is drought tolerant and makes tangy red berries."}, /*whose seeds only germinate after fire exposure.??*/
{name: "chantarelle",
available: true,
plantsLeft: 3,
poisonous: false,
funFact: "This is not a plant but a delicious fungus that likes growing under live oaks and Douglas fir."}
]

//Gives game instructions to the user and gets their name and creates an object Player
function begin(){
	alert("Welcome to FORAGE.  You are lost in the forest, don't know your plants, and need to eat.  You will encounter plants and must choose whether to eat them or to pass.  Be aware that some are poisonous and will kill you.  But if you don't eat, you will die of starvation.  If you eat enough, you will survive long enough to be found.  If your nourishment level reaches 10, you survive.  If your nourishment level reaches 0, you will die.  Your current level is 5.");
	var playerName = prompt("What is your first name?");
	var player = new Object(); //put this outside of begin?
	player.firstName = playerName;
	player.energyLevel = 5;
	var removedPlants = [];

//Randomly chooses a plant from the array and removes plants from array whose value equals 0.
	function mysteryPlant(){
		var randomPlantIndex = Math.floor(Math.random() * (flora.length)) + min;
		var randomPlant = flora[randomPlantIndex];
		if (randomPlant.plantsLeft === 0){
			removedPlants = removedPlants.push(flora.splice(randomPlantIndex, 1));
		}
	}

//Adjusts how many plants of an individual type are left. Where to put this? After eat?
function remaining(){
	randomPlant.plantsLeft = plantsLeft -1;
}

//Lets the user choose whether to eat a plant or not and evaluates their choice based on the properties of the plant.
function choicePoint(){
	var choice = prompt("You are still hungry and encountered an attractive plant.  You have two choices: eat it, or leave it.  Be careful, it could be poisonous.  Please choose 'eat' or 'leave'");
	if (choice == "eat" && randomPlant.poisonous == true){
		return ("You just ate " + randomPlant.name + ". " + randomPlant.funFact + "It is poisonous.  You are dead.  Game over.");
	else if (choice == "eat"){

	}
	}
}

//Checks if the player has reached the game-ending survival level or starvation level.

//Sends the player back to another mysteryPlant.

} //closes begin
begin()
// Refactored Code

<commit_msg>Debug up until coordinating functions with each other<commit_after>/*
Design Basic Game Solo Challenge

This is a solo challenge

Your mission description:
Game name:
	FORAGE
Overall mission:
	To survive

Goals:
	To forage for enough food for the week
	To avoid eating poisonous plants
	To avoid starving

Characters:
	Player, Plants
Objects:
	A player with properties of name and nourishment level
	Several different plants (an array of objects) with properties of name, plants left, a fun fact, poisonous or not, availability (true or false)
Functions:
	mysteryPlant: randomly chooses a plant from an array of plant objects.  If none remain of a certain plant, that plant is removed from the array (or randomly choose until one is chosen)
	choicePoint: (modifies Player object) user chooses to eat or skip a plant.  This will result in changed nourishment level or dying of poison
	checkSurvival: evaluates whether the nourishment level has reached starving or survival and returns a statement if so.
	remainingPlants: (modifies plant object) if player chooses to eat a plant, there is one less plant.  If there's none left, availability is false.  Tells the player how many of that plant are left, if any.

Pseudocode
Create an ARRAY called "Flora" of at least 8 plant objects with their plant properties: name, number of plants left, whether its poisonous or not, whether there are any left in the forest, and a fun fact.

Create a function called "Begin" with a welcome message and instructions.
	Create a prompt equal to playerName asking for the players name and add this to a new object called "player"
	Set the player's nourishment level to base level 5.
	Create a function called "mysteryPlant".
		Randomly choose an object (plant) from the ARRAY.
		Create a function called "remaining" that alters the plant property "plantsLeft" by subtracting 1.
			IF there are no remaining individuals of this plant type, remove them from the ARRAY (and put into a new array).  If the ARRAY is empty, game is over, person starves.
		Create a function called choicePoint.
			Tell the user they have encountered a plant.  They have two options: to eat it or to skip it.
			Set a variable that prompts the user for their choice.
			Create a conditional statement:
				IF the player chooses to eat the plant AND it is poisonous:
					Tell the player what they ate, a fun fact, and that it's poisonous and they are dead. Game over.
				ELSE IF they choose to eat (and survive), raise the nourishment level 2 points.
					Adjust the number of plants of that type remaining (see function below).
					Tell the user what they ate, a fun fact,  how many of that plant remains, and their new nourishment level.
				ELSE IF they choose "leave" subtract 1 from the nourishment level.
				ELSE it is not a valid entry, go back to the beginning of choicePoint.
			Check for survival: Create a checkSurvival function.
				IF nourishment level is >= 10, return a winning statement to the user. Game over.
				ELSE IF nourishment level is <=0, return a starvation statement to the user.  Game over.
			Send the user back to find another mysteryPlant.

*/
// Initial Code
//Creates an array of plants and their properties
var flora = [
{name: "poison hemlock",
plantsLeft: 3,
available: true,
poisonous: true,
funFact: "This plant is related to the carrot.  Socrates was killed by this plant."},
{name: "soaproot",
plantsLeft: 3,
available: true,
poisonous: false,
funFact: "The root of this plant can be used as a brush, soap, stunning fish, or food."},
{name: "poison oak",
plantsLeft: 3,
available: true,
poisonous: true,
funFact: "Deer like to nibble on the leaves and eat the red berries.  If you eat it, it will make your throat itch and swell."},
{name: "miner's lettuce",
plantsLeft: 3,
available: true,
poisonous: false,
funFact: "The young leaves look like hearts and the older leaves are circles.  The stems, leaves, and flowers are edible."},
{name: "manzanita",
plantsLeft: 3,
available: true,
poisonous: false,
funFact:"This native CA plant is drought tolerant and makes tangy red berries."}, /*whose seeds only germinate after fire exposure.??*/
{name: "chantarelle",
available: true,
plantsLeft: 3,
poisonous: false,
funFact: "This is not a plant but a delicious fungus that likes growing under live oaks and Douglas fir."}
]

//Gives game instructions to the user and gets their name and creates an object Player

function begin(){
	// alert("Welcome to FORAGE.  You are lost in the forest, don't know your plants, and need to eat.  You will encounter plants and must choose whether to eat them or to pass.  Be aware that some are poisonous and will kill you.  But if you don't eat, you will die of starvation.  If you eat enough, you will survive long enough to be found.  If your nourishment level reaches 10, you survive.  If your nourishment level reaches 0, you will die.  Your current level is 5.");
	// var playerName = prompt("What is your first name?");
	var player = new Object(); //put this outside of begin?
	// player.firstName = playerName;
	player.energyLevel = 5;
	var removedPlants = [];
	//Randomly chooses a plant from the array and removes plants from array whose value equals 0.
	function mysteryPlant(){
		var randomPlantIndex = Math.floor(Math.random() * (flora.length));
		var randomPlant = flora[randomPlantIndex];
		if (randomPlant.plantsLeft === 0){
			removedPlants.push((flora.splice(randomPlantIndex, 1))[0]);
		}
	// 		//put choicePoint() in here after testing.

	}//closes mysteryPlant

//Lets the user choose whether to eat a plant or not and evaluates their choice based on the properties of the plant. Put inside of mysteryPlant?
function choicePoint(){
		var choice = "eat";
		// var choice = prompt("You are still hungry and encountered an attractive plant.  You have two choices: eat it, or leave it.  Be careful, it could be poisonous.  Please choose 'eat' or 'leave'");
		if (choice === "eat" && randomPlant.poisonous == true){
			console.log("You just ate " + randomPlant.name + ". " + randomPlant.funFact + " It is poisonous.  You are dead.  Game over.");}
		else if (choice === "eat"){
			player.energyLevel += 2; console.log(player.energyLevel)
			randomPlant.plantsLeft -= 1;
			alert("You just ate " + randomPlant.name + ". " + randomPlant.funFact + " There's " + randomPlant.plantsLeft + " " +randomPlant.name + " remaining and your energy level is now " + player.energyLevel + ".");}
		else if(choice === "leave"){
			player.energyLevel -= 1;
			console.log("Say goodbye to this plant then.  Your current energy level is " + player.energyLevel + ".");
			}
		else {
			console.log("That's not one of the options.  Try again.");}
			// choicePoint();} //don't know how to loop back
		survival();
	}//closes function
	// }
//Checks if the player has reached the game-ending survival level or starvation level.

	function survival(){
		if(player.energyLevel >= 10){
			console.log ("Congratulations!  You ate enough and raised your energy level to survive the week.  You win!");
		}
		else if (player.energyLevel <= 0){
			console.log ("You are too depleted.  You starve.  You're done for. Game over.")
		}
	}

} //temporarily closes begin

begin()

// function choicePoint(){
// 	var choice = prompt("You are still hungry and encountered an attractive plant.  You have two choices: eat it, or leave it.  Be careful, it could be poisonous.  Please choose 'eat' or 'leave'");
// 	if (choice === "eat" && randomPlant.poisonous == true){
// 		return ("You just ate " + randomPlant.name + ". " + randomPlant.funFact + " It is poisonous.  You are dead.  Game over.");}
// 	else if (choice === "eat"){
// 		player.energyLevel += 2;
// 		randomPlant.plantsLeft -= 1;
// 		alert("You just ate " + randomPlant.name + ". " + randomPlant.funFact + "There's " + randomPlant.plantsLeft + " and your energy level is now " + player.energyLevel);}
// 	else if(choice === leave){
// 		player.energyLevel -= 1;
// 		alert("Say goodbye to this plant then.  Your current energy level is " + player.energyLevel);
// 		}
// 	else {
// 		alert("That's not one of the options.  Try again.");
// 		choicePoint();}
// 	survival();
// }//closes function

// //Checks if the player has reached the game-ending survival level or starvation level.

// function survival(){
// 	if(energyLevel >= 10){
// 		return ("Congratulations!  You ate enough and raised your energy level to survive the week.  You win!");
// 	}
// 	else if (energyLevel <= 0){
// 		return ("You are too depleted.  You starve.  You're done for. Game over.")
// 	}
// }

//Sends the player back to another mysteryPlant.
//mysteryPlant();

// } //closes begin

// Refactored Code

//Driver Code:
begin()

<|endoftext|>


<commit_before>/*
 * build.js: Titanium Mobile CLI build command
 *
 * Copyright (c) 2012-2013, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	fields = require('fields'),
	fs = require('fs'),
	path = require('path'),
	ti = require('titanium-sdk'),
	tiappxml = require('titanium-sdk/lib/tiappxml'),
	__ = appc.i18n(__dirname).__;

fields.setup({
	formatters: {
		error: function (err) {
			if (err instanceof Error) {
				return ('[ERROR] ' + err.message).red + '\n';
			}
			err = '' + err;
			return '\n' + (/^(\[ERROR\])/i.test(err) ? err : '[ERROR] ' + err.replace(/^Error\:/i, '').trim()).red;
		}
	},
	style: {
		accelerator: 'cyan'
	}
});

exports.cliVersion = '>=3.2';
exports.title = __('Build');
exports.desc = __('builds a project');
exports.extendedDesc = 'Builds an existing app or module project.';

exports.config = function (logger, config, cli) {
	return function (finished) {
		cli.createHook('build.config', function (callback) {
			ti.platformOptions(logger, config, cli, 'build', function (platformConf) {
				var conf = {
					flags: {
						'build-only': {
							abbr: 'b',
							desc: __('only perform the build; if true, does not install or run the app')
						},
						force: {
							abbr: 'f',
							desc: __('force a full rebuild')
						},
						legacy: {
							desc: __('build using the old Python-based builder.py')
						},
						'skip-js-minify': {
							default: false,
							desc: __('bypasses JavaScript minification; %s builds are never minified; only supported for %s and %s', 'simulator'.cyan, 'Android'.cyan, 'iOS'.cyan)
						}
					},
					options: appc.util.mix({
						platform: {
							abbr: 'p',
							callback: function (platform) {
								cli.argv.$originalPlatform = platform;
								platform = ti.resolvePlatform(platform);

								var p = platformConf[platform];
								p && p.options && Object.keys(p.options).forEach(function (name) {
									if (p.options[name].default && cli.argv[name] === undefined) {
										cli.argv[name] = p.options[name].default;
									}
								});

								return platform;
							},
							desc: __('the target build platform'),
							hint: __('platform'),
							order: 2,
							prompt: {
								label: __('Target platform'),
								error: __('Invalid platform'),
								validator: function (platform) {
									if (!platform) {
										throw new Error(__('Invalid platform'));
									} else if (ti.availablePlatforms.indexOf(platform) == -1) {
										throw new Error(__('Invalid platform: %s', platform));
									}
									return true;
								}
							},
							required: true,
							skipValueCheck: true,
							values: ti.targetPlatforms
						},
						'project-dir': {
							abbr: 'd',
							callback: function (projectDir) {
								// load the tiapp.xml
								try {
									var tiapp = cli.tiapp = new tiappxml(path.join(projectDir, 'tiapp.xml'));
								} catch (ex) {
									logger.error(ex);
									logger.log();
									process.exit(1);
								}

								// make sure the tiapp.xml is sane
								ti.validateTiappXml(logger, tiapp);

								// check that the Titanium SDK version is correct
								if (!ti.validateCorrectSDK(logger, config, cli, 'build')) {
									throw new cli.GracefulShutdown;
								}

								return projectDir;
							},
							desc: __('the directory containing the project'),
							default: process.env.SOURCE_ROOT ? path.join(process.env.SOURCE_ROOT, '..', '..') : '.',
							order: 1,
							prompt: function (callback) {
								callback(fields.file({
									promptLabel: __('Where is the __project directory__?'),
									complete: true,
									showHidden: true,
									ignoreDirs: new RegExp(config.get('cli.ignoreDirs')),
									ignoreFiles: /.*/,
									validate: conf.options['project-dir'].validate
								}));
							},
							required: true,
							validate: function (projectDir, callback) {
								var isDefault = projectDir == conf.options['project-dir'].default;

								var dir = appc.fs.resolvePath(projectDir);

								if (!fs.existsSync(dir)) {
									return callback(new Error(__('Project directory does not exist')));
								}

								var tiappFile = path.join(dir, 'tiapp.xml');

								// try to find the tiapp.xml
								while (!fs.existsSync(tiappFile)) {
									dir = path.dirname(dir);
									if (dir == '/') {
										if (!isDefault) {
											callback(new Error(__('Invalid project directory "%s" because tiapp.xml not found', projectDir)));
											return;
										} else {
											callback(true);
											return;
										}
									}
									tiappFile = path.join(dir, 'tiapp.xml');
								}

								callback(null, dir);
							}
						}
					}, ti.commonOptions(logger, config)),
					platforms: platformConf
				};
				callback(conf);
			});
		})(function (err, results, result) {
			finished(result);
		});
	};
};

exports.validate = function (logger, config, cli) {
	// TODO: set the type to 'app' for now, but we'll need to determine if the project is an app or a module
	cli.argv.type = 'app';

	ti.validatePlatform(logger, cli, 'platform');

	// since we need validate() to be async, we return a function in which the cli
	// will immediately call
	return function (finished) {
		function next(result) {
			if (result !== false) {
				// no error, load the tiapp.xml plugins
				ti.loadPlugins(logger, config, cli, cli.argv['project-dir'], function () {
					finished(result);
				});
			} else {
				finished(result);
			}
		}

		// loads the platform specific bulid command and runs its validate() function
		var result = ti.validatePlatformOptions(logger, config, cli, 'build');
		if (result && typeof result == 'function') {
			result(next);
		} else {
			next(result);
		}
	};
};

exports.run = function (logger, config, cli) {
	var buildModule = path.join(__dirname, '..', '..', ti.resolvePlatform(cli.argv.platform), 'cli', 'commands', '_build.js'),
		counter = 0;

	if (!fs.existsSync(buildModule)) {
		logger.error(__('Unable to find platform specific build command') + '\n');
		logger.log(__("Your SDK installation may be corrupt. You can reinstall it by running '%s'.", (cli.argv.$ + ' sdk update --force --default').cyan) + '\n');
		process.exit(1);
	}

	require(buildModule).run(logger, config, cli, function (err) {
		if (!counter++) {
			var delta = appc.time.prettyDiff(cli.startTime, Date.now());
			if (err) {
				logger.error(__('Project failed to build after %s', delta) + '\n');
				process.exit(1);
			} else {
				logger.info(__('Project built successfully in %s', delta.cyan) + '\n');
			}
		}
	});
};
<commit_msg>Updated help description for --legacy.<commit_after>/*
 * build.js: Titanium Mobile CLI build command
 *
 * Copyright (c) 2012-2013, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	fields = require('fields'),
	fs = require('fs'),
	path = require('path'),
	ti = require('titanium-sdk'),
	tiappxml = require('titanium-sdk/lib/tiappxml'),
	__ = appc.i18n(__dirname).__;

fields.setup({
	formatters: {
		error: function (err) {
			if (err instanceof Error) {
				return ('[ERROR] ' + err.message).red + '\n';
			}
			err = '' + err;
			return '\n' + (/^(\[ERROR\])/i.test(err) ? err : '[ERROR] ' + err.replace(/^Error\:/i, '').trim()).red;
		}
	},
	style: {
		accelerator: 'cyan'
	}
});

exports.cliVersion = '>=3.2';
exports.title = __('Build');
exports.desc = __('builds a project');
exports.extendedDesc = 'Builds an existing app or module project.';

exports.config = function (logger, config, cli) {
	return function (finished) {
		cli.createHook('build.config', function (callback) {
			ti.platformOptions(logger, config, cli, 'build', function (platformConf) {
				var conf = {
					flags: {
						'build-only': {
							abbr: 'b',
							desc: __('only perform the build; if true, does not install or run the app')
						},
						force: {
							abbr: 'f',
							desc: __('force a full rebuild')
						},
						legacy: {
							desc: __('build using the old Python-based builder.py; deprecated')
						},
						'skip-js-minify': {
							default: false,
							desc: __('bypasses JavaScript minification; %s builds are never minified; only supported for %s and %s', 'simulator'.cyan, 'Android'.cyan, 'iOS'.cyan)
						}
					},
					options: appc.util.mix({
						platform: {
							abbr: 'p',
							callback: function (platform) {
								cli.argv.$originalPlatform = platform;
								platform = ti.resolvePlatform(platform);

								var p = platformConf[platform];
								p && p.options && Object.keys(p.options).forEach(function (name) {
									if (p.options[name].default && cli.argv[name] === undefined) {
										cli.argv[name] = p.options[name].default;
									}
								});

								return platform;
							},
							desc: __('the target build platform'),
							hint: __('platform'),
							order: 2,
							prompt: {
								label: __('Target platform'),
								error: __('Invalid platform'),
								validator: function (platform) {
									if (!platform) {
										throw new Error(__('Invalid platform'));
									} else if (ti.availablePlatforms.indexOf(platform) == -1) {
										throw new Error(__('Invalid platform: %s', platform));
									}
									return true;
								}
							},
							required: true,
							skipValueCheck: true,
							values: ti.targetPlatforms
						},
						'project-dir': {
							abbr: 'd',
							callback: function (projectDir) {
								// load the tiapp.xml
								try {
									var tiapp = cli.tiapp = new tiappxml(path.join(projectDir, 'tiapp.xml'));
								} catch (ex) {
									logger.error(ex);
									logger.log();
									process.exit(1);
								}

								// make sure the tiapp.xml is sane
								ti.validateTiappXml(logger, tiapp);

								// check that the Titanium SDK version is correct
								if (!ti.validateCorrectSDK(logger, config, cli, 'build')) {
									throw new cli.GracefulShutdown;
								}

								return projectDir;
							},
							desc: __('the directory containing the project'),
							default: process.env.SOURCE_ROOT ? path.join(process.env.SOURCE_ROOT, '..', '..') : '.',
							order: 1,
							prompt: function (callback) {
								callback(fields.file({
									promptLabel: __('Where is the __project directory__?'),
									complete: true,
									showHidden: true,
									ignoreDirs: new RegExp(config.get('cli.ignoreDirs')),
									ignoreFiles: /.*/,
									validate: conf.options['project-dir'].validate
								}));
							},
							required: true,
							validate: function (projectDir, callback) {
								var isDefault = projectDir == conf.options['project-dir'].default;

								var dir = appc.fs.resolvePath(projectDir);

								if (!fs.existsSync(dir)) {
									return callback(new Error(__('Project directory does not exist')));
								}

								var tiappFile = path.join(dir, 'tiapp.xml');

								// try to find the tiapp.xml
								while (!fs.existsSync(tiappFile)) {
									dir = path.dirname(dir);
									if (dir == '/') {
										if (!isDefault) {
											callback(new Error(__('Invalid project directory "%s" because tiapp.xml not found', projectDir)));
											return;
										} else {
											callback(true);
											return;
										}
									}
									tiappFile = path.join(dir, 'tiapp.xml');
								}

								callback(null, dir);
							}
						}
					}, ti.commonOptions(logger, config)),
					platforms: platformConf
				};
				callback(conf);
			});
		})(function (err, results, result) {
			finished(result);
		});
	};
};

exports.validate = function (logger, config, cli) {
	// TODO: set the type to 'app' for now, but we'll need to determine if the project is an app or a module
	cli.argv.type = 'app';

	ti.validatePlatform(logger, cli, 'platform');

	// since we need validate() to be async, we return a function in which the cli
	// will immediately call
	return function (finished) {
		function next(result) {
			if (result !== false) {
				// no error, load the tiapp.xml plugins
				ti.loadPlugins(logger, config, cli, cli.argv['project-dir'], function () {
					finished(result);
				});
			} else {
				finished(result);
			}
		}

		// loads the platform specific bulid command and runs its validate() function
		var result = ti.validatePlatformOptions(logger, config, cli, 'build');
		if (result && typeof result == 'function') {
			result(next);
		} else {
			next(result);
		}
	};
};

exports.run = function (logger, config, cli) {
	var buildModule = path.join(__dirname, '..', '..', ti.resolvePlatform(cli.argv.platform), 'cli', 'commands', '_build.js'),
		counter = 0;

	if (!fs.existsSync(buildModule)) {
		logger.error(__('Unable to find platform specific build command') + '\n');
		logger.log(__("Your SDK installation may be corrupt. You can reinstall it by running '%s'.", (cli.argv.$ + ' sdk update --force --default').cyan) + '\n');
		process.exit(1);
	}

	require(buildModule).run(logger, config, cli, function (err) {
		if (!counter++) {
			var delta = appc.time.prettyDiff(cli.startTime, Date.now());
			if (err) {
				logger.error(__('Project failed to build after %s', delta) + '\n');
				process.exit(1);
			} else {
				logger.info(__('Project built successfully in %s', delta.cyan) + '\n');
			}
		}
	});
};
<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : barChartSpec.js
* Module : UnitTest
* Location : /test/businessTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-29   Filippo Rampado    Initial code
* =========================================================
*/

var BarChart = require('../../../lib/businessTier/graph/barChart.js');
var assert = require('assert');

var socketMock=function(){
    this.p1=null;
    this.p2=null;
    this._namespace='flow1';
    this.sendMessage=function(p1, p2){
        this.p1=p1;
        this.p2=p2;
    };
    this.attachObject=function(p1, p2){
        this.p1=p1;
        this.p2=p2;
    };
};

describe('BarChart', function() {
    it('returns 361 when there are no params', function() {
        assert.strictEqual(new BarChart().hasOwnProperty('_dataBarChart'),false);
    });

    it('returns 362 when there is no valid graphsocket in params', function() {
        assert.strictEqual(new BarChart({is: 1}, {_page: 'dssada'}, {}).hasOwnProperty('_dataBarChart'),false);
    });

    it('returns 393 when page is not valid', function() {
        assert.strictEqual(new BarChart({is: 1}, {}, {_namespace:'bababa'}).hasOwnProperty('_dataBarChart'),false);
    });

    it('returns null if it does not create a BarChartModel', function() {
        assert.strictEqual(new BarChart({is: 1}, {_page: 'dssada'}, new socketMock()).hasOwnProperty('_dataBarChart'),false);
    });

    it('returns a correct BarChart', function() {
        assert.strictEqual(new BarChart({ID: 'dada'}, {_page: 'dssada'}, new socketMock()).hasOwnProperty('_dataBarChart'),true);
    });

    describe('#getFlowByID', function() {
        it('return 262 - no ID in flows', function() {
            var mock=new socketMock();
            var barChart=new BarChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            barChart.createBarChartFlow({ ID:'flow1', name: 'grafico tempo-temperatura', indexKey: 'tempo', valueKey: 'temperatura'});
            assert.strictEqual(barChart.getFlowByID('fl1'),272);
        });
        it('return correct flow', function() {
            var mock=new socketMock();
            var barChart=new BarChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            barChart.createBarChartFlow({ ID:'flow1', name: 'grafico tempo-temperatura', indexKey: 'tempo', valueKey: 'temperatura'});
            barChart.createBarChartFlow({ ID:'flow2', name: 'grafico tempo-temperatura', indexKey: 'tempo', valueKey: 'temperatura'});
            assert.deepEqual(barChart.getFlowByID('flow2')._dataBarChart._ID, 'flow2');
        });
    });

    describe('#createBarChartFlow', function() {
        it('return 212 on creation of flow', function() {
            var mock=new socketMock();
            var barChart=new BarChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            assert.strictEqual(barChart.createBarChartFlow(),212);
        });
        it('return correct object', function() {
            var mock = new socketMock();
            var barChart=new BarChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            var bc=barChart.createBarChartFlow({ ID:'flow1', name: 'grafico tempo-temperatura', indexKey: 'tempo', valueKey: 'temperatura'});
            assert.strictEqual(bc.hasOwnProperty('_dataBarChartFlow'),true);
            assert.strictEqual(mock.p1,'insertFlow');
            assert.strictEqual(mock.p2.ID, 'flow1');
            assert.strictEqual(mock.p2.name, 'grafico tempo-temperatura');
        });
    });
});<commit_msg>fix barchart test<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : barChartSpec.js
* Module : UnitTest
* Location : /test/businessTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-29   Filippo Rampado    Initial code
* =========================================================
*/

var BarChart = require('../../../lib/businessTier/graph/barChart.js');
var assert = require('assert');

var socketMock=function(){
    this.p1=null;
    this.p2=null;
    this._namespace='flow1';
    this.sendMessage=function(p1, p2){
        this.p1=p1;
        this.p2=p2;
    };
    this.attachObject=function(p1, p2){
        this.p1=p1;
        this.p2=p2;
    };
};

describe('BarChart', function() {
    it('returns 361 when there are no params', function() {
        assert.strictEqual(new BarChart().hasOwnProperty('_dataBarChart'),false);
    });

    it('returns 362 when there is no valid graphsocket in params', function() {
        assert.strictEqual(new BarChart({is: 1}, {_page: 'dssada'}, {}).hasOwnProperty('_dataBarChart'),false);
    });

    it('returns 393 when page is not valid', function() {
        assert.strictEqual(new BarChart({is: 1}, {}, {_namespace:'bababa'}).hasOwnProperty('_dataBarChart'),false);
    });

    it('returns null if it does not create a BarChartModel', function() {
        assert.strictEqual(new BarChart({is: 1}, {_page: 'dssada'}, new socketMock()).hasOwnProperty('_dataBarChart'),false);
    });

    it('returns a correct BarChart', function() {
        assert.strictEqual(new BarChart({ID: 'dada'}, {_page: 'dssada'}, new socketMock()).hasOwnProperty('_dataBarChart'),true);
    });

    describe('#getFlowByID', function() {
        it('return 262 - no ID in flows', function() {
            var mock=new socketMock();
            var barChart=new BarChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            barChart.createBarChartFlow({ ID:'flow1', name: 'grafico tempo-temperatura', indexKey: 'tempo', valueKey: 'temperatura'});
            assert.strictEqual(barChart.getFlowByID('fl1'),262);
        });
        it('return correct flow', function() {
            var mock=new socketMock();
            var barChart=new BarChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            barChart.createBarChartFlow({ ID:'flow1', name: 'grafico tempo-temperatura', indexKey: 'tempo', valueKey: 'temperatura'});
            barChart.createBarChartFlow({ ID:'flow2', name: 'grafico tempo-temperatura', indexKey: 'tempo', valueKey: 'temperatura'});
            assert.deepEqual(barChart.getFlowByID('flow2')._dataBarChartFlow._ID, 'flow2');
        });
    });

    describe('#createBarChartFlow', function() {
        it('return 212 on creation of flow', function() {
            var mock=new socketMock();
            var barChart=new BarChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            assert.strictEqual(barChart.createBarChartFlow(),212);
        });
        it('return correct object', function() {
            var mock = new socketMock();
            var barChart=new BarChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            var bc=barChart.createBarChartFlow({ ID:'flow1', name: 'grafico tempo-temperatura', indexKey: 'tempo', valueKey: 'temperatura'});
            assert.strictEqual(bc.hasOwnProperty('_dataBarChartFlow'),true);
            assert.strictEqual(mock.p1,'insertFlow');
            assert.strictEqual(mock.p2.ID, 'flow1');
            assert.strictEqual(mock.p2.name, 'grafico tempo-temperatura');
        });
    });
});<|endoftext|>


<commit_before>var http = require('http'); // http protocol
var express = require('express'); // web server
var socketio = require('socket.io'); // websocket
var request = require('request'); // http trafficer

// web server
var app = express();
var server = http.Server(app);
var io = socketio(server);

const path = require('path');

app.get('/', function(req, res){
	res.sendFile(path.join(__dirname + '/..', '/Client/index.html'));
});

io.on('connection', function(socket){
    socket.on('chat message', function(msg){
    	console.log('message: ' + msg);
  	});
});

server.listen(3000, function(){
  	console.log('listening on *:3000');
});<commit_msg>Fix serve static<commit_after>var http = require('http'); // http protocol
var express = require('express'); // web server
var socketio = require('socket.io'); // websocket
var request = require('request'); // http trafficer

// web server
var app = express();
var server = http.Server(app);
var io = socketio(server);

const path = require('path');

app.use('/', express.static('../Client/'));

io.on('connection', function(socket){
    socket.on('chat message', function(msg){
    	console.log('message: ' + msg);
  	});
});

server.listen(3000, function(){
  	console.log('listening on *:3000');
});<|endoftext|>


<commit_before>var ota = new Date();
var mainTick = -1;
var msec_cnt = 0;
var periodicSync = -1;
var noMatterWhat = -1;

var prevSec = -1;

var tickms = 200;

/* skew timing of top of second display */
var dispFudgeMS = -50;

function updTickInter(t) {
    let newt = parseInt(t);
    if ( newt < 10 ) {
	newt = 75;
    }
    tickms = newt;
    console.log("new tick: "+newt);
    syncToTopOfSec();
}

function updFudge(f) {
    dispFudgeMS = parseInt(f);
    console.log("new timing fudge factor: "+dispFudgeMS);
    syncToTopOfSec();
}

function syncToTopOfSec() {

    let n = new Date();
    let msec = n.getMilliseconds();
    var prevTick = mainTick;

    console.log("Before fudge factor, ms is "+msec);
    dispFudgeMS = parseInt(dispFudgeMS);
    msec += dispFudgeMS;
    if ( msec < 0 ) {
	msec += 1000;
    }

    console.log("about to resync, prevTick: "+prevTick+
		", fudge: "+dispFudgeMS+
		", msec: >"+msec+"<, tickms: >"+tickms+
		"<, secs: >"+n.getSeconds());

    window.setTimeout(
	function ( pt ) {
	    if ( noMatterWhat === -1 ) {
		noMatterWhat = window.setInterval(updTime, 1000);
	    }
	    mainTick = window.setInterval(tickHandler, tickms);
	    if ( pt !== -1 ) {
		console.log("about to clear old tick: "+prevTick);
		window.clearInterval(prevTick);
	    }
	}(prevTick),
	msec);
}

/* Stating that setTimeout() and setInterval() have a resolution of
   msecs because their second argument is in terms of msecs is great,
   but on a practical level, when you go to do things like kick off
   the setInterval() as close as you can to the "top of a second,"
   things fall apart rapidly.  You find out that any sort of
   "steering" you try to do, like adding a fudge factor to get ticked
   early so that you can account for processing delays, is futile.
   You'll also have horrible jitter if you try to do it all with
   setTimeout().

   The best you can really do is tick often and do your processing
   when Date().getMilliseconds() is less or equal to some benchmark,
   such as the tick interval.  So for example, you'd like the display
   of time to be within a tenth of a second, tick every tenth of a
   second.  If the real msecs past the second is less than 100, do
   your update.  In order to lessen the load this proggy puts on the
   system, we might call Date() only around the top of second times.
   In this case, we keep a theoretical msec counter, and only do the
   actual time sampling between two times the tick interval of one
   second.  We also clamp the value at 1000 + the ticking interval
   just in case.  We also reset the theoretical msec value to zero
   after we call the update routine.

   Despite all this, which in theory should work flawlessly, there is
   still some bug, some glitch somewhere, which makes this thing miss
   one or several seconds on occasion, inexplicably.  Therefore, as a
   last-ditch defensive measure, there is an unsynchronized
   setInterval of 1000 msec established to call our updTime()
   routine.  It's kind of a kludge, but for most seconds, we'll get
   the higher accuracy display of ticking often, and as a backup, get
   an update at some quasi-random time during the second.  Try as you
   might with setTimeout(), it seems to be impossible to sync to the
   top of the second.

*/

var lastUpdMS = 0;
function tickHandler() {

    let nd;

    msec_cnt += tickms;

    // console.log("tick at "+msec_cnt);
    let presMS = 10000;
    if ( msec_cnt >= (1000 - ( tickms << 1))
		      && msec_cnt <= (1000 + (tickms << 1)) ) {
	console.log("sampling time.");
	nd = new Date();
	presMS = nd.getMilliseconds();
    }
    if ( presMS <= ( tickms << 1 ) ) {
	// console.log("present milliseconds: "+presMS);
	updTime();
	lastUpdMS = presMS;
	msec_cnt = 0;
    }
    if ( msec_cnt >= (1000 + tickms) ) {
	msec_cnt = 0;
    }

    nd = null;
}

function pasteTime(tim, where) {

    let th = tim.getHours();
    if ( th < 10 ) {
	th = "0" + th;
    }
    let tm = tim.getMinutes();
    if ( tm < 10 ) {
	tm = "0" + tm;
    }
    let ts = tim.getSeconds();
    if ( ts < 10 ) {
	ts = "0"+ts;
    }
    let ms = tim.getMilliseconds();
    if ( ms < 10 ) {
	ms = "00"+ms;
    } else if ( ms < 100 ) {
	ms = "0"+ms;
    }

    var d = document.getElementById(where);
    // console.log("I am d, value of "+d);
    d.innerHTML = th + ":" + tm + ":" + ts+"."+ms;
}

function setUpPeriodicResync() {

    if ( 0 ) {
	let n = new Date();
	let s = n.getSeconds();
	let s10 = s % 10;
	let ms = n.getMilliseconds();
	let to10 = 10 - s10;
	console.log("set up per. sync: I am at "+s+
		    ", and I want to delay "+to10+" plus "+ms+" msec.");
	window.setTimeout(
	    function () {
		console.log("periodic sync, here we go.");
		periodicSync = window.setInterval(syncToTopOfSec, 10000);
	    },
	    to10 * 1000 + ms - 800);
    }
}

function updTime() {
    let n = new Date();
    let nmsec = n.getTime();
    ota.setTime(nmsec + 40000);
    let ts = n.getSeconds();
    if ( prevSec >= 0 ) {
	if ( ( ts == 0 && (prevSec != 59 && prevSec != 0) ) ||
	     ( ts > 0 && ts > ( prevSec + 1 ) ) ) {
	    console.log("Hey! skipped! "+prevSec+":"+ts);
	}
    }
    prevSec = ts;
    pasteTime(n, "timenow");
    pasteTime(ota, "timeAtAir");

    n = null;
}

updTime();
setUpPeriodicResync();
syncToTopOfSec();
tickInt.value = tickms;
fudge.value = dispFudgeMS;
<commit_msg>Delete ShowTimer-old.js<commit_after><|endoftext|>


<commit_before>/* globals initPhotoSwipeFromDOM L10N */

const photoBooth = (function () {
    // vars
    const public = {},
        loader = $('#loader'),
        startPage = $('#start'),
        timeToLive = 90000,
        gallery = $('#gallery'),
        resultPage = $('#result'),
        webcamConstraints = {
            audio: false,
            video: {
                width: 720,
                height: 480,
                facingMode: 'user',
            }
        };

    let timeOut,
        processing = false,
        imgFilter = 'imgPlain';

    const modal = {
        open: function (selector) {
            $(selector).addClass('modal--show');
        },
        close: function (selector) {
            if ($(selector).hasClass('modal--show')) {
                $(selector).removeClass('modal--show');

                return true;
            }

            return false;
        },
        toggle: function (selector) {
            $(selector).toggleClass('modal--show');
        },
        empty: function (selector) {
            modal.close(selector);

            $(selector).find('.modal__body').empty();
        }
    };

    public.reloadPage = function () {
        window.location.reload();
    }

    // timeOut function
    public.resetTimeOut = function () {
        timeOut = setTimeout(function () {
            public.reloadPage();
        }, timeToLive);
    }

    // reset whole thing
    public.reset = function () {
        loader.removeClass('open');
        modal.empty('#qrCode');
        $('.qrbtn').removeClass('active').attr('style', '');
        $('.loading').text('');
        gallery.removeClass('gallery--open');
        gallery.find('.gallery__inner').hide();
        $('.spinner').hide();
        $('.send-mail').hide();
        public.resetMailForm();
    }

    // init
    public.init = function () {
        public.l10n();
        public.reset();

        initPhotoSwipeFromDOM('#galimages');

        startPage.show();
    }

    public.l10n = function (elem) {
        elem = $(elem || 'body');
        elem.find('[data-l10n]').each(function (i, item) {
            item = $(item);
            item.html(L10N[item.data('l10n')]);
        });
    }

    public.openNav = function () {
        $('#mySidenav').addClass('sidenav--open');
    }

    public.closeNav = function () {
        $('#mySidenav').removeClass('sidenav--open');
    }

    public.toggleNav = function () {
        $('#mySidenav').toggleClass('sidenav--open');
    }

    public.startVideo = function () {
        if (!navigator.mediaDevices) {
            return;
        }

        const getMedia = (navigator.mediaDevices.getUserMedia || navigator.mediaDevices.webkitGetUserMedia || navigator.mediaDevices.mozGetUserMedia || false);

        if(!getMedia) {
            return;
        }

        getMedia.call(navigator.mediaDevices, webcamConstraints)
            .then(function(stream) {
                $('#video').show();
                const video = $('#video').get(0);
                video.srcObject = stream;
                public.stream = stream;
            })
            .catch(function (error) {
                console.log('Could not get user media: ', error)
            });
    }

    public.stopVideo = function () {
        if (public.stream) {
            const track = public.stream.getTracks()[0];
            track.stop();
            $('#video').hide();
        }
    }

    public.thrill = function (photoStyle) {
        if (!processing) {
            public.closeNav();
            public.reset();

            if (config.previewFromCam) {
                public.startVideo();
            }

            loader.addClass('open');
            public.startCountdown(config.cntdwn_time, $('#counter'), () => {
                public.cheese(photoStyle);
            });
        }
    }

    // Cheese
    public.cheese = function (photoStyle) {
        if (config.dev) {
            console.log(photoStyle);
        }

        $('#counter').text('');

        if (photoStyle === 'photo') {
            $('.loading').text(L10N.cheese);
        } else {
            $('.loading').text(L10N.cheeseCollage);
        }

        public.takePic(photoStyle);
    }

    // take Picture
    public.takePic = function (photoStyle) {
        processing = true;

        if (config.dev) {
            console.log('Take Picture:' + photoStyle);
        }

        if (config.previewFromCam) {
            public.stopVideo();
        }

        setTimeout(function () {
            $('#counter').text('');

            if ((photoStyle == 'photo')) {
                $('.spinner').show();
                $('.loading').text(L10N.busy);
            } else {
                setTimeout(function () {
                    $('.spinner').show();
                    $('.loading').text(L10N.busyCollage);
                }, config.dev ? 0 : 7500);
            }
        }, config.cheese_time);

        const data = {
            filter: imgFilter,
            style: photoStyle,
        };

        jQuery.post('api/takePic.php', data).done(function (result) {
            if (result.error) {
                public.errorPic(result);
            } else {
                public.renderPic(result);
            }

        }).fail(function (xhr, status, result) {
            public.errorPic(result);
        });
    }

    // Show error Msg and reset
    public.errorPic = function () {
        setTimeout(function () {
            $('.spinner').hide();
            $('.loading').html(L10N.error + '' + L10N.reload + '');
        }, 1100);
    }

    // Render Picture after taking
    public.renderPic = function (result) {
        // Add QR Code Image
        const qrCodeModal = $('#qrCode');
        modal.empty(qrCodeModal);
        $('').on('load', function () {
            const body = qrCodeModal.find('.modal__body');

            $(this).appendTo(body);
            $('
').html(L10N.qrHelp).appendTo(body);
        });

        // Add Print Link
        $(document).off('click touchstart', '.printbtn');
        $(document).on('click', '.printbtn', function (e) {
            e.preventDefault();
            e.stopPropagation();

            public.printImage(result.img, () => {
                public.reloadPage();
            });
        });

        // Add Image to gallery and slider
        public.addImage(result.img);

        // Add Image
        $('').on('load', function () {
            resultPage.css({
                'background-image': 'url(' + config.folders.images + '/' + result.img + ')'
            });
            resultPage.attr('data-img', result.img);

            startPage.fadeOut(400, function () {
                resultPage.fadeIn(400, function () {
                    setTimeout(function () {
                        processing = false;
                        loader.removeClass('open');
                    }, 400);
                    setTimeout(function () {
                        $('.resultInner').addClass('show');
                    }, 400);
                    clearTimeout(timeOut);
                    public.resetTimeOut();
                });
            });
        });
    }

    // add image to Gallery
    public.addImage = function (imageName) {
        const thumbImg = new Image();
        const bigImg = new Image();
        let thumbSize = '';
        let bigSize = '';

        let imgtoLoad = 2;

        thumbImg.onload = function () {
            thumbSize = this.width + 'x' + this.height;
            if (--imgtoLoad == 0) { allLoaded(); }
        }

        bigImg.onload = function () {
            bigSize = this.width + 'x' + this.height;
            if (--imgtoLoad == 0) { allLoaded(); }
        }

        bigImg.src = config.folders.images + '/' + imageName;
        thumbImg.src = config.folders.thumbs + '/' + imageName;

        function allLoaded() {
            const linkElement = $('').html(thumbImg);

            linkElement.attr('data-size', bigSize);
            linkElement.attr('href', config.folders.images + '/' + imageName);
            linkElement.attr('data-med', config.folders.thumbs + '/' + imageName);
            linkElement.attr('data-med-size', thumbSize);

            if (config.newest_first) {
                linkElement.prependTo($('#galimages'));
            } else {
                linkElement.appendTo($('#galimages'));
            }

            $('#galimages').children().not('a').remove();
        }
    }

    // Open Gallery Overview
    public.openGallery = function () {
        if (config.scrollbar) {
            gallery.addClass('scrollbar');
        }

        gallery.addClass('gallery--open');

        setTimeout(() => gallery.find('.gallery__inner').show(), 300);
    }

    public.resetMailForm = function () {
        $('#send-mail-form').trigger('reset');
        $('#mail-form-message').html('');
    };

    // Countdown Function
    public.startCountdown = function (start, element, cb) {
        let count = 0;
        let current = start;

        function timerFunction () {
            element.text(current);
            current--;

            element.removeClass('tick');

            if (count < start) {
                window.setTimeout(() => element.addClass('tick'), 50);
                window.setTimeout(timerFunction, 1000);
            } else {
                cb();
            }
            count++;
        }
        timerFunction();
    }

    public.printImage = function(imageSrc, cb) {
        modal.open('#print_mesg');

        setTimeout(function () {
            $.ajax({
                url: 'api/print.php?filename=' + encodeURI(imageSrc),
            }).done(function (data) {
                if (config.dev) {
                    console.log(data)
                }

                setTimeout(function () {
                    modal.close('#print_mesg');
                    cb();
                }, 5000);
            });
        }, 1000);
    }

    public.toggleMailDialog = function(img) {
        const mail = $('.send-mail');

        if (mail.hasClass('mail-active')) {
            public.resetMailForm();
            mail.removeClass('mail-active').fadeOut('fast');
        } else {
            $('#mail-form-image').val(img);

            mail.addClass('mail-active').fadeIn('fast');
        }
    }

    //Filter
    $('.imageFilter').on('click', function () {
        public.toggleNav();
    });

    $('.sidenav > div').on('click', function () {
        $('.sidenav > div').removeAttr('class');

        $(this).addClass('activeSidenavBtn');

        imgFilter = $(this).attr('id');

        if (config.dev) {
            console.log('Active filter', imgFilter);
        }
    });

    // Take Picture Button
    $('.takePic, .newpic').on('click', function (e) {
        e.preventDefault();

        public.thrill('photo');
    });

    // Take Collage Button
    $('.takeCollage, .newcollage').on('click', function (e) {
        e.preventDefault();

        public.thrill('collage');
    });

    $('#mySidenav .closebtn').on('click', function (e) {
        e.preventDefault();

        public.closeNav();
    });

    // Open Gallery Button
    $('.gallery-button').on('click', function (e) {
        e.preventDefault();

        public.closeNav();
        public.openGallery($(this));
    });

    // Close Gallery Overview
    $('.gallery__close').on('click', function (e) {
        e.preventDefault();

        gallery.find('.gallery__inner').hide();
        gallery.removeClass('gallery--open');
    });

    $('.mailbtn').on('click touchstart', function (e) {
        e.preventDefault();
        e.stopPropagation();

        const img = resultPage.attr('data-img');

        public.toggleMailDialog(img);
    });

    $('#send-mail-form').on('submit', function (e) {
        e.preventDefault();

        const message = $('#mail-form-message');
        message.empty();

        const form = $(this);
        const oldValue = form.find('.btn').html();

        form.find('.btn').html('');

        $.ajax({
            url: 'api/sendPic.php',
            type: 'POST',
            data: form.serialize(),
            dataType: 'json',
            cache: false,
            success: function (result) {
                if (result.success) {
                    message.fadeIn().html('' + L10N.mailSent + '');
                } else {
                    message.fadeIn().html('' + result.error + '');
                }
            },
            error: function () {
                message.fadeIn('fast').html('' + L10N.mailError + '');
            },
            complete: function () {
                form.find('.btn').html(oldValue);
            }
        });
    });

    $('#send-mail-close').on('click', function () {
        public.resetMailForm();
        $('.send-mail').removeClass('mail-active').fadeOut('fast');
    });

    $('#result').on('click', function () {
        if (!modal.close('#qrCode')) {
            $('.resultInner').toggleClass('show');
        }
    });

    // Show QR Code
    $('.qrbtn').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        modal.toggle('#qrCode');
    });

    $('.homebtn').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        public.reloadPage();
    });

    // clear Timeout to not reset the gallery, if you clicked anywhere
    $(document).on('click', function () {
        if (!startPage.is(':visible')) {
            clearTimeout(timeOut);
            public.resetTimeOut();
        }
    });

    // Disable Right-Click
    if (!config.dev) {
        $(this).on('contextmenu', function (e) {
            e.preventDefault();
        });
    }

    return public;
})();

// Init on domready
$(function () {
    photoBooth.init();
});
<commit_msg>fix merge regression<commit_after>/* globals initPhotoSwipeFromDOM L10N */

const photoBooth = (function () {
    // vars
    const public = {},
        loader = $('#loader'),
        startPage = $('#start'),
        timeToLive = 90000,
        gallery = $('#gallery'),
        resultPage = $('#result'),
        webcamConstraints = {
            audio: false,
            video: {
                width: 720,
                height: 480,
                facingMode: 'user',
            }
        };

    let timeOut,
        processing = false,
        imgFilter = 'imgPlain';

    const modal = {
        open: function (selector) {
            $(selector).addClass('modal--show');
        },
        close: function (selector) {
            if ($(selector).hasClass('modal--show')) {
                $(selector).removeClass('modal--show');

                return true;
            }

            return false;
        },
        toggle: function (selector) {
            $(selector).toggleClass('modal--show');
        },
        empty: function (selector) {
            modal.close(selector);

            $(selector).find('.modal__body').empty();
        }
    };

    public.reloadPage = function () {
        window.location.reload();
    }

    // timeOut function
    public.resetTimeOut = function () {
        timeOut = setTimeout(function () {
            public.reloadPage();
        }, timeToLive);
    }

    // reset whole thing
    public.reset = function () {
        loader.removeClass('open');
        modal.empty('#qrCode');
        $('.qrbtn').removeClass('active').attr('style', '');
        $('.loading').text('');
        gallery.removeClass('gallery--open');
        gallery.find('.gallery__inner').hide();
        $('.spinner').hide();
        $('.send-mail').hide();
        public.resetMailForm();
    }

    // init
    public.init = function () {
        public.l10n();
        public.reset();

        initPhotoSwipeFromDOM('#galimages');

        startPage.addClass('open');
    }

    public.l10n = function (elem) {
        elem = $(elem || 'body');
        elem.find('[data-l10n]').each(function (i, item) {
            item = $(item);
            item.html(L10N[item.data('l10n')]);
        });
    }

    public.openNav = function () {
        $('#mySidenav').addClass('sidenav--open');
    }

    public.closeNav = function () {
        $('#mySidenav').removeClass('sidenav--open');
    }

    public.toggleNav = function () {
        $('#mySidenav').toggleClass('sidenav--open');
    }

    public.startVideo = function () {
        if (!navigator.mediaDevices) {
            return;
        }

        const getMedia = (navigator.mediaDevices.getUserMedia || navigator.mediaDevices.webkitGetUserMedia || navigator.mediaDevices.mozGetUserMedia || false);

        if(!getMedia) {
            return;
        }

        getMedia.call(navigator.mediaDevices, webcamConstraints)
            .then(function(stream) {
                $('#video').show();
                const video = $('#video').get(0);
                video.srcObject = stream;
                public.stream = stream;
            })
            .catch(function (error) {
                console.log('Could not get user media: ', error)
            });
    }

    public.stopVideo = function () {
        if (public.stream) {
            const track = public.stream.getTracks()[0];
            track.stop();
            $('#video').hide();
        }
    }

    public.thrill = function (photoStyle) {
        if (!processing) {
            public.closeNav();
            public.reset();

            if (config.previewFromCam) {
                public.startVideo();
            }

            loader.addClass('open');
            public.startCountdown(config.cntdwn_time, $('#counter'), () => {
                public.cheese(photoStyle);
            });
        }
    }

    // Cheese
    public.cheese = function (photoStyle) {
        if (config.dev) {
            console.log(photoStyle);
        }

        $('#counter').text('');

        if (photoStyle === 'photo') {
            $('.loading').text(L10N.cheese);
        } else {
            $('.loading').text(L10N.cheeseCollage);
        }

        public.takePic(photoStyle);
    }

    // take Picture
    public.takePic = function (photoStyle) {
        processing = true;

        if (config.dev) {
            console.log('Take Picture:' + photoStyle);
        }

        if (config.previewFromCam) {
            public.stopVideo();
        }

        setTimeout(function () {
            $('#counter').text('');

            if ((photoStyle == 'photo')) {
                $('.spinner').show();
                $('.loading').text(L10N.busy);
            } else {
                setTimeout(function () {
                    $('.spinner').show();
                    $('.loading').text(L10N.busyCollage);
                }, config.dev ? 0 : 7500);
            }
        }, config.cheese_time);

        const data = {
            filter: imgFilter,
            style: photoStyle,
        };

        jQuery.post('api/takePic.php', data).done(function (result) {
            if (result.error) {
                public.errorPic(result);
            } else {
                public.renderPic(result);
            }

        }).fail(function (xhr, status, result) {
            public.errorPic(result);
        });
    }

    // Show error Msg and reset
    public.errorPic = function () {
        setTimeout(function () {
            $('.spinner').hide();
            $('.loading').html(L10N.error + '' + L10N.reload + '');
        }, 1100);
    }

    // Render Picture after taking
    public.renderPic = function (result) {
        // Add QR Code Image
        const qrCodeModal = $('#qrCode');
        modal.empty(qrCodeModal);
        $('').on('load', function () {
            const body = qrCodeModal.find('.modal__body');

            $(this).appendTo(body);
            $('
').html(L10N.qrHelp).appendTo(body);
        });

        // Add Print Link
        $(document).off('click touchstart', '.printbtn');
        $(document).on('click', '.printbtn', function (e) {
            e.preventDefault();
            e.stopPropagation();

            public.printImage(result.img, () => {
                public.reloadPage();
            });
        });

        // Add Image to gallery and slider
        public.addImage(result.img);

        // Add Image
        $('').on('load', function () {
            resultPage.css({
                'background-image': 'url(' + config.folders.images + '/' + result.img + ')'
            });
            resultPage.attr('data-img', result.img);

            startPage.fadeOut(400, function () {
                resultPage.fadeIn(400, function () {
                    setTimeout(function () {
                        processing = false;
                        loader.removeClass('open');
                    }, 400);
                    setTimeout(function () {
                        $('.resultInner').addClass('show');
                    }, 400);
                    clearTimeout(timeOut);
                    public.resetTimeOut();
                });
            });
        });
    }

    // add image to Gallery
    public.addImage = function (imageName) {
        const thumbImg = new Image();
        const bigImg = new Image();
        let thumbSize = '';
        let bigSize = '';

        let imgtoLoad = 2;

        thumbImg.onload = function () {
            thumbSize = this.width + 'x' + this.height;
            if (--imgtoLoad == 0) { allLoaded(); }
        }

        bigImg.onload = function () {
            bigSize = this.width + 'x' + this.height;
            if (--imgtoLoad == 0) { allLoaded(); }
        }

        bigImg.src = config.folders.images + '/' + imageName;
        thumbImg.src = config.folders.thumbs + '/' + imageName;

        function allLoaded() {
            const linkElement = $('').html(thumbImg);

            linkElement.attr('data-size', bigSize);
            linkElement.attr('href', config.folders.images + '/' + imageName);
            linkElement.attr('data-med', config.folders.thumbs + '/' + imageName);
            linkElement.attr('data-med-size', thumbSize);

            if (config.newest_first) {
                linkElement.prependTo($('#galimages'));
            } else {
                linkElement.appendTo($('#galimages'));
            }

            $('#galimages').children().not('a').remove();
        }
    }

    // Open Gallery Overview
    public.openGallery = function () {
        if (config.scrollbar) {
            gallery.addClass('scrollbar');
        }

        gallery.addClass('gallery--open');

        setTimeout(() => gallery.find('.gallery__inner').show(), 300);
    }

    public.resetMailForm = function () {
        $('#send-mail-form').trigger('reset');
        $('#mail-form-message').html('');
    };

    // Countdown Function
    public.startCountdown = function (start, element, cb) {
        let count = 0;
        let current = start;

        function timerFunction () {
            element.text(current);
            current--;

            element.removeClass('tick');

            if (count < start) {
                window.setTimeout(() => element.addClass('tick'), 50);
                window.setTimeout(timerFunction, 1000);
            } else {
                cb();
            }
            count++;
        }
        timerFunction();
    }

    public.printImage = function(imageSrc, cb) {
        modal.open('#print_mesg');

        setTimeout(function () {
            $.ajax({
                url: 'api/print.php?filename=' + encodeURI(imageSrc),
            }).done(function (data) {
                if (config.dev) {
                    console.log(data)
                }

                setTimeout(function () {
                    modal.close('#print_mesg');
                    cb();
                }, 5000);
            });
        }, 1000);
    }

    public.toggleMailDialog = function(img) {
        const mail = $('.send-mail');

        if (mail.hasClass('mail-active')) {
            public.resetMailForm();
            mail.removeClass('mail-active').fadeOut('fast');
        } else {
            $('#mail-form-image').val(img);

            mail.addClass('mail-active').fadeIn('fast');
        }
    }

    //Filter
    $('.imageFilter').on('click', function () {
        public.toggleNav();
    });

    $('.sidenav > div').on('click', function () {
        $('.sidenav > div').removeAttr('class');

        $(this).addClass('activeSidenavBtn');

        imgFilter = $(this).attr('id');

        if (config.dev) {
            console.log('Active filter', imgFilter);
        }
    });

    // Take Picture Button
    $('.takePic, .newpic').on('click', function (e) {
        e.preventDefault();

        public.thrill('photo');
    });

    // Take Collage Button
    $('.takeCollage, .newcollage').on('click', function (e) {
        e.preventDefault();

        public.thrill('collage');
    });

    $('#mySidenav .closebtn').on('click', function (e) {
        e.preventDefault();

        public.closeNav();
    });

    // Open Gallery Button
    $('.gallery-button').on('click', function (e) {
        e.preventDefault();

        public.closeNav();
        public.openGallery($(this));
    });

    // Close Gallery Overview
    $('.gallery__close').on('click', function (e) {
        e.preventDefault();

        gallery.find('.gallery__inner').hide();
        gallery.removeClass('gallery--open');
    });

    $('.mailbtn').on('click touchstart', function (e) {
        e.preventDefault();
        e.stopPropagation();

        const img = resultPage.attr('data-img');

        public.toggleMailDialog(img);
    });

    $('#send-mail-form').on('submit', function (e) {
        e.preventDefault();

        const message = $('#mail-form-message');
        message.empty();

        const form = $(this);
        const oldValue = form.find('.btn').html();

        form.find('.btn').html('');

        $.ajax({
            url: 'api/sendPic.php',
            type: 'POST',
            data: form.serialize(),
            dataType: 'json',
            cache: false,
            success: function (result) {
                if (result.success) {
                    message.fadeIn().html('' + L10N.mailSent + '');
                } else {
                    message.fadeIn().html('' + result.error + '');
                }
            },
            error: function () {
                message.fadeIn('fast').html('' + L10N.mailError + '');
            },
            complete: function () {
                form.find('.btn').html(oldValue);
            }
        });
    });

    $('#send-mail-close').on('click', function () {
        public.resetMailForm();
        $('.send-mail').removeClass('mail-active').fadeOut('fast');
    });

    $('#result').on('click', function () {
        if (!modal.close('#qrCode')) {
            $('.resultInner').toggleClass('show');
        }
    });

    // Show QR Code
    $('.qrbtn').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        modal.toggle('#qrCode');
    });

    $('.homebtn').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        public.reloadPage();
    });

    // clear Timeout to not reset the gallery, if you clicked anywhere
    $(document).on('click', function () {
        if (!startPage.is(':visible')) {
            clearTimeout(timeOut);
            public.resetTimeOut();
        }
    });

    // Disable Right-Click
    if (!config.dev) {
        $(this).on('contextmenu', function (e) {
            e.preventDefault();
        });
    }

    return public;
})();

// Init on domready
$(function () {
    photoBooth.init();
});
<|endoftext|>


<commit_before>({
    findNestedDependencies: true,
    baseUrl: '../js',
    dir: '../dist',
    mainConfigFile: '../js/main.js',
    optimize: 'uglify2',
    preserveLicenseComments: false,
    removeCombined: true,
    modules: [
        {
            name: "main",
            include: ['backbone', 'marionette', 'jquery', 'underscore', 'backgrid', 'backbone.paginator', 'backgrid-paginator',

                'views/pages', 'views/filter', 'views/table', 'views/form', 'utils/table',

                'modules/types/mx/menu',
                'modules/types/tomo/menu',
                'modules/types/gen/menu',
                'modules/types/saxs/menu',
                'modules/types/em/menu',

            ],

            exclude: ['json!config.json'],
        },
        {
            name: "modules/dc/controller",
            exclude: ['main'],
        },
        {
            name: "modules/shipment/controller",
            exclude: ['main'],
        },
        {
            name: "modules/samples/controller",
            exclude: ['main'],
        },
        {
            name: "modules/projects/controller",
            exclude: ['main'],
        },
        /*{
            name: "modules/cell/controller",
            exclude: ['main'],
        },*/
        /*{
            name: "modules/calendar/controller",
            exclude: ['main'],
        },*/
        {
            name: "modules/contact/controller",
            exclude: ['main'],
        },
        /*{
            name: "modules/status/controller",
            exclude: ['main'],
        },*/
        /*{
            name: "modules/proposal/controller",
            exclude: ['main'],
        },*/
        /*{
            name: "modules/assign/controller",
            exclude: ['main'],
        },*/
        {
            name: "modules/fault/controller",
            exclude: ['main'],
        },
        {
            name: "modules/stats/controller",
            exclude: ['main'],
        },
        {
            name: "modules/blstats/controller",
            exclude: ['main'],
        },

        {
            name: "modules/mc/controller",
            exclude: ['main'],
        },

        {
            name: "modules/admin/controller",
            exclude: ['main'],
        },
    ]
})
<commit_msg>add imaging module to builder<commit_after>({
    findNestedDependencies: true,
    baseUrl: '../js',
    dir: '../dist',
    mainConfigFile: '../js/main.js',
    optimize: 'uglify2',
    preserveLicenseComments: false,
    removeCombined: true,
    modules: [
        {
            name: "main",
            include: ['backbone', 'marionette', 'jquery', 'underscore', 'backgrid', 'backbone.paginator', 'backgrid-paginator',

                'views/pages', 'views/filter', 'views/table', 'views/form', 'utils/table',

                'modules/types/mx/menu',
                'modules/types/tomo/menu',
                'modules/types/gen/menu',
                'modules/types/saxs/menu',
                'modules/types/em/menu',

            ],

            exclude: ['json!config.json'],
        },
        {
            name: "modules/dc/controller",
            exclude: ['main'],
        },
        {
            name: "modules/shipment/controller",
            exclude: ['main'],
        },
        {
            name: "modules/samples/controller",
            exclude: ['main'],
        },
        {
            name: "modules/projects/controller",
            exclude: ['main'],
        },
        /*{
            name: "modules/cell/controller",
            exclude: ['main'],
        },*/
        /*{
            name: "modules/calendar/controller",
            exclude: ['main'],
        },*/
        {
            name: "modules/contact/controller",
            exclude: ['main'],
        },
        /*{
            name: "modules/status/controller",
            exclude: ['main'],
        },*/
        /*{
            name: "modules/proposal/controller",
            exclude: ['main'],
        },*/
        /*{
            name: "modules/assign/controller",
            exclude: ['main'],
        },*/
        {
            name: "modules/fault/controller",
            exclude: ['main'],
        },
        {
            name: "modules/stats/controller",
            exclude: ['main'],
        },
        {
            name: "modules/blstats/controller",
            exclude: ['main'],
        },

        {
            name: "modules/mc/controller",
            exclude: ['main'],
        },

        {
            name: "modules/admin/controller",
            exclude: ['main'],
        },

        {
            name: "modules/imaging/controller",
            exclude: ['main'],
        },
    ]
})
<|endoftext|>


<commit_before>angular.module('mojsart.main.graph', ['ui.router'])

.config(function ($stateProvider) {

  $stateProvider
  .state('mojsart.main.graph', {
    url: '/main',
    templateUrl: 'graph/graph.tpl.html',
    controller: 'GraphController'
  });
})

.controller('GraphController', function ($scope) {
  // this function does not do what it says as of now. for now all it does is update
  // the parent scope's sharedState object, which the sidebar uses to update the
  // song that is playing. this function is fired when the user clicks on any given
  // node in the d3 visualization (see: directives.js and graph.tpl.html)
  $scope.postFeedback = function (d) {
    // TODO: find some nice way to deepcopy the song in question
    $scope.sharedState.songPath = '/md5/' + d.echoData.md5;
    for(var property in d.echoData) {
      $scope.sharedState[property] = d.echoData[property];
    }
    for(property in d.echoData.audio_summary) {
      $scope.sharedState.audio_summary[property] = d.echoData.audio_summary[property];
    }
  };
});<commit_msg>Add click-circle-to-play functionality<commit_after>angular.module('mojsart.main.graph', ['ui.router'])

.config(function ($stateProvider) {

  $stateProvider
  .state('mojsart.main.graph', {
    url: '/main',
    templateUrl: 'graph/graph.tpl.html',
    controller: 'GraphController'
  });
})

.controller('GraphController', function ($scope) {
  // this function does not do what it says as of now. for now all it does is update
  // the parent scope's sharedState object, which the sidebar uses to update the
  // song that is playing. this function is fired when the user clicks on any given
  // node in the d3 visualization (see: directives.js and graph.tpl.html)
  $scope.postFeedback = function (d) {
    // TODO: find some nice way to deepcopy the song in question
    $scope.sharedState.songPath = '/song/md5/' + d.echoData.md5;
    for(var property in d.echoData) {
      $scope.sharedState[property] = d.echoData[property];
    }
    for(property in d.echoData.audio_summary) {
      $scope.sharedState.audio_summary[property] = d.echoData.audio_summary[property];
    }
  };
});<|endoftext|>