<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'base/js/namespace',
    'jquery',
    'base/js/utils',
    'base/js/dialog',
    'base/js/keyboard',
    'moment',
], function(IPython, $, utils, dialog, keyboard, moment) {
    "use strict";

    var SaveWidget = function (selector, options) {
        /**
         * TODO: Remove circular ref.
         */
        this.notebook = undefined;
        this.selector = selector;
        this.events = options.events;
        this._checkpoint_date = undefined;
        this.keyboard_manager = options.keyboard_manager;
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.bind_events();
        }
    };

    SaveWidget.prototype.bind_events = function () {
        var that = this;
        this.element.find('span.filename').click(function () {
            that.rename_notebook({notebook: that.notebook});
        });
        this.events.on('notebook_loaded.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
        });
        this.events.on('notebook_saved.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
        });
        this.events.on('notebook_renamed.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
            that.update_address_bar();
        });
        this.events.on('notebook_save_failed.Notebook', function () {
            that.set_save_status('Autosave Failed!');
        });
        this.events.on('notebook_read_only.Notebook', function () {
            that.set_save_status('(read only)');
            // disable future set_save_status
            that.set_save_status = function () {};
        });
        this.events.on('checkpoints_listed.Notebook', function (event, data) {
            that._set_last_checkpoint(data[0]);
        });

        this.events.on('checkpoint_created.Notebook', function (event, data) {
            that._set_last_checkpoint(data);
        });
        this.events.on('set_dirty.Notebook', function (event, data) {
            that.set_autosaved(data.value);
        });
    };

    SaveWidget.prototype.rename_notebook = function (options) {
        options = options || {};
        var that = this;
        var dialog_body = $('
').append(
            $("
").addClass("rename-message")
                .text('Enter a new notebook name:')
        ).append(
            $("
")
        ).append(
            $('<input/>').attr('type','text').attr('size','25').addClass('form-control')
            .val(options.notebook.get_notebook_name())
        );
        var d = dialog.modal({
            title: "Rename Notebook",
            body: dialog_body,
            notebook: options.notebook,
            keyboard_manager: this.keyboard_manager,
            buttons : {
                "OK": {
                    class: "btn-primary",
                    click: function () {
                        var new_name = d.find('input').val();
                        if (!options.notebook.test_notebook_name(new_name)) {
                            d.find('.rename-message').text(
                                "Invalid notebook name. Notebook names must "+
                                "have 1 or more characters and can contain any characters " +
                                "except :/\\. Please enter a new notebook name:"
                            );
                            return false;
                        } else {
                            d.find('.rename-message').text("Renaming...");
                            d.find('input[type="text"]').prop('disabled', true);
                            that.notebook.rename(new_name).then(
                                function () {
                                    d.modal('hide');
                                }, function (error) {
                                    d.find('.rename-message').text(error.message || 'Unknown error');
                                    d.find('input[type="text"]').prop('disabled', false).focus().select();
                                }
                            );
                            return false;
                        }
                    }
                },
                "Cancel": {}
                },
            open : function () {
                /**
                 * Upon ENTER, click the OK button.
                 */
                d.find('input[type="text"]').keydown(function (event) {
                    if (event.which === keyboard.keycodes.enter) {
                        d.find('.btn-primary').first().click();
                        return false;
                    }
                });
                d.find('input[type="text"]').focus().select();
            }
        });
    };

    SaveWidget.prototype.update_notebook_name = function () {
        var nbname = this.notebook.get_notebook_name();
        this.element.find('span.filename').text(nbname);
    };

    SaveWidget.prototype.update_document_title = function () {
        var nbname = this.notebook.get_notebook_name();
        document.title = nbname;
    };

    SaveWidget.prototype.update_address_bar = function(){
        var base_url = this.notebook.base_url;
        var path = this.notebook.notebook_path;
        var state = {path : path};
        window.history.replaceState(state, "", utils.url_join_encode(
            base_url,
            "notebooks",
            path)
        );
    };

    SaveWidget.prototype.set_save_status = function (msg) {
        this.element.find('span.autosave_status').text(msg);
    };

    SaveWidget.prototype._set_checkpoint_status = function (human_date, iso_date) {
        var el = this.element.find('span.checkpoint_status');
        if(human_date){
            el.text("Last Checkpoint: "+human_date).attr('title',iso_date);
        } else {
            el.text('').attr('title', 'no-checkpoint');
        }
    };

    // compute (roughly) the remaining time in millisecond until the next
    // moment.js relative time update of the string, which by default
    // happend at
    //  (a few seconds ago)
    //  - 45sec,
    //  (a minute ago)
    //  - 90sec,
    //      ( x minutes ago)
    //      - then every minutes until
    //  - 45 min,
    //      (an hour ago)
    //  - 1h45,
    //      (x hours ago )
    //      - then every hours
    //  - 22 hours ago
    var _next_timeago_update = function(deltatime_ms){
        var s = 1000;
        var m = 60*s;
        var h = 60*m;

        var mtt = moment.relativeTimeThreshold;

        if(deltatime_ms < mtt.s*s){
            return mtt.s*s-deltatime_ms;
        } else if (deltatime_ms < (mtt.s*s+m)) {
            return (mtt.s*s+m)-deltatime_ms;
        } else if (deltatime_ms < mtt.m*m){
            return m;
        } else if (deltatime_ms < (mtt.m*m+h)){
            return (mtt.m*m+h)-deltatime_ms;
        } else  {
            return h;
        }
    };

    SaveWidget.prototype._regularly_update_checkpoint_date = function(){
       if (!this._checkpoint_date) {
            this._set_checkpoint_status(null);
            console.log('no checkpoint done');
            return;
        }
        var chkd = moment(this._checkpoint_date);
        var longdate = chkd.format('llll');

        var that = this;
        var recall  = function(t){
            /**
             * recall slightly later (1s) as long timeout in js might be imprecise,
             * and you want to be call **after** the change of formatting should happend.
             */
            return setTimeout(
                $.proxy(that._regularly_update_checkpoint_date, that),
                t + 1000
            );
        };
        var tdelta = Math.ceil(new Date()-this._checkpoint_date);

        // update regularly for the first 6hours and show
        // <x time> ago
        if(tdelta < 6*3600*1000){
            recall(_next_timeago_update(tdelta));
            this._set_checkpoint_status(chkd.fromNow(), longdate);
        // otherwise update every hour and show
        // <Today | yesterday|...> at hh,mm,ss
        } else  {
            recall(1*3600*1000);
            this._set_checkpoint_status(chkd.calendar(), longdate);
        }
    };

    SaveWidget.prototype._set_last_checkpoint = function (checkpoint) {
        if (checkpoint) {
            this._checkpoint_date = new Date(checkpoint.last_modified);
        } else {
            this._checkpoint_date = null;
        }
        this._regularly_update_checkpoint_date();

    };

    SaveWidget.prototype.set_autosaved = function (dirty) {
        if (dirty) {
            this.set_save_status("(unsaved changes)");
        } else {
            this.set_save_status("(autosaved)");
        }
    };

    // Backwards compatibility.
    IPython.SaveWidget = SaveWidget;

    return {'SaveWidget': SaveWidget};

});
<commit_msg>fix regular checkpoint updates in notebook<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'base/js/namespace',
    'jquery',
    'base/js/utils',
    'base/js/dialog',
    'base/js/keyboard',
    'moment',
], function(IPython, $, utils, dialog, keyboard, moment) {
    "use strict";

    var SaveWidget = function (selector, options) {
        /**
         * TODO: Remove circular ref.
         */
        this.notebook = undefined;
        this.selector = selector;
        this.events = options.events;
        this._checkpoint_date = undefined;
        this.keyboard_manager = options.keyboard_manager;
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.bind_events();
        }
    };

    SaveWidget.prototype.bind_events = function () {
        var that = this;
        this.element.find('span.filename').click(function () {
            that.rename_notebook({notebook: that.notebook});
        });
        this.events.on('notebook_loaded.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
        });
        this.events.on('notebook_saved.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
        });
        this.events.on('notebook_renamed.Notebook', function () {
            that.update_notebook_name();
            that.update_document_title();
            that.update_address_bar();
        });
        this.events.on('notebook_save_failed.Notebook', function () {
            that.set_save_status('Autosave Failed!');
        });
        this.events.on('notebook_read_only.Notebook', function () {
            that.set_save_status('(read only)');
            // disable future set_save_status
            that.set_save_status = function () {};
        });
        this.events.on('checkpoints_listed.Notebook', function (event, data) {
            that._set_last_checkpoint(data[0]);
        });

        this.events.on('checkpoint_created.Notebook', function (event, data) {
            that._set_last_checkpoint(data);
        });
        this.events.on('set_dirty.Notebook', function (event, data) {
            that.set_autosaved(data.value);
        });
    };

    SaveWidget.prototype.rename_notebook = function (options) {
        options = options || {};
        var that = this;
        var dialog_body = $('
').append(
            $("
").addClass("rename-message")
                .text('Enter a new notebook name:')
        ).append(
            $("
")
        ).append(
            $('<input/>').attr('type','text').attr('size','25').addClass('form-control')
            .val(options.notebook.get_notebook_name())
        );
        var d = dialog.modal({
            title: "Rename Notebook",
            body: dialog_body,
            notebook: options.notebook,
            keyboard_manager: this.keyboard_manager,
            buttons : {
                "OK": {
                    class: "btn-primary",
                    click: function () {
                        var new_name = d.find('input').val();
                        if (!options.notebook.test_notebook_name(new_name)) {
                            d.find('.rename-message').text(
                                "Invalid notebook name. Notebook names must "+
                                "have 1 or more characters and can contain any characters " +
                                "except :/\\. Please enter a new notebook name:"
                            );
                            return false;
                        } else {
                            d.find('.rename-message').text("Renaming...");
                            d.find('input[type="text"]').prop('disabled', true);
                            that.notebook.rename(new_name).then(
                                function () {
                                    d.modal('hide');
                                }, function (error) {
                                    d.find('.rename-message').text(error.message || 'Unknown error');
                                    d.find('input[type="text"]').prop('disabled', false).focus().select();
                                }
                            );
                            return false;
                        }
                    }
                },
                "Cancel": {}
                },
            open : function () {
                /**
                 * Upon ENTER, click the OK button.
                 */
                d.find('input[type="text"]').keydown(function (event) {
                    if (event.which === keyboard.keycodes.enter) {
                        d.find('.btn-primary').first().click();
                        return false;
                    }
                });
                d.find('input[type="text"]').focus().select();
            }
        });
    };

    SaveWidget.prototype.update_notebook_name = function () {
        var nbname = this.notebook.get_notebook_name();
        this.element.find('span.filename').text(nbname);
    };

    SaveWidget.prototype.update_document_title = function () {
        var nbname = this.notebook.get_notebook_name();
        document.title = nbname;
    };

    SaveWidget.prototype.update_address_bar = function(){
        var base_url = this.notebook.base_url;
        var path = this.notebook.notebook_path;
        var state = {path : path};
        window.history.replaceState(state, "", utils.url_join_encode(
            base_url,
            "notebooks",
            path)
        );
    };

    SaveWidget.prototype.set_save_status = function (msg) {
        this.element.find('span.autosave_status').text(msg);
    };

    SaveWidget.prototype._set_last_checkpoint = function (checkpoint) {
        if (checkpoint) {
            this._checkpoint_date = new Date(checkpoint.last_modified);
        } else {
            this._checkpoint_date = null;
        }
        this._render_checkpoint();
    };

    SaveWidget.prototype._render_checkpoint = function () {
        /** actually set the text in the element, from our _checkpoint value

        called directly, and periodically in timeouts.
        */
        this._schedule_render_checkpoint();
        var el = this.element.find('span.checkpoint_status');
        if (!this._checkpoint_date) {
            el.text('').attr('title', 'no checkpoint');
            return;
        }
        var chkd = moment(this._checkpoint_date);
        var long_date = chkd.format('llll');
        var human_date;
        var tdelta = Math.ceil(new Date() - this._checkpoint_date);
        if (tdelta < utils.time.milliseconds.d){
            // less than 24 hours old, use relative date
            human_date = chkd.fromNow();
        } else {
            // otherwise show calendar
            // <Today | yesterday|...> at hh,mm,ss
            human_date = chkd.calendar();
        }
        el.text('Last Checkpoint: ' + human_date).attr('title', long_date);
    };

    SaveWidget.prototype._schedule_render_checkpoint = function () {
        /** schedule the next update to relative date

        periodically updated, so short values like 'a few seconds ago' don't get stale.
        */
        if (!this._checkpoint_date) {
            return;
        }
        if ((this._checkpoint_timeout)) {
            clearTimeout(this._checkpoint_timeout);
        }
        var dt = Math.ceil(new Date() - this._checkpoint_date);
        this._checkpoint_timeout = setTimeout(
            $.proxy(this._render_checkpoint, this),
            utils.time.timeout_from_dt(dt)
        );
    };

    SaveWidget.prototype.set_autosaved = function (dirty) {
        if (dirty) {
            this.set_save_status("(unsaved changes)");
        } else {
            this.set_save_status("(autosaved)");
        }
    };

    // Backwards compatibility.
    IPython.SaveWidget = SaveWidget;

    return {'SaveWidget': SaveWidget};

});
<|endoftext|>


