<commit_before>"use strict";

var Freya = Freya || {};

Freya.get_popup = function (url, $button) {

    // Ability to load popup via ajax url
    $.get(url).done(function (data, textStatus, jqXHR) {
        if (data) {
            var $popup = $(data.data_html);
            $('body').append($popup);
            window.rebind($popup);
            $popup.modal('show');
            $popup.on('hidden.bs.modal', function (event) {
                $popup.remove();
            });
            if (data.flash_html) {
                $alerts.append(data.flash_html);
            } else if (data.flash_html === '') {
                $alerts.html('');
            }
        }
    })
    .always(function () {
        if ($button !== undefined ) {
            $button.prop('disabled', false);
        }
    });
};

$(function () {

    var $alerts = $alerts || $('#alerts');

    var done_handler = function (data, textStatus, jqXHR, $initiator) {

        if (data) {
            if (data.redirect_url) {
                if (data.redirect_url == document.URL) {
                    location.reload();
                } else {
                    window.location.href = data.redirect_url;
                }
            }

            // new wrapper can be the same as current, or be insede, or be outside
            if (data.data_html || data.data_html === '') {
                var wrapper, $wrapper;
                var $newData = $(data.data_html);
                if (data.settings && data.settings['openPopup']) {
                    var $popup = $newData;
                    $('body').append($popup);
                    window.rebind($popup);
                    $popup.modal('show');
                    $popup.on('hidden.bs.modal', function (event) {
                        $popup.remove();
                    });
                } else {
                    if ($initiator) {
                        if ($initiator.data('wrapper')) {
                            $wrapper = $initiator.closest($initiator.data('wrapper'));
                            if ($wrapper.length) {
                                if ($initiator.data('wrapper') == '.modal-content') {
                                    $newData = $newData.find('.modal-content');
                                }
                            } else {
                                $wrapper = $($initiator.data("wrapper"));
                            }
                        } else if ($initiator.is('form')) {
                            $wrapper = $initiator.closest('form');
                        } else if ($initiator.is('button')) {
                            $wrapper = $initiator.closest('.model-item');
                        }
                    } else if (data.settings && data.settings['wrapper']) {
                        $wrapper = $(data.settings['wrapper']);
                    }
                }
                if ($wrapper && $wrapper.length) {
                    $wrapper = $newData.replaceAll($wrapper);
                    window.rebind($wrapper, data.settings);
                }
            } else if (data.settings) {
                window.rebind($('body'), data.settings);
            }

            if (data.flash_html) {
                $alerts.html(data.flash_html);
            }

        } else {
            console.log('Data from ajax request is empty')
        }
    };

    // API for BUTTON that updates content on page (using GET method)
    $(document.body).on('click', 'button[data-api="ajax.get"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');
        var confirm = $button.attr('data-confirm');

        //To prevent multisending
        $button.prop('disabled', true);

        function handle() {
            $.ajax({
                type: 'get',
                url: url,
                data: {'value': $button.val(), 'next': document.URL}
            })
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $button);
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                }
            });
        } else {
            handle();
        }
    });

    // API for FORM that updates content on page by changing any field
    $(document.body).on('change', 'form[data-api="ajax.autoreload"] :input', function (event) {
        event.preventDefault();
        var $form = $(this).closest('form');
        var $submit = $form.find('input[type="submit"]');

        // To prevent multisending
        $submit.prop('disabled', true);

        // Update URL if form.method == GET
        if ($form.attr('method') == 'GET') {
            var url = $form.attr('action');
            var path = url.indexOf("?") >=0 ? url + '&' + $form.serialize() : url + '?' + $form.serialize();
            path += "&" + $submit.attr("name") + "=" + $submit.val();
            window.history.pushState({}, $(document).find("title").text(), path);
        }

        var formData = $form.serializeArray();
        formData.push({ name: $submit.attr("name"), value: $submit.val() });

        function handle() {
            $.ajax({
                type: $form.attr('method'),
                url: $form.data('api-action') || $form.attr('action'),
                data: formData,
            })
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $form);
            })
            .always(function () {
              $submit.prop('disabled', false);
            });
        }

        handle();
    });

    // API for BUTTON that updates model on page (card usual)
    $(document.body).on('click', 'button[data-api="ajax.update"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');
        var confirm = $button.attr('data-confirm');

        //To prevent multisending
        if (!confirm) {
            $button.prop('disabled', true);
        }

        function handle() {
            if (LocalStorage.get('conf.csrfToken')) {
                var setting = { beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-CSRFToken", LocalStorage.get('conf.csrfToken'))
                }}
            }
            $.ajax($.extend(setting, {
                type: 'post',
                url: url,
                data: {'value': $button.val(), 'next': document.URL}
            }))
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $button);
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                }
            });
        } else {
            handle();
        }
    });

    // API for FORM that works by ajax
    $(document.body).on('click', 'form[data-api="ajax.update"] input[type="submit"]', function (event) {
        event.preventDefault();
        var $form = $(this).closest('form[data-api="ajax.update"]');
        var formData = $form.serializeArray();

        var $submitBtn = $(this);

        // To prevent multisending
        $submitBtn.prop('disabled', true);

        formData.push({ name: this.name, value: this.value });
        formData.push({ name: 'next', value: document.URL });
        $.ajax({
            type: 'post',
            url: $form.attr('action'),
            data: formData
        })
        .done(function (data, textStatus, jqXHR) {
            done_handler(data, textStatus, jqXHR, $form);
        })
        .always(function () {
            $submitBtn.prop('disabled', false);
        });
    });

    // POPUP - GET
    $(document.body).on('click', 'button[data-api="ajax.popup"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');

        // To prevent multisending
        $button.prop('disabled', true);

        Freya.get_popup(url, $button);
    });

    // POPUP - FORM
    $(document.body).on('click', '.modal[data-api="ajax.popup"] form [type="submit"]', function (event) {
        event.preventDefault();

        var $button = $(this);
        var $form = $button.closest('form');
        var $popup = $form.closest('.modal[data-api="ajax.popup"]');
        var confirm = $button.attr('data-confirm');
        var url = $form.attr('action');

        //To prevent multisending
        $button.prop('disabled', true);

        function handle() {
            if (LocalStorage.get('conf.csrfToken')) {
                var setting = { beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-CSRFToken", LocalStorage.get('conf.csrfToken'))
                }}
            }

            var formData = $form.serializeArray();
            formData.push({ name: this.name, value: this.value });
            formData.push({ name: 'next', value: document.URL });

            $.post(url, formData).done(function (data, textStatus, jqXHR) {
                if (data) {
                    if (data.redirect_url) {
                        if (data.redirect_url == document.URL) {
                            location.reload();
                        } else {
                            window.location.href = data.redirect_url;
                        }
                    }
                    if (data.settings && data.settings['closePopup']) {
                        $popup.modal('hide');
                        done_handler(data, textStatus, jqXHR, null);
                    } else {
                        window.location.href = data.redirect_url;
                        if (data.data_html) {
                            // To make update quicker and to not reinit popup
                            $popup.find('.modal-body').replaceWith($(data.data_html).find('.modal-body'));
                            window.rebind($popup);
                        }
                        if (data.flash_html) {
                            $alerts.append(data.flash_html);
                        } else if (data.flash_html === '') {
                            $alerts.html('');
                        }
                    }
                }
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                }
            });
        } else {
            handle();
        }
    });
});
<commit_msg>DEV-398 Close popup when confirm box is launched<commit_after>"use strict";

var Freya = Freya || {};

Freya.get_popup = function (url, $button) {

    // Ability to load popup via ajax url
    $.get(url).done(function (data, textStatus, jqXHR) {
        if (data) {
            var $popup = $(data.data_html);
            $('body').append($popup);
            window.rebind($popup);
            $popup.modal('show');
            $popup.on('hidden.bs.modal', function (event) {
                $popup.remove();
            });
            if (data.flash_html) {
                $alerts.append(data.flash_html);
            } else if (data.flash_html === '') {
                $alerts.html('');
            }
        }
    })
    .always(function () {
        if ($button !== undefined ) {
            $button.prop('disabled', false);
        }
    });
};

