<commit_before>/*Made by Cp any use of copy/paste of this code WILL be reported to the copy n paste police!!, no seriously
feel free to copy my code but PLEASE JUST GIVE ME CREDIT -__- Have a nice day*/

/* Just a quick self note for whats what:
	hideAll -- hides all content until script is finshed
	jaNu -- prefix sentence of yes to the question of www.nu.nl
	neeNu -- prefix sentence of no to the question of www.nu.nl
	jaRefresh -- prefix sentence of yes to the question of F5 spam
	neeRefresh-- prefix sentence of no to the question of F5 spam
	reTrueNuTrue -- nu.nl is true and refresh is true
	reTrueNuFalse -- nu.nl is false and refresh is true
	reFalseNuTrue -- nu.nl is true and refresh is false
	reFalseNUFalse -- nu.nl is false and refresh is false
	setAll -- loads every lil pre made bit of code
	klachtRun -- runs the klacht procedure
	nameAsk -- asks for clients name
	modemAsk -- asks for clients modem
	internetAsk -- asks 2 questions ( F5 and nu.nl)
	oplossingPrintKlacht -- prints the result of the 2 questions
	datumAsk -- seeks the date
	showAll -- reveals the page
	storingRun -- same as klachtRun but for storing
	abnmtRun -- same as klacht but for abbonement
	naam -- name of client
	NEED MORE EXPLAINATION
*/

function setAll(){
	hideAll();
	jaNu = "De klant kan naar www.nu.nl, ";
	neeNu = "De klant kan niet naar www.nu.nl, ";
	jaRefresh = "de website reageert snel na het herladen.";
	neeRefresh = "de website reageert traag na het herladen.";
	reTrueNuTrue = "Alles werkt zoals het hoort, geen oplossing vereist.";
	reTrueNuFalse = "Herstart de router 1.";
	reFalseNuTrue = "Herstart de router 2.";
	reFalseNuFalse = "Herstart de router 3.";
	refresh = null;
	internet = null;
}