<commit_before>	var VA3C = {};
// 	var info, stats, renderer, scene, camera, controls;

	var obj, light;

	var latlon, latlong = [42.3482, -75.189];

//	VA3C.fname = '../json/twoMobius.json';
//	VA3C.fname = '../RvtVa3c/models/Wall.rvt.js';
//	VA3C.fname = '../json/Project2.rvt.js';
	VA3C.fname = '../json/revit/rac_basic_sample_project.rvt.js';

	var pi = Math.PI, pi05 = pi * 0.5, pi2 = pi + pi;
	var d2r = pi / 180, r2d = 180 / pi;  // degrees / radians

	var projector;
    var targetList = [];
    var geometry, material, mesh;

	function init() {

		document.body.style.cssText = 'font: 600 12pt monospace; margin: 0; overflow: hidden' ;

		VA3C.info = document.body.appendChild( document.createElement( 'div' ) );

		VA3C.info.style.cssText = 'left: 20px; position: absolute; top: 0px; width: 100% ';
		VA3C.info.innerHTML = '
' + document.title + '
' +
			'

';

		VA3C.stats = new Stats();
		VA3C.stats.domElement.style.cssText = 'bottom: 0; position: absolute; left: 0; zIndex: 100; ';
		document.body.appendChild( VA3C.stats.domElement );

		VA3C.renderer = new THREE.WebGLRenderer( { alpha: 1, antialias: true, clearColor: 0xffffff }  );
		VA3C.renderer.setSize( window.innerWidth, window.innerHeight );
		VA3C.renderer.shadowMapEnabled = true;
		document.body.appendChild( VA3C.renderer.domElement );
		VA3C.scene = new THREE.Scene();

		VA3C.camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 100000 );
		VA3C.camera.position.set( 15000, 15000, 15000 );
		VA3C.controls = new THREE.OrbitControls( VA3C.camera, VA3C.renderer.domElement );

		projector = new THREE.Projector();
    document.addEventListener( 'click', clickHandler, false );

		loadJS( VA3C.fname );
	}

	function loadJS ( fname ) {
		if ( obj ) VA3C.scene.remove( obj );
		obj = new THREE.Object3D();
		var loader = new THREE.ObjectLoader();
        loader.load(fname, function(obj){
            VA3C.scene = obj;

            VA3C.scene.add(new THREE.AmbientLight(0x444444));

		updateLight( 2014, 5, 18, 22, 30, 00, 42, -75 );

// axes
            function v( x, y, z ){ return new THREE.Vector3( x, y, z ); }
            VA3C.scene.add( new THREE.ArrowHelper( v(1, 0, 0), v(0, 0, 0), 30, 0xcc0000) );
            VA3C.scene.add( new THREE.ArrowHelper( v(0, 1, 0), v(0, 0, 0), 30, 0x00cc00) );
            VA3C.scene.add( new THREE.ArrowHelper( v(0, 0, 1), v(0, 0, 0), 30, 0x0000cc) );

// ground box

            geometry = new THREE.BoxGeometry( 20000, 100, 20000 );
            material = new THREE.MeshBasicMaterial( { color: 0xaaaaaa } );
            mesh = new THREE.Mesh( geometry, material );
            mesh.position.set( 0, -10, 0 );

            mesh.castShadow = true;
            mesh.receiveShadow = true;
            VA3C.scene.add( mesh );

            //call compute function
            computeNormalsAndFaces();
        });
	}

	function v( x, y, z ){ return new THREE.Vector3( x, y, z ); }

	function updateLight() {
			if ( light ) { VA3C.scene.remove( light ); }

            light = new THREE.DirectionalLight( 0xffffff, 1 );
// (year, month, day, hour, minutes, sec, lat, long)
			latlon = sunPosition( 2014, month.value, day.value, hour.value, 60, 00, latlong[0], latlong[1]  );
// console.log ( latlon );
			var pos = convertPosition(  latlon[0], latlon[1], 10000 );
		// var pos = convertPosition(  43, -75, 10000 );

            light.position = pos;
            light.castShadow = true;
            light.shadowMapWidth = 2048;
            light.shadowMapHeight = 2048;
            var d = 10000;
            light.shadowCameraLeft = -d;
            light.shadowCameraRight = d;
            light.shadowCameraTop = d * 2;
            light.shadowCameraBottom = -d * 2;

            light.shadowCameraNear = 1000;
            light.shadowCameraFar = 20000;
//            light.shadowCameraVisible = true;
            VA3C.scene.add( light );
	}

	function convertPosition( lat, lon, radius ) {
		var rc = radius * Math.cos( lat * d2r );
		return v( rc * Math.cos( lon * d2r ), radius * Math.sin( lat * d2r ), rc * Math.sin( lon * d2r) );
	}

	function getComboA(sel) {
// console.log( sel );
			var value = sel.value;
			//alert(value);
			// var latlong;
			switch(value) {
			case "New York":
				latlong = [42.3482, -75.189];
				break;
			case "Sao Paulo":
				latlong = [-23.55, -46.633];
				break;
			case "Paris":
				latlong = [48.8567, 2.3508];
				break;
			case "Moscow":
				latlong = [55.75, 37.6167];
				break;
			case "Tokyo":
				latlong = [35.6895, 139.6917];
				break;
			default:
				latlong = [42.3482, -75.189];
			}
			//tokyoLatitude:35.6895, Longitude:139.6917
			//New York coordinates
			//Latitude:42.3482, Longitude:-75.189
			//saoaulo
			//Latitude:-23.55, Longitude:-46.633
			//Moscow coordinates
			//Latitude:55.75, Longitude:37.6167
			//Paris coordinates
			//Latitude:48.8567, Longitude:2.3508
//			alert(latlong);
			updateLight( 2014, 5, 18, 22, 30, 00, latlong[0], latlong[2])
		}

	function animate() {
		requestAnimationFrame( animate );
		VA3C.renderer.render( VA3C.scene, VA3C.camera );
		VA3C.controls.update( );
		VA3C.stats.update();
	}

	function computeNormalsAndFaces() {
		for(var i=0; i<VA3C.scene.children.length; i++){
			if( VA3C.scene.children[i].hasOwnProperty("geometry")){
				VA3C.scene.children[i].geometry.mergeVertices();
				VA3C.scene.children[i].castShadow = true;
				VA3C.scene.children[i].geometry.computeFaceNormals();
                targetList.push(VA3C.scene.children[i])
			}
		}
	}

    function clickHandler(event){
// console.log( event );
        event.preventDefault();

        var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
        projector.unprojectVector( vector, VA3C.camera );

        var raycaster = new THREE.Raycaster( VA3C.camera.position, vector.sub( VA3C.camera.position ).normalize() );
        //var raycaster = new THREE.Raycaster( VA3C.camera.position, vector.sub( ).normalize() );

        var intersects = raycaster.intersectObjects( targetList );
        //var intersects = raycaster.intersectObjects( VA3C.scene.children.geometry );

        if ( intersects.length > 0 ) {

         //   intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
         //console.log(intersects[0].object.userData);

         var j =0;
         while(j<intersects.length){
             if(!$.isEmptyObject(intersects[j].object.userData)){
                 console.log(intersects[j].object.userData);
                 break;
             }
             j++;
         }

        }
    }
<commit_msg>selection to work with revit files<commit_after>	var VA3C = {};
// 	var info, stats, renderer, scene, camera, controls;

	var obj, light;

	var latlon, latlong = [42.3482, -75.189];