$(function () {

    var $alerts = $alerts || $('#alerts');

    var done_handler = function (data, textStatus, jqXHR, $initiator) {

        if (data) {
            if (data.redirect_url) {
                if (data.redirect_url == document.URL) {
                    location.reload();
                } else {
                    window.location.href = data.redirect_url;
                }
            }

            // new wrapper can be the same as current, or be insede, or be outside
            if (data.data_html || data.data_html === '') {
                var wrapper, $wrapper;
                var $newData = $(data.data_html);
                if (data.settings && data.settings['openPopup']) {
                    var $popup = $newData;
                    $('body').append($popup);
                    window.rebind($popup);
                    $popup.modal('show');
                    $popup.on('hidden.bs.modal', function (event) {
                        $popup.remove();
                    });
                } else {
                    if ($initiator) {
                        if ($initiator.data('wrapper')) {
                            $wrapper = $initiator.closest($initiator.data('wrapper'));
                            if ($wrapper.length) {
                                if ($initiator.data('wrapper') == '.modal-content') {
                                    $newData = $newData.find('.modal-content');
                                }
                            } else {
                                $wrapper = $($initiator.data("wrapper"));
                            }
                        } else if ($initiator.is('form')) {
                            $wrapper = $initiator.closest('form');
                        } else if ($initiator.is('button')) {
                            $wrapper = $initiator.closest('.model-item');
                        }
                    } else if (data.settings && data.settings['wrapper']) {
                        $wrapper = $(data.settings['wrapper']);
                    }
                }
                if ($wrapper && $wrapper.length) {
                    $wrapper = $newData.replaceAll($wrapper);
                    window.rebind($wrapper, data.settings);
                }
            } else if (data.settings) {
                window.rebind($('body'), data.settings);
            }

            if (data.flash_html) {
                $alerts.html(data.flash_html);
            }

        } else {
            console.log('Data from ajax request is empty')
        }
    };

    // API for BUTTON that updates content on page (using GET method)
    $(document.body).on('click', 'button[data-api="ajax.get"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');
        var confirm = $button.attr('data-confirm');

        //To prevent multisending
        $button.prop('disabled', true);

        function handle() {
            $.ajax({
                type: 'get',
                url: url,
                data: {'value': $button.val(), 'next': document.URL}
            })
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $button);
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                }
            });
        } else {
            handle();
        }
    });

    // API for FORM that updates content on page by changing any field
    $(document.body).on('change', 'form[data-api="ajax.autoreload"] :input', function (event) {
        event.preventDefault();
        var $form = $(this).closest('form');
        var $submit = $form.find('input[type="submit"]');

        // To prevent multisending
        $submit.prop('disabled', true);

        // Update URL if form.method == GET
        if ($form.attr('method') == 'GET') {
            var url = $form.attr('action');
            var path = url.indexOf("?") >=0 ? url + '&' + $form.serialize() : url + '?' + $form.serialize();
            path += "&" + $submit.attr("name") + "=" + $submit.val();
            window.history.pushState({}, $(document).find("title").text(), path);
        }

        var formData = $form.serializeArray();
        formData.push({ name: $submit.attr("name"), value: $submit.val() });

        function handle() {
            $.ajax({
                type: $form.attr('method'),
                url: $form.data('api-action') || $form.attr('action'),
                data: formData,
            })
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $form);
            })
            .always(function () {
              $submit.prop('disabled', false);
            });
        }

        handle();
    });

    // API for BUTTON that updates model on page (card usual)
    $(document.body).on('click', 'button[data-api="ajax.update"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');
        var confirm = $button.attr('data-confirm');

        //To prevent multisending
        if (!confirm) {
            $button.prop('disabled', true);
        }

        function handle() {
            if (LocalStorage.get('conf.csrfToken')) {
                var setting = { beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-CSRFToken", LocalStorage.get('conf.csrfToken'))
                }}
            }
            $.ajax($.extend(setting, {
                type: 'post',
                url: url,
                data: {'value': $button.val(), 'next': document.URL}
            }))
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $button);
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                }
            });
        } else {
            handle();
        }
    });

    // API for FORM that works by ajax
    $(document.body).on('click', 'form[data-api="ajax.update"] input[type="submit"]', function (event) {
        event.preventDefault();
        var $form = $(this).closest('form[data-api="ajax.update"]');
        var formData = $form.serializeArray();

        var $submitBtn = $(this);

        // To prevent multisending
        $submitBtn.prop('disabled', true);

        formData.push({ name: this.name, value: this.value });
        formData.push({ name: 'next', value: document.URL });
        $.ajax({
            type: 'post',
            url: $form.attr('action'),
            data: formData
        })
        .done(function (data, textStatus, jqXHR) {
            done_handler(data, textStatus, jqXHR, $form);
        })
        .always(function () {
            $submitBtn.prop('disabled', false);
        });
    });

    // POPUP - GET
    $(document.body).on('click', 'button[data-api="ajax.popup"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');

        // To prevent multisending
        $button.prop('disabled', true);

        Freya.get_popup(url, $button);
    });

    // POPUP - FORM
    $(document.body).on('click', '.modal[data-api="ajax.popup"] form [type="submit"]', function (event) {
        event.preventDefault();

        var $button = $(this);
        var $form = $button.closest('form');
        var $popup = $form.closest('.modal[data-api="ajax.popup"]');
        var confirm = $button.attr('data-confirm');
        var url = $form.attr('action');

        //To prevent multisending
        $button.prop('disabled', true);

        function handle() {
            if (LocalStorage.get('conf.csrfToken')) {
                var setting = { beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-CSRFToken", LocalStorage.get('conf.csrfToken'))
                }}
            }

            var formData = $form.serializeArray();
            formData.push({ name: this.name, value: this.value });
            formData.push({ name: 'next', value: document.URL });

            $.post(url, formData).done(function (data, textStatus, jqXHR) {
                if (data) {
                    if (data.redirect_url) {
                        if (data.redirect_url == document.URL) {
                            location.reload();
                        } else {
                            window.location.href = data.redirect_url;
                        }
                    }
                    if (data.settings && data.settings['closePopup']) {
                        done_handler(data, textStatus, jqXHR, null);
                    } else {
                        window.location.href = data.redirect_url;
                        if (data.data_html) {
                            // To make update quicker and to not reinit popup
                            $popup.find('.modal-body').replaceWith($(data.data_html).find('.modal-body'));
                            window.rebind($popup);
                        }
                        if (data.flash_html) {
                            $alerts.append(data.flash_html);
                        } else if (data.flash_html === '') {
                            $alerts.html('');
                        }
                    }
                }
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            $popup.modal('hide');
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                } else {
                    $button.prop('disabled', false);
                }
            });
        } else {
            handle();
        }
    });
});
<|endoftext|>


<commit_before>import trueish from './trueish'

export default function (props) {
  return trueish(props, 'ariaHidden')
}
<commit_msg>use de-normalize `aria-hidden`<commit_after>import hasProp from './has-prop'
import trueish from './trueish'

export default function (props) {
  return trueish(props, 'aria-hidden')
}
<|endoftext|>


<commit_before>var myFirebaseRef = new Firebase("https://fiery-inferno-6630.firebaseio.com/");

var message = myFirebaseRef.child("message");
var selection = myFirebaseRef.child("selection");
var gyr_x = myFirebaseRef.child("gyr_x");
var gyr_y = myFirebaseRef.child("gyr_y");
var gyr_z = myFirebaseRef.child("gyr_z");
var acc_x = myFirebaseRef.child("acc_x");
var acc_y = myFirebaseRef.child("acc_y");
var acc_z = myFirebaseRef.child("acc_z");

var go = myFirebaseRef.child("go");

var $right = $(".glyphicon-chevron-right");
var $left = $(".glyphicon-chevron-left");

var $first = $('div:first', '#menu'),
	$last = $('div:last', '#menu');

dir = {}

var going = false;

dir.gyr_x_val = 0;
dir.gyr_y_val = 0;
dir.gyr_z_val = 0;
dir.acc_x_val = 0;
dir.acc_y_val = 0;
dir.acc_z_val = 0;

message.on("value", function(snapshot) {
	if(snapshot.val() != null) {
		$("#message").text(snapshot.val());
	}
});

selection.on("value", function(snapshot) {
  	if(snapshot.val() == "up") {
  		var $prev, $selected = $(".selected");

	    $prev = $selected.prev('div').length ? $selected.prev('div') : $last;
	    $selected.removeClass("selected");
	    $prev.addClass('selected');
  	} else if(snapshot.val() == "down") {
  		var $next, $selected = $(".selected");

	    $next = $selected.next('div').length ? $selected.next('div') : $first;
	    $selected.removeClass("selected");
	    $next.addClass('selected');
  	} else if(snapshot.val() == "Toggle") {
  		console.log("toggle");
  		$selected = $(".selected");
  		$selected.click();
  	}
  	message.set(null);
});

gyr_x.on("value", function(snapshot) {
	var val = Math.round( snapshot.val() * 10) / 10
	if(val > 2) {
		dir.gyr_x_val = 1
	} else if (val < -2) {
		dir.gyr_x_val = -1
	} else if (val > -.05 && val < .05){
		dir.gyr_x_val = 0;
	}
	$("#gyr_x").text(dir.gyr_x_val);
});

gyr_y.on("value", function(snapshot) {
	var val = Math.round( snapshot.val() * 10) / 10
	if(val > 2) {
		dir.gyr_y_val = 1
	} else if (val < -2) {
		dir.gyr_y_val = -1
	} else if (val > -.05 && val < .05) {
		dir.gyr_y_val = 0;
	}
	$("#gyr_y").text(dir.gyr_y_val);
});

gyr_z.on("value", function(snapshot) {
	var val = Math.round( snapshot.val() * 10) / 10
	if(val > 2) {
		dir.gyr_z_val = 1
	} else if (val < -2) {
		dir.gyr_z_val = -1
	} else if (val > -.1 && val < .1){
		dir.gyr_z_val = 0;
	}
	$("#gyr_z").text(dir.gyr_z_val);
});

acc_x.on("value", function(snapshot) {
	dir.acc_x_val += snapshot.val()
	$("#acc_x").text(dir.acc_x_val);
});

acc_y.on("value", function(snapshot) {
	dir.acc_y_val = Math.round( snapshot.val() * 10) / 10
	$("#acc_y").text(dir.acc_y_val);
});

acc_z.on("value", function(snapshot) {
	dir.acc_z_val = Math.round( snapshot.val() * 10) / 10
	$("#acc_z").text(dir.acc_z_val);
});

go.on("value", function(snapshot) {
	going = snapshot.val();
})

$( ".settings" ).click(function() {
	console.log("settings");
	$("#settings").toggle();
});

$( ".jetpack_dir" ).click(function() {
	console.log("jetpack_dir");
	$("#jetpack").toggle();
});

$(".message").click(function() {
	$("#message").text("Messages sent!")
	$("#message").fadeOut( "slow" , function() {
		$("#message").text("");
		$("#message").show();
	});
})

var renderer	= new THREE.WebGLRenderer({
	antialias	: true
});
renderer.setSize( window.innerWidth, window.innerHeight );
document.getElementById('hud').appendChild( renderer.domElement );
renderer.shadowMapEnabled	= true

var onRenderFcts= [];
var scene	= new THREE.Scene();
var camera	= new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.01, 1000 );
camera.position.z = 1;
var light	= new THREE.AmbientLight( 0x222222 )
scene.add( light )
var light	= new THREE.DirectionalLight( 0xffffff, 1 )
light.position.set(5,5,5)
scene.add( light )
light.castShadow	= true
light.shadowCameraNear	= 0.01
light.shadowCameraFar	= 15
light.shadowCameraFov	= 45
light.shadowCameraLeft	= -1
light.shadowCameraRight	=  1
light.shadowCameraTop	=  1
light.shadowCameraBottom= -1
// light.shadowCameraVisible	= true
light.shadowBias	= 0.001
light.shadowDarkness	= 0.2
light.shadowMapWidth	= 1024
light.shadowMapHeight	= 1024

//////////////////////////////////////////////////////////////////////////////////
//		added starfield							//
//////////////////////////////////////////////////////////////////////////////////

var starSphere	= THREEx.Planets.createStarfield()
scene.add(starSphere)