function klachtRun(){
	setAll();
	alert("klacht eh");
	nameAsk();
	modemAsk();
	internetAsk();
	oplossingPrintKlacht();
	datumAsk();
	document.write("<button class = 'button' onclick = 'reset()' id = 'reset'>Herstart</button>
");
	showAll();
}

function storingRun(){
	alert("storing eh");
	nameAsk();
	modemAsk();
	datumAsk();
	document.write("<button class = 'button' onclick = 'reset()' id = 'reset'>Herstart</button>");
	showAll();
}

function abnmtRun(){
	alert("abbo eh");
	nameAsk();
	modemAsk();
	datumAsk();
	document.write("<button class = 'button' onclick = 'reset()' id = 'reset'>Herstart</button>");
	showAll();
}

function nameAsk() {
	naam = prompt("Geef de naam");
	if (naam.length < 1){
		alert("Geen naam gegeven");
		nameAsk();
	}
	else {
		document.write("

Naam: " + "" + naam + " " + "<button id='naamwijzig' class='wijzig' onclick='naamWijzig()'>Wijzig</button>
");
	}
}

function datumAsk() {
	datum = Date();
		document.write("
Datum: " + datum + "
");
}

function modemAsk() {
	modem = prompt("Wat voor type modem gebruikt de klant?");
	if (modem.length < 1){
		alert("Geef een geldige modem op");
		modemAsk();
	}
	else{
		document.write("
Modem: " + "" + modem + " " + "<button id='naamwijzig' class='wijzig' onclick='modemWijzig()'>Wijzig</button>
");
	}
}

function internetAsk() {
	internet = confirm("Kan de klant naar nu.nl?");
	if (internet == true){
		refresh = confirm("Laadt de pagina snel als u vaak op F5 drukt?");
		if (refresh == true){
			document.write("
Internet: " + "" + jaNu + " " + jaRefresh + "" + "<button id='naamwijzig' class='wijzig' onclick='internetWijzig()'>Wijzig</button>
");
		}
		else{
			document.write("
Internet: " + "" + jaNu + " " + neeRefresh + "" + "<button id='naamwijzig' class='wijzig' onclick='internetWijzig()'>Wijzig</button>
");
		}
	}
	else if(internet == false){
		refresh = confirm("Laadt de pagina snel als u vaak op F5 drukt?");
		if(refresh == true){
			document.write("
Internet: " + "" + neeNu + " " +  jaRefresh + "" + "<button id='naamwijzig' class='wijzig' onclick='internetWijzig()'>Wijzig</button>
");
		}
		else if (refresh == false){
			document.write("
Internet: " + "" + neeNu + " " +  neeRefresh + "" + "<button id='naamwijzig' class='wijzig' onclick='internetWijzig()'>Wijzig</button>
");
		}
	}
}

function oplossingPrintKlacht(){
	if (internet == true){
		if(refresh == true){
			document.write("
Oplossing: " + "" + reTrueNuTrue + "" + "
");
		}
		else if(refresh == false){
			document.write("
Oplossing: " + "" + reFalseNuTrue + "" + "
");
		}
	}
	else if (internet == false){
		if(refresh == true){
			document.write("
Oplossing: " + "" + reTrueNuFalse + "" + "
");
		}
	else if(refresh == false){
		document.write("
Oplossing: " + "" + reFalseNuFalse + "" + "
");
		}
	}
}

function callAsk(){
	call = prompt("Heeft u problemen met bellen?");
	if (call == true){
		toon = prompt("Hoort u de kiestoon als u op een getal drukt?");
		if (toon == true){
			callPhone = prompt("Kunt u bellen met bijvoorbeeld een mobiel nummer?");
			if (callPhone == true){

			}
		}
	}
	else if(call == false){

	}
}

function reset(){
	window.location.reload();
	/*This function is only meant for reloading the page A.K.A. restarting the script*/
}

function naamWijzig(){
	naam = prompt("Geef de naam");
	if (naam.length < 1){
		alert("Geen naam gegeven");
		nameAsk();
	}
	else {
		document.getElementById("naam").innerHTML = naam;
	}
}

function modemWijzig(){
	modem = prompt("Wat voor type modem gebruikt de klant?");
	if (modem.length < 1){
		alert("Geef een geldige modem op");
		modemAsk();
	}
	else{
		document.getElementById("modem").innerHTML = modem;
	}
}

function internetWijzig(){
	internet = confirm("Kan de klant naar nu.nl?");
	if (internet == true){
		refresh = confirm("Laadt de pagina snel als u vaak op F5 drukt?");
		if(refresh == true){
			document.getElementById("internet").innerHTML = jaNu + " " + jaRefresh + "";
		}
		else if(refresh == false){
			document.getElementById("internet").innterHTML = jaNu + " " + neeRefresh + "";
		}
	}
	else if(internet == false){
		refresh = confirm("Laadt de pagina snel als u vaak op F5 drukt?");
		if(refresh == true){
			document.getElementById("internet").innerHTML =  neeNu + " " + jaRefresh + "";
		}
		else if(refresh == false){
			document.getElementById("internet").innerHTML = neeNu + " " + neeRefresh + ""
		}
	}
}

function hideAll(){
	document.getElementById("container").style.cssText = "display:none;"
}

function showAll(){
	document.getElementById("container").style.cssText = "display:show;"
}<commit_msg>added a new function<commit_after>/*Made by Cp any use of copy/paste of this code WILL be reported to the copy n paste police!!, no seriously
feel free to copy my code but PLEASE JUST GIVE ME CREDIT -__- Have a nice day*/

/* Just a quick self note for whats what:
	hideAll -- hides all content until script is finshed
	jaNu -- prefix sentence of yes to the question of www.nu.nl
	neeNu -- prefix sentence of no to the question of www.nu.nl
	jaRefresh -- prefix sentence of yes to the question of F5 spam
	neeRefresh-- prefix sentence of no to the question of F5 spam
	reTrueNuTrue -- nu.nl is true and refresh is true
	reTrueNuFalse -- nu.nl is false and refresh is true
	reFalseNuTrue -- nu.nl is true and refresh is false
	reFalseNUFalse -- nu.nl is false and refresh is false
	setAll -- loads every lil pre made bit of code
	klachtRun -- runs the klacht procedure
	nameAsk -- asks for clients name
	modemAsk -- asks for clients modem
	internetAsk -- asks 2 questions ( F5 and nu.nl)
	oplossingPrintKlacht -- prints the result of the 2 questions
	datumAsk -- seeks the date
	showAll -- reveals the page
	storingRun -- same as klachtRun but for storing
	abnmtRun -- same as klacht but for abbonement
	naam -- name of client
	NEED MORE EXPLAINATION
*/

function setAll(){
	hideAll();
	jaNu = "De klant kan naar www.nu.nl, ";
	neeNu = "De klant kan niet naar www.nu.nl, ";
	jaRefresh = "de website reageert snel na het herladen.";
	neeRefresh = "de website reageert traag na het herladen.";
	reTrueNuTrue = "Alles werkt zoals het hoort, geen oplossing vereist.";
	reTrueNuFalse = "Herstart de router 1.";
	reFalseNuTrue = "Herstart de router 2.";
	reFalseNuFalse = "Herstart de router 3.";
	refresh = null;
	internet = null;
}

function klachtRun(){
	setAll();
	alert("klacht eh");
	nameAsk();
	modemAsk();
	internetAsk();
	oplossingPrintKlacht();
	callAsk();
	tvAsk();
	datumAsk();
	document.write("<button class = 'button' onclick = 'reset()' id = 'reset'>Herstart</button>
");
	showAll();
}

function storingRun(){
	alert("storing eh");
	nameAsk();
	modemAsk();
	datumAsk();
	document.write("<button class = 'button' onclick = 'reset()' id = 'reset'>Herstart</button>");
	showAll();
}

function abnmtRun(){
	alert("abbo eh");
	nameAsk();
	modemAsk();
	datumAsk();
	document.write("<button class = 'button' onclick = 'reset()' id = 'reset'>Herstart</button>");
	showAll();
}

function nameAsk() {
	naam = prompt("Geef de naam");
	if (naam.length < 1){
		alert("Geen naam gegeven");
		nameAsk();
	}
	else {
		document.write("

Naam: " + "" + naam + " " + "<button id='naamwijzig' class='wijzig' onclick='naamWijzig()'>Wijzig</button>
");
	}
}

function datumAsk() {
	datum = Date();
		document.write("
Datum: " + datum + "
");
}

function modemAsk() {
	modem = prompt("Wat voor type modem gebruikt de klant?");
	if (modem.length < 1){
		alert("Geef een geldige modem op");
		modemAsk();
	}
	else{
		document.write("
Modem: " + "" + modem + " " + "<button id='naamwijzig' class='wijzig' onclick='modemWijzig()'>Wijzig</button>
");
	}
}

function internetAsk() {
	internet = confirm("Kan de klant naar nu.nl?");
	if (internet == true){
		refresh = confirm("Laadt de pagina snel als u vaak op F5 drukt?");
		if (refresh == true){
			document.write("
Internet: " + "" + jaNu + " " + jaRefresh + "" + "<button id='naamwijzig' class='wijzig' onclick='internetWijzig()'>Wijzig</button>
");
		}
		else{
			document.write("
Internet: " + "" + jaNu + " " + neeRefresh + "" + "<button id='naamwijzig' class='wijzig' onclick='internetWijzig()'>Wijzig</button>
");
		}
	}
	else if(internet == false){
		refresh = confirm("Laadt de pagina snel als u vaak op F5 drukt?");
		if(refresh == true){
			document.write("
Internet: " + "" + neeNu + " " +  jaRefresh + "" + "<button id='naamwijzig' class='wijzig' onclick='internetWijzig()'>Wijzig</button>
");
		}
		else if (refresh == false){
			document.write("
Internet: " + "" + neeNu + " " +  neeRefresh + "" + "<button id='naamwijzig' class='wijzig' onclick='internetWijzig()'>Wijzig</button>
");
		}
	}
}

function oplossingPrintKlacht(){
	if (internet == true){
		if(refresh == true){
			document.write("
Oplossing: " + "" + reTrueNuTrue + "" + "
");
		}
		else if(refresh == false){
			document.write("
Oplossing: " + "" + reFalseNuTrue + "" + "
");
		}
	}
	else if (internet == false){
		if(refresh == true){
			document.write("
Oplossing: " + "" + reTrueNuFalse + "" + "
");
		}
	else if(refresh == false){
		document.write("
Oplossing: " + "" + reFalseNuFalse + "" + "
");
		}
	}
}

function callAsk(){
	call = prompt("Heeft u problemen met bellen?");
	if (call == true){
		toon = prompt("Hoort u de kiestoon als u op een getal drukt?");
		if (toon == true){
			callPhone = prompt("Kunt u bellen met bijvoorbeeld een mobiel nummer?");
			if (callPhone == true){
				/* document.write */
				tvAsk();
			}
		}
		else if (callPhone == false){
			/*document.write */
			tvAsk();
		}
	}
	else if(call == false){
		/*document.write */
		tvAsk();
	}
}

function tvAsk(){

}

function reset(){
	window.location.reload();
	/*This function is only meant for reloading the page A.K.A. restarting the script*/
}

function naamWijzig(){
	naam = prompt("Geef de naam");
	if (naam.length < 1){
		alert("Geen naam gegeven");
		nameAsk();
	}
	else {
		document.getElementById("naam").innerHTML = naam;
	}
}

function modemWijzig(){
	modem = prompt("Wat voor type modem gebruikt de klant?");
	if (modem.length < 1){
		alert("Geef een geldige modem op");
		modemAsk();
	}
	else{
		document.getElementById("modem").innerHTML = modem;
	}
}

function internetWijzig(){
	internet = confirm("Kan de klant naar nu.nl?");
	if (internet == true){
		refresh = confirm("Laadt de pagina snel als u vaak op F5 drukt?");
		if(refresh == true){
			document.getElementById("internet").innerHTML = jaNu + " " + jaRefresh + "";
		}
		else if(refresh == false){
			document.getElementById("internet").innterHTML = jaNu + " " + neeRefresh + "";
		}
	}
	else if(internet == false){
		refresh = confirm("Laadt de pagina snel als u vaak op F5 drukt?");
		if(refresh == true){
			document.getElementById("internet").innerHTML =  neeNu + " " + jaRefresh + "";
		}
		else if(refresh == false){
			document.getElementById("internet").innerHTML = neeNu + " " + neeRefresh + ""
		}
	}
}

function hideAll(){
	document.getElementById("container").style.cssText = "display:none;"
}

function showAll(){
	document.getElementById("container").style.cssText = "display:show;"
}<|endoftext|>


<commit_before>'use strict';

var EventHandler = require('./../utilities/event-handler');
var Utilities = require('./../utilities/utilities');
var Injector = require('./injector');
var VirtualDOM = require('./../virtual-dom/virtual-dom');
var DataStore = require('./../data-store/data-store');
var Logger = require('./../logger/logger');
var Dispatcher = require('./dispatcher');

var COMPONENT_DELIM = ':';
var PUBLIC_KEY = '$public';
var PRIVATE_KEY = '$private';
var LIFECYCLE_KEY = '$lifecycle';
var PASS_THROUGH_KEY = '$pass-through';
var DESCENDANT_KEY = 'descendant';
var MISS_KEY = '$miss';
var ANY_KEY = '$any';
var INDEX_KEY = '$index';
var REPEAT_PAYLOAD_KEY = '$repeatPayload';

function Events(eventGroups, name, dependencies, rootNode) {
    EventHandler.apply(this);
    this.name = name;
    this.dependencies = dependencies;
    this.dispatcher = new Dispatcher(rootNode);
    this.eventStore = Events.processEventGroups(eventGroups);
}

Events.prototype = Object.create(EventHandler.prototype);
Events.prototype.constructor = Events;

Events.prototype.initializeDescendantEvents = function initializeDescendantEvents(expandedBlueprint, uid, uidWhiteList) {
    var events;
    var event;
    var selector;
    var eventName;
    var targets;
    for (selector in this.eventStore[DESCENDANT_KEY]) {
        events = this.eventStore[DESCENDANT_KEY][selector];
        targets = VirtualDOM.query(expandedBlueprint, selector);

        // If white list is included, only attach events to nodes corresponding to UIDs in
        // that white list (i.e., dynamically added nodes).
        if (uidWhiteList) {
            var whiteListTargets = [];
            for (var i = 0; i < targets.length; i++) {
                if (uidWhiteList.indexOf(VirtualDOM.getUID(targets[i])) !== -1) {
                    whiteListTargets.push(targets[i]);
                }
            }
            targets = whiteListTargets;
        }

        for (eventName in events) {
            event = events[eventName];
            if (eventName.indexOf(COMPONENT_DELIM) >= 0) {
                this.setupProxyEvent(event, targets, uid);
            }
            else {
                this.setupDispatchedEvent(event, targets, uid);
            }
        }
    }
};

/*
example:
events:
    '#surface'
        'famous:events:click' ()=>
 */
Events.prototype.setupProxyEvent = function setupProxyEvent(event, targets, uid) {
    var trigger = Events.getDirectEventAction(event.name, this.dependencies);
    var triggerParams = Utilities.getParameterNames(trigger);
    var lastDelimIdx = event.name.lastIndexOf(COMPONENT_DELIM);
    var eventName = event.name.slice(lastDelimIdx + 1); // 'famous:events:click' -> 'click'
    var payload = {
        eventName: eventName
    };
    var targetUID;
    var triggerArgs;
    var listenerArgs;
    var component;
    var $indexIndex;
    var $repeatPayloadIndex;
    for (var i = 0; i < targets.length; i++) {
        targetUID = VirtualDOM.getUID(targets[i]);

        // If $index is injected into an event handler, the value of $index should
        // correspond to the $index associated with the item that is capturing the event.
        // For example, if items are repeated, the $index value on a click handler should be
        // the index of the repeated item, not the parent component.
        $indexIndex = event.params.indexOf(INDEX_KEY);
        $repeatPayloadIndex = event.params.indexOf(REPEAT_PAYLOAD_KEY);
        if ($indexIndex !== -1 || $repeatPayloadIndex !== -1) {
            component = Utilities.getComponent(targets[i]);
            payload.listener = function(component, eventPayload) {
                listenerArgs = Injector.getArgs(event.params, eventPayload, uid);
                listenerArgs[$indexIndex] = component.states.get(INDEX_KEY);
                listenerArgs[$repeatPayloadIndex] = component.states.get(REPEAT_PAYLOAD_KEY);
                event.action.apply(null, listenerArgs);
            }.bind(null, component);
        }
        else {
            payload.listener = function(eventPayload) {
                listenerArgs = Injector.getArgs(event.params, eventPayload, uid);
                event.action.apply(null, listenerArgs);
            };
        }

        triggerArgs = Injector.getArgs(triggerParams, payload, targetUID);
        trigger.apply(null, triggerArgs);
    }
};

/*
example:
events:
    '#surface'
        'custom-event' ()=>
 */
Events.prototype.setupDispatchedEvent = function setupDispatchedEvent(event, targets, uid) {
    var self = this;
    var component;
    for (var i = 0; i < targets.length; i++) {
        component = DataStore.getComponent(VirtualDOM.getUID(targets[i]));
        component.events.dispatcher.on(event.name, function(message) {
            self.sendDescendantMessage(event.name, message, event.selector, uid);
        });
    }
};

Events.prototype.sendDescendantMessage = function sendDescendantMessage(eventName, message, selector, uid) {
    var eventsToFire = [];
    var descendantEvents = this.eventStore[DESCENDANT_KEY][selector] || {};
    var i;
    var event;
    for (var descendantEventName in descendantEvents) {
        event = descendantEvents[descendantEventName];
        if (descendantEventName === eventName) {
            eventsToFire.push(event);
        }
    }

    if (eventsToFire.length < 1) {
        throw new Error('Unknown event `' + eventName + '` for `' + this.name + '` (' + selector + ')');
    }

    for (i = 0; i < eventsToFire.length; i++) {
        event = eventsToFire[i];
        event.action.apply(null, Injector.getArgs(event.params, message, uid));
    }
};

Events.prototype.getPublicEvent = function getPublicEvent(eventName) {
    return this.eventStore[PUBLIC_KEY][eventName];
};

Events.prototype.getPrivateEvent = function getPrivateEvent(eventName) {
    return this.eventStore[PRIVATE_KEY][eventName];
};

Events.prototype.triggerDirectEventHandler = function triggerDirectEventHandler(name, payload, uid) {
    var handler = Events.getDirectEventAction(name, this.dependencies);
    var handlerParams = Utilities.getParameterNames(handler);
    var handlerArgs = Injector.getArgs(handlerParams, payload, uid);
    handler.apply(null, handlerArgs);
};

/*
Used to find behavior handlers for behavior's with '$self' selector:
i.e.:
behaviors
    $self
        set-content =>

$private takes precendence of $public
 */
Events.prototype.getSelfEvent = function getSelfEvent(eventName) {
    var event = this.getPrivateEvent(eventName) ||
                this.getPublicEvent(eventName);

    if (!event) {
        throw new Error('`' + this.name + '` does not have a `$private` or `$public` event named `' + eventName + '`.');
    }

    return event;
};

Events.prototype.triggerEvent = function(event, payload, uid) {
    var selector = event.selector;
    switch (selector) {
        case PUBLIC_KEY:
        case PRIVATE_KEY:
            this._executeEvent(event, payload, uid);
            break;
        case LIFECYCLE_KEY: this.triggerLifecycleEvent(event.name, payload, uid); break;
        default: throw new Error('`' + selector + '` is not a valid event selector');
    }
};

Events.prototype.triggerLifecycleEvent = function(name, uid) {
    var event = this.eventStore[LIFECYCLE_KEY][name];
    if (event) {
        this._executeEvent(event, null, uid);
    }
};

Events.prototype._executeEvent = function _executeEvent(event, payload, uid) {
    var args = Injector.getArgs(event.params, payload, uid);
    event.action.apply(null, args);
};

/*
events
    $pass-through
        selector: *
        (Every public message gets passed along to selected elements)

        selector: ['position', 'opacity']
        (Whitelist of public messages get passed along to selected elements)

        selector: {
            child-position: position,
            child-opacity: opacity
        }
        (Whitelist of public messages get passed along where key is public event &
        value is the public message that gets sent to )
 */
Events.prototype._processPassThroughEvents = function _processPassThroughEvents(messageKey, messagePayload, uid) {
    var passThroughEvents = this.eventStore[PASS_THROUGH_KEY];
    var eventPassedThrough = false;
    var selector;
    var event;
    var value;
    for (selector in passThroughEvents) {
        event = passThroughEvents[selector];
        selector = event.name;
        value = event.action;
        if (value === '*') {
            Events.sendMessageBySelector(messageKey, messagePayload, uid, selector);
            eventPassedThrough = true;
        }
        else if (Array.isArray(value)) {
            if (value.indexOf(messageKey) > -1) {
                Events.sendMessageBySelector(messageKey, messagePayload, uid, selector);
                eventPassedThrough = true;
            }
        }
        else if (typeof value === 'object') {
            if (messageKey in value) {
                Events.sendMessageBySelector(value[messageKey], messagePayload, uid, selector);
                eventPassedThrough = true;
            }
        }
        else {
            throw new Error('`' + value + '` is not a valid value for a $pass-through event');
        }
    }

    return eventPassedThrough;
};

Events.prototype.sendMessage = function sendMessage(key, payload, uid) {
    // Check public events
    var publicEvents = this.eventStore[PUBLIC_KEY];
    var eventsToFire = [];
    if (publicEvents[ANY_KEY]) {
        eventsToFire.push(publicEvents[key]);
    }
    if (publicEvents[key]) {
        eventsToFire.push(publicEvents[key]);
    }
    else {
        if (publicEvents[MISS_KEY]) {
            eventsToFire.push(publicEvents[MISS_KEY]);
        }
    }

    // Check pass through events
    var messagePassedThrough = this._processPassThroughEvents(key, payload, uid);

    //  Trigger events
    if (eventsToFire.length < 1) {
        if (!messagePassedThrough) {
            Logger.log('Unknown public/passthrough event `' + key + '` for `' + this.name + '`', 1);
        }
    }
    else {
        var event;
        for (var i = 0; i < eventsToFire.length; i++) {
            event = eventsToFire[i];
            this._executeEvent(event, payload, uid);
        }
    }
};

Events.prototype.sendMessages = function sendMessages(messages, uid) {
    for (var key in messages) {
        this.sendMessage(key, messages[key], uid);
    }
};

Events.sendMessageBySelector = function sendMessageBySelector(key, value, uid, selector) {
    var parentComponent = DataStore.getComponent(uid);
    var targets = VirtualDOM.query(parentComponent.tree.getExpandedBlueprint(), selector);
    var component;
    for (var i = 0; i < targets.length; i++) {
        component = DataStore.getComponent(VirtualDOM.getUID(targets[i]));
        component.sendMessage(key, value);
    }
};

Events.processEventGroups = function processEventGroups(groups) {
    var list = {};
    list[PUBLIC_KEY] = {};
    list[PRIVATE_KEY] = {};
    list[LIFECYCLE_KEY] = {};
    list[PASS_THROUGH_KEY] = {};
    list[DESCENDANT_KEY] = {};

    var selector;
    var events;
    var eventName;
    var store;
    for (selector in groups) {
        events = groups[selector];
        store = {};
        for (eventName in events) {
            store[eventName] = {
                name: eventName,
                action: events[eventName],
                selector: selector,
                params: Utilities.getParameterNames(events[eventName])
            };
        }

        switch (selector) {
            case PUBLIC_KEY: list[PUBLIC_KEY] = store; break;
            case PRIVATE_KEY: list[PRIVATE_KEY] = store; break;
            case LIFECYCLE_KEY: list[LIFECYCLE_KEY] = store; break;
            case PASS_THROUGH_KEY: list[PASS_THROUGH_KEY] = store; break;
            default: list[DESCENDANT_KEY][selector] = store; break;
        }
    }

    return list;
};

Events.getDirectEventAction = function getDirectEventAction(name, dependencies) {
    var lastDelimIdx = name.lastIndexOf(COMPONENT_DELIM);
    var moduleName = name.slice(0, lastDelimIdx);
    var handlerName = name.slice(lastDelimIdx + 1);
    var moduleTag = dependencies[moduleName];
    var bestModule = DataStore.getModuleDefinition(moduleName, moduleTag);

    var foundEvent;
    var fallbackEvent;
    var action;
    for (var eventName in bestModule.events[PUBLIC_KEY]) {
        action = bestModule.events[PUBLIC_KEY][eventName];
        if (eventName === handlerName) {
            foundEvent = action;
            break;
        }
        else if (eventName === MISS_KEY || eventName === ANY_KEY) {
            fallbackEvent = action;
        }
    }

    var handler = foundEvent || fallbackEvent;
    if (!handler) {
        throw new Error('Unknown behavior handler `' + name + '`');
    }
    return handler;
};

module.exports = Events;
<commit_msg>Another check for the expanded blueprint before trying to query it<commit_after>'use strict';

var EventHandler = require('./../utilities/event-handler');
var Utilities = require('./../utilities/utilities');
var Injector = require('./injector');
var VirtualDOM = require('./../virtual-dom/virtual-dom');
var DataStore = require('./../data-store/data-store');
var Logger = require('./../logger/logger');
var Dispatcher = require('./dispatcher');

var COMPONENT_DELIM = ':';
var PUBLIC_KEY = '$public';
var PRIVATE_KEY = '$private';
var LIFECYCLE_KEY = '$lifecycle';
var PASS_THROUGH_KEY = '$pass-through';
var DESCENDANT_KEY = 'descendant';
var MISS_KEY = '$miss';
var ANY_KEY = '$any';
var INDEX_KEY = '$index';
var REPEAT_PAYLOAD_KEY = '$repeatPayload';

function Events(eventGroups, name, dependencies, rootNode) {
    EventHandler.apply(this);
    this.name = name;
    this.dependencies = dependencies;
    this.dispatcher = new Dispatcher(rootNode);
    this.eventStore = Events.processEventGroups(eventGroups);
}

Events.prototype = Object.create(EventHandler.prototype);
Events.prototype.constructor = Events;

Events.prototype.initializeDescendantEvents = function initializeDescendantEvents(expandedBlueprint, uid, uidWhiteList) {
    var events;
    var event;
    var selector;
    var eventName;
    var targets;
    for (selector in this.eventStore[DESCENDANT_KEY]) {
        events = this.eventStore[DESCENDANT_KEY][selector];
        targets = VirtualDOM.query(expandedBlueprint, selector);

        // If white list is included, only attach events to nodes corresponding to UIDs in
        // that white list (i.e., dynamically added nodes).
        if (uidWhiteList) {
            var whiteListTargets = [];
            for (var i = 0; i < targets.length; i++) {
                if (uidWhiteList.indexOf(VirtualDOM.getUID(targets[i])) !== -1) {
                    whiteListTargets.push(targets[i]);
                }
            }
            targets = whiteListTargets;
        }

        for (eventName in events) {
            event = events[eventName];
            if (eventName.indexOf(COMPONENT_DELIM) >= 0) {
                this.setupProxyEvent(event, targets, uid);
            }
            else {
                this.setupDispatchedEvent(event, targets, uid);
            }
        }
    }
};

/*
example:
events:
    '#surface'
        'famous:events:click' ()=>
 */
Events.prototype.setupProxyEvent = function setupProxyEvent(event, targets, uid) {
    var trigger = Events.getDirectEventAction(event.name, this.dependencies);
    var triggerParams = Utilities.getParameterNames(trigger);
    var lastDelimIdx = event.name.lastIndexOf(COMPONENT_DELIM);
    var eventName = event.name.slice(lastDelimIdx + 1); // 'famous:events:click' -> 'click'
    var payload = {
        eventName: eventName
    };
    var targetUID;
    var triggerArgs;
    var listenerArgs;
    var component;
    var $indexIndex;
    var $repeatPayloadIndex;
    for (var i = 0; i < targets.length; i++) {
        targetUID = VirtualDOM.getUID(targets[i]);

        // If $index is injected into an event handler, the value of $index should
        // correspond to the $index associated with the item that is capturing the event.
        // For example, if items are repeated, the $index value on a click handler should be
        // the index of the repeated item, not the parent component.
        $indexIndex = event.params.indexOf(INDEX_KEY);
        $repeatPayloadIndex = event.params.indexOf(REPEAT_PAYLOAD_KEY);
        if ($indexIndex !== -1 || $repeatPayloadIndex !== -1) {
            component = Utilities.getComponent(targets[i]);
            payload.listener = function(component, eventPayload) {
                listenerArgs = Injector.getArgs(event.params, eventPayload, uid);
                listenerArgs[$indexIndex] = component.states.get(INDEX_KEY);
                listenerArgs[$repeatPayloadIndex] = component.states.get(REPEAT_PAYLOAD_KEY);
                event.action.apply(null, listenerArgs);
            }.bind(null, component);
        }
        else {
            payload.listener = function(eventPayload) {
                listenerArgs = Injector.getArgs(event.params, eventPayload, uid);
                event.action.apply(null, listenerArgs);
            };
        }

        triggerArgs = Injector.getArgs(triggerParams, payload, targetUID);
        trigger.apply(null, triggerArgs);
    }
};

/*
example:
events:
    '#surface'
        'custom-event' ()=>
 */
Events.prototype.setupDispatchedEvent = function setupDispatchedEvent(event, targets, uid) {
    var self = this;
    var component;
    for (var i = 0; i < targets.length; i++) {
        component = DataStore.getComponent(VirtualDOM.getUID(targets[i]));
        component.events.dispatcher.on(event.name, function(message) {
            self.sendDescendantMessage(event.name, message, event.selector, uid);
        });
    }
};

Events.prototype.sendDescendantMessage = function sendDescendantMessage(eventName, message, selector, uid) {
    var eventsToFire = [];
    var descendantEvents = this.eventStore[DESCENDANT_KEY][selector] || {};
    var i;
    var event;
    for (var descendantEventName in descendantEvents) {
        event = descendantEvents[descendantEventName];
        if (descendantEventName === eventName) {
            eventsToFire.push(event);
        }
    }

    if (eventsToFire.length < 1) {
        throw new Error('Unknown event `' + eventName + '` for `' + this.name + '` (' + selector + ')');
    }

    for (i = 0; i < eventsToFire.length; i++) {
        event = eventsToFire[i];
        event.action.apply(null, Injector.getArgs(event.params, message, uid));
    }
};

Events.prototype.getPublicEvent = function getPublicEvent(eventName) {
    return this.eventStore[PUBLIC_KEY][eventName];
};

Events.prototype.getPrivateEvent = function getPrivateEvent(eventName) {
    return this.eventStore[PRIVATE_KEY][eventName];
};

Events.prototype.triggerDirectEventHandler = function triggerDirectEventHandler(name, payload, uid) {
    var handler = Events.getDirectEventAction(name, this.dependencies);
    var handlerParams = Utilities.getParameterNames(handler);
    var handlerArgs = Injector.getArgs(handlerParams, payload, uid);
    handler.apply(null, handlerArgs);
};

/*
Used to find behavior handlers for behavior's with '$self' selector:
i.e.:
behaviors
    $self
        set-content =>

$private takes precendence of $public
 */
Events.prototype.getSelfEvent = function getSelfEvent(eventName) {
    var event = this.getPrivateEvent(eventName) ||
                this.getPublicEvent(eventName);

    if (!event) {
        throw new Error('`' + this.name + '` does not have a `$private` or `$public` event named `' + eventName + '`.');
    }

    return event;
};

Events.prototype.triggerEvent = function(event, payload, uid) {
    var selector = event.selector;
    switch (selector) {
        case PUBLIC_KEY:
        case PRIVATE_KEY:
            this._executeEvent(event, payload, uid);
            break;
        case LIFECYCLE_KEY: this.triggerLifecycleEvent(event.name, payload, uid); break;
        default: throw new Error('`' + selector + '` is not a valid event selector');
    }
};

Events.prototype.triggerLifecycleEvent = function(name, uid) {
    var event = this.eventStore[LIFECYCLE_KEY][name];
    if (event) {
        this._executeEvent(event, null, uid);
    }
};

Events.prototype._executeEvent = function _executeEvent(event, payload, uid) {
    var args = Injector.getArgs(event.params, payload, uid);
    event.action.apply(null, args);
};

/*
events
    $pass-through
        selector: *
        (Every public message gets passed along to selected elements)

        selector: ['position', 'opacity']
        (Whitelist of public messages get passed along to selected elements)

        selector: {
            child-position: position,
            child-opacity: opacity
        }
        (Whitelist of public messages get passed along where key is public event &
        value is the public message that gets sent to )
 */
Events.prototype._processPassThroughEvents = function _processPassThroughEvents(messageKey, messagePayload, uid) {
    var passThroughEvents = this.eventStore[PASS_THROUGH_KEY];
    var eventPassedThrough = false;
    var selector;
    var event;
    var value;
    for (selector in passThroughEvents) {
        event = passThroughEvents[selector];
        selector = event.name;
        value = event.action;
        if (value === '*') {
            Events.sendMessageBySelector(messageKey, messagePayload, uid, selector);
            eventPassedThrough = true;
        }
        else if (Array.isArray(value)) {
            if (value.indexOf(messageKey) > -1) {
                Events.sendMessageBySelector(messageKey, messagePayload, uid, selector);
                eventPassedThrough = true;
            }
        }
        else if (typeof value === 'object') {
            if (messageKey in value) {
                Events.sendMessageBySelector(value[messageKey], messagePayload, uid, selector);
                eventPassedThrough = true;
            }
        }
        else {
            throw new Error('`' + value + '` is not a valid value for a $pass-through event');
        }
    }

    return eventPassedThrough;
};

Events.prototype.sendMessage = function sendMessage(key, payload, uid) {
    // Check public events
    var publicEvents = this.eventStore[PUBLIC_KEY];
    var eventsToFire = [];
    if (publicEvents[ANY_KEY]) {
        eventsToFire.push(publicEvents[key]);
    }
    if (publicEvents[key]) {
        eventsToFire.push(publicEvents[key]);
    }
    else {
        if (publicEvents[MISS_KEY]) {
            eventsToFire.push(publicEvents[MISS_KEY]);
        }
    }

    // Check pass through events
    var messagePassedThrough = this._processPassThroughEvents(key, payload, uid);

    //  Trigger events
    if (eventsToFire.length < 1) {
        if (!messagePassedThrough) {
            Logger.log('Unknown public/passthrough event `' + key + '` for `' + this.name + '`', 1);
        }
    }
    else {
        var event;
        for (var i = 0; i < eventsToFire.length; i++) {
            event = eventsToFire[i];
            this._executeEvent(event, payload, uid);
        }
    }
};

Events.prototype.sendMessages = function sendMessages(messages, uid) {
    for (var key in messages) {
        this.sendMessage(key, messages[key], uid);
    }
};

Events.sendMessageBySelector = function sendMessageBySelector(key, value, uid, selector) {
    var parentComponent = DataStore.getComponent(uid);
    var expandedBlueprint = parentComponent.tree.getExpandedBlueprint();
    if (expandedBlueprint) {
        var targets = VirtualDOM.query(expandedBlueprint, selector);
        var component;
        for (var i = 0; i < targets.length; i++) {
            component = DataStore.getComponent(VirtualDOM.getUID(targets[i]));
            component.sendMessage(key, value);
        }
    }
};

Events.processEventGroups = function processEventGroups(groups) {
    var list = {};
    list[PUBLIC_KEY] = {};
    list[PRIVATE_KEY] = {};
    list[LIFECYCLE_KEY] = {};
    list[PASS_THROUGH_KEY] = {};
    list[DESCENDANT_KEY] = {};

    var selector;
    var events;
    var eventName;
    var store;
    for (selector in groups) {
        events = groups[selector];
        store = {};
        for (eventName in events) {
            store[eventName] = {
                name: eventName,
                action: events[eventName],
                selector: selector,
                params: Utilities.getParameterNames(events[eventName])
            };
        }

        switch (selector) {
            case PUBLIC_KEY: list[PUBLIC_KEY] = store; break;
            case PRIVATE_KEY: list[PRIVATE_KEY] = store; break;
            case LIFECYCLE_KEY: list[LIFECYCLE_KEY] = store; break;
            case PASS_THROUGH_KEY: list[PASS_THROUGH_KEY] = store; break;
            default: list[DESCENDANT_KEY][selector] = store; break;
        }
    }

    return list;
};

Events.getDirectEventAction = function getDirectEventAction(name, dependencies) {
    var lastDelimIdx = name.lastIndexOf(COMPONENT_DELIM);
    var moduleName = name.slice(0, lastDelimIdx);
    var handlerName = name.slice(lastDelimIdx + 1);
    var moduleTag = dependencies[moduleName];
    var bestModule = DataStore.getModuleDefinition(moduleName, moduleTag);

    var foundEvent;
    var fallbackEvent;
    var action;
    for (var eventName in bestModule.events[PUBLIC_KEY]) {
        action = bestModule.events[PUBLIC_KEY][eventName];
        if (eventName === handlerName) {
            foundEvent = action;
            break;
        }
        else if (eventName === MISS_KEY || eventName === ANY_KEY) {
            fallbackEvent = action;
        }
    }

    var handler = foundEvent || fallbackEvent;
    if (!handler) {
        throw new Error('Unknown behavior handler `' + name + '`');
    }
    return handler;
};

module.exports = Events;
<|endoftext|>


<commit_before>/* @flow */
import { connect } from 'react-redux';

import React, { PureComponent } from 'react';
import { Platform, StatusBar, View } from 'react-native';
import Color from 'color';

import type { Dimensions, StatusBarStyle, ThemeType } from '../types';
import { getSession, getSettings, getTitleBackgroundColor, getTitleTextColor } from '../selectors';
import getStatusBarStyle from '../utils/getStatusBarStyle';
import getStatusBarColor from '../utils/getStatusBarColor';

type Props = {
  barStyle?: StatusBarStyle,
  hidden: boolean,
  theme: ThemeType,
  backgroundColor: string,
  safeAreaInsets: Dimensions,
  textColor: string,
  orientation: string,
};

/**
 * Controls the status bar settings depending on platform
 * and current navigation position.
 * If narrowed to a stream or topic the color of the status bar
 * matches that of the stream.
 *
 * @prop [narrow] - Currently active narrow.
 */
class ZulipStatusBar extends PureComponent<Props> {
  props: Props;

  static defaultProps = {
    hidden: false,
  };

  render() {
    const {
      theme,
      backgroundColor,
      textColor,
      hidden,
      barStyle,
      safeAreaInsets,
      orientation,
    } = this.props;
    const style = { height: hidden ? 0 : safeAreaInsets.top, backgroundColor };
    const statusBarStyle = !barStyle
      ? getStatusBarStyle(backgroundColor, textColor, theme)
      : barStyle;
    const statusBarColor = getStatusBarColor(backgroundColor, theme);
    return (
      orientation === 'PORTRAIT' && (
        <View style={style}>
          <StatusBar
            animated
            showHideTransition="slide"
            hidden={hidden && Platform.OS !== 'android'}
            backgroundColor={Color(statusBarColor).darken(0.1)}
            barStyle={statusBarStyle}
          />
        </View>
      )
    );
  }
}

export default connect((state, props) => ({
  safeAreaInsets: getSession(state).safeAreaInsets,
  theme: getSettings(state).theme,
  // Prettier messes up the ternary so the linter complains.
  // prettier-ignore
  backgroundColor: !props.backgroundColor
    ? getTitleBackgroundColor(props.narrow)(state)
    : props.backgroundColor,
  textColor: getTitleTextColor(props.narrow)(state),
  orientation: getSession(state).orientation,
}))(ZulipStatusBar);
<commit_msg>status bar: Simplify an overcomplicated ternary.<commit_after>/* @flow */
import { connect } from 'react-redux';

import React, { PureComponent } from 'react';
import { Platform, StatusBar, View } from 'react-native';
import Color from 'color';

import type { Dimensions, StatusBarStyle, ThemeType } from '../types';
import { getSession, getSettings, getTitleBackgroundColor, getTitleTextColor } from '../selectors';
import getStatusBarStyle from '../utils/getStatusBarStyle';
import getStatusBarColor from '../utils/getStatusBarColor';

type Props = {
  barStyle?: StatusBarStyle,
  hidden: boolean,
  theme: ThemeType,
  backgroundColor: string,
  safeAreaInsets: Dimensions,
  textColor: string,
  orientation: string,
};

/**
 * Controls the status bar settings depending on platform
 * and current navigation position.
 * If narrowed to a stream or topic the color of the status bar
 * matches that of the stream.
 *
 * @prop [narrow] - Currently active narrow.
 */
class ZulipStatusBar extends PureComponent<Props> {
  props: Props;

  static defaultProps = {
    hidden: false,
  };

  render() {
    const {
      theme,
      backgroundColor,
      textColor,
      hidden,
      barStyle,
      safeAreaInsets,
      orientation,
    } = this.props;
    const style = { height: hidden ? 0 : safeAreaInsets.top, backgroundColor };
    const statusBarStyle = !barStyle
      ? getStatusBarStyle(backgroundColor, textColor, theme)
      : barStyle;
    const statusBarColor = getStatusBarColor(backgroundColor, theme);
    return (
      orientation === 'PORTRAIT' && (
        <View style={style}>
          <StatusBar
            animated
            showHideTransition="slide"
            hidden={hidden && Platform.OS !== 'android'}
            backgroundColor={Color(statusBarColor).darken(0.1)}
            barStyle={statusBarStyle}
          />
        </View>
      )
    );
  }
}

export default connect((state, props) => ({
  safeAreaInsets: getSession(state).safeAreaInsets,
  theme: getSettings(state).theme,
  backgroundColor: props.backgroundColor || getTitleBackgroundColor(props.narrow)(state),
  textColor: getTitleTextColor(props.narrow)(state),
  orientation: getSession(state).orientation,
}))(ZulipStatusBar);
<|endoftext|>


<commit_before>/***************************************************************************************************
 * WINGS.AJAX  --  contains: functions used to process ajax requests
 **************************************************************************************************/

// Create module namespace
wingS.namespace("ajax");

/**
 * Requests any available component updates from the server.
 */
wingS.ajax.requestUpdates = function() {
    wingS.request.sendEvent(null, false, true);
};

/**
 * Submits the given form by means of an asynchronous request.
 * @param {Object} form - the form to be submitted
 */
wingS.ajax.submitForm = function(form) {
    var enc = "multipart/form-data";
    if (form.enctype == enc || form.encoding == enc) {
        YAHOO.util.Connect.setForm(form, true);
    } else {
        YAHOO.util.Connect.setForm(form);
    }

    wingS.ajax.sendRequest(form.method.toUpperCase(), wingS.util.getUpdateResource());
};

/**
 * Invokes an asynchronous request with the given parameters.
 * @param {String} method - the HTTP transaction method
 * @param {String} uri - the fully qualified path of resource
 * @param {String} postData - the POST body (in case of "POST")
 */
wingS.ajax.sendRequest = function(method, uri, postData) {
    wingS.ajax.requestIsActive = true;
    // the activity indicator is shown with a slight delay, as not to
    // make the end user nervous and shorten the felt request time.
    var responded = false;
    window.setTimeout(function () {if (!responded) {wingS.ajax.setActivityIndicatorsVisible(true);}},750);

    // Since some browsers cache GET requests via the XMLHttpRequest
    // object, an additional parameter called "_xhrID" will be added
    // to the request URI with a unique numeric value.
    if (method.toUpperCase() == "GET") {
        uri += ((uri.indexOf("?")>-1) ? "&" : "?");
        uri += "_xhrID=" + new Date().getTime();
    }

  var callbackProxy = {
        success : function(request) { responded = true; wingS.ajax.callbackObject.success(request); },
        failure : function(request) { responded = true; wingS.ajax.callbackObject.failure(request); },
        upload  : function(request) { responded = true; wingS.ajax.callbackObject.upload(request); }
    }

    wingS.ajax.connectionObject =
        YAHOO.util.Connect.asyncRequest(method, uri, callbackProxy, postData);
};

/**
 * Aborts the currently active request, in case there is any.
 * @return {boolean} true if successfully aborted, false otherwise
 */
wingS.ajax.abortRequest = function() {
    if (YAHOO.util.Connect.isCallInProgress(wingS.ajax.connectionObject)) {
        return YAHOO.util.Connect.abort(wingS.ajax.connectionObject, wingS.ajax.callbackObject);
    }
    return false;
};

/**
 * Callback method which processes any request failures.
 * @param {Object} request - the request to process
 */
wingS.ajax.processRequestFailure = function(request) {
    if (wingS.global.debugMode)
        wingS.ajax.updateDebugView(request);

    if ("console" in window && window.console)
        console.error("Error occured while processing request %o", request);

    // Reset activity indicators and active flag
    wingS.ajax.setActivityIndicatorsVisible(false);
    wingS.ajax.requestIsActive = false;

    // Clear enqueued request
    wingS.ajax.requestQueue = new Array();

    if (request.status == -1) {
        // Transaction has been aborted --> OK!
    } else if (request.status == 0) {
        // Happens in case of a communication
        // failure, i.e if the server has mean-
        // while been shut down --> do reload!
        wingS.request.reloadFrame();
    }
};

/**
 * Callback method which processes any successful request.
 * @param {Object} request - the request to process
 */
wingS.ajax.processRequestSuccess = function(request) {
    if (wingS.global.debugMode)
        wingS.ajax.updateDebugView(request);

    // Get the received XML response
    var xmlDoc = request.responseXML;
    if (xmlDoc == null) {
        // In case we don't get any XML there is nothing more
        // what we can do here; the only thing --> do reload!
        wingS.request.reloadFrame();
        // Better?: wingS.ajax.processRequestFailure(request);
        return;
    }

    // Get the document's root element
    var xmlRoot = xmlDoc.getElementsByTagName("updates")[0];
    if (xmlRoot == null) {
        // Workaround to prevent IE from showing JS errors
        // if session has meanwhile timed out --> do reload!
        wingS.request.reloadFrame();
        // Better?: wingS.ajax.processRequestFailure(request);
        return;
    }

    // Process each incremental update
    var updates = xmlRoot.getElementsByTagName("update");
    if (updates.length > 0) {
        for (var i = 0; i < updates.length; i++) {
            try {
                // Dispatch update to the corresponding
                // handler function simply by evaluation
                window.eval(updates[i].firstChild.data);
            } catch(e) {
                var errorMsg = "Failure while processing the reponse of an AJAX request!\n" +
                               "**********************************************\n\n" +
                               "Error Message: " + e.message + "!\n\n" +
                               "The error occurred while evaluating the following JS code:\n" +
                               updates[i].firstChild.data;

                if ("console" in window && window.console)
                    console.error("%o", errorMsg);
                alert(errorMsg);
            }
        }
    }

    // So far we applied all updates. If there are
    // no headers downloaded asynchronously at this
    // stage, we are finished with this request and
    // ready to process the next one from the queue.
    // Otherwise there will be a callback when all
    // header downloads and header callbacks ended.
    if (wingS.global.asyncHeaderQueue.length == 0) {
        // Reset activity indicators and active flag
        wingS.ajax.setActivityIndicatorsVisible(false);
        wingS.ajax.requestIsActive = false;

        // Send the next enqueued request
        wingS.ajax.dequeueNextRequest();
    }
};

/**
 * Enqueues the given request if another one is still in action.
 * @param {Function} send - the function to send the request with
 * @param {Array} args - the arguments needed by the send function
 * @return {boolean} true, if request was enqueued, false otherwise
 */
wingS.ajax.enqueueThisRequest = function(send, args) {
    if (wingS.ajax.requestIsActive) {
        wingS.ajax.requestQueue.push( {"send" : send, "args" : args} );
        return true;
    }
    return false;
};

/**
 * Grabs the next available request from the queue and invokes it.
 */
wingS.ajax.dequeueNextRequest = function() {
    if (wingS.ajax.requestQueue.length > 0) {
        var request = wingS.ajax.requestQueue.shift();
        var args = request.args;
        request.send(args[0], args[1], args[2], args[3], args[4]);
    }
};

/**
 * Makes the activity indicators either visible or invisible.
 * @param {boolean} visible - true to set indicators visible
 */
wingS.ajax.setActivityIndicatorsVisible = function(visible) {
    if (wingS.global.updateCursor.enabled) {
        wingS.ajax.activityCursor.setVisible(visible);
        // An alternative to the cursor might be something like
        // if (visible) document.body.style.cursor = "progress";
        // else document.body.style.cursor = "default";
    }
    var indicator = document.getElementById("ajaxActivityIndicator");
    if (indicator != null) {
        if (visible) indicator.style.visibility = "visible";
        else indicator.style.visibility = "hidden";
    }
};

/**
 * Initializes the appearance of the activity cursor.
 */
wingS.ajax.ActivityCursor = function() {
    this.dx = wingS.global.updateCursor.dx;
    this.dy = wingS.global.updateCursor.dy;
    this.div = document.createElement("div");
    this.div.style.position = "absolute";
    this.div.style.zIndex = "9999";
    this.div.style.display = "none";
    this.div.innerHTML = "";
    document.body.insertBefore(this.div, document.body.firstChild);
    document.onmousemove = this.followMouse.bind(this);
};

/**
 * Calculates the new position of the activity cursor.
 * @param {Object} event - the event object
 */
wingS.ajax.ActivityCursor.prototype.followMouse = function(event) {
    event = wingS.event.getEvent(event);
    var target = wingS.event.getTarget(event);

    var posX = 0;
    var posY = 0;
    if (event.pageX || event.pageY) {
        posX = event.pageX;
        posY = event.pageY;
    } else if (event.clientX || event.clientY) {
        posX = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        posY = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    if (target.nodeName == "OPTION" && !wingS.util.checkUserAgent('msie')) {
        posX += wingS.util.absLeft(target);
        posY += wingS.util.absTop(target.parentNode) + 18;
    }

    var newX = posX + this.dx;
    if (newX > 0 && newX < (YAHOO.util.Dom.getDocumentWidth() - wingS.global.updateCursor.width - 2)) {
        this.div.style.left = newX + "px";
    }
    var newY = posY + this.dy;
    if (newY > 0 && newY < (YAHOO.util.Dom.getDocumentHeight() - wingS.global.updateCursor.height - 2)) {
        this.div.style.top = newY + "px";
    }
};

/**
 * Sets the activity cursor either visible or invisible.
 * @param {boolean} visible - true to set cursor visible
 */
wingS.ajax.ActivityCursor.prototype.setVisible = function(visible) {
    if (visible) this.div.style.display = "block";
    else this.div.style.display = "none";
};

/**
 * Prints some debug information about the given AJAX request.
 * @param {Object} request - the request object to debug
 */
wingS.ajax.updateDebugView = function(request) {
    var debugArea = document.getElementById("ajaxDebugView");
    if (debugArea == null) {
        var debugHtmlCode =
            '
\n' +
            '  AJAX DEBUG VIEW:  XML RESPONSE\n' +
            '
\n' +
            '<textarea readonly="readonly" style="width:100%; height:190px;\n' +
            '  border-top:1px dashed #000000; border-bottom:1px dashed #000000;\n' +
            '  font:11px monospace; padding:10px;"></textarea>\n';
        debugArea = document.createElement("div");
        debugArea.id = "ajaxDebugView";
        debugArea.style.display = "none";
        debugArea.innerHTML = debugHtmlCode;
        document.body.appendChild(debugArea);
    }

    var output = "";
    if (request != null) {
        output += "Status: " + request.statusText + " (";
        output += request.status + ") | TID: " + request.tId + "\n";
        var response = "";
        if (request.status > 0) {
            output += "\n" + request.getAllResponseHeaders + "\n";
            response = request.responseText;
            if (response == null) {
                response = (new XMLSerializer()).serializeToString(request.responseXML);
            }
            output += response;
        }
        debugArea.getElementsByTagName("SPAN")[0].innerHTML = "| " + response.length + " chars";
    } else {
        output += "Currently there is no XML response available..." +
                  "\nProbably no asynchronous request has been sent.";
    }
    debugArea.getElementsByTagName("TEXTAREA")[0].value = output;
};

/**
 * Returns the current visibility state of the debug view.
 * @return {boolean} true if view is visible, false otherwise
 */
wingS.ajax.isDebugViewVisible = function() {
    var debugArea = document.getElementById("ajaxDebugView");
    if (debugArea != null && debugArea.style.display != "none") {
        return true;
    }
    return false;
};

/**
 * Makes the debug view either visible or invisible. Furthermore
 * the wingS.global.debugMode flag ist set accordingly.
 * @param {boolean} visible - true to set debug view visible
 */
wingS.ajax.setDebugViewVisible = function(visible) {
    var debugArea = document.getElementById("ajaxDebugView");
    if (debugArea != null) {
        if (visible) {
            wingS.global.debugMode = true;
            debugArea.style.display = "block";
        } else {
            wingS.global.debugMode = false;
            debugArea.style.display = "none";
        }
    } else {
        wingS.ajax.updateDebugView();
        wingS.ajax.setDebugViewVisible(true);
    }
};

/**
 * Toggles the visibility of the debug view.
 */
wingS.ajax.toggleDebugView = function() {
    if (wingS.ajax.isDebugViewVisible())
        wingS.ajax.setDebugViewVisible(false);
    else wingS.ajax.setDebugViewVisible(true);
};

<commit_msg>o better error logging<commit_after>/***************************************************************************************************
 * WINGS.AJAX  --  contains: functions used to process ajax requests
 **************************************************************************************************/

// Create module namespace
wingS.namespace("ajax");

/**
 * Requests any available component updates from the server.
 */
wingS.ajax.requestUpdates = function() {
    wingS.request.sendEvent(null, false, true);
};

/**
 * Submits the given form by means of an asynchronous request.
 * @param {Object} form - the form to be submitted
 */
wingS.ajax.submitForm = function(form) {
    var enc = "multipart/form-data";
    if (form.enctype == enc || form.encoding == enc) {
        YAHOO.util.Connect.setForm(form, true);
    } else {
        YAHOO.util.Connect.setForm(form);
    }

    wingS.ajax.sendRequest(form.method.toUpperCase(), wingS.util.getUpdateResource());
};

/**
 * Invokes an asynchronous request with the given parameters.
 * @param {String} method - the HTTP transaction method
 * @param {String} uri - the fully qualified path of resource
 * @param {String} postData - the POST body (in case of "POST")
 */
wingS.ajax.sendRequest = function(method, uri, postData) {
    wingS.ajax.requestIsActive = true;
    // the activity indicator is shown with a slight delay, as not to
    // make the end user nervous and shorten the felt request time.
    var responded = false;
    window.setTimeout(function () {if (!responded) {wingS.ajax.setActivityIndicatorsVisible(true);}},750);

    // Since some browsers cache GET requests via the XMLHttpRequest
    // object, an additional parameter called "_xhrID" will be added
    // to the request URI with a unique numeric value.
    if (method.toUpperCase() == "GET") {
        uri += ((uri.indexOf("?")>-1) ? "&" : "?");
        uri += "_xhrID=" + new Date().getTime();
    }

  var callbackProxy = {
        success : function(request) { responded = true; wingS.ajax.callbackObject.success(request); },
        failure : function(request) { responded = true; wingS.ajax.callbackObject.failure(request); },
        upload  : function(request) { responded = true; wingS.ajax.callbackObject.upload(request); }
    }

    wingS.ajax.connectionObject =
        YAHOO.util.Connect.asyncRequest(method, uri, callbackProxy, postData);
};

/**
 * Aborts the currently active request, in case there is any.
 * @return {boolean} true if successfully aborted, false otherwise
 */
wingS.ajax.abortRequest = function() {
    if (YAHOO.util.Connect.isCallInProgress(wingS.ajax.connectionObject)) {
        return YAHOO.util.Connect.abort(wingS.ajax.connectionObject, wingS.ajax.callbackObject);
    }
    return false;
};

/**
 * Callback method which processes any request failures.
 * @param {Object} request - the request to process
 */
wingS.ajax.processRequestFailure = function(request) {
    if (wingS.global.debugMode)
        wingS.ajax.updateDebugView(request);

    if ("console" in window && window.console)
        console.error("Error occured while processing request %o", request);

    // Reset activity indicators and active flag
    wingS.ajax.setActivityIndicatorsVisible(false);
    wingS.ajax.requestIsActive = false;

    // Clear enqueued request
    wingS.ajax.requestQueue = new Array();

    if (request.status == -1) {
        // Transaction has been aborted --> OK!
    } else if (request.status == 0) {
        // Happens in case of a communication
        // failure, i.e if the server has mean-
        // while been shut down --> do reload!
        wingS.request.reloadFrame();
    }
};

/**
 * Callback method which processes any successful request.
 * @param {Object} request - the request to process
 */
wingS.ajax.processRequestSuccess = function(request) {
    if (wingS.global.debugMode)
        wingS.ajax.updateDebugView(request);

    // Get the received XML response
    var xmlDoc = request.responseXML;
    if (xmlDoc == null) {
        // In case we don't get any XML there is nothing more
        // what we can do here; the only thing --> do reload!
        wingS.request.reloadFrame();
        // Better?: wingS.ajax.processRequestFailure(request);
        return;
    }

    // Get the document's root element
    var xmlRoot = xmlDoc.getElementsByTagName("updates")[0];
    if (xmlRoot == null) {
        // Workaround to prevent IE from showing JS errors
        // if session has meanwhile timed out --> do reload!
        wingS.request.reloadFrame();
        // Better?: wingS.ajax.processRequestFailure(request);
        return;
    }

    // Process each incremental update
    var updates = xmlRoot.getElementsByTagName("update");
    if (updates.length > 0) {
        for (var i = 0; i < updates.length; i++) {
            try {
                // Dispatch update to the corresponding
                // handler function simply by evaluation
                window.eval(updates[i].firstChild.data);
            } catch(e) {
                var errorMsg = "Failure while processing the reponse of an AJAX request!\n" +
                               "**********************************************\n\n" +
                               "Error Message: " + e.message + "!\n\n" +
                               "The error occurred while evaluating the following JS code:\n" +
                               updates[i].firstChild.data;

                if ("console" in window && window.console)
                    console.error("message: %o\nexception: %o\nupdate: %o", e.message, e, updates[i].firstChild.data);
                alert(errorMsg);
            }
        }
    }

    // So far we applied all updates. If there are
    // no headers downloaded asynchronously at this
    // stage, we are finished with this request and
    // ready to process the next one from the queue.
    // Otherwise there will be a callback when all
    // header downloads and header callbacks ended.
    if (wingS.global.asyncHeaderQueue.length == 0) {
        // Reset activity indicators and active flag
        wingS.ajax.setActivityIndicatorsVisible(false);
        wingS.ajax.requestIsActive = false;

        // Send the next enqueued request
        wingS.ajax.dequeueNextRequest();
    }
};

/**
 * Enqueues the given request if another one is still in action.
 * @param {Function} send - the function to send the request with
 * @param {Array} args - the arguments needed by the send function
 * @return {boolean} true, if request was enqueued, false otherwise
 */
wingS.ajax.enqueueThisRequest = function(send, args) {
    if (wingS.ajax.requestIsActive) {
        wingS.ajax.requestQueue.push( {"send" : send, "args" : args} );
        return true;
    }
    return false;
};

/**
 * Grabs the next available request from the queue and invokes it.
 */
wingS.ajax.dequeueNextRequest = function() {
    if (wingS.ajax.requestQueue.length > 0) {
        var request = wingS.ajax.requestQueue.shift();
        var args = request.args;
        request.send(args[0], args[1], args[2], args[3], args[4]);
    }
};

/**
 * Makes the activity indicators either visible or invisible.
 * @param {boolean} visible - true to set indicators visible
 */
wingS.ajax.setActivityIndicatorsVisible = function(visible) {
    if (wingS.global.updateCursor.enabled) {
        wingS.ajax.activityCursor.setVisible(visible);
        // An alternative to the cursor might be something like
        // if (visible) document.body.style.cursor = "progress";
        // else document.body.style.cursor = "default";
    }
    var indicator = document.getElementById("ajaxActivityIndicator");
    if (indicator != null) {
        if (visible) indicator.style.visibility = "visible";
        else indicator.style.visibility = "hidden";
    }
};

/**
 * Initializes the appearance of the activity cursor.
 */
wingS.ajax.ActivityCursor = function() {
    this.dx = wingS.global.updateCursor.dx;
    this.dy = wingS.global.updateCursor.dy;
    this.div = document.createElement("div");
    this.div.style.position = "absolute";
    this.div.style.zIndex = "9999";
    this.div.style.display = "none";
    this.div.innerHTML = "";
    document.body.insertBefore(this.div, document.body.firstChild);
    document.onmousemove = this.followMouse.bind(this);
};

/**
 * Calculates the new position of the activity cursor.
 * @param {Object} event - the event object
 */
wingS.ajax.ActivityCursor.prototype.followMouse = function(event) {
    event = wingS.event.getEvent(event);
    var target = wingS.event.getTarget(event);

    var posX = 0;
    var posY = 0;
    if (event.pageX || event.pageY) {
        posX = event.pageX;
        posY = event.pageY;
    } else if (event.clientX || event.clientY) {
        posX = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        posY = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    if (target.nodeName == "OPTION" && !wingS.util.checkUserAgent('msie')) {
        posX += wingS.util.absLeft(target);
        posY += wingS.util.absTop(target.parentNode) + 18;
    }

    var newX = posX + this.dx;
    if (newX > 0 && newX < (YAHOO.util.Dom.getDocumentWidth() - wingS.global.updateCursor.width - 2)) {
        this.div.style.left = newX + "px";
    }
    var newY = posY + this.dy;
    if (newY > 0 && newY < (YAHOO.util.Dom.getDocumentHeight() - wingS.global.updateCursor.height - 2)) {
        this.div.style.top = newY + "px";
    }
};

/**
 * Sets the activity cursor either visible or invisible.
 * @param {boolean} visible - true to set cursor visible
 */
wingS.ajax.ActivityCursor.prototype.setVisible = function(visible) {
    if (visible) this.div.style.display = "block";
    else this.div.style.display = "none";
};

/**
 * Prints some debug information about the given AJAX request.
 * @param {Object} request - the request object to debug
 */
wingS.ajax.updateDebugView = function(request) {
    var debugArea = document.getElementById("ajaxDebugView");
    if (debugArea == null) {
        var debugHtmlCode =
            '
\n' +
            '  AJAX DEBUG VIEW:  XML RESPONSE\n' +
            '
\n' +
            '<textarea readonly="readonly" style="width:100%; height:190px;\n' +
            '  border-top:1px dashed #000000; border-bottom:1px dashed #000000;\n' +
            '  font:11px monospace; padding:10px;"></textarea>\n';
        debugArea = document.createElement("div");
        debugArea.id = "ajaxDebugView";
        debugArea.style.display = "none";
        debugArea.innerHTML = debugHtmlCode;
        document.body.appendChild(debugArea);
    }

    var output = "";
    if (request != null) {
        output += "Status: " + request.statusText + " (";
        output += request.status + ") | TID: " + request.tId + "\n";
        var response = "";
        if (request.status > 0) {
            output += "\n" + request.getAllResponseHeaders + "\n";
            response = request.responseText;
            if (response == null) {
                response = (new XMLSerializer()).serializeToString(request.responseXML);
            }
            output += response;
        }
        debugArea.getElementsByTagName("SPAN")[0].innerHTML = "| " + response.length + " chars";
    } else {
        output += "Currently there is no XML response available..." +
                  "\nProbably no asynchronous request has been sent.";
    }
    debugArea.getElementsByTagName("TEXTAREA")[0].value = output;
};

/**
 * Returns the current visibility state of the debug view.
 * @return {boolean} true if view is visible, false otherwise
 */
wingS.ajax.isDebugViewVisible = function() {
    var debugArea = document.getElementById("ajaxDebugView");
    if (debugArea != null && debugArea.style.display != "none") {
        return true;
    }
    return false;
};

/**
 * Makes the debug view either visible or invisible. Furthermore
 * the wingS.global.debugMode flag ist set accordingly.
 * @param {boolean} visible - true to set debug view visible
 */
wingS.ajax.setDebugViewVisible = function(visible) {
    var debugArea = document.getElementById("ajaxDebugView");
    if (debugArea != null) {
        if (visible) {
            wingS.global.debugMode = true;
            debugArea.style.display = "block";
        } else {
            wingS.global.debugMode = false;
            debugArea.style.display = "none";
        }
    } else {
        wingS.ajax.updateDebugView();
        wingS.ajax.setDebugViewVisible(true);
    }
};

/**
 * Toggles the visibility of the debug view.
 */
wingS.ajax.toggleDebugView = function() {
    if (wingS.ajax.isDebugViewVisible())
        wingS.ajax.setDebugViewVisible(false);
    else wingS.ajax.setDebugViewVisible(true);
};

<|endoftext|>


<commit_before>// Bola (JS Object)
var bola = {
	raio: 10,
	x: null,
	y: null,
	baixo: false,
	angulo: 5,
	velocidade: 10,
	resetX : null,
	resetY : null,
	countFail : null,
	pontuacao:null,

	init : function(width, y){//largura do canvas e y do jogador
		bola.resetX = bola.x = width / 2;
		bola.resetY = bola.y = y - bola.raio;
		bola.countFail = 0;
		bola.pontuacao = 0;
	},
	render : function(root){
		root.fillStyle = "red";
		root.beginPath();
		root.arc(bola.x, bola.y, bola.raio, 0, Math.PI*2, true);
		root.closePath();
		root.fill();
	},
	atualizar : function(y, x, w, width, height, polling){
		// Movimenta����o bola
		if(bola.baixo){
			bola.colisaoJogador(y, x, w);
			bola.y += bola.velocidade;

		}
		else {
			bola.y -= bola.velocidade;
		}
		// Colis��o paredes
		if(bola.x - bola.raio <= 0 || bola.x + bola.raio >= width){
			bola.angulo *= -1;
		}
		//Colisao bloco
		bola.colisaoBloco();

		//Colisao chao
		bola.colisaoChao(height, polling);
		//Altera o angulo da bola
		bola.x += bola.angulo;
	},
	clear : function()
	{
		bola.x = bola.resetX;
		bola.y = bola.resetY;
		bola.baixo = false;
		bola.angulo = 5;
		bola.velocidade = 10;

	},
	colisaoJogador : function(y, x, w){
		// Colis��o jogador
		if((bola.y + bola.raio >= y) &&
			(bola.x >= x) &&
			(bola.x <= x + w)){
			bola.baixo = false;
		//	console.log("Colisao jogador");
		}
	},
	colisaoBloco : function(){
		//Colisao bloco
		if(bola.y - bola.raio <= 100 && bola.y >= 0){
			var linha  = Math.floor(((bola.y - bola.raio)-20)/20);
			var coluna = Math.floor((bola.x - bola.raio)/60);
			console.log("linha: " + linha + "coluna:" + coluna);

			if(coluna >= 0 && linha >= 0){
				if(bloco.blocos[linha][coluna] == 0){
					bola.baixo = !bola.baixo;
					bloco.blocos[linha][coluna] = 1;
				}

				console.log("Colisao bloco");
				bola.pontuacao++;
				console.log(bola.pontuacao);

			}else{
				bola.baixo = !bola.baixo;
			}
		}
	},

	colisaoChao : function(height, polling){
		//Colisao chao
		if(bola.y + bola.raio >= height){
			bola.baixo = !bola.baixo;
			console.log("Colisao chao");
			bola.clear(); // A bola retorna a posicao inicial
			jogador.clear(); // O jogador retorna a posicao inicial
			bola.countFail++;
			console.log(bola.countFail);
			if(bola.countFail == 4){
				jogador.derrota = true;
				clearInterval(polling);
			}
		}
	}
};<commit_msg>Corrigindo bug pontuacao<commit_after>// Bola (JS Object)
var bola = {
	raio: 10,
	x: null,
	y: null,
	baixo: false,
	angulo: 5,
	velocidade: 10,
	resetX : null,
	resetY : null,
	countFail : null,
	pontuacao:null,

	init : function(width, y){//largura do canvas e y do jogador
		bola.resetX = bola.x = width / 2;
		bola.resetY = bola.y = y - bola.raio;
		bola.countFail = 0;
		bola.pontuacao = 0;
	},
	render : function(root){
		root.fillStyle = "red";
		root.beginPath();
		root.arc(bola.x, bola.y, bola.raio, 0, Math.PI*2, true);
		root.closePath();
		root.fill();
	},
	atualizar : function(y, x, w, width, height, polling){
		// Movimentar a bola
		if(bola.baixo){
			bola.colisaoJogador(y, x, w);
			bola.y += bola.velocidade;

		}
		else {
			bola.y -= bola.velocidade;
		}
		// Colisao paredes
		if(bola.x - bola.raio <= 0 || bola.x + bola.raio >= width){
			bola.angulo *= -1;
		}
		//Colisao bloco
		bola.colisaoBloco();

		//Colisao chao
		bola.colisaoChao(height, polling);
		//Altera o angulo da bola
		bola.x += bola.angulo;
	},
	clear : function()
	{
		bola.x = bola.resetX;
		bola.y = bola.resetY;
		bola.baixo = false;
		bola.angulo = 5;
		bola.velocidade = 10;

	},
	colisaoJogador : function(y, x, w){
		// Colis��o jogador
		if((bola.y + bola.raio >= y) &&
			(bola.x >= x) &&
			(bola.x <= x + w)){
			bola.baixo = false;
		//	console.log("Colisao jogador");
		}
	},
	colisaoBloco : function(){
		//Colisao bloco
		if(bola.y - bola.raio <= 100 && bola.y >= 0){
			var linha  = Math.floor(((bola.y - bola.raio)-20)/20);
			var coluna = Math.floor((bola.x - bola.raio)/60);
			console.log("linha: " + linha + "coluna:" + coluna);

			if(coluna >= 0 && linha >= 0){
				if(bloco.blocos[linha][coluna] == 0){
					bola.baixo = !bola.baixo;
					bloco.blocos[linha][coluna] = 1;
					bola.pontuacao++;
					console.log(bola.pontuacao);
				}
				console.log("Colisao bloco");
			}else{
				bola.baixo = !bola.baixo;
			}
		}
	},

	colisaoChao : function(height, polling){
		//Colisao chao
		if(bola.y + bola.raio >= height){
			bola.baixo = !bola.baixo;
			console.log("Colisao chao");
			bola.clear(); // A bola retorna a posicao inicial
			jogador.clear(); // O jogador retorna a posicao inicial
			bola.countFail++;
			console.log(bola.countFail);
			if(bola.countFail == 4){
				jogador.derrota = true;
				clearInterval(polling);
			}
		}
	}
};<|endoftext|>


<commit_before>var os = require('os'),
	tmpDir = os.tmpdir();
module.exports = function multipart(req, res, next){
	if(!req.files){
		req.files = {};
	}
	if(!req.body){
		req.body = {};
	}

	if(req.busboy){
		req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype){
			var filePath = path.join(tmpDir, filename || 'temp.tmp'),
				fileData;

			if(!filename){
				return file.emit('end');
			}

			file.on('limit', function(){
				var err = new Error('File size too large');
				err.status = 413;
				next(err);
			});

			file.on('end', function(){
				req.files[fieldname] = {
					type: mimetype,
					encoding: encoding,
					name: filename,
					path: filePath
				};
			});

			file.pipe(fs.createWriteStream(filePath));
		});
		req.busboy.on('field', function(fieldname, val) {
			req.body[fieldname] = val;
		});
		req.busboy.on('end', function(){
			next();
		});
		req.pipe(req.busboy);
	}else{
		next();
	}
};<commit_msg>Remove unused variable<commit_after>var os = require('os'),
	tmpDir = os.tmpdir();
module.exports = function multipart(req, res, next){
	if(!req.files){
		req.files = {};
	}
	if(!req.body){
		req.body = {};
	}

	if(req.busboy){
		req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype){
			var filePath = path.join(tmpDir, filename || 'temp.tmp');

			if(!filename){
				return file.emit('end');
			}

			file.on('limit', function(){
				var err = new Error('File size too large');
				err.status = 413;
				next(err);
			});

			file.on('end', function(){
				req.files[fieldname] = {
					type: mimetype,
					encoding: encoding,
					name: filename,
					path: filePath
				};
			});

			file.pipe(fs.createWriteStream(filePath));
		});
		req.busboy.on('field', function(fieldname, val) {
			req.body[fieldname] = val;
		});
		req.busboy.on('end', function(){
			next();
		});
		req.pipe(req.busboy);
	}else{
		next();
	}
};<|endoftext|>


<commit_before>/**
 * Bookmarks.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.dom.Bookmarks',
  [
    'tinymce.core.Env',
    'tinymce.core.caret.CaretBookmark',
    'tinymce.core.caret.CaretContainer',
    'tinymce.core.caret.CaretPosition',
    'tinymce.core.dom.NodeType',
    'tinymce.core.selection.RangeNodes',
    'tinymce.core.text.Zwsp',
    'tinymce.core.util.Tools'
  ],
  function (Env, CaretBookmark, CaretContainer, CaretPosition, NodeType, RangeNodes, Zwsp, Tools) {
    var isContentEditableFalse = NodeType.isContentEditableFalse;

    var getNormalizedTextOffset = function (container, offset) {
      var node, trimmedOffset;

      trimmedOffset = Zwsp.trim(container.data.slice(0, offset)).length;
      for (node = container.previousSibling; node && node.nodeType === 3; node = node.previousSibling) {
        trimmedOffset += Zwsp.trim(node.data).length;
      }

      return trimmedOffset;
    };

    var trimEmptyTextNode = function (node) {
      if (NodeType.isText(node) && node.data.length === 0) {
        node.parentNode.removeChild(node);
      }
    };

    var getBookmark = function (selection, type, normalized) {
      var rng, rng2, id, collapsed, name, element, chr = '', styles;
      var dom = selection.dom;

      var findIndex = function (name, element) {
        var count = 0;

        Tools.each(dom.select(name), function (node) {
          if (node.getAttribute('data-mce-bogus') === 'all') {
            return;
          }

          if (node == element) {
            return false;
          }

          count++;
        });

        return count;
      };

      var normalizeTableCellSelection = function (rng) {
        var moveEndPoint = function (start) {
          var container, offset, childNodes, prefix = start ? 'start' : 'end';

          container = rng[prefix + 'Container'];
          offset = rng[prefix + 'Offset'];

          if (container.nodeType == 1 && container.nodeName == "TR") {
            childNodes = container.childNodes;
            container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
            if (container) {
              offset = start ? 0 : container.childNodes.length;
              rng['set' + (start ? 'Start' : 'End')](container, offset);
            }
          }
        };

        moveEndPoint(true);
        moveEndPoint();

        return rng;
      };

      var getLocation = function (rng) {
        var root = dom.getRoot(), bookmark = {};

        var getPoint = function (rng, start) {
          var container = rng[start ? 'startContainer' : 'endContainer'],
            offset = rng[start ? 'startOffset' : 'endOffset'], point = [], childNodes, after = 0;

          if (container.nodeType === 3) {
            point.push(normalized ? getNormalizedTextOffset(container, offset) : offset);
          } else {
            childNodes = container.childNodes;

            if (offset >= childNodes.length && childNodes.length) {
              after = 1;
              offset = Math.max(0, childNodes.length - 1);
            }

            point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
          }

          for (; container && container != root; container = container.parentNode) {
            point.push(dom.nodeIndex(container, normalized));
          }

          return point;
        };

        bookmark.start = getPoint(rng, true);

        if (!selection.isCollapsed()) {
          bookmark.end = getPoint(rng);
        }

        return bookmark;
      };

      var findAdjacentContentEditableFalseElm = function (rng) {
        var findSibling = function (node, offset) {
          var sibling;

          if (NodeType.isElement(node)) {
            node = RangeNodes.getNode(node, offset);
            if (isContentEditableFalse(node)) {
              return node;
            }
          }

          if (CaretContainer.isCaretContainer(node)) {
            if (NodeType.isText(node) && CaretContainer.isCaretContainerBlock(node)) {
              node = node.parentNode;
            }

            sibling = node.previousSibling;
            if (isContentEditableFalse(sibling)) {
              return sibling;
            }

            sibling = node.nextSibling;
            if (isContentEditableFalse(sibling)) {
              return sibling;
            }
          }
        };

        return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
      };

      if (type == 2) {
        element = selection.getNode();
        name = element ? element.nodeName : null;
        rng = selection.getRng();

        if (isContentEditableFalse(element) || name == 'IMG') {
          return { name: name, index: findIndex(name, element) };
        }

        element = findAdjacentContentEditableFalseElm(rng);
        if (element) {
          name = element.tagName;
          return { name: name, index: findIndex(name, element) };
        }

        return getLocation(rng);
      }

      if (type == 3) {
        rng = selection.getRng();

        return {
          start: CaretBookmark.create(dom.getRoot(), CaretPosition.fromRangeStart(rng)),
          end: CaretBookmark.create(dom.getRoot(), CaretPosition.fromRangeEnd(rng))
        };
      }

      // Handle simple range
      if (type) {
        return { rng: selection.getRng() };
      }

      rng = selection.getRng();
      id = dom.uniqueId();
      collapsed = selection.isCollapsed();
      styles = 'overflow:hidden;line-height:0px';
      element = selection.getNode();
      name = element.nodeName;
      if (name == 'IMG') {
        return { name: name, index: findIndex(name, element) };
      }

      // W3C method
      rng2 = normalizeTableCellSelection(rng.cloneRange());

      // Insert end marker
      if (!collapsed) {
        rng2.collapse(false);
        var endBookmarkNode = dom.create('span', { 'data-mce-type': "bookmark", id: id + '_end', style: styles }, chr);
        rng2.insertNode(endBookmarkNode);
        trimEmptyTextNode(endBookmarkNode.nextSibling);
      }

      rng = normalizeTableCellSelection(rng);
      rng.collapse(true);
      var startBookmarkNode = dom.create('span', { 'data-mce-type': "bookmark", id: id + '_start', style: styles }, chr);
      rng.insertNode(startBookmarkNode);
      trimEmptyTextNode(startBookmarkNode.previousSibling);

      selection.moveToBookmark({ id: id, keep: 1 });

      return { id: id };
    };

    var moveToBookmark = function (selection, bookmark) {
      var rng, root, startContainer, endContainer, startOffset, endOffset;
      var dom = selection.dom;

      var setEndPoint = function (start) {
        var point = bookmark[start ? 'start' : 'end'], i, node, offset, children;

        if (point) {
          offset = point[0];

          // Find container node
          for (node = root, i = point.length - 1; i >= 1; i--) {
            children = node.childNodes;

            if (point[i] > children.length - 1) {
              return;
            }

            node = children[point[i]];
          }

          // Move text offset to best suitable location
          if (node.nodeType === 3) {
            offset = Math.min(point[0], node.nodeValue.length);
          }

          // Move element offset to best suitable location
          if (node.nodeType === 1) {
            offset = Math.min(point[0], node.childNodes.length);
          }

          // Set offset within container node
          if (start) {
            rng.setStart(node, offset);
          } else {
            rng.setEnd(node, offset);
          }
        }

        return true;
      };

      var restoreEndPoint = function (suffix) {
        var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep;

        if (marker) {
          node = marker.parentNode;

          if (suffix == 'start') {
            if (!keep) {
              idx = dom.nodeIndex(marker);
            } else {
              node = marker.firstChild;
              idx = 1;
            }

            startContainer = endContainer = node;
            startOffset = endOffset = idx;
          } else {
            if (!keep) {
              idx = dom.nodeIndex(marker);
            } else {
              node = marker.firstChild;
              idx = 1;
            }

            endContainer = node;
            endOffset = idx;
          }

          if (!keep) {
            prev = marker.previousSibling;
            next = marker.nextSibling;

            // Remove all marker text nodes
            Tools.each(Tools.grep(marker.childNodes), function (node) {
              if (node.nodeType == 3) {
                node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
              }
            });

            // Remove marker but keep children if for example contents where inserted into the marker
            // Also remove duplicated instances of the marker for example by a
            // split operation or by WebKit auto split on paste feature
            while ((marker = dom.get(bookmark.id + '_' + suffix))) {
              dom.remove(marker, 1);
            }

            // If siblings are text nodes then merge them unless it's Opera since it some how removes the node
            // and we are sniffing since adding a lot of detection code for a browser with 3% of the market
            // isn't worth the effort. Sorry, Opera but it's just a fact
            if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !Env.opera) {
              idx = prev.nodeValue.length;
              prev.appendData(next.nodeValue);
              dom.remove(next);

              if (suffix == 'start') {
                startContainer = endContainer = prev;
                startOffset = endOffset = idx;
              } else {
                endContainer = prev;
                endOffset = idx;
              }
            }
          }
        }
      };

      var addBogus = function (node) {
        // Adds a bogus BR element for empty block elements
        if (dom.isBlock(node) && !node.innerHTML && !Env.ie) {
          node.innerHTML = '
';
        }

        return node;
      };

      var resolveCaretPositionBookmark = function () {
        var rng, pos;

        rng = dom.createRng();
        pos = CaretBookmark.resolve(dom.getRoot(), bookmark.start);
        rng.setStart(pos.container(), pos.offset());

        pos = CaretBookmark.resolve(dom.getRoot(), bookmark.end);
        rng.setEnd(pos.container(), pos.offset());

        return rng;
      };

      if (bookmark) {
        if (Tools.isArray(bookmark.start)) {
          rng = dom.createRng();
          root = dom.getRoot();

          if (setEndPoint(true) && setEndPoint()) {
            selection.setRng(rng);
          }
        } else if (typeof bookmark.start == 'string') {
          selection.setRng(resolveCaretPositionBookmark(bookmark));
        } else if (bookmark.id) {
          // Restore start/end points
          restoreEndPoint('start');
          restoreEndPoint('end');

          if (startContainer) {
            rng = dom.createRng();
            rng.setStart(addBogus(startContainer), startOffset);
            rng.setEnd(addBogus(endContainer), endOffset);
            selection.setRng(rng);
          }
        } else if (bookmark.name) {
          selection.select(dom.select(bookmark.name)[bookmark.index]);
        } else if (bookmark.rng) {
          selection.setRng(bookmark.rng);
        }
      }
    };

    var isBookmarkNode = function (node) {
      return node && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
    };

    return {
      getBookmark: getBookmark,
      moveToBookmark: moveToBookmark,
      isBookmarkNode: isBookmarkNode
    };
  }
);<commit_msg>TINY-1423: cleanup<commit_after>/**
 * Bookmarks.js
 *
 * Released under LGPL License.
 * Copyright (c) 1999-2017 Ephox Corp. All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

define(
  'tinymce.core.dom.Bookmarks',
  [
    'tinymce.core.Env',
    'tinymce.core.caret.CaretBookmark',
    'tinymce.core.caret.CaretContainer',
    'tinymce.core.caret.CaretPosition',
    'tinymce.core.dom.NodeType',
    'tinymce.core.selection.RangeNodes',
    'tinymce.core.text.Zwsp',
    'tinymce.core.util.Tools'
  ],
  function (Env, CaretBookmark, CaretContainer, CaretPosition, NodeType, RangeNodes, Zwsp, Tools) {
    var isContentEditableFalse = NodeType.isContentEditableFalse;

    var getNormalizedTextOffset = function (container, offset) {
      var node, trimmedOffset;

      trimmedOffset = Zwsp.trim(container.data.slice(0, offset)).length;
      for (node = container.previousSibling; node && node.nodeType === 3; node = node.previousSibling) {
        trimmedOffset += Zwsp.trim(node.data).length;
      }

      return trimmedOffset;
    };

    var getLocation = function (selection, normalized, rng) {
      var dom = selection.dom, root = dom.getRoot(), bookmark = {};

      var getPoint = function (rng, start) {
        var container = rng[start ? 'startContainer' : 'endContainer'],
          offset = rng[start ? 'startOffset' : 'endOffset'], point = [], childNodes, after = 0;

        if (container.nodeType === 3) {
          point.push(normalized ? getNormalizedTextOffset(container, offset) : offset);
        } else {
          childNodes = container.childNodes;

          if (offset >= childNodes.length && childNodes.length) {
            after = 1;
            offset = Math.max(0, childNodes.length - 1);
          }

          point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
        }

        for (; container && container != root; container = container.parentNode) {
          point.push(dom.nodeIndex(container, normalized));
        }

        return point;
      };

      bookmark.start = getPoint(rng, true);

      if (!selection.isCollapsed()) {
        bookmark.end = getPoint(rng);
      }

      return bookmark;
    };

    var trimEmptyTextNode = function (node) {
      if (NodeType.isText(node) && node.data.length === 0) {
        node.parentNode.removeChild(node);
      }
    };

    var findIndex = function (dom, name, element) {
      var count = 0;

      Tools.each(dom.select(name), function (node) {
        if (node.getAttribute('data-mce-bogus') === 'all') {
          return;
        }

        if (node === element) {
          return false;
        }

        count++;
      });

      return count;
    };

    var normalizeTableCellSelection = function (rng) {
      var moveEndPoint = function (start) {
        var container, offset, childNodes, prefix = start ? 'start' : 'end';

        container = rng[prefix + 'Container'];
        offset = rng[prefix + 'Offset'];

        if (NodeType.isElement(container) && container.nodeName === "TR") {
          childNodes = container.childNodes;
          container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
          if (container) {
            offset = start ? 0 : container.childNodes.length;
            rng['set' + (start ? 'Start' : 'End')](container, offset);
          }
        }
      };

      moveEndPoint(true);
      moveEndPoint();

      return rng;
    };

    var findAdjacentContentEditableFalseElm = function (rng) {
      var findSibling = function (node, offset) {
        var sibling;

        if (NodeType.isElement(node)) {
          node = RangeNodes.getNode(node, offset);
          if (isContentEditableFalse(node)) {
            return node;
          }
        }

        if (CaretContainer.isCaretContainer(node)) {
          if (NodeType.isText(node) && CaretContainer.isCaretContainerBlock(node)) {
            node = node.parentNode;
          }

          sibling = node.previousSibling;
          if (isContentEditableFalse(sibling)) {
            return sibling;
          }

          sibling = node.nextSibling;
          if (isContentEditableFalse(sibling)) {
            return sibling;
          }
        }
      };

      return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
    };

    var addBogus = function (dom, node) {
      // Adds a bogus BR element for empty block elements
      if (dom.isBlock(node) && !node.innerHTML && !Env.ie) {
        node.innerHTML = '
';
      }

      return node;
    };

    var resolveCaretPositionBookmark = function (dom, bookmark) {
      var rng, pos;

      rng = dom.createRng();
      pos = CaretBookmark.resolve(dom.getRoot(), bookmark.start);
      rng.setStart(pos.container(), pos.offset());

      pos = CaretBookmark.resolve(dom.getRoot(), bookmark.end);
      rng.setEnd(pos.container(), pos.offset());

      return rng;
    };

    var getBookmark = function (selection, type, normalized) {
      var rng, rng2, id, collapsed, name, element, chr = '', styles;
      var dom = selection.dom;

      if (type === 2) {
        element = selection.getNode();
        name = element ? element.nodeName : null;
        rng = selection.getRng();

        if (isContentEditableFalse(element) || name === 'IMG') {
          return { name: name, index: findIndex(dom, name, element) };
        }

        element = findAdjacentContentEditableFalseElm(rng);
        if (element) {
          name = element.tagName;
          return { name: name, index: findIndex(dom, name, element) };
        }

        return getLocation(selection, normalized, rng);
      }

      if (type === 3) {
        rng = selection.getRng();

        return {
          start: CaretBookmark.create(dom.getRoot(), CaretPosition.fromRangeStart(rng)),
          end: CaretBookmark.create(dom.getRoot(), CaretPosition.fromRangeEnd(rng))
        };
      }

      // Handle simple range
      if (type) {
        return { rng: selection.getRng() };
      }

      rng = selection.getRng();
      id = dom.uniqueId();
      collapsed = selection.isCollapsed();
      styles = 'overflow:hidden;line-height:0px';
      element = selection.getNode();
      name = element.nodeName;
      if (name === 'IMG') {
        return { name: name, index: findIndex(dom, name, element) };
      }

      // W3C method
      rng2 = normalizeTableCellSelection(rng.cloneRange());

      // Insert end marker
      if (!collapsed) {
        rng2.collapse(false);
        var endBookmarkNode = dom.create('span', { 'data-mce-type': "bookmark", id: id + '_end', style: styles }, chr);
        rng2.insertNode(endBookmarkNode);
        trimEmptyTextNode(endBookmarkNode.nextSibling);
      }

      rng = normalizeTableCellSelection(rng);
      rng.collapse(true);
      var startBookmarkNode = dom.create('span', { 'data-mce-type': "bookmark", id: id + '_start', style: styles }, chr);
      rng.insertNode(startBookmarkNode);
      trimEmptyTextNode(startBookmarkNode.previousSibling);

      selection.moveToBookmark({ id: id, keep: 1 });

      return { id: id };
    };

    var setEndPoint = function (dom, start, bookmark, rng) {
      var point = bookmark[start ? 'start' : 'end'], i, node, offset, children, root = dom.getRoot();

      if (point) {
        offset = point[0];

        // Find container node
        for (node = root, i = point.length - 1; i >= 1; i--) {
          children = node.childNodes;

          if (point[i] > children.length - 1) {
            return;
          }

          node = children[point[i]];
        }

        // Move text offset to best suitable location
        if (node.nodeType === 3) {
          offset = Math.min(point[0], node.nodeValue.length);
        }

        // Move element offset to best suitable location
        if (node.nodeType === 1) {
          offset = Math.min(point[0], node.childNodes.length);
        }

        // Set offset within container node
        if (start) {
          rng.setStart(node, offset);
        } else {
          rng.setEnd(node, offset);
        }
      }

      return true;
    };

    var moveToBookmark = function (selection, bookmark) {
      var rng, startContainer, endContainer, startOffset, endOffset;
      var dom = selection.dom;

      var restoreEndPoint = function (suffix) {
        var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep;

        if (marker) {
          node = marker.parentNode;

          if (suffix === 'start') {
            if (!keep) {
              idx = dom.nodeIndex(marker);
            } else {
              node = marker.firstChild;
              idx = 1;
            }

            startContainer = endContainer = node;
            startOffset = endOffset = idx;
          } else {
            if (!keep) {
              idx = dom.nodeIndex(marker);
            } else {
              node = marker.firstChild;
              idx = 1;
            }

            endContainer = node;
            endOffset = idx;
          }

          if (!keep) {
            prev = marker.previousSibling;
            next = marker.nextSibling;

            // Remove all marker text nodes
            Tools.each(Tools.grep(marker.childNodes), function (node) {
              if (NodeType.isText(node)) {
                node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
              }
            });

            // Remove marker but keep children if for example contents where inserted into the marker
            // Also remove duplicated instances of the marker for example by a
            // split operation or by WebKit auto split on paste feature
            while ((marker = dom.get(bookmark.id + '_' + suffix))) {
              dom.remove(marker, 1);
            }

            // If siblings are text nodes then merge them unless it's Opera since it some how removes the node
            // and we are sniffing since adding a lot of detection code for a browser with 3% of the market
            // isn't worth the effort. Sorry, Opera but it's just a fact
            if (prev && next && prev.nodeType === next.nodeType && NodeType.isText(prev) && !Env.opera) {
              idx = prev.nodeValue.length;
              prev.appendData(next.nodeValue);
              dom.remove(next);

              if (suffix === 'start') {
                startContainer = endContainer = prev;
                startOffset = endOffset = idx;
              } else {
                endContainer = prev;
                endOffset = idx;
              }
            }
          }
        }
      };

      if (bookmark) {
        if (Tools.isArray(bookmark.start)) {
          rng = dom.createRng();

          if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
            selection.setRng(rng);
          }
        } else if (typeof bookmark.start === 'string') {
          selection.setRng(resolveCaretPositionBookmark(dom, bookmark));
        } else if (bookmark.id) {
          // Restore start/end points
          restoreEndPoint('start');
          restoreEndPoint('end');

          if (startContainer) {
            rng = dom.createRng();
            rng.setStart(addBogus(dom, startContainer), startOffset);
            rng.setEnd(addBogus(dom, endContainer), endOffset);
            selection.setRng(rng);
          }
        } else if (bookmark.name) {
          selection.select(dom.select(bookmark.name)[bookmark.index]);
        } else if (bookmark.rng) {
          selection.setRng(bookmark.rng);
        }
      }
    };

    var isBookmarkNode = function (node) {
      return node && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
    };

    return {
      getBookmark: getBookmark,
      moveToBookmark: moveToBookmark,
      isBookmarkNode: isBookmarkNode
    };
  }
);<|endoftext|>