//	VA3C.fname = '../json/twoMobius.json';
//	VA3C.fname = '../RvtVa3c/models/Wall.rvt.js';
//	VA3C.fname = '../json/Project2.rvt.js';
	VA3C.fname = '../json/revit/rac_basic_sample_project.rvt.js';

	var pi = Math.PI, pi05 = pi * 0.5, pi2 = pi + pi;
	var d2r = pi / 180, r2d = 180 / pi;  // degrees / radians

	var projector;
    var targetList = [];
    var geometry, material, mesh;

	function init() {

		document.body.style.cssText = 'font: 600 12pt monospace; margin: 0; overflow: hidden' ;

		VA3C.info = document.body.appendChild( document.createElement( 'div' ) );

		VA3C.info.style.cssText = 'left: 20px; position: absolute; top: 0px; width: 100% ';
		VA3C.info.innerHTML = '
' + document.title + '
' +
			'

';

		VA3C.stats = new Stats();
		VA3C.stats.domElement.style.cssText = 'bottom: 0; position: absolute; left: 0; zIndex: 100; ';
		document.body.appendChild( VA3C.stats.domElement );

		VA3C.renderer = new THREE.WebGLRenderer( { alpha: 1, antialias: true, clearColor: 0xffffff }  );
		VA3C.renderer.setSize( window.innerWidth, window.innerHeight );
		VA3C.renderer.shadowMapEnabled = true;
		document.body.appendChild( VA3C.renderer.domElement );
		VA3C.scene = new THREE.Scene();

		VA3C.camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 100000 );
		VA3C.camera.position.set( 15000, 15000, 15000 );
		VA3C.controls = new THREE.OrbitControls( VA3C.camera, VA3C.renderer.domElement );

		projector = new THREE.Projector();
    document.addEventListener( 'click', clickHandler, false );

		loadJS( VA3C.fname );
	}

	function loadJS ( fname ) {
		if ( obj ) VA3C.scene.remove( obj );
		obj = new THREE.Object3D();
		var loader = new THREE.ObjectLoader();
        loader.load(fname, function(obj){
            VA3C.scene = obj;

            VA3C.scene.add(new THREE.AmbientLight(0x444444));

		updateLight( 2014, 5, 18, 22, 30, 00, 42, -75 );

// axes
            function v( x, y, z ){ return new THREE.Vector3( x, y, z ); }
            VA3C.scene.add( new THREE.ArrowHelper( v(1, 0, 0), v(0, 0, 0), 30, 0xcc0000) );
            VA3C.scene.add( new THREE.ArrowHelper( v(0, 1, 0), v(0, 0, 0), 30, 0x00cc00) );
            VA3C.scene.add( new THREE.ArrowHelper( v(0, 0, 1), v(0, 0, 0), 30, 0x0000cc) );

// ground box

            geometry = new THREE.BoxGeometry( 20000, 100, 20000 );
            material = new THREE.MeshBasicMaterial( { color: 0xaaaaaa } );
            mesh = new THREE.Mesh( geometry, material );
            mesh.position.set( 0, -10, 0 );

            mesh.castShadow = true;
            mesh.receiveShadow = true;
            VA3C.scene.add( mesh );

            //call compute function
            computeNormalsAndFaces();
        });
	}

	function v( x, y, z ){ return new THREE.Vector3( x, y, z ); }

	function updateLight() {
			if ( light ) { VA3C.scene.remove( light ); }

            light = new THREE.DirectionalLight( 0xffffff, 1 );
// (year, month, day, hour, minutes, sec, lat, long)
			latlon = sunPosition( 2014, month.value, day.value, hour.value, 60, 00, latlong[0], latlong[1]  );
// console.log ( latlon );
			var pos = convertPosition(  latlon[0], latlon[1], 10000 );
		// var pos = convertPosition(  43, -75, 10000 );

            light.position = pos;
            light.castShadow = true;
            light.shadowMapWidth = 2048;
            light.shadowMapHeight = 2048;
            var d = 10000;
            light.shadowCameraLeft = -d;
            light.shadowCameraRight = d;
            light.shadowCameraTop = d * 2;
            light.shadowCameraBottom = -d * 2;

            light.shadowCameraNear = 1000;
            light.shadowCameraFar = 20000;
//            light.shadowCameraVisible = true;
            VA3C.scene.add( light );
	}

	function convertPosition( lat, lon, radius ) {
		var rc = radius * Math.cos( lat * d2r );
		return v( rc * Math.cos( lon * d2r ), radius * Math.sin( lat * d2r ), rc * Math.sin( lon * d2r) );
	}

	function getComboA(sel) {
// console.log( sel );
			var value = sel.value;
			//alert(value);
			// var latlong;
			switch(value) {
			case "New York":
				latlong = [42.3482, -75.189];
				break;
			case "Sao Paulo":
				latlong = [-23.55, -46.633];
				break;
			case "Paris":
				latlong = [48.8567, 2.3508];
				break;
			case "Moscow":
				latlong = [55.75, 37.6167];
				break;
			case "Tokyo":
				latlong = [35.6895, 139.6917];
				break;
			default:
				latlong = [42.3482, -75.189];
			}
			//tokyoLatitude:35.6895, Longitude:139.6917
			//New York coordinates
			//Latitude:42.3482, Longitude:-75.189
			//saoaulo
			//Latitude:-23.55, Longitude:-46.633
			//Moscow coordinates
			//Latitude:55.75, Longitude:37.6167
			//Paris coordinates
			//Latitude:48.8567, Longitude:2.3508
//			alert(latlong);
			updateLight( 2014, 5, 18, 22, 30, 00, latlong[0], latlong[2])
		}

	function animate() {
		requestAnimationFrame( animate );
		VA3C.renderer.render( VA3C.scene, VA3C.camera );
		VA3C.controls.update( );
		VA3C.stats.update();
	}

	function computeNormalsAndFaces() {
		for(var i=0; i<VA3C.scene.children.length; i++){
			if( VA3C.scene.children[i].hasOwnProperty("geometry")){
				VA3C.scene.children[i].geometry.mergeVertices();
				VA3C.scene.children[i].castShadow = true;
				VA3C.scene.children[i].geometry.computeFaceNormals();
                targetList.push(VA3C.scene.children[i])
			}
            if(VA3C.scene.children[i].children.length > 0){
                for (var k=0; k<VA3C.scene.children[i].children.length ; k++){
                    if(VA3C.scene.children[i].children[k].hasOwnProperty("geometry")){
                        targetList.push(VA3C.scene.children[i].children[k]);
                    }
                }
            }
		}
	}

    function clickHandler(event){
// console.log( event );
        event.preventDefault();

        var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
        projector.unprojectVector( vector, VA3C.camera );

        var raycaster = new THREE.Raycaster( VA3C.camera.position, vector.sub( VA3C.camera.position ).normalize() );
        //var raycaster = new THREE.Raycaster( VA3C.camera.position, vector.sub( ).normalize() );

        var intersects = raycaster.intersectObjects( targetList );
        //var intersects = raycaster.intersectObjects( VA3C.scene.children.geometry );

        if ( intersects.length > 0 ) {

         //   intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
         //console.log(intersects[0].object.userData);

         var j =0;
         while(j<intersects.length){
             if(!$.isEmptyObject(intersects[j].object.userData)){
                 console.log(intersects[j].object.userData);
                 break;
             }
             j++;
         }

        }
    }
<|endoftext|>


<commit_before>
import API from 'src/util/api';
import UI from 'src/util/ui';

import Status from './Status';

var roc;

async function processAction(actionName, actionValue) {
  roc = this.roc;
  switch (actionName) {
    case 'requestFromScan':
      requestFromScan(actionValue);
      break;
    case 'requestFromUUID':
      requestFromUUID(actionValue);
      break;
    case 'changeStatus':
      {
        let request = API.getData('request');
        var newStatus = await askNewStatus(request);
        await prependStatus(request, newStatus);
        API.doAction('refreshRequests');
        API.createData('status', []);
        API.doAction('setSelected', []);
      }
      break;
    case 'createForm':
      createForm();
      break;
    case 'refreshRequests':
      refreshRequests(API.getData('preferences'));
      break;
    case 'updateFilters':
      refreshRequests(actionValue);
      break;
    case 'bulkChangeStatus':
      await bulkChangeStatus(API.getData('selected'));
      API.doAction('refreshRequests');
      API.createData('status', []);
      API.doAction('setSelected', []);
      break;
    default:
      throw Error(`the action "${actionValue}" is unknown`);
  }
}

function requestFromScan(scan) {
  let uuid = scan.replace(/[^a-z0-9:_]/g, '');
  if (uuid.includes('_')) {
    uuid = uuid.replace(/.*_r:([a-z0-9]*).*/, '$1');
  }
  if (uuid.length === 0) return;
  if (uuid.length !== 32) {
    UI.showNotification(`Not found uuid: ${uuid}`);
    return;
  }
  requestFromUUID(uuid);
}

async function refreshRequests(options) {
  var queryOptions = {
    sort: (a, b) => a.value.status.date - b.value.status.date
  };
  if (String(options.group) === 'mine') {
    queryOptions.mine = true;
  } else {
    queryOptions.groups = [String(options.group)];
  }
  if (String(options.status) !== 'any') {
    var statusCode = Status.getStatusCode(String(options.status));
    queryOptions.startkey = [statusCode];
    queryOptions.endkey = [statusCode];
  }
  var results = await roc.query('analysisRequestByKindAndStatus', queryOptions);
  results.forEach((result) => {
    result.color = Status.getStatusColor(Number(result.value.status.status));
  });
  API.createData('requests', results);
}

async function requestFromUUID(uuid) {
  if (!uuid) {
    API.createData('request', {});
    return;
  }
  let request = await roc.document(uuid);
  API.createData('request', request);
  let requestVar = await API.getVar('request');
  API.setVariable('status', requestVar, ['$content', 'status']);
}

async function bulkChangeStatus(selected) {
  var newStatus = await askNewStatus();
  for (var requestToc of selected) {
    var request = await roc.document(String(requestToc.id));
    ensureStatus(request);
    await prependStatus(request, newStatus);
  }
}

function ensureStatus(request) {
  if (!request.$content) request.$content = {};
  if (!request.$content.status) request.$content.status = [];
}

async function askNewStatus(request) {
  var currentStatusCode = '';
  if (request) {
    ensureStatus(request);
    let status = request.$content.status;
    currentStatusCode = status.length > 0 ? String(status[0].status) : '';
  }
  var statusArray = Status.getStatusArray();
  var currentStatus = -1;
  statusArray.forEach((item, i) => {
    if (String(currentStatusCode) === item.code) currentStatus = i;
  });
  if (currentStatus < statusArray.length - 1) {
    currentStatus++;
  }

  let newStatus = await UI.form(`

            Please select the new status

            <form>
                <select name="status">
                    ${statusArray.map((item, i) =>
    `<option value="${i}" ${(i === currentStatus) ? 'selected' : ''}>${item.description}</option>`
  )}
                </select>
                <input type="submit" value="Submit"/>
            </form>

    `, {});
  return statusArray[newStatus.status].code;
}

async function prependStatus(request, newStatus) {
  request.$content.status.unshift({
    status: Number(newStatus),
    date: Date.now()
  });
  await roc.update(request);
}