//////////////////////////////////////////////////////////////////////////////////
//		add an object and make it move					//
//////////////////////////////////////////////////////////////////////////////////
// var datGUI	= new dat.GUI()
var containerEarth	= new THREE.Object3D()
//containerEarth.rotateZ(-23.4 * Math.PI/180)
containerEarth.position.z	= 0
scene.add(containerEarth)
var moonMesh	= THREEx.Planets.createMoon()
moonMesh.position.set(0.5,0.5,0.5)
moonMesh.scale.multiplyScalar(1/5)
moonMesh.receiveShadow	= true
//moonMesh.castShadow	= true
containerEarth.add(moonMesh)
var earthMesh	= THREEx.Planets.createEarth()
earthMesh.receiveShadow	= true
//earthMesh.castShadow	= true
containerEarth.add(earthMesh)
// onRenderFcts.push(function(delta, now){
// 	earthMesh.rotation.y += 1/32 * delta;
// })
var geometry	= new THREE.SphereGeometry(0.5, 32, 32)
var material	= THREEx.createAtmosphereMaterial()
material.uniforms.glowColor.value.set(0x00b3ff)
material.uniforms.coeficient.value	= 0.8
material.uniforms.power.value		= 2.0
var mesh	= new THREE.Mesh(geometry, material );
mesh.scale.multiplyScalar(1.01);
containerEarth.add( mesh );

// new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)
var geometry	= new THREE.SphereGeometry(0.5, 32, 32)
var material	= THREEx.createAtmosphereMaterial()
material.side	= THREE.BackSide
material.uniforms.glowColor.value.set(0x00b3ff)
material.uniforms.coeficient.value	= 0.5
material.uniforms.power.value		= 4.0
var mesh	= new THREE.Mesh(geometry, material );
mesh.scale.multiplyScalar(1.15);
containerEarth.add( mesh );

// new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)
var earthCloud	= THREEx.Planets.createEarthCloud()
earthCloud.receiveShadow	= true
//earthCloud.castShadow	= true
containerEarth.add(earthCloud)
onRenderFcts.push(function(delta, now){
	earthCloud.rotation.y += 1/8 * delta;
})

//////////////////////////////////////////////////////////////////////////////////
//		Camera Controls							//
//////////////////////////////////////////////////////////////////////////////////
// var mouse	= {x : 0, y : 0}
// document.addEventListener('mousemove', function(event){
// 	mouse.x	= (dir.gyr_x_val / window.innerWidth ) - 0.5
// 	mouse.y	= (dir.gyr_y_val / window.innerHeight) - 0.5
// }, false)
onRenderFcts.push(function(delta, now){
	//camera.position.x -= (dir.acc_x_val/100 )//- camera.position.x) * (delta*3)
	//camera.position.y -= (dir.acc_z_val/100) //- camera.position.y) * (delta*3)
	if(dir.gyr_x_val >= 1) {
		camera.rotation.x +=.01;
	} else if (dir.gyr_x_val <= -1) {
		camera.rotation.x -= .01;
	}
	if(dir.gyr_z_val >= 1) {
		camera.rotation.y +=.01;
	} else if (dir.gyr_z_val <= -1) {
		camera.rotation.y -= .01;
	}
	if(dir.gyr_y_val >= 1) {
		camera.rotation.z -=.01;
	} else if (dir.gyr_y_val <= -1) {
		camera.rotation.z += .01;
	}

	if(going) {
		camera.position.z -= .001
	}

	camera.position.x += dir.acc_x_val / 100;

	//camera.position.z += (dir.gyr_x_val/100) //- camera.position.z) //* (delta*3)
	// camera.rotation.x += (dir.gyr_x_val/100 )//- camera.rotation.x) * (delta*3)
	// camera.rotation.y += (dir.gyr_y_val/100 )//- camera.rotation.y) * (delta*3)
	// camera.rotation.z += (dir.gyr_z_val/100 )//- camera.rotation.z) * (delta*3)

	// camera.position.x += (gyr_x*5 - camera.position.x) * (delta*3);
	// camera.position.y += (gyr_y*5 - camera.position.y) * (delta*3);
	//camera.lookAt( scene.position )
})
//////////////////////////////////////////////////////////////////////////////////
//		render the scene						//
//////////////////////////////////////////////////////////////////////////////////
onRenderFcts.push(function(){
	renderer.render( scene, camera );
})

//////////////////////////////////////////////////////////////////////////////////
//		loop runner							//
//////////////////////////////////////////////////////////////////////////////////
var lastTimeMsec= null
requestAnimationFrame(function animate(nowMsec){
	// keep looping
	requestAnimationFrame( animate );
	// measure time
	lastTimeMsec	= lastTimeMsec || nowMsec-1000/60
	var deltaMsec	= Math.min(200, nowMsec - lastTimeMsec)
	lastTimeMsec	= nowMsec
	// call each update function
	onRenderFcts.forEach(function(onRenderFct){
		onRenderFct(deltaMsec/1000, nowMsec/1000)
	})
})<commit_msg>added y and z motion<commit_after>var myFirebaseRef = new Firebase("https://fiery-inferno-6630.firebaseio.com/");

var message = myFirebaseRef.child("message");
var selection = myFirebaseRef.child("selection");
var gyr_x = myFirebaseRef.child("gyr_x");
var gyr_y = myFirebaseRef.child("gyr_y");
var gyr_z = myFirebaseRef.child("gyr_z");
var acc_x = myFirebaseRef.child("acc_x");
var acc_y = myFirebaseRef.child("acc_y");
var acc_z = myFirebaseRef.child("acc_z");

var go = myFirebaseRef.child("go");

var $right = $(".glyphicon-chevron-right");
var $left = $(".glyphicon-chevron-left");

var $first = $('div:first', '#menu'),
	$last = $('div:last', '#menu');

dir = {}

var going = false;

dir.gyr_x_val = 0;
dir.gyr_y_val = 0;
dir.gyr_z_val = 0;
dir.acc_x_val = 0;
dir.acc_y_val = 0;
dir.acc_z_val = 0;

message.on("value", function(snapshot) {
	if(snapshot.val() != null) {
		$("#message").text(snapshot.val());
	}
});

selection.on("value", function(snapshot) {
  	if(snapshot.val() == "up") {
  		var $prev, $selected = $(".selected");

	    $prev = $selected.prev('div').length ? $selected.prev('div') : $last;
	    $selected.removeClass("selected");
	    $prev.addClass('selected');
  	} else if(snapshot.val() == "down") {
  		var $next, $selected = $(".selected");

	    $next = $selected.next('div').length ? $selected.next('div') : $first;
	    $selected.removeClass("selected");
	    $next.addClass('selected');
  	} else if(snapshot.val() == "Toggle") {
  		console.log("toggle");
  		$selected = $(".selected");
  		$selected.click();
  	}
  	message.set(null);
});

gyr_x.on("value", function(snapshot) {
	var val = Math.round( snapshot.val() * 10) / 10
	if(val > 2) {
		dir.gyr_x_val = 1
	} else if (val < -2) {
		dir.gyr_x_val = -1
	} else if (val > -.05 && val < .05){
		dir.gyr_x_val = 0;
	}
	$("#gyr_x").text(dir.gyr_x_val);
});

gyr_y.on("value", function(snapshot) {
	var val = Math.round( snapshot.val() * 10) / 10
	if(val > 2) {
		dir.gyr_y_val = 1
	} else if (val < -2) {
		dir.gyr_y_val = -1
	} else if (val > -.05 && val < .05) {
		dir.gyr_y_val = 0;
	}
	$("#gyr_y").text(dir.gyr_y_val);
});

gyr_z.on("value", function(snapshot) {
	var val = Math.round( snapshot.val() * 10) / 10
	if(val > 2) {
		dir.gyr_z_val = 1
	} else if (val < -2) {
		dir.gyr_z_val = -1
	} else if (val > -.1 && val < .1){
		dir.gyr_z_val = 0;
	}
	$("#gyr_z").text(dir.gyr_z_val);
});

acc_x.on("value", function(snapshot) {
	dir.acc_x_val += snapshot.val();
	acc_x.set(0);
	$("#acc_x").text(dir.acc_x_val);
});

acc_y.on("value", function(snapshot) {
	dir.acc_y_val += snapshot.val();
	acc_y.set(0);
	$("#acc_y").text(dir.acc_y_val);
});

acc_z.on("value", function(snapshot) {
	dir.acc_z_val += snapshot.val();
	acc_z.set(0);
	$("#acc_z").text(dir.acc_z_val);
});

go.on("value", function(snapshot) {
	going = snapshot.val();
})

$( ".settings" ).click(function() {
	console.log("settings");
	$("#settings").toggle();
});

$( ".jetpack_dir" ).click(function() {
	console.log("jetpack_dir");
	$("#jetpack").toggle();
});

$(".message").click(function() {
	$("#message").text("Messages sent!")
	$("#message").fadeOut( "slow" , function() {
		$("#message").text("");
		$("#message").show();
	});
})

var renderer	= new THREE.WebGLRenderer({
	antialias	: true
});
renderer.setSize( window.innerWidth, window.innerHeight );
document.getElementById('hud').appendChild( renderer.domElement );
renderer.shadowMapEnabled	= true

var onRenderFcts= [];
var scene	= new THREE.Scene();
var camera	= new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.01, 1000 );
camera.position.z = 1;
var light	= new THREE.AmbientLight( 0x222222 )
scene.add( light )
var light	= new THREE.DirectionalLight( 0xffffff, 1 )
light.position.set(5,5,5)
scene.add( light )
light.castShadow	= true
light.shadowCameraNear	= 0.01
light.shadowCameraFar	= 15
light.shadowCameraFov	= 45
light.shadowCameraLeft	= -1
light.shadowCameraRight	=  1
light.shadowCameraTop	=  1
light.shadowCameraBottom= -1
// light.shadowCameraVisible	= true
light.shadowBias	= 0.001
light.shadowDarkness	= 0.2
light.shadowMapWidth	= 1024
light.shadowMapHeight	= 1024

//////////////////////////////////////////////////////////////////////////////////
//		added starfield							//
//////////////////////////////////////////////////////////////////////////////////

var starSphere	= THREEx.Planets.createStarfield()
scene.add(starSphere)

//////////////////////////////////////////////////////////////////////////////////
//		add an object and make it move					//
//////////////////////////////////////////////////////////////////////////////////
// var datGUI	= new dat.GUI()
var containerEarth	= new THREE.Object3D()
//containerEarth.rotateZ(-23.4 * Math.PI/180)
containerEarth.position.z	= 0
scene.add(containerEarth)
var moonMesh	= THREEx.Planets.createMoon()
moonMesh.position.set(0.5,0.5,0.5)
moonMesh.scale.multiplyScalar(1/5)
moonMesh.receiveShadow	= true
//moonMesh.castShadow	= true
containerEarth.add(moonMesh)
var earthMesh	= THREEx.Planets.createEarth()
earthMesh.receiveShadow	= true
//earthMesh.castShadow	= true
containerEarth.add(earthMesh)
// onRenderFcts.push(function(delta, now){
// 	earthMesh.rotation.y += 1/32 * delta;
// })
var geometry	= new THREE.SphereGeometry(0.5, 32, 32)
var material	= THREEx.createAtmosphereMaterial()
material.uniforms.glowColor.value.set(0x00b3ff)
material.uniforms.coeficient.value	= 0.8
material.uniforms.power.value		= 2.0
var mesh	= new THREE.Mesh(geometry, material );
mesh.scale.multiplyScalar(1.01);
containerEarth.add( mesh );

// new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)
var geometry	= new THREE.SphereGeometry(0.5, 32, 32)
var material	= THREEx.createAtmosphereMaterial()
material.side	= THREE.BackSide
material.uniforms.glowColor.value.set(0x00b3ff)
material.uniforms.coeficient.value	= 0.5
material.uniforms.power.value		= 4.0
var mesh	= new THREE.Mesh(geometry, material );
mesh.scale.multiplyScalar(1.15);
containerEarth.add( mesh );

// new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)
var earthCloud	= THREEx.Planets.createEarthCloud()
earthCloud.receiveShadow	= true
//earthCloud.castShadow	= true
containerEarth.add(earthCloud)
onRenderFcts.push(function(delta, now){
	earthCloud.rotation.y += 1/8 * delta;
})

//////////////////////////////////////////////////////////////////////////////////
//		Camera Controls							//
//////////////////////////////////////////////////////////////////////////////////
// var mouse	= {x : 0, y : 0}
// document.addEventListener('mousemove', function(event){
// 	mouse.x	= (dir.gyr_x_val / window.innerWidth ) - 0.5
// 	mouse.y	= (dir.gyr_y_val / window.innerHeight) - 0.5
// }, false)
onRenderFcts.push(function(delta, now){
	//camera.position.x -= (dir.acc_x_val/100 )//- camera.position.x) * (delta*3)
	//camera.position.y -= (dir.acc_z_val/100) //- camera.position.y) * (delta*3)
	if(dir.gyr_x_val >= 1) {
		camera.rotation.x +=.01;
	} else if (dir.gyr_x_val <= -1) {
		camera.rotation.x -= .01;
	}
	if(dir.gyr_z_val >= 1) {
		camera.rotation.y +=.01;
	} else if (dir.gyr_z_val <= -1) {
		camera.rotation.y -= .01;
	}
	if(dir.gyr_y_val >= 1) {
		camera.rotation.z -=.01;
	} else if (dir.gyr_y_val <= -1) {
		camera.rotation.z += .01;
	}

	if(going) {
		camera.position.z -= .001
	}

	camera.position.x += dir.acc_x_val / 100;
	camera.position.y += dir.acc_y_val / 100;
	camera.position.z += dir.acc_z_val / 100;

	//camera.position.z += (dir.gyr_x_val/100) //- camera.position.z) //* (delta*3)
	// camera.rotation.x += (dir.gyr_x_val/100 )//- camera.rotation.x) * (delta*3)
	// camera.rotation.y += (dir.gyr_y_val/100 )//- camera.rotation.y) * (delta*3)
	// camera.rotation.z += (dir.gyr_z_val/100 )//- camera.rotation.z) * (delta*3)

	// camera.position.x += (gyr_x*5 - camera.position.x) * (delta*3);
	// camera.position.y += (gyr_y*5 - camera.position.y) * (delta*3);
	//camera.lookAt( scene.position )
})
//////////////////////////////////////////////////////////////////////////////////
//		render the scene						//
//////////////////////////////////////////////////////////////////////////////////
onRenderFcts.push(function(){
	renderer.render( scene, camera );
})

//////////////////////////////////////////////////////////////////////////////////
//		loop runner							//
//////////////////////////////////////////////////////////////////////////////////
var lastTimeMsec= null
requestAnimationFrame(function animate(nowMsec){
	// keep looping
	requestAnimationFrame( animate );
	// measure time
	lastTimeMsec	= lastTimeMsec || nowMsec-1000/60
	var deltaMsec	= Math.min(200, nowMsec - lastTimeMsec)
	lastTimeMsec	= nowMsec
	// call each update function
	onRenderFcts.forEach(function(onRenderFct){
		onRenderFct(deltaMsec/1000, nowMsec/1000)
	})
})<|endoftext|>


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

    /*
     * Data Tables
     */

    // Setup - add a text input to each footer cell
    $('#maplist tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );

    var table = $('#maplist').DataTable( {
        "ajax": "data/maps.json",
        "lengthMenu": [[50, 100, 250, 500, 1000], [50, 100, 250, 500, 1000]],
        "pageLength": 250,
        "colReorder": true,
        "stateSave": true,
        "fixedHeader": true,
        "processing": true,
        "deferRender": true,
        "buttons": [
            {
                "extend": "csvHtml5",
                "text": ' Download CSV',
            },
            {
                "extend": "colvis",
                "postfixButtons": [ 'colvisRestore' ],
                "text": ' Toggle Columns'
            }
        ],
        "dom": "<'row'<'col-sm-6'l><'col-sm-6'<'pull-right'B>>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        "columns": [
            { "data": "pk3" },
            { "data": "bsp[, ]" },
            { "data": "filesize" },
            { "data": "filesize" },
            { "data": "shasum" },
            { "data": "title" },
            { "data": "author" },
            { "data": "mapshot" },
            { "data": "gametypes[, ]" },
            { "data": "map[, ]" },
            { "data": "radar[, ]" },
            { "data": "waypoints[, ]" },
            { "data": "license" },
            { "data": "date" }
        ],
        "columnDefs": [
            {   // pk3
                "targets": 0,
                "render": function ( data, type, full, meta ) {
                    var pk3 = data;
                    if (type === 'display' && data.length > 40) {
                        data = ''+data.substr( 0, 38 )+'...';
                    }
                    return '' + data + '';
                }
            },
            {   // bsp
                "targets": 1,
                "render": function ( data, type, full, meta ) {
                    if (data != false && data.length > 0) {
            			if (data.length > 40 && data.indexOf(',') == -1) {
                            data = ''+data.substr( 0, 38 )+'...';
        		    	}
        		    }
                    return data;
                }
            },
            {   // filesize
                "targets": 2,
                "orderData": 3,
                "render": function ( data, type, full, meta ) {
                    return(bytesToSize(data));
                }
            },
            {   // filesize for sorting
                "targets": 3,
                "visible": false,
                "searchable": false
            },
            {   // mapshot file
                "targets": 7,
                "render": function ( data, type, full, meta ) {
                    var string = "";
                    if (data.length > 0) {
                        data.forEach(function(value, index, array) {
                            string += '';
                        });
                    }
                    return string;
                }
            },
            {   // map file
                "targets": 9,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {   // radar file
                "targets": 10,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {   // waypoints file
                "targets": 11,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {
                // date
                "targets": 13,
                "render": function ( data, type, full, meta ) {
                    d = new Date(0);
                    d.setUTCSeconds(data);
                    return d.toISOString().slice(0,10);
                }
            }
        ],
        "initComplete": function( settings, json ) {
            // clear filters on page load
            $("tfoot input").val('').trigger('change');
        },
        "drawCallback": function( settings) {
            $('a[rel=popover]').popover({
                html: true,
                trigger: 'hover',
                content: function () {
                    return '';
                }
            });
        }
    } );

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );

    table.on( 'column-reorder', function ( e, settings, details ) {
        table.draw();
    } );

    /*
     * Charts
     */
    $.get('data/charts.json', function(data) {

        // Pie
        c3.generate(data.mapinfos);
        c3.generate(data.mapshots);
        c3.generate(data.maps);
        c3.generate(data.radars);
        c3.generate(data.waypoints);
        c3.generate(data.licenses);

        // Scatter
        var filesizes = {
            axis: { x: { show: false }, rotated: true },
            tooltip: {
                format: {
                    title: function (x) { return; },
                    name: function (name, ratio, id, index) { return "size"; },
                    value: function (value, ratio, id, index) { return bytesToSize(value); }
                }
            }
        };

        $.extend(filesizes, data.filesizes);
        c3.generate(filesizes);

        // Line
        c3.generate(data.mapsbyyear);

    });

} );

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