async function createForm() {
  var groups = (await roc.getGroupMembership()).map((g) => g.name);
  var possibleGroups = ['mine'].concat(groups);
  var defaultGroup = window.localStorage.getItem('eln-default-sample-group');
  if (possibleGroups.indexOf(defaultGroup) === -1) {
    defaultGroup = 'all';
  }
  var possibleStatus = ['any'].concat(Status.getStatusArray().map((s) => s.description));
  var schema = {
    type: 'object',
    properties: {
      group: {
        type: 'string',
        enum: possibleGroups,
        default: defaultGroup,
        required: true
      },
      status: {
        type: 'string',
        enum: possibleStatus,
        default: '30',
        required: true
      }
    }
  };
  API.createData('formSchema', schema);
}

export default processAction;
<commit_msg>change requestManager processAction to remove duplicate code<commit_after>
import API from 'src/util/api';
import UI from 'src/util/ui';

import Status from './Status';

var roc;

async function processAction(actionName, actionValue) {
  roc = this.roc;
  switch (actionName) {
    case 'requestFromScan':
      requestFromScan(actionValue);
      break;
    case 'requestFromUUID':
      requestFromScan(actionValue);
      break;
    case 'changeStatus':
      {
        let request = API.getData('request');
        var newStatus = await askNewStatus(request);
        await prependStatus(request, newStatus);
        API.doAction('refreshRequests');
        API.createData('status', []);
        API.doAction('setSelected', []);
      }
      break;
    case 'createForm':
      createForm();
      break;
    case 'refreshRequests':
      refreshRequests(API.getData('preferences'));
      break;
    case 'updateFilters':
      refreshRequests(actionValue);
      break;
    case 'bulkChangeStatus':
      await bulkChangeStatus(API.getData('selected'));
      API.doAction('refreshRequests');
      API.createData('status', []);
      API.doAction('setSelected', []);
      break;
    default:
      throw Error(`the action "${actionValue}" is unknown`);
  }
}

async function requestFromScan(scan) {
  var request = await this.getRequest(scan);
  if (!request) {
    API.createData('request', {});
    return;
  }
  API.createData('request', request);
  let requestVar = await API.getVar('request');
  API.setVariable('status', requestVar, ['$content', 'status']);
}

async function refreshRequests(options) {
  var queryOptions = {
    sort: (a, b) => a.value.status.date - b.value.status.date
  };
  if (String(options.group) === 'mine') {
    queryOptions.mine = true;
  } else {
    queryOptions.groups = [String(options.group)];
  }
  if (String(options.status) !== 'any') {
    var statusCode = Status.getStatusCode(String(options.status));
    queryOptions.startkey = [statusCode];
    queryOptions.endkey = [statusCode];
  }
  var results = await roc.query('analysisRequestByKindAndStatus', queryOptions);
  results.forEach((result) => {
    result.color = Status.getStatusColor(Number(result.value.status.status));
  });
  API.createData('requests', results);
}

async function bulkChangeStatus(selected) {
  var newStatus = await askNewStatus();
  for (var requestToc of selected) {
    var request = await roc.document(String(requestToc.id));
    ensureStatus(request);
    await prependStatus(request, newStatus);
  }
}

function ensureStatus(request) {
  if (!request.$content) request.$content = {};
  if (!request.$content.status) request.$content.status = [];
}

async function askNewStatus(request) {
  var currentStatusCode = '';
  if (request) {
    ensureStatus(request);
    let status = request.$content.status;
    currentStatusCode = status.length > 0 ? String(status[0].status) : '';
  }
  var statusArray = Status.getStatusArray();
  var currentStatus = -1;
  statusArray.forEach((item, i) => {
    if (String(currentStatusCode) === item.code) currentStatus = i;
  });
  if (currentStatus < statusArray.length - 1) {
    currentStatus++;
  }

  let newStatus = await UI.form(`

            Please select the new status

            <form>
                <select name="status">
                    ${statusArray.map((item, i) =>
    `<option value="${i}" ${(i === currentStatus) ? 'selected' : ''}>${item.description}</option>`
  )}
                </select>
                <input type="submit" value="Submit"/>
            </form>

    `, {});
  return statusArray[newStatus.status].code;
}

async function prependStatus(request, newStatus) {
  request.$content.status.unshift({
    status: Number(newStatus),
    date: Date.now()
  });
  await roc.update(request);
}

async function createForm() {
  var groups = (await roc.getGroupMembership()).map((g) => g.name);
  var possibleGroups = ['mine'].concat(groups);
  var defaultGroup = window.localStorage.getItem('eln-default-sample-group');
  if (possibleGroups.indexOf(defaultGroup) === -1) {
    defaultGroup = 'all';
  }
  var possibleStatus = ['any'].concat(Status.getStatusArray().map((s) => s.description));
  var schema = {
    type: 'object',
    properties: {
      group: {
        type: 'string',
        enum: possibleGroups,
        default: defaultGroup,
        required: true
      },
      status: {
        type: 'string',
        enum: possibleStatus,
        default: '30',
        required: true
      }
    }
  };
  API.createData('formSchema', schema);
}

export default processAction;
<|endoftext|>


<commit_before>/* Router: maps hash navigation */

$.ajaxSetup({
  headers: {
    "Authorization": "Token " + window.access_token,
    "Content-Type": "application/json"
  }
});

Atmo.Router = Backbone.Router.extend({
  routes: {
    "": "instances",
    "instances": "instances",
    "instances/:instance_id": "select_instance",
    "volumes": "volumes",
    "volumes/:volume_id": "select_volume",
    "new_instance": "new_instance",
    "new_instance/:image_query": "select_image",
    "settings": "settings"
  },
  initialize: function () {
    Atmo.profile = new Atmo.Models.Profile();
    Atmo.profile.fetch({
      async: false,
      success: function (profile, foo, bar) {
        $("#username").html(profile.get('id'));

        window.Intercom('boot', {
          app_id: window.intercom_app_id,
          name: profile.get("username"),
          username: profile.get("username"),
          email: profile.get("email"),
          company: {
            id: window.intercom_company_id,
            name: window.intercom_company_name
          }
          // TODO: The current logged in user's sign-up date as a Unix timestamp.
          //created_at: 1234567890
        });
      },
      error: function () {
        // If we end up here, the user has an iPlant account but doesn't
        // have access to Atmosphere itself.
        // Redirect the user to the forbidden page with more info
        window.location.pathname = "/forbidden";
      }
    });

    Atmo.Utils.update_weather();
    Atmo.providers = new Atmo.Collections.Providers();
    Atmo.providers.fetch({
      async: false,
      success: function (providers, foo, bar) {
      }
    });
    Atmo.identities = new Atmo.Collections.Identities();
    Atmo.identities.fetch({
      async: false
    });

    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");

    Atmo.maintenances = new Atmo.Collections.Maintenances();
    Atmo.maintenances.fetch({
      async: false
    });
    Atmo.instances = new Atmo.Collections.Instances();
    Atmo.volumes = new Atmo.Collections.Volumes();
    Atmo.images = new Atmo.Collections.Machines();
    if (Atmo.profile.get('is_staff') === true) {
      Atmo.instance_hypervisors = new Atmo.Collections.Hypervisors();
      Atmo.instance_hypervisors.fetch({async: false});
    }
    Atmo.instance_types = new Atmo.Collections.Sizes();

    Atmo.notifications = new Atmo.Collections.Notifications();

    this.main = new Atmo.Views.Main({el: $('#main')[0]}).render();
    new Atmo.Views.Sidebar({el: $('#menu_wrapper')}).render();

    setInterval(function () {
      $('#refresh_instances_button').click();
    }, 5 * 60 * 1000);

    new Atmo.Views.FeedbackLink({el: $('#feedback_link')[0]});
    Atmo.request_resources_modal = new Atmo.Views.RequestResourcesModal();
    $('body').append(Atmo.request_resources_modal.render().el);

    Atmo.alert_modal = new Atmo.Views.AlertModal();
    $('body').append(Atmo.alert_modal.render().el);

    // Populate the top menu with a provider switcher
    for (var i = 0; i < Atmo.identities.length; i++) {
      var identity = Atmo.identities.models[i];
      var identity_provider_id = identity.get('provider_id');
      var in_maintenance = Atmo.maintenances.in_maintenance(identity_provider_id);
      var result = '';
      var name = Atmo.identities.models[i].get('provider').get('location');
      $('#providers_menu').append($('
', {
        html: function () {
          if (identity.get('selected')) {
            result = ' ' + name;
          } else {
            result = '' + name;
          }
          if (in_maintenance) {
            result += ' ';
          }
          result += '';
          return result;
        },
        click: function (e) {
          e.preventDefault();
          var identity = $(this).data();
          if (in_maintenance) {
            Atmo.Utils.notify('Error', identity.get('provider').get('type') + ' is currently in maintenance.');
            return false;
          }
          if (identity.get('selected')) {
            Atmo.Utils.notify('Error', 'You are already using ' + identity.get('provider').get('type') + ' as your provider.');
            return false;
          }
          else {
            Atmo.profile.save({'selected_identity': identity.get('id')},
              {'async': false,
                'patch': true,
                success: location.reload()});
          }
        }
      }).data(identity));
    }

    $('#contact_support').click(function (e) {
      e.preventDefault();
      $('#feedback_link').trigger('click');
    });
    $.ajax({
      type: 'GET',
      url: Atmo.API_ROOT + '/version',
      statusCode: {
        200: function (response) {
          $('#version').html(''
            + new Date(response['commit_date']).toString("F") + ' '
            + '(' + response['git_sha_abbrev'] + ')');
        }
      }
    });
    $('#total_cpu_time a').click(function () {
      $('#cpu_modal').modal('show');
    });
    new Atmo.Views.NotificationHolder({el: $('#alert_holder')[0]});
  },
  instances: function () {
    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");
    if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
      this.main.show_instance_screen();
      Atmo.instances.on('reset', function (collection) {
        if (!collection.isEmpty() && !collection.selected_instance)
          collection.select_instance(collection.at(0));
      });
      // Hide all help tips so none remain after navigating away from it
      Atmo.Utils.hide_all_help();
    }
  },
  volumes: function () {
    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");
    if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
      this.main.show_volume_screen();
      // Hide all help tips so none remain after navigating away from it
      Atmo.Utils.hide_all_help();
    }
  },
  new_instance: function (options) {
    this.main.show_new_instance_screen();
    // Hide all help tips so none remain after navigating away from it
    Atmo.Utils.hide_all_help();
  },
  settings: function () {
    this.main.show_settings_screen();
  },
  select_instance: function (instance_id) {
    this.instances();
    var instance;
    if (instance = Atmo.instances.get(instance_id))
      Atmo.instances.select_instance(instance);
  },
  select_volume: function (volume_id) {
    var volume = Atmo.volumes.get(volume_id);
    if (volume)
      Atmo.volumes.select_volume(volume);
    //console.log(volume_id);
  },
  select_image: function (image_query) {
    if (this.new_instance_screen)
      this.new_instance_screen.set_query(image_query);
    else
      this.new_instance({'query': image_query});
  }
});