<commit_msg>little prettier<commit_after>$(document).ready(function() {

    /*
     * Data Tables
     */

    // Setup - add a text input to each footer cell
    $('#maplist tfoot th').each( function () {
        var title = $(this).text();
        if (title != "mapshot?") {
            $(this).html( '<input type="text" placeholder="filter '+title+'" />' );
        }
    } );

    var table = $('#maplist').DataTable( {
        "ajax": "data/maps.json",
        "lengthMenu": [[50, 100, 250, 500, 1000], [50, 100, 250, 500, 1000]],
        "pageLength": 250,
        "colReorder": true,
        "stateSave": true,
        "fixedHeader": true,
        "processing": true,
        "deferRender": true,
        "buttons": [
            {
                "extend": "csvHtml5",
                "text": ' Download CSV',
            },
            {
                "extend": "colvis",
                "postfixButtons": [ 'colvisRestore' ],
                "text": ' Toggle Columns'
            }
        ],
        "dom": "<'row'<'col-sm-6'l><'col-sm-6'<'pull-right'B>>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        "columns": [
            { "data": "pk3" },
            { "data": "bsp[
 ]" },
            { "data": "filesize" },
            { "data": "filesize" },
            { "data": "shasum" },
            { "data": "title" },
            { "data": "author" },
            { "data": "mapshot" },
            { "data": "gametypes[, ]" },
            { "data": "map[, ]" },
            { "data": "radar[, ]" },
            { "data": "waypoints[, ]" },
            { "data": "license" },
            { "data": "date" }
        ],
        "columnDefs": [
            {   // pk3
                "targets": 0,
                "render": function ( data, type, full, meta ) {
                    var pk3 = data;
                    if (type === 'display' && data.length > 40) {
                        data = ''+data.substr( 0, 38 )+'...';
                    }
                    return '' + data + '';
                }
            },
            {   // bsp
                "targets": 1,
                "render": function ( data, type, full, meta ) {
                    if (data != false && data.length > 0) {
            			if (data.length > 40 && data.indexOf('
') == -1) {
                            data = ''+data.substr( 0, 38 )+'...';
        		    	}
        		    }
                    return data;
                }
            },
            {   // filesize
                "targets": 2,
                "orderData": 3,
                "render": function ( data, type, full, meta ) {
                    return(bytesToSize(data));
                }
            },
            {   // filesize for sorting
                "targets": 3,
                "visible": false,
                "searchable": false
            },
            {   // mapshot file
                "targets": 7,
                "render": function ( data, type, full, meta ) {
                    var string = "";
                    if (data.length > 0) {
                        data.forEach(function(value, index, array) {
                            string += '';
                        });
                    }
                    return string;
                }
            },
            {   // map file
                "targets": 9,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {   // radar file
                "targets": 10,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {   // waypoints file
                "targets": 11,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? true : false;
                }
            },
            {
                // date
                "targets": 13,
                "render": function ( data, type, full, meta ) {
                    d = new Date(0);
                    d.setUTCSeconds(data);
                    return d.toISOString().slice(0,10);
                }
            }
        ],
        "initComplete": function( settings, json ) {
            // clear filters on page load
            $("tfoot input").val('').trigger('change');
        },
        "drawCallback": function( settings) {
            $('a[rel=popover]').popover({
                html: true,
                trigger: 'hover',
                content: function () {
                    return '';
                }
            });
        }
    } );

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );

    table.on( 'column-reorder', function ( e, settings, details ) {
        table.draw();
    } );

    /*
     * Charts
     */
    $.get('data/charts.json', function(data) {

        // Pie
        c3.generate(data.mapinfos);
        c3.generate(data.mapshots);
        c3.generate(data.maps);
        c3.generate(data.radars);
        c3.generate(data.waypoints);
        c3.generate(data.licenses);

        // Scatter
        var filesizes = {
            axis: { x: { show: false }, rotated: true },
            tooltip: {
                format: {
                    title: function (x) { return; },
                    name: function (name, ratio, id, index) { return "size"; },
                    value: function (value, ratio, id, index) { return bytesToSize(value); }
                }
            }
        };

        $.extend(filesizes, data.filesizes);
        c3.generate(filesizes);

        // Line
        c3.generate(data.mapsbyyear);

    });

} );

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

<|endoftext|>


<commit_before>  document.addEventListener("DOMContentLoaded", function(event) {

    console.log("DOM fully loaded and parsed");

    // Upload a photo

    var uploadPhoto = document.getElementById("uploadPhotoBtn");
    var userPhoto = document.getElementById("userPhoto");

    var grayscaleBtn = document.getElementsByTagName("button")[0];
    var canvas = document.getElementById("imgCanvas");
    var ctx = canvas.getContext("2d");
    var grayscaleRangeSlider = document.getElementById("grayscaleRange");
    var brightenRangeSlider = document.getElementById("brightenRange");
    var blurRangeSlider = document.getElementById("blurRange");
    var negativeRangeSlider = document.getElementById("negativeRange");
    var resetBtn = document.getElementById("resetBtn");
    var download = document.getElementById("download");

    var moveTop = document.getElementById("moveTop");
    var moveRight = document.getElementById("moveRight");
    var moveLeft = document.getElementById("moveLeft");
    var moveBottom = document.getElementById("moveBottom");

    var zoomIn = document.getElementById("zoom-in");
    var zoomOut = document.getElementById("zoom-out");

    var rotateControl = document.querySelector(".rotation-circle");
    var x;
    var y;

    var hRatio = canvas.width / userPhoto.width;
    var vRatio = canvas.height / userPhoto.height;

    if (typeof x === "undefined") {
      x = 0;
    }

    if (typeof y === "undefined") {
      y = 0;
    }

    function drawNewImage() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, 0, 0);
      // ctx.drawImage(userPhoto, 0, 0, userPhoto.width * hRatio, userPhoto.height * vRatio,
      //   0, 0, canvas.width, canvas.height);
      var MAX_WIDTH = 374;
      var MAX_HEIGHT = 502;
      var width = userPhoto.width;
      var height = userPhoto.height;

      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(userPhoto, 0, 0, width, height);

    }

    // Photo Uploader

    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(event) {
          var canvas = document.getElementById("imgCanvas");
          var ctx = canvas.getContext("2d");
          userPhoto.setAttribute("src", event.target.result);
          var canvas = document.createElement("canvas");
          ctx.drawImage(userPhoto, 0, 0);

          var MAX_WIDTH = 374;
          var MAX_HEIGHT = 502;
          var width = userPhoto.width;
          var height = userPhoto.height;

          if (width > height) {
            if (width > MAX_WIDTH) {
              height *= MAX_WIDTH / width;
              width = MAX_WIDTH;
            }
          } else {
            if (height > MAX_HEIGHT) {
              width *= MAX_HEIGHT / height;
              height = MAX_HEIGHT;
            }
          }
          canvas.width = width;
          canvas.height = height;
          var ctx = canvas.getContext("2d");
          ctx.drawImage(userPhoto, 0, 0, width, height);

          var dataurl = canvas.toDataURL("image/png");
          userPhoto.setAttribute("src", dataurl);
        }

        reader.readAsDataURL(input.files[0]);
      }
    }

    uploadPhoto.addEventListener("change", function(event) {
      readURL(this);
      drawNewImage();
      ctx.save();
    }, false);

    // Filters: Grayscale

    grayscaleRangeSlider.addEventListener("input", function(event) {
      drawNewImage();
      var imageData = ctx.getImageData(x, y, userPhoto.width, userPhoto.height);
      //pobierz pozycję i wymiary z kontekstu
      var data = imageData.data;
      //zapisz te dane do zmiennej data,
      //imageData.data przechowuje wartości poszczególnych pikseli (0-255)
      var grayscaleVal = grayscaleRangeSlider.value * 0.01;

      drawNewImage();

      for (var i = 0; i < data.length; i += 4) {
        var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];

        data[i] = brightness / grayscaleVal; // red
        data[i + 1] = brightness / grayscaleVal // green
        data[i + 2] = brightness / grayscaleVal; // blue
      }
      // overwrite original image

      ctx.putImageData(imageData, x, y);
      //przetworzone dane umieść z powrotem na danej pozycji x i y
    }, false);

    // Filters: Brighten

    brightenRangeSlider.addEventListener("input", function(event) {
      drawNewImage();
      var imageData = ctx.getImageData(x, y, userPhoto.width, userPhoto.height);
      var data = imageData.data;
      var brightenVal = brightenRangeSlider.value * 0.75;

      for (var i = 0; i < data.length; i += 4) {
        data[i] += brightenVal; // red
        data[i + 1] += brightenVal; // green
        data[i + 2] += brightenVal; // blue
      }
      ctx.putImageData(imageData, x, y);
    }, false);

    // Filters: Blur

    blurRangeSlider.addEventListener("input", function(event) {

      var blurVal = blurRangeSlider.value / 3;

      drawNewImage();
      var passes = 1 * blurVal;
      ctx.globalAlpha = 1 / (blurVal * 2);
      //overlay eight instances of the image over the original, each with 1/8th of full opacity
      for (var i = 1; i <= passes; i++) {
        for (var y = -1; y < 2; y++) {
          for (var x = -1; x < 2; x++) {
            ctx.drawImage(userPhoto, x, y);
          }
        }
      }
      ctx.globalAlpha = 1.0 * blurVal;

    }, false);

    // Filters: Negative

    negativeRangeSlider.addEventListener("input", function(event) {

      drawNewImage();

      var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      var data = imageData.data;
      var negativeVal = negativeRangeSlider.value * 0.0005;

      for (var i = 0; i < data.length; i += 4) {
        data[i] = 255 - data[i] / (negativeVal / 0.01); // red
        data[i + 1] = 255 - data[i + 1] / (negativeVal / 0.02); // green
        data[i + 2] = 255 - data[i + 2] / (negativeVal / 0.05); // blue
        //          data[i + 3] = 255 - data[i + 3] * negativeVal * 0.9; // alpha
      }

      // overwrite original image
      ctx.putImageData(imageData, 0, 0);

    }, false);

    // przycinanie obrazu

    // window.onload(function() {

    // 	ctx.beginPath();
    // 	ctx.rect(canvas.width / 2, canvas.height / 2, 187, 251);
    // 	ctx.clip();
    // 	ctx.scale(2, 2);
    // 	ctx.drawImage(userPhoto);

    // });

    // Zoom-in, Zoom-out

    zoomIn.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      ctx.scale(0.99, 0.99);
    }, false);

    zoomOut.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      ctx.scale(1.01, 1.01);
    }, false);

    // Move

    moveTop.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      y -= 2;
    }, false);

    moveRight.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      x += 2;
    }, false);

    moveLeft.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      x -= 2;
    }, false);

    moveBottom.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      y += 2;
    }, false);

    // Rotation

    rotateControl.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.translate(93.5, 125.5);
      ctx.rotate(15 * Math.PI / 180);
      ctx.translate(-93.5, -125.5);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
    }, false);

    // Reset

    resetBtn.addEventListener("click", function(event) {
      userPhoto.style.webkitFilter = "blur(0px)";
      ctx.restore();
      ctx.drawImage(userPhoto, 0, 0, canvas.width, canvas.height);
    }, false);

    // Download Polaroid

    function downloadCanvas(link, canvasId, filename) {
      link.href = canvas.toDataURL();
      link.download = filename;
    }

    //add Polaroid border

    function borderImage(x) {
      ctx.beginPath();
      ctx.lineWidth = x; // This is your border thickness
      canvas.width += x * 2;
      canvas.height += x * 2;
      ctx.fillStyle = "#fff";
      ctx.strokeStyle = "#fff";
      ctx.globalCompositeOperation="source-over";
      ctx.rect(0, 0, canvas.width, 30);
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.stroke();
      ctx.drawImage(userPhoto, x, x, canvas.width - 2 * x, canvas.height - 2 * x - 50);
    }

    download.addEventListener("click", function(event) {
      borderImage(20);
      downloadCanvas(this, "imgCanvas", "impossible-photo.png");
    }, false);

  });<commit_msg>One step further.<commit_after>  document.addEventListener("DOMContentLoaded", function(event) {

    console.log("DOM fully loaded and parsed");

    // Upload a photo

    var uploadPhoto = document.getElementById("uploadPhotoBtn");
    var userPhoto = document.getElementById("userPhoto");

    var grayscaleBtn = document.getElementsByTagName("button")[0];
    var canvas = document.getElementById("imgCanvas");
    var ctx = canvas.getContext("2d");
    var grayscaleRangeSlider = document.getElementById("grayscaleRange");
    var brightenRangeSlider = document.getElementById("brightenRange");
    var blurRangeSlider = document.getElementById("blurRange");
    var negativeRangeSlider = document.getElementById("negativeRange");
    var resetBtn = document.getElementById("resetBtn");
    var download = document.getElementById("download");

    var moveTop = document.getElementById("moveTop");
    var moveRight = document.getElementById("moveRight");
    var moveLeft = document.getElementById("moveLeft");
    var moveBottom = document.getElementById("moveBottom");

    var zoomIn = document.getElementById("zoom-in");
    var zoomOut = document.getElementById("zoom-out");

    var rotateControl = document.querySelector(".rotation-circle");
    var x;
    var y;

    var hRatio = canvas.width / userPhoto.width;
    var vRatio = canvas.height / userPhoto.height;

    if (typeof x === "undefined") {
      x = 0;
    }

    if (typeof y === "undefined") {
      y = 0;
    }

    function drawNewImage() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, 0, 0);
      // ctx.drawImage(userPhoto, 0, 0, userPhoto.width * hRatio, userPhoto.height * vRatio,
      //   0, 0, canvas.width, canvas.height);
      var MAX_WIDTH = 374;
      var MAX_HEIGHT = 502;
      var width = userPhoto.width;
      var height = userPhoto.height;

      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(userPhoto, 0, 0, width, height);

    }

    // Photo Uploader

    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(event) {
          var canvas = document.getElementById("imgCanvas");
          var ctx = canvas.getContext("2d");
          userPhoto.setAttribute("src", event.target.result);
          var canvas = document.createElement("canvas");
          ctx.drawImage(userPhoto, 0, 0);

          var MAX_WIDTH = 374;
          var MAX_HEIGHT = 502;
          var width = userPhoto.width;
          var height = userPhoto.height;

          if (width > height) {
            if (width > MAX_WIDTH) {
              height *= MAX_WIDTH / width;
              width = MAX_WIDTH;
            }
          } else {
            if (height > MAX_HEIGHT) {
              width *= MAX_HEIGHT / height;
              height = MAX_HEIGHT;
            }
          }
          canvas.width = width;
          canvas.height = height;
          var ctx = canvas.getContext("2d");
          ctx.drawImage(userPhoto, 0, 0, width, height);

          var dataurl = canvas.toDataURL("image/png");
          userPhoto.setAttribute("src", dataurl);
        }

        reader.readAsDataURL(input.files[0]);
      }
    }

    uploadPhoto.addEventListener("change", function(event) {
      readURL(this);
      drawNewImage();
      ctx.save();
    }, false);

    // Filters: Grayscale

    grayscaleRangeSlider.addEventListener("input", function(event) {
      drawNewImage();
      var imageData = ctx.getImageData(x, y, userPhoto.width, userPhoto.height);
      //pobierz pozycję i wymiary z kontekstu
      var data = imageData.data;
      //zapisz te dane do zmiennej data,
      //imageData.data przechowuje wartości poszczególnych pikseli (0-255)
      var grayscaleVal = grayscaleRangeSlider.value * 0.01;

      drawNewImage();

      for (var i = 0; i < data.length; i += 4) {
        var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];

        data[i] = brightness / grayscaleVal; // red
        data[i + 1] = brightness / grayscaleVal // green
        data[i + 2] = brightness / grayscaleVal; // blue
      }
      // overwrite original image

      ctx.putImageData(imageData, x, y);
      //przetworzone dane umieść z powrotem na danej pozycji x i y
    }, false);

    // Filters: Brighten

    brightenRangeSlider.addEventListener("input", function(event) {
      drawNewImage();
      var imageData = ctx.getImageData(x, y, userPhoto.width, userPhoto.height);
      var data = imageData.data;
      var brightenVal = brightenRangeSlider.value * 0.75;

      for (var i = 0; i < data.length; i += 4) {
        data[i] += brightenVal; // red
        data[i + 1] += brightenVal; // green
        data[i + 2] += brightenVal; // blue
      }
      ctx.putImageData(imageData, x, y);
    }, false);

    // Filters: Blur

    blurRangeSlider.addEventListener("input", function(event) {

      var blurVal = blurRangeSlider.value / 3;

      drawNewImage();
      var passes = 1 * blurVal;
      ctx.globalAlpha = 1 / (blurVal * 2);
      //overlay eight instances of the image over the original, each with 1/8th of full opacity
      for (var i = 1; i <= passes; i++) {
        for (var y = -1; y < 2; y++) {
          for (var x = -1; x < 2; x++) {
            ctx.drawImage(userPhoto, x, y);
          }
        }
      }
      ctx.globalAlpha = 1.0 * blurVal;

    }, false);

    // Filters: Negative

    negativeRangeSlider.addEventListener("input", function(event) {

      drawNewImage();

      var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      var data = imageData.data;
      var negativeVal = negativeRangeSlider.value * 0.0005;

      for (var i = 0; i < data.length; i += 4) {
        data[i] = 255 - data[i] / (negativeVal / 0.01); // red
        data[i + 1] = 255 - data[i + 1] / (negativeVal / 0.02); // green
        data[i + 2] = 255 - data[i + 2] / (negativeVal / 0.05); // blue
        //          data[i + 3] = 255 - data[i + 3] * negativeVal * 0.9; // alpha
      }

      // overwrite original image
      ctx.putImageData(imageData, 0, 0);

    }, false);

    // przycinanie obrazu

    // window.onload(function() {

    // 	ctx.beginPath();
    // 	ctx.rect(canvas.width / 2, canvas.height / 2, 187, 251);
    // 	ctx.clip();
    // 	ctx.scale(2, 2);
    // 	ctx.drawImage(userPhoto);

    // });

    // Zoom-in, Zoom-out

    zoomIn.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      ctx.scale(0.99, 0.99);
    }, false);

    zoomOut.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      ctx.scale(1.01, 1.01);
    }, false);

    // Move

    moveTop.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      y -= 2;
    }, false);

    moveRight.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      x += 2;
    }, false);

    moveLeft.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      x -= 2;
    }, false);

    moveBottom.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
      y += 2;
    }, false);

    // Rotation

    rotateControl.addEventListener("click", function(event) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.translate(93.5, 125.5);
      ctx.rotate(15 * Math.PI / 180);
      ctx.translate(-93.5, -125.5);
      ctx.drawImage(userPhoto, x, y);
      userPhoto.style.display = "none";
    }, false);

    // Reset

    resetBtn.addEventListener("click", function(event) {
      userPhoto.style.webkitFilter = "blur(0px)";
      ctx.restore();
      ctx.drawImage(userPhoto, 0, 0, canvas.width, canvas.height);
    }, false);

    // Download Polaroid

    function downloadCanvas(link, canvasId, filename) {
      link.href = canvas.toDataURL();
      link.download = filename;
    }

    //add Polaroid border

    function borderImage(x) {
      ctx.beginPath();
      ctx.lineWidth = x; // This is your border thickness
      canvas.width += x * 2;
      canvas.height += x * 2;
      ctx.fillStyle = "#fff";
      ctx.strokeStyle = "#fff";
      ctx.globalCompositeOperation="source-over";
      ctx.rect(0, 0, canvas.width, 30);
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.stroke();
      ctx.drawImage(userPhoto, x, x, canvas.width - 2 * x, canvas.height - 2 * x - 50);
      ctx.strokeStyle = "#000";
      canvas.stroke();
    }

    download.addEventListener("click", function(event) {
      borderImage(20);
      downloadCanvas(this, "imgCanvas", "impossible-photo.png");
    }, false);

  });<|endoftext|>


<commit_before>/**
 * Ternific Copyright (c) 2014 Miguel Castillo.
 *
 * Licensed under MIT
 */

define(function (require, exports, module) {
    "use strict";

    var FileSystem   = brackets.getModule("filesystem/FileSystem"),
        spromise     = require("libs/js/spromise"),
        FileStream   = require("FileStream"),
        ProjectFiles = require("ProjectFiles");

    var inProgress = {};
    var httpCache  = {};

    /**
     * Load file from a remote location via http
     *
     * @param {string} fileName is the name of the file to load
     * @returns {spromise}
     */
    function fromHttp (fileName) {
        if (inProgress[fileName]) {
            return inProgress[fileName];
        }

        if (httpCache[fileName]) {
            return httpCache[fileName];
        }

        inProgress[fileName] = spromise.thenable($.ajax(fileName, {"contentType": "text"}))
            .always(function() {
                delete inProgress[fileName];
            })
            .then(function(content) {
                return {
                    fileName: fileName,
                    fullPath: fileName,
                    content: content
                };
            });

        return inProgress[fileName];
    }

    /**
     * Load file from local filesystem
     *
     * @param {string} fileName is the name of the file to open
     * @param {string} filePath is a fully resolved file path to search fileName in
     * @returns {spromise} if successful, the file meta data is provider. If failed, the reason
     *   is provided.
     */
    function fromDirectory (fileName, filePath) {
        var handle = FileSystem.getFileForPath(filePath + fileName);

        return spromise(function(resolve, reject) {
            handle.exists(function(err, exists) {
                if (err || !exists) {
                    reject(err);
                }
                else {
                    resolve(new FileStream({
                        handle: handle,
                        fileName: fileName,
                        filePath: filePath
                    }));
                }
            });
        });
    }

    /**
     * Interface to load a file
     *
     * @param {string} fileName is the name of the file to open
     * @param {string} filePath is a fully resolved file path to search fileName in
     * @returns {spromise} if successful, the file meta data is provider. If failed, the reason
     *   is provided.
     */
    function readFile (fileName, filePath) {
        if (/^https?:\/\//.test(fileName)) {
            return fromHTTP(fileName);
        }

        return spromise(function(resolve, reject) {
            openFile(fileName, filePath)
                .done(function(file) {
                    file.read().done(resolve);
                })
                .fail(reject);
        });
    }

    /**
     * Opens a file from local filesystem.
     *
     * @param {string} fileName is the name of the file to open
     * @param {string} filePath is a fully resolved file path to search fileName in
     * @returns {spromise} if successful, the file meta data is provider. If failed, the reason
     *   is provided.
     */
    function openFile (fileName, filePath) {
        return spromise(function(resolve, reject) {
            fromDirectory(fileName, filePath).done(resolve)
                .fail(function() {
                    fromDirectory(fileName, ProjectFiles.currentProject.fullPath).done(resolve).fail(reject);
                });
        }).fail(function(err) {
            console.log("====> error", err, fileName, filePath);
        });
    }

    return {
        readFile: readFile,
        openFile: openFile,
        fromHttp: fromHttp,
        fromDirectory: fromDirectory
    };
});