$(document).ready(function () {
  window.app = new Atmo.Router();
  Backbone.history.start();

  var identity = Atmo.profile.get('selected_identity');
  var identity_provider_id = identity.get("provider_id");
  if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
    Atmo.instance_types.fetch({async: false});
    Atmo.instances.fetch();
    Atmo.volumes.fetch();
    Atmo.images.fetch();

    $('.beta-toggle').click(function (e) {
      e.preventDefault();
      console.log('beta switch clicked');

      var header = 'New UI Preview';
      var body = "
We've been working hard to create an improved experience for Atmosphere. Check out the new features in the video below and try it out for yourself.  We'd love to hear what you think!
";
      body += '';
      var ok_button = 'Take me to the new UI';
      var on_confirm = function() {
        window.location = '/application?beta=true';
      };

      Atmo.Utils.confirm(header, body, { ok_button: ok_button, on_confirm: on_confirm });
    });
  }
});
<commit_msg>redirect to maintenance page on any 503<commit_after>/* Router: maps hash navigation */

$.ajaxSetup({
  headers: {
    "Authorization": "Token " + window.access_token,
    "Content-Type": "application/json"
  }
});

// Watch all AJAX requests for 503 responses.  If any request returns a 503,
// Atmosphere is under maintenance so redirect to the maintenance page
$(document).ajaxError(function(e, response, xhr){
  if(response.status === 503){
    window.location.pathname = "/atmo_maintenance";
  }
});

Atmo.Router = Backbone.Router.extend({
  routes: {
    "": "instances",
    "instances": "instances",
    "instances/:instance_id": "select_instance",
    "volumes": "volumes",
    "volumes/:volume_id": "select_volume",
    "new_instance": "new_instance",
    "new_instance/:image_query": "select_image",
    "settings": "settings"
  },
  initialize: function () {
    Atmo.profile = new Atmo.Models.Profile();
    Atmo.profile.fetch({
      async: false,
      success: function (profile, foo, bar) {
        $("#username").html(profile.get('id'));

        window.Intercom('boot', {
          app_id: window.intercom_app_id,
          name: profile.get("username"),
          username: profile.get("username"),
          email: profile.get("email"),
          company: {
            id: window.intercom_company_id,
            name: window.intercom_company_name
          }
          // TODO: The current logged in user's sign-up date as a Unix timestamp.
          //created_at: 1234567890
        });
      },
      error: function (attrs, response, xhr) {
        if(response.status === 503){
          // if profile returns a 503, Atmosphere is under maintenance
          // so redirect to the maintenance page
          window.location.pathname = "/atmo_maintenance";
        }else{
          // If we end up here, the user has an iPlant account but doesn't
          // have access to Atmosphere itself. Redirect the user to the
          // forbidden page with more info
          window.location.pathname = "/forbidden";
        }
      }
    });

    Atmo.Utils.update_weather();
    Atmo.providers = new Atmo.Collections.Providers();
    Atmo.providers.fetch({
      async: false,
      success: function (providers, foo, bar) {
      }
    });
    Atmo.identities = new Atmo.Collections.Identities();
    Atmo.identities.fetch({
      async: false
    });

    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");

    Atmo.maintenances = new Atmo.Collections.Maintenances();
    Atmo.maintenances.fetch({
      async: false
    });
    Atmo.instances = new Atmo.Collections.Instances();
    Atmo.volumes = new Atmo.Collections.Volumes();
    Atmo.images = new Atmo.Collections.Machines();
    if (Atmo.profile.get('is_staff') === true) {
      Atmo.instance_hypervisors = new Atmo.Collections.Hypervisors();
      Atmo.instance_hypervisors.fetch({async: false});
    }
    Atmo.instance_types = new Atmo.Collections.Sizes();

    Atmo.notifications = new Atmo.Collections.Notifications();

    this.main = new Atmo.Views.Main({el: $('#main')[0]}).render();
    new Atmo.Views.Sidebar({el: $('#menu_wrapper')}).render();

    setInterval(function () {
      $('#refresh_instances_button').click();
    }, 5 * 60 * 1000);

    new Atmo.Views.FeedbackLink({el: $('#feedback_link')[0]});
    Atmo.request_resources_modal = new Atmo.Views.RequestResourcesModal();
    $('body').append(Atmo.request_resources_modal.render().el);

    Atmo.alert_modal = new Atmo.Views.AlertModal();
    $('body').append(Atmo.alert_modal.render().el);

    // Populate the top menu with a provider switcher
    for (var i = 0; i < Atmo.identities.length; i++) {
      var identity = Atmo.identities.models[i];
      var identity_provider_id = identity.get('provider_id');
      var in_maintenance = Atmo.maintenances.in_maintenance(identity_provider_id);
      var result = '';
      var name = Atmo.identities.models[i].get('provider').get('location');
      $('#providers_menu').append($('
', {
        html: function () {
          if (identity.get('selected')) {
            result = ' ' + name;
          } else {
            result = '' + name;
          }
          if (in_maintenance) {
            result += ' ';
          }
          result += '';
          return result;
        },
        click: function (e) {
          e.preventDefault();
          var identity = $(this).data();
          if (in_maintenance) {
            Atmo.Utils.notify('Error', identity.get('provider').get('type') + ' is currently in maintenance.');
            return false;
          }
          if (identity.get('selected')) {
            Atmo.Utils.notify('Error', 'You are already using ' + identity.get('provider').get('type') + ' as your provider.');
            return false;
          }
          else {
            Atmo.profile.save({'selected_identity': identity.get('id')},
              {'async': false,
                'patch': true,
                success: location.reload()});
          }
        }
      }).data(identity));
    }

    $('#contact_support').click(function (e) {
      e.preventDefault();
      $('#feedback_link').trigger('click');
    });
    $.ajax({
      type: 'GET',
      url: Atmo.API_ROOT + '/version',
      statusCode: {
        200: function (response) {
          $('#version').html(''
            + new Date(response['commit_date']).toString("F") + ' '
            + '(' + response['git_sha_abbrev'] + ')');
        }
      }
    });
    $('#total_cpu_time a').click(function () {
      $('#cpu_modal').modal('show');
    });
    new Atmo.Views.NotificationHolder({el: $('#alert_holder')[0]});
  },
  instances: function () {
    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");
    if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
      this.main.show_instance_screen();
      Atmo.instances.on('reset', function (collection) {
        if (!collection.isEmpty() && !collection.selected_instance)
          collection.select_instance(collection.at(0));
      });
      // Hide all help tips so none remain after navigating away from it
      Atmo.Utils.hide_all_help();
    }
  },
  volumes: function () {
    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");
    if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
      this.main.show_volume_screen();
      // Hide all help tips so none remain after navigating away from it
      Atmo.Utils.hide_all_help();
    }
  },
  new_instance: function (options) {
    this.main.show_new_instance_screen();
    // Hide all help tips so none remain after navigating away from it
    Atmo.Utils.hide_all_help();
  },
  settings: function () {
    this.main.show_settings_screen();
  },
  select_instance: function (instance_id) {
    this.instances();
    var instance;
    if (instance = Atmo.instances.get(instance_id))
      Atmo.instances.select_instance(instance);
  },
  select_volume: function (volume_id) {
    var volume = Atmo.volumes.get(volume_id);
    if (volume)
      Atmo.volumes.select_volume(volume);
    //console.log(volume_id);
  },
  select_image: function (image_query) {
    if (this.new_instance_screen)
      this.new_instance_screen.set_query(image_query);
    else
      this.new_instance({'query': image_query});
  }
});

$(document).ready(function () {
  window.app = new Atmo.Router();
  Backbone.history.start();

  var identity = Atmo.profile.get('selected_identity');
  var identity_provider_id = identity.get("provider_id");
  if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
    Atmo.instance_types.fetch({async: false});
    Atmo.instances.fetch();
    Atmo.volumes.fetch();
    Atmo.images.fetch();

    $('.beta-toggle').click(function (e) {
      e.preventDefault();
      console.log('beta switch clicked');

      var header = 'New UI Preview';
      var body = "
We've been working hard to create an improved experience for Atmosphere. Check out the new features in the video below and try it out for yourself.  We'd love to hear what you think!
";
      body += '';
      var ok_button = 'Take me to the new UI';
      var on_confirm = function() {
        window.location = '/application?beta=true';
      };

      Atmo.Utils.confirm(header, body, { ok_button: ok_button, on_confirm: on_confirm });
    });
  }
});
<|endoftext|>