<commit_msg>Commenting out file loading error reporting<commit_after>/**
 * Ternific Copyright (c) 2014 Miguel Castillo.
 *
 * Licensed under MIT
 */

define(function (require, exports, module) {
    "use strict";

    var FileSystem   = brackets.getModule("filesystem/FileSystem"),
        spromise     = require("libs/js/spromise"),
        FileStream   = require("FileStream"),
        ProjectFiles = require("ProjectFiles");

    var inProgress = {};
    var httpCache  = {};

    /**
     * Load file from a remote location via http
     *
     * @param {string} fileName is the name of the file to load
     * @returns {spromise}
     */
    function fromHttp (fileName) {
        if (inProgress[fileName]) {
            return inProgress[fileName];
        }

        if (httpCache[fileName]) {
            return httpCache[fileName];
        }

        inProgress[fileName] = spromise.thenable($.ajax(fileName, {"contentType": "text"}))
            .always(function() {
                delete inProgress[fileName];
            })
            .then(function(content) {
                return {
                    fileName: fileName,
                    fullPath: fileName,
                    content: content
                };
            });

        return inProgress[fileName];
    }

    /**
     * Load file from local filesystem
     *
     * @param {string} fileName is the name of the file to open
     * @param {string} filePath is a fully resolved file path to search fileName in
     * @returns {spromise} if successful, the file meta data is provider. If failed, the reason
     *   is provided.
     */
    function fromDirectory (fileName, filePath) {
        var handle = FileSystem.getFileForPath(filePath + fileName);

        return spromise(function(resolve, reject) {
            handle.exists(function(err, exists) {
                if (err || !exists) {
                    reject(err);
                }
                else {
                    resolve(new FileStream({
                        handle: handle,
                        fileName: fileName,
                        filePath: filePath
                    }));
                }
            });
        });
    }

    /**
     * Interface to load a file
     *
     * @param {string} fileName is the name of the file to open
     * @param {string} filePath is a fully resolved file path to search fileName in
     * @returns {spromise} if successful, the file meta data is provider. If failed, the reason
     *   is provided.
     */
    function readFile (fileName, filePath) {
        if (/^https?:\/\//.test(fileName)) {
            return fromHTTP(fileName);
        }

        return spromise(function(resolve, reject) {
            openFile(fileName, filePath)
                .done(function(file) {
                    file.read().done(resolve);
                })
                .fail(reject);
        });
    }

    /**
     * Opens a file from local filesystem.
     *
     * @param {string} fileName is the name of the file to open
     * @param {string} filePath is a fully resolved file path to search fileName in
     * @returns {spromise} if successful, the file meta data is provider. If failed, the reason
     *   is provided.
     */
    function openFile (fileName, filePath) {
        return spromise(function(resolve, reject) {
            fromDirectory(fileName, filePath).done(resolve)
                .fail(function() {
                    fromDirectory(fileName, ProjectFiles.currentProject.fullPath).done(resolve).fail(reject);
                });
        }).fail(function(err) {
            //console.log("====> error", err, fileName, filePath);
        });
    }

    return {
        readFile: readFile,
        openFile: openFile,
        fromHttp: fromHttp,
        fromDirectory: fromDirectory
    };
});

<|endoftext|>


<commit_before>var config = {
  app: 8080,
  stream: 8081,
  token: 'foobar',
  token_changed: false
}

var HTTP = require('http')
  , SocketIO = require('socket.io')
  , net = require('net')
  , msgpack = require('msgpack')
  , sys = require('sys')
  , crypto = require('crypto')

var app = HTTP.createServer(function (request, response) {
  response.writeHead(301, {'Location': 'http://www.google.com/'});
  response.end('');
});
app.listen(config.app);
var io = SocketIO.listen(app);
io.log.info('Listening app');

var streams = {};
streams.broadcast = function (msg) {
  for(var k in streams) {
    if(!streams.hasOwnProperty(k)) continue;
    if(typeof streams[k] == 'function') continue;
    streams[k].write(msgpack.pack(msg));
  }
}
var stream_hooks = {};

var util = {
  emitter: function(m, global) {
    var emitter = (global && m.global) ? io.sockets : io.sockets.sockets[m.socket];
    if(!emitter) return r({error: 404, message: 'socket not found'});
    if(m.broadcast) emitter = emitter.broadcast;
    if(m.volatile) emitter = emitter.volatile;
    if(m.json) emitter = emitter.json;
    return emitter;
  }
}

var stream_handlers = {
  on: function(m, c, r) {
    // TODO: socket less hook
    var socket = io.sockets.sockets[m.socket];
    if(!socket) return r({error: 404, message: 'socket not found'});
    if(!stream_hooks[c.cid]) stream_hooks[c.cid] = {};

    var hid = crypto.createHash('md5').update(c.cid+Date.now()+m.kind+m.socket).digest('hex');

    var hook = function(data, callback) {
      console.log(hook.hid + " callback:", data);
      c.write(msgpack.pack({
        type: 'event',
        hook: hook.hid,
        data: data
      }));
    }
    socket.on(m.kind, hook);
    hook.hid = hid;

    stream_hooks[c.cid][hook.hid] = hook;
    r({type: 'on', kind: m.kind, hook: hook.hid});
  },
  emit: function(m, c, r) {
    util.emitter(m, true).emit(m.kind, m.message);
    r({type: 'emit', kind: m.kind, done: true});
  },
  send: function(m, c, r) {
    util.emitter(m, true).send(m.message);
    r({type: 'send', done: true});
  },
  get: function(m, c, r) {
  },
  set: function(m, c, r) {
  },
  set_token: function(m, c, r) {
    if(config.token_changed) r({error: 406, message: 'token already set, cannot overwrite'});
    config.token = m.token;
    config.token_changed = true;
    r({type: 'set_token', done: true});
  }
};

var server = net.createServer(function (c) {
  var authorized = false;
  c.cid = crypto.createHash('md5').update(c.remoteAddress + c.remotePort + Date.now()).digest('hex');

  io.log.info('stream: new connection - ' + c.cid);
  c.on('end', function() {
    delete streams[c.cid];
    io.log.info('stream: connection end - ' + c.cid);
  });

  var ms = new msgpack.Stream(c);
  ms.addListener('msg', function (m) {
    if (authorized && m.type) {
      io.log.debug('stream ' + c.cid + ': handle - ' + sys.inspect(m));

      var handler = stream_handlers[m.type];
      if (!handler) {
        io.log.error('stream ' + c.cid + ': handler for ' + m.type + ' not found, ignoring.');
        c.write(msgpack.pack({error: 400, message: 'handler for "' + m.type + '" not found.', reply_to: m.id}));
        return;
      }

      handler(m, c, function(reply) {
        reply.reply_to = m.id;
        io.log.debug('stream ' + c.cid + ': replying - ' + sys.inspect(m));
        c.write(msgpack.pack(reply));
      });
    } else if (!authorized) {
      if (m.auth == config.token) {
        authorized = true;
        streams[c.cid] = c;
        c.write(msgpack.pack({auth: true}));

        io.log.info('stream ' + c.cid + ': authorized');
      } else {
        c.write(msgpack.pack({auth: false}));
        c.destroy();

        io.log.warn('stream ' + c.cid + ': AUTH FAILED');
      }
    } else {
      io.log.error('stream ' + c.cid + ': no type specified, ignoreing.')
      c.write(msgpack.pack({error: 400, message: "'type' not specified"}));
    }
  });
});
server.listen(config.stream);
io.log.info('Listening stream');

io.sockets.on('connection', function (socket) {
  streams.broadcast({type: 'connect', socket: socket.id});
  var sockid = socket.id;
  socket.on('disconnect', function (sock) {
    streams.broadcast({type: 'disconnect', socket: sockid});
  });
});
<commit_msg>take config from argv<commit_after>var config = {
  app: process.argv[1],
  stream: process.argv[2],
  token: process.argv[3],
  token_changed: false
}
if (app.match(/^\d+$/))    config.app    = parseInt(config.app, 10);
if (stream.match(/^\d+$/)) config.stream = parseInt(config.stream, 10);

var HTTP = require('http')
  , SocketIO = require('socket.io')
  , net = require('net')
  , msgpack = require('msgpack')
  , sys = require('sys')
  , crypto = require('crypto')

var app = HTTP.createServer(function (request, response) {
  response.writeHead(301, {'Location': 'http://www.google.com/'});
  response.end('');
});
app.listen(config.app);
var io = SocketIO.listen(app);
io.log.info('Listening app');

var streams = {};
streams.broadcast = function (msg) {
  for(var k in streams) {
    if(!streams.hasOwnProperty(k)) continue;
    if(typeof streams[k] == 'function') continue;
    streams[k].write(msgpack.pack(msg));
  }
}
var stream_hooks = {};

var util = {
  emitter: function(m, global) {
    var emitter = (global && m.global) ? io.sockets : io.sockets.sockets[m.socket];
    if(!emitter) return r({error: 404, message: 'socket not found'});
    if(m.broadcast) emitter = emitter.broadcast;
    if(m.volatile) emitter = emitter.volatile;
    if(m.json) emitter = emitter.json;
    return emitter;
  }
}