<commit_before>var KillKat =
{
	init: 	function(){
        //if (confirm("Ready to kill Katz ??"))
        //{
            KillKat.staticFiles.load(function(){
                KillKat.initImagesHandler();
                KillKat.setSoundPlayer();
            });
        //}
	},
    currentImg: null,
    currentImgIndex: -1,
    currentOverlay: null,
    sound: null,
    domImgs : [],
    listImgs : [],
    icons: {
       iconKillable: {
            width: '30px',
            height: '30px',
            marginRight: '5px'
       }
    },
    rules : {
        IMG_MIN_WIDTH : '100px',
        IMG_MIN_HEIGHT : '100px'
    },
    styles :{
        OVERLAY_CLASS: 'killkat-overlay',
        KILLABLE_CLASS : 'killkat-icon-killable',
        KILLED_CLASS : 'killkat-overlay-splatter',
        TARGET_CLASS : 'killkat-overlay-target'
    },
    //GITHUB : 'https://rawgit.com/jorisgrouillet/killkat/master',
    GITHUB : 'http://sandbox.local/killkat/',

    requirements: {
        'min-dimensions' : function(domImg){ return ((domImg.width * domImg.height) > (parseInt(KillKat.rules.IMG_MIN_WIDTH) * parseInt(KillKat.rules.IMG_MIN_HEIGHT))); }
    },

    staticFiles: {
        load : function(callback){
            KillKat.staticFiles.loadStyles();
            KillKat.staticFiles.loadJS(callback);
        },
        loadStyles: function()
        {
            var stylesheet = document.createElement('link');
            stylesheet.href = KillKat.GITHUB+'/css/killkat.css';
            stylesheet.rel = 'stylesheet';
            stylesheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(stylesheet);

            var stylesheet = document.createElement('link');
            stylesheet.href = '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css';
            stylesheet.rel = 'stylesheet';
            stylesheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(stylesheet);

        },
        loadJS : function(callback){

            KillKat.loadFirstJSFile('//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.11/require.min.js', function()
            {
                require.config(
                {
                        paths: {
                            'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min',
                            'jquery-ui' : '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min'

                        },
                        shim: {
                            'jQuery': {
                                exports: 'jQuery'
                            }
                        }
                });

                require(['jquery', 'jquery-ui'],
                        function(){
                            jQuery.noConflict();
                            require.config({
                                paths : {
                                    'jquery-transform': '//rawgit.com/louisremi/jquery.transform.js/master/jquery.transform2d',
                                    'jquery-viewport' : KillKat.GITHUB+'/js/jquery.viewport.min'
                                }
                            });
                            require(['jquery-transform', 'jquery-viewport'], function(){
                                callback.call(this);
                            });

                        });
            });
        }
    },
	initImagesHandler : function()
	{
        KillKat.domImgs = jQuery('img');
        KillKat.domImgs.each(
			function(idx, domImg){
				KillKat.filterImg(domImg);
            }
		);
        KillKat.razCurrentImg();
	},
    razCurrentImg: function()
    {
        KillKat.currentImg = null;
        KillKat.currentImgIndex = -1;
        KillKat.currentOverlay = null;
    },
    setCurrentImg: function(domImg)
    {
        if (domImg.tagName.toLowerCase() =='div'){
            domImg = jQuery(domImg).parent().find('img:eq(0)').get(0);
        }
        KillKat.currentImg = jQuery(domImg);
        KillKat.currentImgIndex = KillKat.getImgIndex();
        if (KillKat.currentImgIndex > -1){
            KillKat.currentOverlay = jQuery('#killkat-overlay-'+KillKat.currentImgIndex);
        }

    },

	filterImg : function(domImg)
	{
        if (KillKat.meetRequirements(domImg))
        {
            KillKat.currentImg = null;
            KillKat.setCurrentImg(domImg);
            KillKat.setImageBehaviour();
		}
	},

	meetRequirements : function(domImg)
	{
		var reqs = KillKat.requirements || [];
		var validateReqs = true;
		for (var rIdx in reqs){
			if (typeof(reqs[rIdx]) == 'function'){
				validateReqs &= reqs[rIdx].call(this, domImg);
			}
		}
		return (validateReqs===1);
	},

    setImageId: function(){
        if (typeof(KillKat.currentImg.get(0).id) =='undefined'){
            KillKat.currentImg.attr('id', 'killable-img-'+KillKat.currentImgIndex);
        }
    },
	setImageBehaviour: function()
	{
        KillKat.setImageId();
        var overlay = KillKat.setOverlay();
        KillKat.overrideClickEvent(overlay);
	},
    setOverlay: function()
    {
        var domOverlay = KillKat.currentOverlay;

        if (! domOverlay.length)
        {
            var _parent = KillKat.currentImg.parent();
            domOverlay = jQuery('

')
                .css({  'width' : _parent.innerWidth()+'px',
                    'height' : _parent.innerHeight()+'px',
                    //'left' : (_parent.innerWidth()/4)+'px',
                    'z-index' : 1
                })
                .insertBefore(KillKat.currentImg.parent());
            KillKat.currentImg.closest('div').css({ position : 'relative'});
            return domOverlay;
        }
    },
    overrideClickEvent: function(target)
	{
		var fct = KillKat.getClickEventFunction();
		//KillKat.currentImg.unbind('click').click(fct);
        target.click(fct);
        KillKat.setIconKillable();
	},
	getClickEventFunction: function()
	{
		return function(e){
            e.preventDefault();
            KillKat.razCurrentImg();
            KillKat.setCurrentImg(this);
            KillKat.handleTarget();

			return false;
		};
	},
	handleTarget: function()
	{
        KillKat.toggleSplatter();
    },

    toggleSplatter: function(pos)
    {
        if (! KillKat.currentOverlay.hasClass(KillKat.styles.KILLED_CLASS)){
            KillKat.removeSprite('target');
            KillKat.playSound();
            KillKat.applyVisualEffect();
        }
    },
    removeSprite : function(type)
    {
        KillKat.currentOverlay.addClass(KillKat.styles.KILLED_CLASS)
                             .removeClass(KillKat.styles.TARGET_CLASS);
    },
    applyVisualEffect : function()
    {
        // on efface le splatter
        KillKat.currentOverlay.fadeOut(1200);

        // on applique l'effet d'image : flip et collapse
        KillKat.currentImg
            .css({position :'relative'})
            .animate({ top: '-60px'}, 200, 'swing').dequeue()  // upping
            .animate({ 'transform' : 'rotate(360deg)'}, 1200) // rotation
            .animate({ top: '+=800px' }, 2000, 'swing') // collapses
            .effect( 'explode', 1200) // explodes
            .fadeOut()  // hides
        ;
            /*
            .slideToggle(
            {    easing: 'easeOutExpo',
                duration: 200,
                complete: function()
                {
                    jQuery(this).slideToggle(
                        {
                            easing: 'easeOutExpo',
                            duration: 200,
                            complete : function(){
                                jQuery(this).animate({
                                    top: '+=800px'
                                }, 2000, 'swing').fadeOut(function(){ jQuery(this).hide();});
                            }
                        });
                }
            });
            */
    },
    setIconKillable: function()
    {
        var domIconKillable = jQuery('#'+KillKat.styles.KILLABLE_CLASS+'-'+KillKat.currentImgIndex);
        if (! domIconKillable.length)
        {
            var _parent = KillKat.currentImg.parent();
            jQuery('

')
                .css({
                    'top' : 0,
                    'left' : _parent.outerWidth() - parseInt(KillKat.icons.iconKillable.width) +'px'
                })
                .insertBefore(KillKat.currentImg.parent());
        }
    },
    highlightKillables: function(){

        var loops = 0;
        var lst = jQuery('.'+KillKat.styles.KILLABLE_CLASS+':in-viewport');

        lst.on('transitionend webkitTransitionEnd', function(){
            if (loops==lst.length){
                lst.animate({ 'transform' : 'scale(1)', 'background-color' : 'rgb(242, 222, 222)'}, 700);
                loops=0;
            }
        })
        .animate({ 'transform' : 'scale(2)', 'background-color': '#e88888'}, 700, function(){ loops++; });

        //jQuery.when( doit() ).done(function(){
          //  console.log('done');
           // lst.animate({ 'transform' : 'scale(1)'}, 700);
        //});
            //.animate({ 'transform' : 'scale(1)'}, 700);

    },

	isKatKilled: function(jqImg)
	{
		return (jqImg.parent().hasClass(KillKat.styles.KILLED_CLASS));
	},

    getImgIndex : function()
    {
        return KillKat.domImgs.index(KillKat.currentImg);
    },
    playSound : function()
    {
        if (! jQuery('#killkat-sound').length){
            KillKat.setSoundPlayer();
        }
        KillKat.sound.play();
    },
    setSoundPlayer: function()
    {
        if (! jQuery('#killkat-sound').length)
        {
            var sound = jQuery('<audio id="killkat-sound" preload="auto">'+
                '<source src="'+KillKat.GITHUB+'/audio/splatter-sound.mp3" type="audio/mp3" />'+
                            //'<source src="http://www.freesfx.co.uk/rx2/mp3s/2/1871_1272479313.mp3" type="audio/mp3" />'+
                            'Votre navigateur n\'est pas compatible'+
                            '</audio>');

            jQuery('body').append(sound);
            KillKat.sound = sound.get(0);
        }
    },
	convertImgToBase64 : function(url, callback, outputFormat)
	{
	    var canvas = document.createElement('canvas'),
	    ctx = canvas.getContext('2d'),
	    img = new Image();
	    img.crossOrigin = 'Anonymous';
	    img.onload = function(){
	        canvas.height = img.height;
	        canvas.width = img.width;
	        ctx.drawImage(img,0,0);
	        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
	        callback.call(this, dataURL);
	        canvas = null;
	    };
	    img.src = url;
	},
    loadFirstJSFile: function(url, callback)
    {
        var script = document.createElement("script")
        script.type = "text/javascript";

        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    if (callback) callback();
                }
            };
        } else { //Others
            script.onload = function () {
                if (callback) callback();

            };
        }
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }

};

KillKat.init();

<commit_msg>switching de l'url de github<commit_after>var KillKat =
{
	init: 	function(){
        //if (confirm("Ready to kill Katz ??"))
        //{
            KillKat.staticFiles.load(function(){
                KillKat.initImagesHandler();
                KillKat.setSoundPlayer();
            });
        //}
	},
    currentImg: null,
    currentImgIndex: -1,
    currentOverlay: null,
    sound: null,
    domImgs : [],
    listImgs : [],
    icons: {
       iconKillable: {
            width: '30px',
            height: '30px',
            marginRight: '5px'
       }
    },
    rules : {
        IMG_MIN_WIDTH : '100px',
        IMG_MIN_HEIGHT : '100px'
    },
    styles :{
        OVERLAY_CLASS: 'killkat-overlay',
        KILLABLE_CLASS : 'killkat-icon-killable',
        KILLED_CLASS : 'killkat-overlay-splatter',
        TARGET_CLASS : 'killkat-overlay-target'
    },
    GITHUB : 'https://rawgit.com/jorisgrouillet/killkat/master',
    ///GITHUB : 'http://sandbox.local/killkat/',

    requirements: {
        'min-dimensions' : function(domImg){ return ((domImg.width * domImg.height) > (parseInt(KillKat.rules.IMG_MIN_WIDTH) * parseInt(KillKat.rules.IMG_MIN_HEIGHT))); }
    },

    staticFiles: {
        load : function(callback){
            KillKat.staticFiles.loadStyles();
            KillKat.staticFiles.loadJS(callback);
        },
        loadStyles: function()
        {
            var stylesheet = document.createElement('link');
            stylesheet.href = KillKat.GITHUB+'/css/killkat.css';
            stylesheet.rel = 'stylesheet';
            stylesheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(stylesheet);

            var stylesheet = document.createElement('link');
            stylesheet.href = '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css';
            stylesheet.rel = 'stylesheet';
            stylesheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(stylesheet);

        },
        loadJS : function(callback){

            KillKat.loadFirstJSFile('//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.11/require.min.js', function()
            {
                require.config(
                {
                        paths: {
                            'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min',
                            'jquery-ui' : '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min'

                        },
                        shim: {
                            'jQuery': {
                                exports: 'jQuery'
                            }
                        }
                });

                require(['jquery', 'jquery-ui'],
                        function(){
                            jQuery.noConflict();
                            require.config({
                                paths : {
                                    'jquery-transform': '//rawgit.com/louisremi/jquery.transform.js/master/jquery.transform2d',
                                    'jquery-viewport' : KillKat.GITHUB+'/js/jquery.viewport.min'
                                }
                            });
                            require(['jquery-transform', 'jquery-viewport'], function(){
                                callback.call(this);
                            });

                        });
            });
        }
    },
	initImagesHandler : function()
	{
        KillKat.domImgs = jQuery('img');
        KillKat.domImgs.each(
			function(idx, domImg){
				KillKat.filterImg(domImg);
            }
		);
        KillKat.razCurrentImg();
	},
    razCurrentImg: function()
    {
        KillKat.currentImg = null;
        KillKat.currentImgIndex = -1;
        KillKat.currentOverlay = null;
    },
    setCurrentImg: function(domImg)
    {
        if (domImg.tagName.toLowerCase() =='div'){
            domImg = jQuery(domImg).parent().find('img:eq(0)').get(0);
        }
        KillKat.currentImg = jQuery(domImg);
        KillKat.currentImgIndex = KillKat.getImgIndex();
        if (KillKat.currentImgIndex > -1){
            KillKat.currentOverlay = jQuery('#killkat-overlay-'+KillKat.currentImgIndex);
        }

    },

	filterImg : function(domImg)
	{
        if (KillKat.meetRequirements(domImg))
        {
            KillKat.currentImg = null;
            KillKat.setCurrentImg(domImg);
            KillKat.setImageBehaviour();
		}
	},

	meetRequirements : function(domImg)
	{
		var reqs = KillKat.requirements || [];
		var validateReqs = true;
		for (var rIdx in reqs){
			if (typeof(reqs[rIdx]) == 'function'){
				validateReqs &= reqs[rIdx].call(this, domImg);
			}
		}
		return (validateReqs===1);
	},

    setImageId: function(){
        if (typeof(KillKat.currentImg.get(0).id) =='undefined'){
            KillKat.currentImg.attr('id', 'killable-img-'+KillKat.currentImgIndex);
        }
    },
	setImageBehaviour: function()
	{
        KillKat.setImageId();
        var overlay = KillKat.setOverlay();
        KillKat.overrideClickEvent(overlay);
	},
    setOverlay: function()
    {
        var domOverlay = KillKat.currentOverlay;

        if (! domOverlay.length)
        {
            var _parent = KillKat.currentImg.parent();
            domOverlay = jQuery('

')
                .css({  'width' : _parent.innerWidth()+'px',
                    'height' : _parent.innerHeight()+'px',
                    //'left' : (_parent.innerWidth()/4)+'px',
                    'z-index' : 1
                })
                .insertBefore(KillKat.currentImg.parent());
            KillKat.currentImg.closest('div').css({ position : 'relative'});
            return domOverlay;
        }
    },
    overrideClickEvent: function(target)
	{
		var fct = KillKat.getClickEventFunction();
		//KillKat.currentImg.unbind('click').click(fct);
        target.click(fct);
        KillKat.setIconKillable();
	},
	getClickEventFunction: function()
	{
		return function(e){
            e.preventDefault();
            KillKat.razCurrentImg();
            KillKat.setCurrentImg(this);
            KillKat.handleTarget();

			return false;
		};
	},
	handleTarget: function()
	{
        KillKat.toggleSplatter();
    },

    toggleSplatter: function(pos)
    {
        if (! KillKat.currentOverlay.hasClass(KillKat.styles.KILLED_CLASS)){
            KillKat.removeSprite('target');
            KillKat.playSound();
            KillKat.applyVisualEffect();
        }
    },
    removeSprite : function(type)
    {
        KillKat.currentOverlay.addClass(KillKat.styles.KILLED_CLASS)
                             .removeClass(KillKat.styles.TARGET_CLASS);
    },
    applyVisualEffect : function()
    {
        // on efface le splatter
        KillKat.currentOverlay.fadeOut(1200);

        // on applique l'effet d'image : flip et collapse
        KillKat.currentImg
            .css({position :'relative'})
            .animate({ top: '-60px'}, 200, 'swing').dequeue()  // upping
            .animate({ 'transform' : 'rotate(360deg)'}, 1200) // rotation
            .animate({ top: '+=800px' }, 2000, 'swing') // collapses
            .effect( 'explode', 1200) // explodes
            .fadeOut()  // hides
        ;
            /*
            .slideToggle(
            {    easing: 'easeOutExpo',
                duration: 200,
                complete: function()
                {
                    jQuery(this).slideToggle(
                        {
                            easing: 'easeOutExpo',
                            duration: 200,
                            complete : function(){
                                jQuery(this).animate({
                                    top: '+=800px'
                                }, 2000, 'swing').fadeOut(function(){ jQuery(this).hide();});
                            }
                        });
                }
            });
            */
    },
    setIconKillable: function()
    {
        var domIconKillable = jQuery('#'+KillKat.styles.KILLABLE_CLASS+'-'+KillKat.currentImgIndex);
        if (! domIconKillable.length)
        {
            var _parent = KillKat.currentImg.parent();
            jQuery('

')
                .css({
                    'top' : 0,
                    'left' : _parent.outerWidth() - parseInt(KillKat.icons.iconKillable.width) +'px'
                })
                .insertBefore(KillKat.currentImg.parent());
        }
    },
    highlightKillables: function(){

        var loops = 0;
        var lst = jQuery('.'+KillKat.styles.KILLABLE_CLASS+':in-viewport');

        lst.on('transitionend webkitTransitionEnd', function(){
            if (loops==lst.length){
                lst.animate({ 'transform' : 'scale(1)', 'background-color' : 'rgb(242, 222, 222)'}, 700);
                loops=0;
            }
        })
        .animate({ 'transform' : 'scale(2)', 'background-color': '#e88888'}, 700, function(){ loops++; });

        //jQuery.when( doit() ).done(function(){
          //  console.log('done');
           // lst.animate({ 'transform' : 'scale(1)'}, 700);
        //});
            //.animate({ 'transform' : 'scale(1)'}, 700);

    },

	isKatKilled: function(jqImg)
	{
		return (jqImg.parent().hasClass(KillKat.styles.KILLED_CLASS));
	},

    getImgIndex : function()
    {
        return KillKat.domImgs.index(KillKat.currentImg);
    },
    playSound : function()
    {
        if (! jQuery('#killkat-sound').length){
            KillKat.setSoundPlayer();
        }
        KillKat.sound.play();
    },
    setSoundPlayer: function()
    {
        if (! jQuery('#killkat-sound').length)
        {
            var sound = jQuery('<audio id="killkat-sound" preload="auto">'+
                '<source src="'+KillKat.GITHUB+'/audio/splatter-sound.mp3" type="audio/mp3" />'+
                            //'<source src="http://www.freesfx.co.uk/rx2/mp3s/2/1871_1272479313.mp3" type="audio/mp3" />'+
                            'Votre navigateur n\'est pas compatible'+
                            '</audio>');

            jQuery('body').append(sound);
            KillKat.sound = sound.get(0);
        }
    },
	convertImgToBase64 : function(url, callback, outputFormat)
	{
	    var canvas = document.createElement('canvas'),
	    ctx = canvas.getContext('2d'),
	    img = new Image();
	    img.crossOrigin = 'Anonymous';
	    img.onload = function(){
	        canvas.height = img.height;
	        canvas.width = img.width;
	        ctx.drawImage(img,0,0);
	        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
	        callback.call(this, dataURL);
	        canvas = null;
	    };
	    img.src = url;
	},
    loadFirstJSFile: function(url, callback)
    {
        var script = document.createElement("script")
        script.type = "text/javascript";

        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    if (callback) callback();
                }
            };
        } else { //Others
            script.onload = function () {
                if (callback) callback();

            };
        }
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }

};

KillKat.init();

<|endoftext|>