var stream_handlers = {
  on: function(m, c, r) {
    // TODO: socket less hook
    var socket = io.sockets.sockets[m.socket];
    if(!socket) return r({error: 404, message: 'socket not found'});
    if(!stream_hooks[c.cid]) stream_hooks[c.cid] = {};

    var hid = crypto.createHash('md5').update(c.cid+Date.now()+m.kind+m.socket).digest('hex');

    var hook = function(data, callback) {
      console.log(hook.hid + " callback:", data);
      c.write(msgpack.pack({
        type: 'event',
        hook: hook.hid,
        data: data
      }));
    }
    socket.on(m.kind, hook);
    hook.hid = hid;

    stream_hooks[c.cid][hook.hid] = hook;
    r({type: 'on', kind: m.kind, hook: hook.hid});
  },
  emit: function(m, c, r) {
    util.emitter(m, true).emit(m.kind, m.message);
    r({type: 'emit', kind: m.kind, done: true});
  },
  send: function(m, c, r) {
    util.emitter(m, true).send(m.message);
    r({type: 'send', done: true});
  },
  get: function(m, c, r) {
  },
  set: function(m, c, r) {
  },
  set_token: function(m, c, r) {
    if(config.token_changed) r({error: 406, message: 'token already set, cannot overwrite'});
    config.token = m.token;
    config.token_changed = true;
    r({type: 'set_token', done: true});
  }
};

var server = net.createServer(function (c) {
  var authorized = false;
  c.cid = crypto.createHash('md5').update(c.remoteAddress + c.remotePort + Date.now()).digest('hex');

  io.log.info('stream: new connection - ' + c.cid);
  c.on('end', function() {
    delete streams[c.cid];
    io.log.info('stream: connection end - ' + c.cid);
  });

  var ms = new msgpack.Stream(c);
  ms.addListener('msg', function (m) {
    if (authorized && m.type) {
      io.log.debug('stream ' + c.cid + ': handle - ' + sys.inspect(m));

      var handler = stream_handlers[m.type];
      if (!handler) {
        io.log.error('stream ' + c.cid + ': handler for ' + m.type + ' not found, ignoring.');
        c.write(msgpack.pack({error: 400, message: 'handler for "' + m.type + '" not found.', reply_to: m.id}));
        return;
      }

      handler(m, c, function(reply) {
        reply.reply_to = m.id;
        io.log.debug('stream ' + c.cid + ': replying - ' + sys.inspect(m));
        c.write(msgpack.pack(reply));
      });
    } else if (!authorized) {
      if (m.auth == config.token) {
        authorized = true;
        streams[c.cid] = c;
        c.write(msgpack.pack({auth: true}));

        io.log.info('stream ' + c.cid + ': authorized');
      } else {
        c.write(msgpack.pack({auth: false}));
        c.destroy();

        io.log.warn('stream ' + c.cid + ': AUTH FAILED');
      }
    } else {
      io.log.error('stream ' + c.cid + ': no type specified, ignoreing.')
      c.write(msgpack.pack({error: 400, message: "'type' not specified"}));
    }
  });
});
server.listen(config.stream);
io.log.info('Listening stream');

io.sockets.on('connection', function (socket) {
  streams.broadcast({type: 'connect', socket: socket.id});
  var sockid = socket.id;
  socket.on('disconnect', function (sock) {
    streams.broadcast({type: 'disconnect', socket: sockid});
  });
});
<|endoftext|>


<commit_before>'use strict';

var storeHours = ['6am','7am','9am','10am','11am','12pm','1pm','2pm','3pm','4pm','5pm','6pm','7pm','8pm','Total'];

var body = document.getElementsByTagName('body')[0];

function cookieShops (minCust, maxCust, avgCookie, name) {
  this.minCust = minCust;
  this.maxCust = maxCust;
  this.avgCookie = avgCookie;
  this.name = name;
  this.salesArray = [];

  this.randCust = function() {
    return Math.floor (Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
  };

  this.cookieSales = function() {
    var total = 0;
    for (var i = 0; i < storeHours.length - 1; i++) {
      var salesPerhour = Math.floor(this.randCust() * this.avgCookie);
      this.salesArray.push(salesPerhour);
      total += salesPerhour;
    }
    this.salesArray.push(total);
  };

  this.createListItems = function(){
    var newHeading = document.createElement('h2');
    body.appendChild(newHeading);
    newHeading.innerText = this.name;
    var newUL = document.createElement('ul');
    for (var i = 0; i < storeHours.length; i++) {
      var newLI = document.createElement('li');
      newLI.innerText = storeHours[i] + ': ' + this.salesArray[i] + ' cookies';
      newUL.appendChild(newLI);
    }
    body.appendChild(newUL);
  };
};
var shopsOne = new cookieShops(23, 65, 6.3,'1st and Pike');
var shopsTwo = new cookieShops(3, 24, 1.2,'SeaTac Airport');
var shopsThree = new cookieShops(11, 38, 3.7,'Seattle Center');
var shopsFour = new cookieShops(20, 38, 2.3,'Capitol Hill');
var shopsFive = new cookieShops(2, 16, 4.6,'Alki');
<commit_msg>Update<commit_after>'use strict';

var storeHours = ['6am','7am','9am','10am','11am','12pm','1pm','2pm','3pm','4pm','5pm','6pm','7pm','8pm','Total'];

var body = document.getElementsByTagName('body')[0];

function cookieShops (minCust, maxCust, avgCookie, name) {
  this.minCust = minCust;
  this.maxCust = maxCust;
  this.avgCookie = avgCookie;
  this.name = name;
  this.salesArray = [];

  this.randCust = function() {
    return Math.floor (Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
  };

  this.cookieSales = function() {
    var total = 0;
    for (var i = 0; i < storeHours.length - 1; i++) {
      var salesPerhour = Math.floor(this.randCust() * this.avgCookie);
      this.salesArray.push(salesPerhour);
      total += salesPerhour;
    }
    this.salesArray.push(total);
  };

  this.createListItems = function(){
    var newHeading = document.createElement('h2');
    body.appendChild(newHeading);
    newHeading.innerText = this.name;
    var newUL = document.createElement('ul');
    for (var i = 0; i < storeHours.length; i++) {
      var newLI = document.createElement('li');
      newLI.innerText = storeHours[i] + ': ' + this.salesArray[i] + ' cookies';
      newUL.appendChild(newLI);
    }
    body.appendChild(newUL);
  };
};

this.cookiesTable = function() {
  var table = document.createElement('table');
  body.appendChild(table);
  var tableRow = document.createElement('tr');
  table.appendChild(table);
  var tableHeader = document.createElement('th');
  tableRow.appendChild(tableHeader);
  var tableCells = document.createElement('th');
  tableCells.innerText = 'hours[i]';
  for (var i = 0; i < storeHours.length + 1; i++)
    var headerCells = document.createElement('th');

};

var shopsOne = new cookieShops(23, 65, 6.3,'1st and Pike');
var shopsTwo = new cookieShops(3, 24, 1.2,'SeaTac Airport');
var shopsThree = new cookieShops(11, 38, 3.7,'Seattle Center');
var shopsFour = new cookieShops(20, 38, 2.3,'Capitol Hill');
var shopsFive = new cookieShops(2, 16, 4.6,'Alki');
<|endoftext|>


<commit_before>function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function backToTop() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
}

function passwordsMatch() {
  console.log("passwordsMatch()");

  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");
    $('#passwordError').addClass("hidden");

    return true;
  }

  $('#passGroup').addClass("has-error");
  $('#passwordError').removeClass("hidden");

  backToTop();

  return false;
}

function onMessageChange() {
    console.log("onMessageChange()");
    var m = $('#message');

    $("#count").text( m.val().length  );

    m.autosize({ append: '\n'});
    m.trigger('autosize.resize');
}

function messageUpdated() {
  $('#message').select();
  onMessageChange();
}

function clearMessage() {
  $('#message').val('');
  onMessageChange();
}

function pageEncrypt() {
  console.log("pageEncrypt()");
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

function pageDecrypt() {
  console.log("pageDecrypt()");
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

$( function() {

  $("#message").change( onMessageChange );
  $("#message").keyup( onMessageChange );

  $('#encrypt').click( pageEncrypt );
  $('#decrypt').click( pageDecrypt );

  $('#backToTop').click( backToTop );
  $('#reset').click( clearMessage );

  onMessageChange();

  $('.page').show();
  $('#splashscreen').fadeOut('slow')

  console.log('Page loaded');
});
<commit_msg>Update app.js<commit_after>function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function backToTop() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
}

function passwordsMatch() {
  console.log("passwordsMatch()");

  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");
    $('#passwordError').addClass("hidden");

    return true;
  }

  $('#passGroup').addClass("has-error");
  $('#passwordError').removeClass("hidden");

  backToTop();

  return false;
}

function onMessageChange() {
    console.log("onMessageChange()");
    var m = $('#message');

    $("#count").text( m.val().length  );

    m.autosize({ append: '\n'});
    m.trigger('autosize.resize');
}

function messageUpdated() {
  $('#message').select();
  onMessageChange();
}

function clearMessage() {
  $('#message').val('');
  onMessageChange();
}

function pageEncrypt() {
  console.log("pageEncrypt()");
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

function pageDecrypt() {
  console.log("pageDecrypt()");
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

$( function() {

  $("#message").change( onMessageChange );
  $("#message").keyup( onMessageChange );

  $('#encrypt').click( pageEncrypt );
  $('#decrypt').click( pageDecrypt );

  $('#backToTop').click( backToTop );
  $('#reset').click( clearMessage );

  onMessageChange();

  $('#splashscreen').fadeOut('slow')

  console.log('Page loaded');
});
<|endoftext|>


<commit_before>'use strict';

var main = require('./main');
main.debug = true;
require('./StoneConstants');
require('./rb');

require('./test/TestAi');
require('./test/TestGameLogic');
require('./test/TestGroup');
require('./test/TestStone');

main.tests.run();
<commit_msg>Test all now<commit_after>'use strict';

var main = require('./main');
main.debug = true;
require('./StoneConstants');
require('./rb');

require('./test/TestAll');

main.tests.run();
<|endoftext|>