<commit_before>/* vim:ts=4:sts=4:sw=4:
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *      Mihai Sucan <mihai DOT sucan AT gmail DOT com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

var event = require("pilot/event");
var useragent = require("pilot/useragent");
var dom = require("pilot/dom");

var TextInput = function(parentNode, host) {

    var text = dom.createElement("textarea");
    text.style.left = "-10000px";
    parentNode.appendChild(text);

    var PLACEHOLDER = String.fromCharCode(0);
    sendText();

    var inCompostion = false;
    var copied = false;
    var pasted = false;
    var tempStyle = '';

    function select() {
        try {
            text.select();
        } catch (e) {}
    };

    function sendText(valueToSend) {
        if (!copied) {
            var value = valueToSend || text.value;
            if (value) {
                if (value.charCodeAt(value.length-1) == PLACEHOLDER.charCodeAt(0)) {
                    value = value.slice(0, -1);
                    if (value)
                        host.onTextInput(value, !pasted);
                }
                else {
                    host.onTextInput(value, !pasted);
                }

                // If editor is no longer focused we quit immediately, since
                // it means that something else is in charge now.
                if (!isFocused())
                    return false;
            }
        }

        copied = false;
        pasted = false;

        // Safari doesn't fire copy events if no text is selected
        text.value = PLACEHOLDER;
        select();
    }

    var onTextInput = function(e) {
        setTimeout(function () {
            if (!inCompostion)
                sendText(e.data);
        }, 0);
    };

    var onPropertyChange = function(e) {
        if (useragent.isOldIE && text.value.charCodeAt(0) > 128) return;
        setTimeout(function() {
            if (!inCompostion)
                sendText();
        }, 0);
    };

    var onCompositionStart = function(e) {
        inCompostion = true;
        host.onCompositionStart();
        if (!useragent.isGecko) setTimeout(onCompositionUpdate, 0);
    };

    var onCompositionUpdate = function() {
        if (!inCompostion) return;
        host.onCompositionUpdate(text.value);
    };

    var onCompositionEnd = function(e) {
        inCompostion = false;
        host.onCompositionEnd();
    };

    var onCopy = function(e) {
        copied = true;
        var copyText = host.getCopyText();
        if(copyText)
            text.value = copyText;
        else
            e.preventDefault();
        select();
        setTimeout(function () {
            sendText();
        }, 0);
    };

    var onCut = function(e) {
        copied = true;
        var copyText = host.getCopyText();
        if(copyText) {
            text.value = copyText;
            host.onCut();
        } else
            e.preventDefault();
        select();
        setTimeout(function () {
            sendText();
        }, 0);
    };

    event.addCommandKeyListener(text, host.onCommandKey.bind(host));
    if (useragent.isOldIE) {
        var keytable = { 13:1, 27:1 };
        event.addListener(text, "keyup", function (e) {
            if (inCompostion && (!text.value || keytable[e.keyCode]))
                setTimeout(onCompositionEnd, 0);
            if ((text.value.charCodeAt(0)|0) < 129) {
                return;
            };
            inCompostion ? onCompositionUpdate() : onCompositionStart();
        });
    };

    if ("onpropertychange" in text && !("oninput" in text))
        event.addListener(text, "propertychange", onPropertyChange);
    else
        event.addListener(text, "input", onTextInput);

    event.addListener(text, "paste", function(e) {
        // Mark that the next input text comes from past.
        pasted = true;
        // Some browsers support the event.clipboardData API. Use this to get
        // the pasted content which increases speed if pasting a lot of lines.
        if (e.clipboardData && e.clipboardData.getData) {
            sendText(e.clipboardData.getData("text/plain"));
            e.preventDefault();
        }
        else {
            // If a browser doesn't support any of the things above, use the regular
            // method to detect the pasted input.
            onPropertyChange();
        }
    });

    if ("onbeforecopy" in text) {
        event.addListener(text, "beforecopy", function(e) {
            var copyText = host.getCopyText();
            if(copyText)
                clipboardData.setData("Text", copyText);
            else
                e.preventDefault();
        });
        event.addListener(parentNode, "keydown", function(e) {
            if (e.ctrlKey && e.keyCode == 88) {
                var copyText = host.getCopyText();
                if (copyText) {
                    clipboardData.setData("Text", copyText);
                    host.onCut();
                }
                event.preventDefault(e)
            }
        });
    }
    else {
        event.addListener(text, "copy", onCopy);
        event.addListener(text, "cut", onCut);
    }

    event.addListener(text, "compositionstart", onCompositionStart);
    if (useragent.isGecko) {
        event.addListener(text, "text", onCompositionUpdate);
    };
    if (useragent.isWebKit) {
        event.addListener(text, "keyup", onCompositionUpdate);
    };
    event.addListener(text, "compositionend", onCompositionEnd);

    event.addListener(text, "blur", function() {
        host.onBlur();
    });

    event.addListener(text, "focus", function() {
        host.onFocus();
        select();
    });

    this.focus = function() {
        host.onFocus();
        select();
        text.focus();
    };

    this.blur = function() {
        text.blur();
    };

    function isFocused() {
        return document.activeElement === text;
    };
    this.isFocused = isFocused;

    this.getElement = function() {
        return text;
    };

    this.onContextMenu = function(mousePos, isEmpty){
        if (mousePos) {
            if(!tempStyle)
                tempStyle = text.style.cssText;
            text.style.cssText = 'position:fixed; z-index:1000;' +
                    'left:' + (mousePos.x - 2) + 'px; top:' + (mousePos.y - 2) + 'px;'

        }
        if (isEmpty)
            text.value='';
    }

    this.onContextMenuClose = function(){
        setTimeout(function () {
            if (tempStyle) {
                text.style.cssText = tempStyle;
                tempStyle = '';
            }
            sendText();
        }, 0);
    }
};

exports.TextInput = TextInput;
});
<commit_msg>fix autocaps issue<commit_after>/* vim:ts=4:sts=4:sw=4:
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *      Mihai Sucan <mihai DOT sucan AT gmail DOT com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

var event = require("pilot/event");
var useragent = require("pilot/useragent");
var dom = require("pilot/dom");

var TextInput = function(parentNode, host) {

    var text = dom.createElement("textarea");
    if (useragent.isTouchPad)
    	text.setAttribute('x-palm-disable-auto-cap',true);
    text.style.left = "-10000px";
    parentNode.appendChild(text);

    var PLACEHOLDER = String.fromCharCode(0);
    sendText();

    var inCompostion = false;
    var copied = false;
    var pasted = false;
    var tempStyle = '';

    function select() {
        try {
            text.select();
        } catch (e) {}
    };

    function sendText(valueToSend) {
        if (!copied) {
            var value = valueToSend || text.value;
            if (value) {
                if (value.charCodeAt(value.length-1) == PLACEHOLDER.charCodeAt(0)) {
                    value = value.slice(0, -1);
                    if (value)
                        host.onTextInput(value, !pasted);
                }
                else {
                    host.onTextInput(value, !pasted);
                }

                // If editor is no longer focused we quit immediately, since
                // it means that something else is in charge now.
                if (!isFocused())
                    return false;
            }
        }

        copied = false;
        pasted = false;

        // Safari doesn't fire copy events if no text is selected
        text.value = PLACEHOLDER;
        select();
    }

    var onTextInput = function(e) {
        setTimeout(function () {
            if (!inCompostion)
                sendText(e.data);
        }, 0);
    };

    var onPropertyChange = function(e) {
        if (useragent.isOldIE && text.value.charCodeAt(0) > 128) return;
        setTimeout(function() {
            if (!inCompostion)
                sendText();
        }, 0);
    };

    var onCompositionStart = function(e) {
        inCompostion = true;
        host.onCompositionStart();
        if (!useragent.isGecko) setTimeout(onCompositionUpdate, 0);
    };

    var onCompositionUpdate = function() {
        if (!inCompostion) return;
        host.onCompositionUpdate(text.value);
    };

    var onCompositionEnd = function(e) {
        inCompostion = false;
        host.onCompositionEnd();
    };

    var onCopy = function(e) {
        copied = true;
        var copyText = host.getCopyText();
        if(copyText)
            text.value = copyText;
        else
            e.preventDefault();
        select();
        setTimeout(function () {
            sendText();
        }, 0);
    };

    var onCut = function(e) {
        copied = true;
        var copyText = host.getCopyText();
        if(copyText) {
            text.value = copyText;
            host.onCut();
        } else
            e.preventDefault();
        select();
        setTimeout(function () {
            sendText();
        }, 0);
    };

    event.addCommandKeyListener(text, host.onCommandKey.bind(host));
    if (useragent.isOldIE) {
        var keytable = { 13:1, 27:1 };
        event.addListener(text, "keyup", function (e) {
            if (inCompostion && (!text.value || keytable[e.keyCode]))
                setTimeout(onCompositionEnd, 0);
            if ((text.value.charCodeAt(0)|0) < 129) {
                return;
            };
            inCompostion ? onCompositionUpdate() : onCompositionStart();
        });
    };

    if ("onpropertychange" in text && !("oninput" in text))
        event.addListener(text, "propertychange", onPropertyChange);
    else
        event.addListener(text, "input", onTextInput);

    event.addListener(text, "paste", function(e) {
        // Mark that the next input text comes from past.
        pasted = true;
        // Some browsers support the event.clipboardData API. Use this to get
        // the pasted content which increases speed if pasting a lot of lines.
        if (e.clipboardData && e.clipboardData.getData) {
            sendText(e.clipboardData.getData("text/plain"));
            e.preventDefault();
        }
        else {
            // If a browser doesn't support any of the things above, use the regular
            // method to detect the pasted input.
            onPropertyChange();
        }
    });

    if ("onbeforecopy" in text) {
        event.addListener(text, "beforecopy", function(e) {
            var copyText = host.getCopyText();
            if(copyText)
                clipboardData.setData("Text", copyText);
            else
                e.preventDefault();
        });
        event.addListener(parentNode, "keydown", function(e) {
            if (e.ctrlKey && e.keyCode == 88) {
                var copyText = host.getCopyText();
                if (copyText) {
                    clipboardData.setData("Text", copyText);
                    host.onCut();
                }
                event.preventDefault(e)
            }
        });
    }
    else {
        event.addListener(text, "copy", onCopy);
        event.addListener(text, "cut", onCut);
    }

    event.addListener(text, "compositionstart", onCompositionStart);
    if (useragent.isGecko) {
        event.addListener(text, "text", onCompositionUpdate);
    };
    if (useragent.isWebKit) {
        event.addListener(text, "keyup", onCompositionUpdate);
    };
    event.addListener(text, "compositionend", onCompositionEnd);

    event.addListener(text, "blur", function() {
        host.onBlur();
    });

    event.addListener(text, "focus", function() {
        host.onFocus();
        select();
    });

    this.focus = function() {
        host.onFocus();
        select();
        text.focus();
    };

    this.blur = function() {
        text.blur();
    };

    function isFocused() {
        return document.activeElement === text;
    };
    this.isFocused = isFocused;

    this.getElement = function() {
        return text;
    };

    this.onContextMenu = function(mousePos, isEmpty){
        if (mousePos) {
            if(!tempStyle)
                tempStyle = text.style.cssText;
            text.style.cssText = 'position:fixed; z-index:1000;' +
                    'left:' + (mousePos.x - 2) + 'px; top:' + (mousePos.y - 2) + 'px;'

        }
        if (isEmpty)
            text.value='';
    }

    this.onContextMenuClose = function(){
        setTimeout(function () {
            if (tempStyle) {
                text.style.cssText = tempStyle;
                tempStyle = '';
            }
            sendText();
        }, 0);
    }
};

exports.TextInput = TextInput;
});
<|endoftext|>


<commit_before>import firebase from "firebase/app";
import "firebase/auth";

import firebaseConfig from "./config/firebaseConfig";

// const firebaseConfig = {
//   apiKey: process.env.REACT_APP_API_KEY,
//   authDomain: process.env.REACT_APP_AUTH_DOMAIN,
//   projectId: process.env.REACT_APP_PROJECT_ID,
//   storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
//   messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
//   appId: process.env.REACT_APP_APP_ID,
//   measurementId: process.env.REACT_APP_MEASUREMENT_ID,
// };

firebase.initializeApp(firebaseConfig);

export const auth = firebase.auth();

const googleProvider = new firebase.auth.GoogleAuthProvider();
export const signInWithGoogle = () => {
  auth
    .signInWithPopup(googleProvider)
    .then()
    .catch((error) => {
      console.log(error.message);
    });
};

export const onAuthStateChange = (callback) => {
  return firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      callback({
        signedIn: true,
        name: user.displayName,
        email: user.email,
      });
    } else {
      callback({
        signedIn: false,
      });
    }
  });
};

export const signOut = () => {
  firebase.auth().signOut();
};
<commit_msg>Delete unnecessary comments'<commit_after>import firebase from "firebase/app";
import "firebase/auth";
import firebaseConfig from "./config/firebaseConfig";

firebase.initializeApp(firebaseConfig);

export const auth = firebase.auth();

const googleProvider = new firebase.auth.GoogleAuthProvider();
export const signInWithGoogle = () => {
  auth
    .signInWithPopup(googleProvider)
    .then()
    .catch((error) => {
      console.log(error.message);
    });
};

export const onAuthStateChange = (callback) => {
  return firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      callback({
        signedIn: true,
        name: user.displayName,
        email: user.email,
      });
    } else {
      callback({
        signedIn: false,
      });
    }
  });
};

export const signOut = () => {
  firebase.auth().signOut();
};
<|endoftext|>