<commit_before>// Eheeey! Welcome to POP.js

var POP = function(params) {
    var that = this;
    that.configs = {
        controls   : true,
        editorMode : true
    };
    that.mode = 'desktop'; // or 'vr'
    that.three = {};
    that.container = (params && params.container) || document.body;
    that.elements = [];
    that.worlds = params.worlds || [];
    that.selectedWorld = params.selectedWorld || 0;
    that.cursorCoords = {};

    that.events = {
        resize            : function() {
            that.three.camera.aspect = window.innerWidth / window.innerHeight;
            that.three.camera.updateProjectionMatrix();

            that.three.rendererGL.setSize(window.innerWidth, window.innerHeight);
            that.three.rendererCSS.setSize(window.innerWidth, window.innerHeight);

            if(that.mode == 'vr') {
                that.effect && that.effect.setSize( window.innerWidth, window.innerHeight );
            }
        },
        addMovingClass    : function() {
            document.body.setAttribute('move', 'true');
        },
        removeMovingClass : function() {
            document.body.removeAttribute('move');
        }
    };

    that.saveImage = function(){

        // This is experiment, fuck this shit

        var planes = [];

        var capture = function(index){
            if(index + 1 != that.elements.length) return;

            var position = {
                x: that.three.camera.position.x,
                y: that.three.camera.position.y,
                z: that.three.camera.position.z
            }

            that.three.camera.position.set(0, 0, 0);
            that.three.equi.update( that.three.camera, that.three.sceneGL );

            setTimeout(function(){
                debugger;
                that.three.camera.position.set(position.x, position.y, position.z)
            }, 300);

            planes.forEach(function(item){
                that.three.sceneGL.remove(item);
            });
        }

        that.elements.forEach(function(element, i){
            var copy = element.element.cloneNode(true);;
            var style = copy.getAttribute('style');

            var x = copy.getAttribute('x'),
                y = copy.getAttribute('y'),
                z = copy.getAttribute('z'),
                world = copy.getAttribute('world');

            var W = element.element.offsetWidth,
                H = element.element.offsetHeight;

            if(world != that.selectedWorld()) return;

            copy.removeAttribute('style');
            document.body.appendChild(copy);

            html2canvas(copy, {
              allowTaint: true,
              logging: true,
              width: W,
              height: H
          }).then(function(canvas){
                var texture = new THREE.Texture(canvas);
                texture.needsUpdate = true;

                texture.wrapS = THREE.RepeatWrapping;
                texture.repeat.x = - 1;

                var geometry = new THREE.PlaneGeometry( W, H );
                var material = new THREE.MeshBasicMaterial( { map: texture, side: THREE.DoubleSide, transparent: true, alphaTest: 0.5 } );
                var plane = new THREE.Mesh( geometry, material );
                that.three.sceneGL.add( plane );

                plane.position.set(x, y, z);
                plane.lookAt(that.three.camera.position);

                console.log(plane);

                planes.push(plane);

                document.body.removeChild(copy);

                setTimeout(function(){
                    capture(i);
                }, 100);
          });
        });
    };

    that.init = function() {
        that.three.sceneGL = new THREE.Scene();
        that.three.sceneCSS = new THREE.Scene();

        // -- Setting up the camera -- //
        that.three.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000000);
        that.three.camera.position.z = 1;

        // -- Defining the WebGL and CSS3D Renderers -- //
        var rendererCSS = null;

        rendererCSS = that.mode == 'vr' ? new THREE.CSS3DStereoRenderer() : new THREE.CSS3DRenderer();
        rendererCSS.setSize(window.innerWidth, window.innerHeight);
        rendererCSS.domElement.id = 'renderer-css';

        var rendererGL = new THREE.WebGLRenderer({
            alpha     : true,
            antialias : true,
            preserveDrawingBuffer: true
        });
        rendererGL.setClearColor(0x00ff00, 0.0);
        rendererGL.domElement.id = 'renderer-gl';

        if(that.mode == 'vr') {
            var effect = new THREE.StereoEffect( rendererGL );
            effect.setSize( window.innerWidth, window.innerHeight );

            that.effect = effect;
        }

        that.three.equi = new THREE.CubemapToEquirectangular( rendererGL, true );

        rendererGL.setSize(window.innerWidth, window.innerHeight);
        rendererCSS.domElement.appendChild(rendererGL.domElement);

        that.container.appendChild(rendererCSS.domElement);

        that.three.rendererGL = rendererGL;
        that.three.rendererCSS = rendererCSS;

        that.three.raycaster = new THREE.Raycaster();
        that.three.mouse = new THREE.Vector2();

        // -- Adding the orbit controls -- //
        if(that.configs.controls) {
            that.three.controls = new THREE.OrbitControls(that.three.camera, that.three.rendererGL.domElement);
            that.three.controls.zoomSpeed = 0;
            that.three.controls.enablePan = false;
        }

        that.addPopElements();
        that.attachingTheEvents();
        that.animate();
    };
    that.createWorld = function(options, cb) {
        options.koColor = options.koColor || ko.observable('blue');
        options.color = options.koColor();
        options.depthTest = false;

        var world = new THREE.Mesh(
            new THREE.SphereGeometry(options.size, 100, 50),
            new THREE.MeshBasicMaterial(that.configs.editorMode ? { side: THREE.DoubleSide } : options)
        );
        var sphereFrame;
        world.options = options;
        world.material.side = THREE.DoubleSide;
        that.three.sceneGL.add(world);

        if(that.configs.editorMode) {
            var sphereFrameGeo = new THREE.EdgesGeometry(world.geometry);
            var sphereFrameMat = new THREE.LineBasicMaterial({color : 'rgb(0,0,0)', linewidth : 1, transparent: true, opacity: 0.2});
            sphereFrame = new THREE.LineSegments(sphereFrameGeo, sphereFrameMat);

            var frameHolder = new THREE.Mesh(
                new THREE.SphereGeometry(options.size, 100, 50),
                new THREE.MeshBasicMaterial({side: THREE.DoubleSide, transparent: true, opacity: 0})
            );

            that.three.sceneGL.add(frameHolder);

            frameHolder.scale.set(0.5, 0.5, 0.5);
            sphereFrame.scale.set(0.6, 0.6, 0.6);

            sphereFrame.frameHolder = frameHolder;
            sphereFrame.visible = false;
            sphereFrame.world = world;
            sphereFrame.options = options;
        }
        that.three.sceneGL.add(sphereFrame);
        that.worlds.push(sphereFrame || world);

        that.selectWorld(that.worlds().length - 1);

        cb && cb();
    };
    that.selectWorld = function(index) {
        if(params.selectedWorld)
            params.selectedWorld(index);
        else
            that.selectedWorld = index;

        var helements = document.querySelectorAll('.pop-element:not([world="' + index + '"])'), // Elements I should hide
            selements = document.querySelectorAll('.pop-element[world="' + index + '"]'); // Elements I should show

            helements.forEach(function(element){
                element.style.display = 'none';
            });

            selements.forEach(function(element){
                element.style.display = 'block';
            });

        that.worlds().forEach(function(item, i) {
            if(i == index) {
                if(!item.world) item.world = {};

                item.visible = item.frameHolder.visible = item.world.visible = true;
            } else {
                if(!item.world) item.world = {};

                item.visible = item.frameHolder.visible = item.world.visible = false;
            }
        });
    };
    that.addPopElements = function(cb) {
        var popElements = document.querySelectorAll('.pop-element');
        for(var i = 0; i < popElements.length; i++) {
            if(that.elements.indexOf(popElements[i]) < 0) {
                that.addPopElement(popElements[i], {
                    world : popElements[i].getAttribute('world'),
                    x     : popElements[i].getAttribute('x'),
                    y     : popElements[i].getAttribute('y'),
                    z     : popElements[i].getAttribute('z')
                });
            }
        }
        cb && cb();
    };
    that.addPopElement = function(element, option, cb) {
        if(option.world === false) {
            console.error("The 'world' attribute is required for the element.")
            return;
        }

        that.addHtml({
            world   : option.world,
            x       : option.x || 0,
            y       : option.y || 0,
            z       : option.z || 0,
            content : element
        });
        cb && cb();
    };
    that.attachingTheEvents = function() {
        window.addEventListener('resize', that.events.resize);
        that.three.rendererGL.domElement.addEventListener('mousedown', that.events.addMovingClass);
        that.three.rendererGL.domElement.addEventListener('mousemove', function(e) {
            that.cursorCoords = that.getCoordsFromWorld(e, 1);
        });
        that.three.rendererGL.domElement.addEventListener('dragover', function(e) {
            that.cursorCoords = that.getCoordsFromWorld(e, 1);
        });
        that.three.rendererGL.domElement.addEventListener('mouseup', that.events.removeMovingClass);
    };
    that.getCoordsFromWorld = function(event, index) {
        event.preventDefault();
        var point;

        that.three.mouse.x = ( event.clientX / that.three.rendererGL.domElement.clientWidth ) * 2 - 1;
        that.three.mouse.y = -( event.clientY / that.three.rendererGL.domElement.clientHeight ) * 2 + 1;

        that.three.raycaster.setFromCamera(that.three.mouse, that.three.camera);

        var intersects = that.three.raycaster.intersectObjects(that.three.sceneGL.children);

        if(intersects.length > 0) {
            if(!intersects[0].face) intersects[0] = intersects[1];

            point = intersects[0].point;
            return point;
        }
    };
    that.changeMode = function(mode) {
        var that = this;

        if(mode){
            that.mode = mode;
        } else {
            that.mode = that.mode == 'vr' ? 'desktop' : 'vr';
        }

        if(that.mode == 'vr' && !that.effect) {
            var effect = new THREE.StereoEffect( that.three.rendererGL );
            effect.setSize( window.innerWidth, window.innerHeight );

            that.effect = effect;
        }

        that.rerender();
        that.events.resize();
    };
    that.rerender = function(){

        document.body.removeChild(document.querySelector('#renderer-css'));

        that.three.rendererCSS = that.mode == 'vr' ? new THREE.CSS3DStereoRenderer() : new THREE.CSS3DRenderer();
        that.three.rendererCSS.setSize(window.innerWidth, window.innerHeight);
        that.three.rendererCSS.domElement.id = 'renderer-css';

        that.three.rendererCSS.domElement.appendChild(that.three.rendererGL.domElement);

        that.container.appendChild(that.three.rendererCSS.domElement);

        that.selectWorld(that.selectedWorld());

    };
    that.animate = function() {
        requestAnimationFrame(that.animate);

        that.three.rendererGL.render(that.three.sceneGL, that.three.camera);
        that.three.rendererCSS.render(that.three.sceneCSS, that.three.camera);

        if(that.mode == 'vr')
            that.effect && that.effect.render(that.three.sceneGL, that.three.camera);

        if(that.configs.controls)
            that.three.controls.update();
    };
    that.init();
};

POP.prototype.addHtml = function(params) {
    var that = this,
        htmlObject = new THREE.CSS3DObject(params.content);

    params.content.setAttribute('world', params.world);
    params.content.setAttribute('x', params.x);
    params.content.setAttribute('y', params.y);
    params.content.setAttribute('z', params.z);

    htmlObject.position.z = params.z || 0;
    htmlObject.position.y = params.y || 0;
    htmlObject.position.x = params.x || 0;

    htmlObject.element = params.content;
    htmlObject.index = that.elements.length;
    params.content.object = htmlObject;

    htmlObject.lookAt(that.three.camera.position);

    // -- Adding the HTML Content to scene -- //
    that.three.sceneCSS.add(htmlObject);
    that.elements.push(htmlObject);
};
POP.prototype.add3dObject = function(params) {
    // :TODO -- This function supports .obj, .js, .collada model formats -- //
    var that = this;
};
<commit_msg>Added a light into the world<commit_after>// Eheeey! Welcome to POP.js

var POP = function(params) {
    var that = this;
    that.configs = {
        controls   : true,
        editorMode : true
    };
    that.mode = 'desktop'; // or 'vr'
    that.three = {};
    that.container = (params && params.container) || document.body;
    that.elements = [];
    that.worlds = params.worlds || [];
    that.objects = [];
    that.selectedWorld = params.selectedWorld || 0;
    that.cursorCoords = {};

    that.events = {
        resize            : function() {
            that.three.camera.aspect = window.innerWidth / window.innerHeight;
            that.three.camera.updateProjectionMatrix();

            that.three.rendererGL.setSize(window.innerWidth, window.innerHeight);
            that.three.rendererCSS.setSize(window.innerWidth, window.innerHeight);

            if(that.mode == 'vr') {
                that.effect && that.effect.setSize( window.innerWidth, window.innerHeight );
            }
        },
        addMovingClass    : function() {
            document.body.setAttribute('move', 'true');
        },
        removeMovingClass : function() {
            document.body.removeAttribute('move');
        }
    };

    that.utils = {
        hasFormat: function(){
            String.prototype.hasFormat = function(formats) {
                var value = this.toString();

                var filter = formats.filter(function(item){
                    return value.indexOf(item) > -1;
                });

                return filter[0] && filter[0].replace('.', '') || false;
            }
        }
    };

    that.saveImage = function(){

        // This is experiment, fuck this shit

        var planes = [];

        var capture = function(index){
            if(index + 1 != that.elements.length) return;

            var position = {
                x: that.three.camera.position.x,
                y: that.three.camera.position.y,
                z: that.three.camera.position.z
            };

            that.three.camera.position.set(0, 0, 0);
            that.three.equi.update( that.three.camera, that.three.sceneGL );

            setTimeout(function(){
                debugger;
                that.three.camera.position.set(position.x, position.y, position.z)
            }, 300);

            planes.forEach(function(item){
                that.three.sceneGL.remove(item);
            });
        };

        that.elements.forEach(function(element, i){
            var copy = element.element.cloneNode(true);
            var style = copy.getAttribute('style');

            var x = copy.getAttribute('x'),
                y = copy.getAttribute('y'),
                z = copy.getAttribute('z'),
                world = copy.getAttribute('world');

            var W = element.element.offsetWidth,
                H = element.element.offsetHeight;

            if(world != that.selectedWorld()) return;

            copy.removeAttribute('style');
            document.body.appendChild(copy);

            html2canvas(copy, {
              allowTaint: true,
              logging: true,
              width: W,
              height: H
          }).then(function(canvas){
                var texture = new THREE.Texture(canvas);
                texture.needsUpdate = true;

                var geometry = new THREE.PlaneGeometry( W, H );
                var material = new THREE.MeshBasicMaterial( { map: texture, side: THREE.DoubleSide, transparent: true, alphaTest: 0.5 } );
                var plane = new THREE.Mesh( geometry, material );
                that.three.sceneGL.add( plane );

                plane.position.set(x, y, z);
                plane.lookAt(that.three.camera.position);

                console.log(plane);

                planes.push(plane);

                document.body.removeChild(copy);

                setTimeout(function(){
                    capture(i);
                }, 100);
          });
        });
    };

    that.init = function() {
        that.three.sceneGL = new THREE.Scene();
        that.three.sceneCSS = new THREE.Scene();

        // -- Setting up the camera -- //
        that.three.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000000);
        that.three.camera.position.z = 1;

        var light;

        light = new THREE.DirectionalLight(0xffffff, 4);
        light.position.set(0, 800, 0);

        light.castShadow = true;

        light.shadow.mapSize.width = 2024;
        light.shadow.mapSize.height = 2024;

        var d = 200;

        light.shadow.camera.left = -d;
        light.shadow.camera.right = d;
        light.shadow.camera.top = d;
        light.shadow.camera.bottom = -d;

        light.shadow.camera.far = 2000;

        that.three.sceneGL.add(light);
        that.three.dlight = light;

        ambient = new THREE.AmbientLight(0xffffff, 0.6);
        that.three.sceneGL.add(ambient);
        that.three.alight = ambient;

        // -- Defining the WebGL and CSS3D Renderers -- //
        var rendererCSS = null;

        rendererCSS = that.mode == 'vr' ? new THREE.CSS3DStereoRenderer() : new THREE.CSS3DRenderer();
        rendererCSS.setSize(window.innerWidth, window.innerHeight);
        rendererCSS.domElement.id = 'renderer-css';

        var rendererGL = new THREE.WebGLRenderer({
            alpha     : true,
            antialias : true,
            preserveDrawingBuffer: true
        });
        rendererGL.setClearColor(0x00ff00, 0.0);
        rendererGL.domElement.id = 'renderer-gl';

        if(that.mode == 'vr') {
            var effect = new THREE.StereoEffect( rendererGL );
            effect.setSize( window.innerWidth, window.innerHeight );

            that.effect = effect;
        }

        that.three.equi = new THREE.CubemapToEquirectangular( rendererGL, true );

        rendererGL.setSize(window.innerWidth, window.innerHeight);
        rendererCSS.domElement.appendChild(rendererGL.domElement);

        that.container.appendChild(rendererCSS.domElement);

        that.three.rendererGL = rendererGL;
        that.three.rendererCSS = rendererCSS;

        that.three.raycaster = new THREE.Raycaster();
        that.three.mouse = new THREE.Vector2();

        // -- Adding the orbit controls -- //
        if(that.configs.controls) {
            that.three.controls = new THREE.OrbitControls(that.three.camera, that.three.rendererGL.domElement);
            that.three.controls.zoomSpeed = 0;
            that.three.controls.enablePan = false;
        }

        // -- Adding a method to the string class -- //
        that.utils.hasFormat();

        that.addPopElements();
        that.attachingTheEvents();
        that.animate();
    };
    that.createWorld = function(options, cb) {
        options.koColor = options.koColor || ko.observable('blue');
        options.color = options.koColor();
        options.depthTest = false;

        var world = new THREE.Mesh(
            new THREE.SphereGeometry(options.size, 100, 50),
            new THREE.MeshBasicMaterial(that.configs.editorMode ? { side: THREE.DoubleSide } : options)
        );
        var sphereFrame;
        world.options = options;
        world.material.side = THREE.DoubleSide;
        that.three.sceneGL.add(world);

        if(that.configs.editorMode) {
            var sphereFrameGeo = new THREE.EdgesGeometry(world.geometry);
            var sphereFrameMat = new THREE.LineBasicMaterial({color : 'rgb(0,0,0)', linewidth : 1, transparent: true, opacity: 0.2});
            sphereFrame = new THREE.LineSegments(sphereFrameGeo, sphereFrameMat);

            var frameHolder = new THREE.Mesh(
                new THREE.SphereGeometry(options.size, 100, 50),
                new THREE.MeshBasicMaterial({side: THREE.DoubleSide, transparent: true, opacity: 0})
            );

            that.three.sceneGL.add(frameHolder);

            frameHolder.scale.set(0.5, 0.5, 0.5);
            sphereFrame.scale.set(0.6, 0.6, 0.6);

            sphereFrame.frameHolder = frameHolder;
            sphereFrame.visible = false;
            sphereFrame.world = world;
            sphereFrame.options = options;
        }
        that.three.sceneGL.add(sphereFrame);
        that.worlds.push(sphereFrame || world);

        that.selectWorld(that.worlds().length - 1);

        cb && cb();
    };
    that.selectWorld = function(index) {
        if(params.selectedWorld)
            params.selectedWorld(index);
        else
            that.selectedWorld = index;

        var helements = document.querySelectorAll('.pop-element:not([world="' + index + '"])'), // Elements I should hide
            selements = document.querySelectorAll('.pop-element[world="' + index + '"]'); // Elements I should show

            helements.forEach(function(element){
                element.style.display = 'none';
            });

            selements.forEach(function(element){
                element.style.display = 'block';
            });

        that.worlds().forEach(function(item, i) {
            if(i == index) {
                if(!item.world) item.world = {};

                item.visible = item.frameHolder.visible = item.world.visible = true;
            } else {
                if(!item.world) item.world = {};

                item.visible = item.frameHolder.visible = item.world.visible = false;
            }
        });
    };
    that.fileExists = function(url, cb) {
        var xmlhttp;
        // compatible with IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        xmlhttp.onreadystatechange = function (oEvent) {
            if (xmlhttp.readyState === 4) {
                if (xmlhttp.status === 200) {
                   cb();
                }
            }
        };
    };
    that.addPopElements = function(cb) {
        var popElements = document.querySelectorAll('.pop-element');
        for(var i = 0; i < popElements.length; i++) {
            if(that.elements.indexOf(popElements[i]) < 0) {
                that.addPopElement(popElements[i], {
                    world : popElements[i].getAttribute('world'),
                    x     : popElements[i].getAttribute('x'),
                    y     : popElements[i].getAttribute('y'),
                    z     : popElements[i].getAttribute('z')
                });
            }
        }
        cb && cb();
    };
    that.addPopElement = function(element, option, cb) {
        if(option.world === false) {
            console.error("The 'world' attribute is required for the element.")
            return;
        }

        that.addHtml({
            world   : option.world,
            x       : option.x || 0,
            y       : option.y || 0,
            z       : option.z || 0,
            content : element
        });
        cb && cb();
    };
    that.attachingTheEvents = function() {
        window.addEventListener('resize', that.events.resize);
        that.three.rendererGL.domElement.addEventListener('mousedown', that.events.addMovingClass);
        that.three.rendererGL.domElement.addEventListener('mousemove', function(e) {
            that.cursorCoords = that.getCoordsFromWorld(e, 1);
        });
        that.three.rendererGL.domElement.addEventListener('dragover', function(e) {
            that.cursorCoords = that.getCoordsFromWorld(e, 1);
        });
        that.three.rendererGL.domElement.addEventListener('mouseup', that.events.removeMovingClass);
    };
    that.getCoordsFromWorld = function(event, index) {
        event.preventDefault();
        var point;

        that.three.mouse.x = ( event.clientX / that.three.rendererGL.domElement.clientWidth ) * 2 - 1;
        that.three.mouse.y = -( event.clientY / that.three.rendererGL.domElement.clientHeight ) * 2 + 1;

        that.three.raycaster.setFromCamera(that.three.mouse, that.three.camera);

        var intersects = that.three.raycaster.intersectObjects(that.three.sceneGL.children);

        if(intersects.length > 0) {
            if(!intersects[0].face) intersects[0] = intersects[1];

            point = intersects[0].point;
            return point;
        }
    };
    that.changeMode = function(mode) {
        var that = this;

        if(mode){
            that.mode = mode;
        } else {
            that.mode = that.mode == 'vr' ? 'desktop' : 'vr';
        }

        if(that.mode == 'vr' && !that.effect) {
            var effect = new THREE.StereoEffect( that.three.rendererGL );
            effect.setSize( window.innerWidth, window.innerHeight );

            that.effect = effect;
        }

        that.rerender();
        that.events.resize();
    };
    that.rerender = function(){

        document.body.removeChild(document.querySelector('#renderer-css'));

        that.three.rendererCSS = that.mode == 'vr' ? new THREE.CSS3DStereoRenderer() : new THREE.CSS3DRenderer();
        that.three.rendererCSS.setSize(window.innerWidth, window.innerHeight);
        that.three.rendererCSS.domElement.id = 'renderer-css';

        that.three.rendererCSS.domElement.appendChild(that.three.rendererGL.domElement);

        that.container.appendChild(that.three.rendererCSS.domElement);

        that.selectWorld(that.selectedWorld());

    };
    that.animate = function() {
        requestAnimationFrame(that.animate);

        that.objects.forEach(function(obj) {
            var worldNumber = obj.options.world;

            if(worldNumber != that.selectedWorld()) {
                obj.visible = false;
            } else {
                obj.visible = true;
            }
        });

        that.three.rendererGL.render(that.three.sceneGL, that.three.camera);
        that.three.rendererCSS.render(that.three.sceneCSS, that.three.camera);

        if(that.mode == 'vr')
            that.effect && that.effect.render(that.three.sceneGL, that.three.camera);

        if(that.configs.controls)
            that.three.controls.update();
    };
    that.init();
};

POP.prototype.addHtml = function(params) {
    var that = this,
        htmlObject = new THREE.CSS3DObject(params.content);

    params.content.setAttribute('world', params.world);
    params.content.setAttribute('x', params.x);
    params.content.setAttribute('y', params.y);
    params.content.setAttribute('z', params.z);

    htmlObject.position.z = params.z || 0;
    htmlObject.position.y = params.y || 0;
    htmlObject.position.x = params.x || 0;

    htmlObject.element = params.content;
    htmlObject.index = that.elements.length;
    params.content.object = htmlObject;

    htmlObject.lookAt(that.three.camera.position);

    // -- Adding the HTML Content to scene -- //
    that.three.sceneCSS.add(htmlObject);
    that.elements.push(htmlObject);
};
POP.prototype.add3dObject = function(params) {
    // :TODO -- This function supports .obj, .js, .collada model formats -- //
    var that = this;
};
<|endoftext|>


<commit_before>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var OAE = require('oae-util/lib/oae');
var OaeUtil = require('oae-util/lib/util');

var FollowingAPI = require('oae-following');

/**
 * @REST tenantGetFollowingUserIdFollowers
 *
 * Get all the followers of the user identified by the given `userId`
 *
 * @Server      tenant
 * @Method      GET
 * @Path        /following/{userId}/followers
 * @PathParam   {string}                userId              Unique identifier for user whose followers are requested
 * @QueryParam  {number}                [limit]             Maximum number of users to return (defaults to 10, limited to between 1 and 25)
 * @QueryParam  {string}                [start]             Marker for continuing search (starts at beginning by default)
 * @Return      {FollowingResults}                          Returns an object containing followers of user
 */
OAE.tenantRouter.on('get', '/api/following/:userId/followers', function(req, res) {
    var limit = OaeUtil.getNumberParam(req.query.limit, 10, 1, 25);
    FollowingAPI.getFollowers(req.ctx, req.params.userId, req.query.start, limit, function(err, followers, nextToken) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        return res.send(200, {'results': followers, 'nextToken': nextToken});
    });
});

/**
 * @REST tenantGetFollowingUserIdFollowing
 *
 * Get all the users that the user identified by the given `userId` follows
 *
 * @Server      tenant
 * @Method      GET
 * @Path        /following/{userId}/following
 * @PathParam   {string}                userId              Unique identifier for user to retrieve following information
 * @QueryParam  {number}                [limit]             Maximum number of users to return (defaults to 10, limited to between 1 and 25)
 * @QueryParam  {string}                [start]             Marker for continuing search (starts at beginning by default)
 * @Return      {FollowingResults}                          Returns an object containing followers of user
 */
OAE.tenantRouter.on('get', '/api/following/:userId/following', function(req, res) {
    var limit = OaeUtil.getNumberParam(req.query.limit, 10, 1, 25);
    FollowingAPI.getFollowing(req.ctx, req.params.userId, req.query.start, limit, function(err, following, nextToken) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        return res.send(200, {'results': following, 'nextToken': nextToken});
    });
});

/**
 * @REST tenantPostFollowingUserIdFollow
 *
 * Make the currently authenticated user start following the user identified by the given `userId`
 *
 * @Server      tenant
 * @Method      POST
 * @Path        /following/{userId}/follow
 * @PathParam   {string}                userId              Unique identifier for user to follow
 * @Return      {void}                                      Returns HTTP response status to indicate success or error
 */
OAE.tenantRouter.on('post', '/api/following/:userId/follow', function(req, res) {
    FollowingAPI.follow(req.ctx, req.params.userId, function(err, followers) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        return res.send(200);
    });
});

/**
 * @REST tenantPostFollowingUserIdUnfollow
 *
 * Make the currently authenticated user stop following the user identified by the given `userId`
 *
 * @Server      tenant
 * @Method      POST
 * @Path        /following/{userId}/unfollow
 * @PathParam   {string}                userId              Unique identifier for user to unfollow
 * @Return      {void}                                      Returns HTTP response status to indicate success or error
 */
OAE.tenantRouter.on('post', '/api/following/:userId/unfollow', function(req, res) {
    FollowingAPI.unfollow(req.ctx, req.params.userId, function(err) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        return res.send(200);
    });
});

// Add the REST models for Following

/**
 * @RESTModel FollowingResults
 *
 * @Required  [nextToken,results]
 * @Property  {string}              nextToken           Marker to allow continuation of search
 * @Property  {FollowingUser[]}     results             Array of following or followed users
 */

/**
 * @RESTModel FollowingUser
 *
 * @Required  [displayName,id,lastModified,picture,resourceType,tenant,visibility]
 * @Property    {string}            displayName         Name to display for user
 * @Property    {string}            id                  Unique identifier for user
 * @Property    {string}            lastModified        Time resource last modified (epoch format)
 * @Property    {PictureInfo}       picture             Thumbnails and pictures for user
 * @Property    {string}            resourceType        Type of resource ("user")
 * @Property    {TenantInfo}        tenant              Tenant information for user
 * @Property    {string}            visibility          Visibility of user ("public",...)
 */
<commit_msg>remove server from REST endpoint keys<commit_after>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var OAE = require('oae-util/lib/oae');
var OaeUtil = require('oae-util/lib/util');

var FollowingAPI = require('oae-following');

/**
 * @REST getFollowingUserIdFollowers
 *
 * Get all the followers of the user identified by the given `userId`
 *
 * @Server      tenant
 * @Method      GET
 * @Path        /following/{userId}/followers
 * @PathParam   {string}                userId              Unique identifier for user whose followers are requested
 * @QueryParam  {number}                [limit]             Maximum number of users to return (defaults to 10, limited to between 1 and 25)
 * @QueryParam  {string}                [start]             Marker for continuing search (starts at beginning by default)
 * @Return      {FollowingResults}                          Returns an object containing followers of user
 */
OAE.tenantRouter.on('get', '/api/following/:userId/followers', function(req, res) {
    var limit = OaeUtil.getNumberParam(req.query.limit, 10, 1, 25);
    FollowingAPI.getFollowers(req.ctx, req.params.userId, req.query.start, limit, function(err, followers, nextToken) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        return res.send(200, {'results': followers, 'nextToken': nextToken});
    });
});

/**
 * @REST getFollowingUserIdFollowing
 *
 * Get all the users that the user identified by the given `userId` follows
 *
 * @Server      tenant
 * @Method      GET
 * @Path        /following/{userId}/following
 * @PathParam   {string}                userId              Unique identifier for user to retrieve following information
 * @QueryParam  {number}                [limit]             Maximum number of users to return (defaults to 10, limited to between 1 and 25)
 * @QueryParam  {string}                [start]             Marker for continuing search (starts at beginning by default)
 * @Return      {FollowingResults}                          Returns an object containing followers of user
 */
OAE.tenantRouter.on('get', '/api/following/:userId/following', function(req, res) {
    var limit = OaeUtil.getNumberParam(req.query.limit, 10, 1, 25);
    FollowingAPI.getFollowing(req.ctx, req.params.userId, req.query.start, limit, function(err, following, nextToken) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        return res.send(200, {'results': following, 'nextToken': nextToken});
    });
});

/**
 * @REST postFollowingUserIdFollow
 *
 * Make the currently authenticated user start following the user identified by the given `userId`
 *
 * @Server      tenant
 * @Method      POST
 * @Path        /following/{userId}/follow
 * @PathParam   {string}                userId              Unique identifier for user to follow
 * @Return      {void}                                      Returns HTTP response status to indicate success or error
 */
OAE.tenantRouter.on('post', '/api/following/:userId/follow', function(req, res) {
    FollowingAPI.follow(req.ctx, req.params.userId, function(err, followers) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        return res.send(200);
    });
});

/**
 * @REST postFollowingUserIdUnfollow
 *
 * Make the currently authenticated user stop following the user identified by the given `userId`
 *
 * @Server      tenant
 * @Method      POST
 * @Path        /following/{userId}/unfollow
 * @PathParam   {string}                userId              Unique identifier for user to unfollow
 * @Return      {void}                                      Returns HTTP response status to indicate success or error
 */
OAE.tenantRouter.on('post', '/api/following/:userId/unfollow', function(req, res) {
    FollowingAPI.unfollow(req.ctx, req.params.userId, function(err) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        return res.send(200);
    });
});

// Add the REST models for Following

/**
 * @RESTModel FollowingResults
 *
 * @Required  [nextToken,results]
 * @Property  {string}              nextToken           Marker to allow continuation of search
 * @Property  {FollowingUser[]}     results             Array of following or followed users
 */

/**
 * @RESTModel FollowingUser
 *
 * @Required  [displayName,id,lastModified,picture,resourceType,tenant,visibility]
 * @Property    {string}            displayName         Name to display for user
 * @Property    {string}            id                  Unique identifier for user
 * @Property    {string}            lastModified        Time resource last modified (epoch format)
 * @Property    {PictureInfo}       picture             Thumbnails and pictures for user
 * @Property    {string}            resourceType        Type of resource ("user")
 * @Property    {TenantInfo}        tenant              Tenant information for user
 * @Property    {string}            visibility          Visibility of user ("public",...)
 */
<|endoftext|>


<commit_before>//
//  Created by Mingliang Chen on 17/8/1.
//  illuspas[a]gmail.com
//  Copyright (c) 2018 Nodemedia. All rights reserved.
//

const Https = require('https');
const Logger = require('./node_core_logger');
const NodeRtmpServer = require('./node_rtmp_server');
const NodeHttpServer = require('./node_http_server');
const NodeTransServer = require('./node_trans_server');
const NodeRelayServer = require('./node_relay_server');
const context = require('./node_core_ctx');
const Package = require("./package.json");

class NodeMediaServer {
  constructor(config) {
    this.config = config;
  }

  run() {
    Logger.setLogType(this.config.logType);
    Logger.log(`Node Media Server v${Package.version}`);
    if (this.config.rtmp) {
      this.nrs = new NodeRtmpServer(this.config);
      this.nrs.run();
    }

    if (this.config.http) {
      this.nhs = new NodeHttpServer(this.config);
      this.nhs.run();
    }

    if (this.config.trans) {
      if (this.config.cluster) {
        Logger.log('NodeTransServer does not work in cluster mode');
      } else {
        this.nts = new NodeTransServer(this.config);
        this.nts.run();
      }
    }

    if (this.config.relay) {
      if (this.config.cluster) {
        Logger.log('NodeRelayServer does not work in cluster mode');
      } else {
        this.nls = new NodeRelayServer(this.config);
        this.nls.run();
      }
    }

    process.on('uncaughtException', function (err) {
      Logger.error('uncaughtException', err);
    });

    Https.get("https://registry.npmjs.org/node-media-server", function (res) {
      let size = 0;
      let chunks = [];
      res.on('data', function (chunk) {
        size += chunk.length;
        chunks.push(chunk);
      });
      res.on('end', function () {
        let data = Buffer.concat(chunks, size);
        let jsonData = JSON.parse(data.toString());
        let latestVersion = jsonData['dist-tags']['latest'];
        let latestVersionNum = latestVersion.split('.')[0] << 16 | latestVersion.split('.')[1] << 8 | latestVersion.split('.')[2] & 0xff;
        let thisVersionNum = Package.version.split('.')[0] << 16 | Package.version.split('.')[1] << 8 | Package.version.split('.')[2] & 0xff
        if (thisVersionNum < latestVersionNum) {
          Logger.log(`There is a new version ${latestVersion} that can be updated`);
        }
      });
    }).on('error', function (e) {
    });
  }

  on(eventName, listener) {
    context.nodeEvent.on(eventName, listener);
  }

  stop() {
    if (this.nrs) {
      this.nrs.stop();
    }
    if (this.nhs) {
      this.nhs.stop();
    }
    if (this.nls) {
      this.nls.stop();
    }
    if (this.nis) {
      this.nis.stop();
    }
  }

  getSession(id) {
    return context.sessions.get(id);
  }
}

module.exports = NodeMediaServer<commit_msg>Removed node_media_server.js 'nis' Lint<commit_after>//
//  Created by Mingliang Chen on 17/8/1.
//  illuspas[a]gmail.com
//  Copyright (c) 2018 Nodemedia. All rights reserved.
//

const Https = require('https');
const Logger = require('./node_core_logger');
const NodeRtmpServer = require('./node_rtmp_server');
const NodeHttpServer = require('./node_http_server');
const NodeTransServer = require('./node_trans_server');
const NodeRelayServer = require('./node_relay_server');
const context = require('./node_core_ctx');
const Package = require("./package.json");

class NodeMediaServer {
  constructor(config) {
    this.config = config;
  }

  run() {
    Logger.setLogType(this.config.logType);
    Logger.log(`Node Media Server v${Package.version}`);
    if (this.config.rtmp) {
      this.nrs = new NodeRtmpServer(this.config);
      this.nrs.run();
    }

    if (this.config.http) {
      this.nhs = new NodeHttpServer(this.config);
      this.nhs.run();
    }

    if (this.config.trans) {
      if (this.config.cluster) {
        Logger.log('NodeTransServer does not work in cluster mode');
      } else {
        this.nts = new NodeTransServer(this.config);
        this.nts.run();
      }
    }

    if (this.config.relay) {
      if (this.config.cluster) {
        Logger.log('NodeRelayServer does not work in cluster mode');
      } else {
        this.nls = new NodeRelayServer(this.config);
        this.nls.run();
      }
    }

    process.on('uncaughtException', function (err) {
      Logger.error('uncaughtException', err);
    });

    Https.get("https://registry.npmjs.org/node-media-server", function (res) {
      let size = 0;
      let chunks = [];
      res.on('data', function (chunk) {
        size += chunk.length;
        chunks.push(chunk);
      });
      res.on('end', function () {
        let data = Buffer.concat(chunks, size);
        let jsonData = JSON.parse(data.toString());
        let latestVersion = jsonData['dist-tags']['latest'];
        let latestVersionNum = latestVersion.split('.')[0] << 16 | latestVersion.split('.')[1] << 8 | latestVersion.split('.')[2] & 0xff;
        let thisVersionNum = Package.version.split('.')[0] << 16 | Package.version.split('.')[1] << 8 | Package.version.split('.')[2] & 0xff
        if (thisVersionNum < latestVersionNum) {
          Logger.log(`There is a new version ${latestVersion} that can be updated`);
        }
      });
    }).on('error', function (e) {
    });
  }

  on(eventName, listener) {
    context.nodeEvent.on(eventName, listener);
  }

  stop() {
    if (this.nrs) {
      this.nrs.stop();
    }
    if (this.nhs) {
      this.nhs.stop();
    }
    if (this.nls) {
      this.nls.stop();
    }
  }

  getSession(id) {
    return context.sessions.get(id);
  }
}

module.exports = NodeMediaServer<|endoftext|>


<commit_before>import React from 'react';

import { Bonebasher , Gebuz, Khazak } from 'MAINTAINERS';
import Wrapper from 'common/Wrapper';
import ITEMS from 'common/ITEMS';
import ItemLink from 'common/ItemLink';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';

export default [
    {
      date: new Date('2018-01-30'),
      changes: <Wrapper>Added stats for <SpellLink id={SPELLS.FROST_DEATH_KNIGHT_T21_2SET_BONUS.id} icon /> and <SpellLink id={SPELLS.FROST_DEATH_KNIGHT_T21_4SET_BONUS.id} icon /> </Wrapper>,
      contributors: [Khazak],
    },
    {
      date: new Date('2018-01-29'),
      changes: 'Added overcapped Runes',
      contributors: [Gebuz],
    },
    {
      date: new Date('2017-11-07'),
      changes: <Wrapper>Added <SpellLink id={SPELLS.BREATH_OF_SINDRAGOSA_TALENT.id} icon /> and <SpellLink id={SPELLS.INEXORABLE_ASSAULT_TALENT.id} icon /> talent support; changed extra info.</Wrapper>,
      contributors: [Bonebasher],
    },
    {
      date: new Date('2017-11-02'),
      changes: <Wrapper>Artifact ability cooldown changed, <ItemLink id={ITEMS.COLD_HEART.id} icon /> added, Added folder for shared coding between specs.</Wrapper>,
      contributors: [Bonebasher],
    },
    {
      date: new Date('2017-11-01'),
      changes: 'Feedback implemented.',
      contributors: [Bonebasher],
    },
    {
      date: new Date('2017-10-31'),
      changes: 'Added initial Frost support.',
      contributors: [Bonebasher],
    },
];<commit_msg>update changelog<commit_after>import React from 'react';

import { Bonebasher , Gebuz, Khazak } from 'MAINTAINERS';
import Wrapper from 'common/Wrapper';
import ITEMS from 'common/ITEMS';
import ItemLink from 'common/ItemLink';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';

export default [
    {
      date: new Date('2018-02-11'),
      changes: <Wrapper>Added stat box for <SpellLink id={SPELLS.GATHERING_STORM_TALENT.id} icon /></Wrapper>,
      contributors: [Khazak],
    },
    {
      date: new Date('2018-01-30'),
      changes: <Wrapper>Added stats for <SpellLink id={SPELLS.FROST_DEATH_KNIGHT_T21_2SET_BONUS.id} icon /> and <SpellLink id={SPELLS.FROST_DEATH_KNIGHT_T21_4SET_BONUS.id} icon /> </Wrapper>,
      contributors: [Khazak],
    },
    {
      date: new Date('2018-01-29'),
      changes: 'Added overcapped Runes',
      contributors: [Gebuz],
    },
    {
      date: new Date('2017-11-07'),
      changes: <Wrapper>Added <SpellLink id={SPELLS.BREATH_OF_SINDRAGOSA_TALENT.id} icon /> and <SpellLink id={SPELLS.INEXORABLE_ASSAULT_TALENT.id} icon /> talent support; changed extra info.</Wrapper>,
      contributors: [Bonebasher],
    },
    {
      date: new Date('2017-11-02'),
      changes: <Wrapper>Artifact ability cooldown changed, <ItemLink id={ITEMS.COLD_HEART.id} icon /> added, Added folder for shared coding between specs.</Wrapper>,
      contributors: [Bonebasher],
    },
    {
      date: new Date('2017-11-01'),
      changes: 'Feedback implemented.',
      contributors: [Bonebasher],
    },
    {
      date: new Date('2017-10-31'),
      changes: 'Added initial Frost support.',
      contributors: [Bonebasher],
    },
];<|endoftext|>


<commit_before>var codeMirror = brackets.getModule("thirdparty/CodeMirror2/lib/codemirror");

codeMirror.defineMode("rpm-spec", function() {
  var arch = /^(i386|i586|i686|x86_64|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/;

  var preamble = /^[a-zA-Z0-9()]+:/;
  var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preinstall|preun|postinstall|postun|pretrans|posttrans|pre|post|triggerin|triggerun|verifyscript|check|triggerpostun|triggerprein|trigger)/;
  var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros
  var control_flow_simple = /^%(else|endif)/; // rpm control flow macros
  var operators = /^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/; // operators in control flow macros

  return {
    startState: function () {
        return {
          controlFlow: false,
          macroParameters: false,
          section: false
        };
    },
    token: function (stream, state) {
      var ch = stream.peek();
      if (ch == "#") { stream.skipToEnd(); return "comment"; }

      if (stream.sol()) {
        if (stream.match(preamble)) { return "header"; }
        if (stream.match(section)) { return "atom"; }
      }

      if (stream.match(/^\$\w+/)) { return "def"; } // Variables like '$RPM_BUILD_ROOT'
      if (stream.match(/^\$\{\w+\}/)) { return "def"; } // Variables like '${RPM_BUILD_ROOT}'

      if (stream.match(control_flow_simple)) { return "keyword"; }
      if (stream.match(control_flow_complex)) {
        state.controlFlow = true;
        return "keyword";
      }

      if (state.controlFlow) {
        if (stream.match(operators)) { return "operator"; }
        if (stream.match(/^(\d+)/)) { return "number"; }
        if (stream.eol()) { state.controlFlow = false; }
      }

      if (stream.match(arch)) {
        if (stream.eol()) { state.controlFlow = false; }
        return "number";
      }

      // Macros like '%make_install' or '%attr(0775,root,root)'
      if (stream.match(/^%[\w]+/)) {
        if (stream.match(/^\(/)) { state.macroParameters = true; }
        return "keyword";
      }
      if (state.macroParameters) {
        if (stream.match(/^\d+/)) { return "number";}
        if (stream.match(/^\)/)) {
          state.macroParameters = false;
          return "keyword";
        }
      }
      if (stream.match(/^%\{\??[\w \-\:\!]+\}/)) {
        if (stream.eol()) { state.controlFlow = false; }
        return "def";
      } // Macros like '%{defined fedora}'

      //TODO: Include bash script sub-parser (CodeMirror supports that)
      stream.next();
      return null;
    }
  };
});

codeMirror.defineMIME("text/x-rpm-spec", "rpm-spec");
<commit_msg>Add pp64le to architectures.<commit_after>var codeMirror = brackets.getModule("thirdparty/CodeMirror2/lib/codemirror");

codeMirror.defineMode("rpm-spec", function() {
  var arch = /^(i386|i586|i686|x86_64|ppc64le|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/;

  var preamble = /^[a-zA-Z0-9()]+:/;
  var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preinstall|preun|postinstall|postun|pretrans|posttrans|pre|post|triggerin|triggerun|verifyscript|check|triggerpostun|triggerprein|trigger)/;
  var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros
  var control_flow_simple = /^%(else|endif)/; // rpm control flow macros
  var operators = /^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/; // operators in control flow macros

  return {
    startState: function () {
        return {
          controlFlow: false,
          macroParameters: false,
          section: false
        };
    },
    token: function (stream, state) {
      var ch = stream.peek();
      if (ch == "#") { stream.skipToEnd(); return "comment"; }

      if (stream.sol()) {
        if (stream.match(preamble)) { return "header"; }
        if (stream.match(section)) { return "atom"; }
      }

      if (stream.match(/^\$\w+/)) { return "def"; } // Variables like '$RPM_BUILD_ROOT'
      if (stream.match(/^\$\{\w+\}/)) { return "def"; } // Variables like '${RPM_BUILD_ROOT}'

      if (stream.match(control_flow_simple)) { return "keyword"; }
      if (stream.match(control_flow_complex)) {
        state.controlFlow = true;
        return "keyword";
      }

      if (state.controlFlow) {
        if (stream.match(operators)) { return "operator"; }
        if (stream.match(/^(\d+)/)) { return "number"; }
        if (stream.eol()) { state.controlFlow = false; }
      }

      if (stream.match(arch)) {
        if (stream.eol()) { state.controlFlow = false; }
        return "number";
      }

      // Macros like '%make_install' or '%attr(0775,root,root)'
      if (stream.match(/^%[\w]+/)) {
        if (stream.match(/^\(/)) { state.macroParameters = true; }
        return "keyword";
      }
      if (state.macroParameters) {
        if (stream.match(/^\d+/)) { return "number";}
        if (stream.match(/^\)/)) {
          state.macroParameters = false;
          return "keyword";
        }
      }
      if (stream.match(/^%\{\??[\w \-\:\!]+\}/)) {
        if (stream.eol()) { state.controlFlow = false; }
        return "def";
      } // Macros like '%{defined fedora}'

      //TODO: Include bash script sub-parser (CodeMirror supports that)
      stream.next();
      return null;
    }
  };
});

codeMirror.defineMIME("text/x-rpm-spec", "rpm-spec");
<|endoftext|>


<commit_before>/*global
 define, console
 */
/*jslint
 browser: true,
 white: true
 */
define([
    'bluebird',
    'kb_common_html',
    'kb_common_widgetSet'
],
    function (Promise, html, widgetSetFactory) {
        'use strict';

//        function renderTypePanel(params) {
//            return new Promise(function (resolve) {
//
//                // Widgets
//                // Widgets are an array of functions or promises which are
//                // invoked later...
//                var widgetSet = wigetSet.make({
//                    runtime: runtime
//                })
//
//                // Render panel
//                var div = html.tag('div');
//                var panel = div({class: 'kbase-view kbase-spec-view container-fluid', 'data-kbase-view': 'spec'}, [
//                    div({class: 'row'}, [
//                        div({class: 'col-sm-12'}, [
//                            //div({id: addJQWidget('cardlayoutmanager', 'KBaseCardLayoutManager')}),
//                            div({id: widgets.addFactoryWidget('datatypespec', DataTypeSpecWidget)})
//                        ])
//                    ])
//                ]);
//                resolve({
//                    title: 'Data Type Specification',
//                    content: panel,
//                    widgets: widgets.getWidgets()
//                });
//            });
//        }

        function widget(config) {
            var mount, container,
                runtime = config.runtime,
                widgetSet = widgetSetFactory.make({
                    runtime: runtime
                }),
                content;

             function renderTypePanel() {
                var div = html.tag('div');
                return div({class: 'kbase-view kbase-spec-view container-fluid', dataKbaseView: 'spec'}, [
                    div({class: 'row'}, [
                        div({class: 'col-sm-12'}, [
                            //div({id: addJQWidget('cardlayoutmanager', 'KBaseCardLayoutManager')}),
                            div({id: widgetSet.addWidget('kb_typeview_dataTypeSpec')})
                        ])
                    ])
                ]);
            }

            // API
            function init(config) {
                return Promise.try(function () {
                    content = renderTypePanel();
                    return widgetSet.init(config);
                });
            }
            function attach(node) {
                return Promise.try(function () {
                    mount = node;
                    container = document.createElement('div');
                    mount.appendChild(container);
                    container.innerHTML = content;
                    return widgetSet.attach(container);
                });
            }
            function start(params) {
                return Promise.try(function () {
                    runtime.send('ui', 'setTitle', rendered.title);
                    return widgetSet.start(params);
                });
            }
            function stop() {
                return Promise.try(function () {
                    return widgetSet.stop();
                });
            }
            function detach() {
                return Promise.try(function () {
                    return widgetSet.detach();
                });
            }
            function destroy() {
                return Promise.try(function () {
                    return widgetSet.destroy();
                });
            }

            return {
                init: init,
                attach: attach,
                start: start,
                stop: stop,
                detach: detach,
                destroy: destroy
            };
        }

        return {
            make: function (config) {
                return widget(config);
            }
        };
    });<commit_msg>more fixes<commit_after>/*global
 define, console
 */
/*jslint
 browser: true,
 white: true
 */
define([
    'bluebird',
    'kb_common_html',
    'kb_common_widgetSet'
],
    function (Promise, html, widgetSetFactory) {
        'use strict';

//        function renderTypePanel(params) {
//            return new Promise(function (resolve) {
//
//                // Widgets
//                // Widgets are an array of functions or promises which are
//                // invoked later...
//                var widgetSet = wigetSet.make({
//                    runtime: runtime
//                })
//
//                // Render panel
//                var div = html.tag('div');
//                var panel = div({class: 'kbase-view kbase-spec-view container-fluid', 'data-kbase-view': 'spec'}, [
//                    div({class: 'row'}, [
//                        div({class: 'col-sm-12'}, [
//                            //div({id: addJQWidget('cardlayoutmanager', 'KBaseCardLayoutManager')}),
//                            div({id: widgets.addFactoryWidget('datatypespec', DataTypeSpecWidget)})
//                        ])
//                    ])
//                ]);
//                resolve({
//                    title: 'Data Type Specification',
//                    content: panel,
//                    widgets: widgets.getWidgets()
//                });
//            });
//        }

        function widget(config) {
            var mount, container,
                runtime = config.runtime,
                widgetSet = widgetSetFactory.make({
                    runtime: runtime
                }),
                content;

             function renderTypePanel() {
                var div = html.tag('div');
                return div({class: 'kbase-view kbase-spec-view container-fluid', dataKbaseView: 'spec'}, [
                    div({class: 'row'}, [
                        div({class: 'col-sm-12'}, [
                            //div({id: addJQWidget('cardlayoutmanager', 'KBaseCardLayoutManager')}),
                            div({id: widgetSet.addWidget('kb_typeview_dataTypeSpec')})
                        ])
                    ])
                ]);
            }

            // API
            function init(config) {
                return Promise.try(function () {
                    content = renderTypePanel();
                    return widgetSet.init(config);
                });
            }
            function attach(node) {
                return Promise.try(function () {
                    mount = node;
                    container = document.createElement('div');
                    mount.appendChild(container);
                    container.innerHTML = content;
                    return widgetSet.attach(container);
                });
            }
            function start(params) {
                return Promise.try(function () {
                    runtime.send('ui', 'setTitle', 'Type View Specifcation');
                    return widgetSet.start(params);
                });
            }
            function stop() {
                return Promise.try(function () {
                    return widgetSet.stop();
                });
            }
            function detach() {
                return Promise.try(function () {
                    return widgetSet.detach();
                });
            }
            function destroy() {
                return Promise.try(function () {
                    return widgetSet.destroy();
                });
            }

            return {
                init: init,
                attach: attach,
                start: start,
                stop: stop,
                detach: detach,
                destroy: destroy
            };
        }

        return {
            make: function (config) {
                return widget(config);
            }
        };
    });<|endoftext|>


<commit_before><commit_msg>bugfix autoSwitchSocketNode still..<commit_after><|endoftext|>


<commit_before>import React from 'react';
import { Card } from 'bm-kit';
import './_pillar.schedule.source.scss';

const friday = [
  {
    start: '6:00 PM',
    name: '📋 Check in begins'
  },
  {
    start: '8:00 PM',
    name: '🎤 Opening Ceremonies'
  },
  {
    start: '9:00 PM',
    name: '🤝 Team assembly'
  },
  {
    start: '9:30 PM',
    name: '🌮 Dinner'
  },
  {
    start: '10:00 PM',
    name: '💻 Hacking Begins'
  },
  {
    start: '10:00 PM',
    name: '🤖 Fundamentals of AI with Intel'
  },
  {
    start: '11:00 PM',
    name: '⛷ Activity'
  },
  {
    start: '12:00 AM',
    name: '🥋 Ninja'
  }
];

let saturday = [
  {
    start: '3:00 AM',
    name: '🍿 Late Night Snack'
  },
  {
    start: '8:00 AM',
    name: '🥓 Breakfast'
  },
  {
    start: '9:00 AM',
    name: '🏗 Workshop'
  },
  {
    start: '12:30 PM',
    name: '🍝 Lunch'
  },
  {
    start: '1:00 PM',
    name: '👪 Facebook Tech Talk'
  },
  {
    start: '3:00 PM',
    name: '🍿 Snack'
  },
  {
    start: '3:00 PM',
    name: '🚣🏽 Activity'
  },
  {
    start: '4:00 PM',
    name: '📈 Startups with T.A. MaCann'
  },
  {
    start: '6:00 PM',
    name: '🍕 Dinner'
  },
  {
    start: '9:00 PM',
    name: '🥤 Cup stacking with MLH'
  },
  {
    start: '10:00 PM',
    name: '🍩 Donuts!'
  }
];

let sunday = [
  {
    start: '1:00 AM',
    name: '🍿 Late Night Snack'
  },
  {
    start: '8:00 AM',
    name: '🍳 Breakfast'
  },
  {
    start: '9:30 AM',
    name: '🛑 Hacking Ends'
  },
  {
    start: '10:00 AM',
    name: '📔 Expo Begins'
  },
  {
    start: '11:30 AM',
    name: '🍞 Lunch'
  },
  {
    start: '1:00 PM',
    name: '🎭 Closing Ceremonies'
  },
  {
    start: '2:30 PM',
    name: '🚌 Buses Depart'
  }
];

const ScheduleDay = ({ dayData, title }) => (
  <Card className="p-schedule__day">

{title}

    {dayData.map(item => (

          {item.start}
          {item.name}

{item.info}

    ))}
  </Card>
);

const Schedule = ({ small }) => (

    {small ?
Schedule
 :
Schedule
}

      <ScheduleDay dayData={friday} title="Friday (10/19)" />
      <ScheduleDay dayData={saturday} title="Saturday (10/20)" />
      <ScheduleDay dayData={sunday} title="Sunday (10/21)" />

);

export default Schedule;
<commit_msg>Schedule Update (#159)<commit_after>import React from 'react';
import { Card } from 'bm-kit';
import './_pillar.schedule.source.scss';

const friday = [
  {
    start: '6:00 PM',
    name: '📋 Check in begins'
  },
  {
    start: '8:00 PM',
    name: '🎤 Opening Ceremonies'
  },
  {
    start: '9:00 PM',
    name: '🤝 Team assembly'
  },
  {
    start: '9:30 PM',
    name: '🌮 Dinner'
  },
  {
    start: '10:00 PM',
    name: '💻 Hacking Begins'
  },
  {
    start: '10:00 PM',
    name: '🤖 Fundamentals of AI with Intel'
  },
  {
    start: '11:00 PM',
    name: '⛷ Activity'
  },
  {
    start: '12:00 AM',
    name: '🥋 Ninja'
  }
];

let saturday = [
  {
    start: '3:00 AM',
    name: '🍿 Late Night Snack'
  },
  {
    start: '8:00 AM',
    name: '🥓 Breakfast'
  },
  {
    start: '9:00 AM',
    name: '🏗 Workshop'
  },
  {
    start: '12:30 PM',
    name: '🍝 Lunch'
  },
  {
    start: '1:00 PM',
    name: '👪 Facebook Tech Talk'
  },
  {
    start: '3:00 PM',
    name: '🍿 Snack'
  },
  {
    start: '3:00 PM',
    name: '🚣🏽 Activity'
  },
  {
    start: '4:00 PM',
    name: '📈 Startups with T.A. MaCann'
  },
  {
    start: '6:00 PM',
    name: '🍕 Dinner'
  },
  {
    start: '9:00 PM',
    name: '🥤 Cup stacking with MLH'
  },
  {
    start: '10:00 PM',
    name: '🍩 Donuts and Kona Ice'
  }
];

let sunday = [
  {
    start: '1:00 AM',
    name: '🍿 Late Night Snack'
  },
  {
    start: '8:00 AM',
    name: '🍳 Breakfast'
  },
  {
    start: '9:30 AM',
    name: '🛑 Hacking Ends'
  },
  {
    start: '10:00 AM',
    name: '📔 Expo Begins'
  },
  {
    start: '11:30 AM',
    name: '🍞 Lunch'
  },
  {
    start: '1:00 PM',
    name: '🎭 Closing Ceremonies'
  },
  {
    start: '2:30 PM',
    name: '🚌 Buses Depart'
  }
];

const ScheduleDay = ({ dayData, title }) => (
  <Card className="p-schedule__day">

{title}

    {dayData.map(item => (

          {item.start}
          {item.name}

{item.info}

    ))}
  </Card>
);

const Schedule = ({ small }) => (

    {small ?
Schedule
 :
Schedule
}

      <ScheduleDay dayData={friday} title="Friday (10/19)" />
      <ScheduleDay dayData={saturday} title="Saturday (10/20)" />
      <ScheduleDay dayData={sunday} title="Sunday (10/21)" />

);

export default Schedule;
<|endoftext|>


<commit_before>/*##################################################|*/
/* #CMS# */

// ensuring django namespace is set correctly
window.django = window.django || undefined;

// ensuring jQuery namespace is set correctly
window.jQuery = (django && django.jQuery) ? django.jQuery : window.jQuery || undefined;

// ensuring Class namespace is set correctly
window.Class = window.Class || undefined;

// ensuring CMS namespace is set correctly
var CMS = {
	'$': (jQuery) ? jQuery.noConflict() : undefined,
	'Class': (Class) ? Class.noConflict() : undefined,
	'API': {}
};

/*##################################################|*/
/* #CMS.API# */
(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {
	/*!
	 * CNS.API.Helpers
	 * Multiple helpers used accross all CMS features
	 */
	CMS.API.Helpers = {

		// redirects to a specific url or reloads browser
		reloadBrowser: function (url, timeout, ajax) {
			var that = this;
			// is there a parent window?
			var parent = (window.parent) ? window.parent : window;

			// if there is an ajax reload, prioritize
			if(ajax) {
				parent.CMS.API.locked = true;
				// check if the url has changed, if true redirect to the new path
				// this requires an ajax request
				$.ajax({
					'async': false,
					'type': 'GET',
					'url': parent.CMS.config.request.url,
					'data': {
						'model': parent.CMS.config.request.model,
						'pk': parent.CMS.config.request.pk
					},
					'success': function (response) {
						parent.CMS.API.locked = false;

						if(response === '' && !url) {
							// cancel if response is empty
							return false;
						} else if(parent.location.pathname !== response) {
							// api call to the backend to check if the current path is still the same
							that.reloadBrowser(response);
						} else if(url === 'REFRESH_PAGE') {
							// if on_close provides REFRESH_PAGE, only do a reload
							that.reloadBrowser();
						} else if(url) {
							// on_close can also provide a url, reload to the new destination
							that.reloadBrowser(url);
						}
					}
				});

				// cancel further operations
				return false;
			}

			// add timeout if provided
			parent.setTimeout(function () {
				(url) ? parent.location.href = url : parent.location.reload();
			}, timeout || 0);
		},

		// disable multiple form submissions
		preventSubmit: function () {
			var forms = $('#cms_toolbar').find('form');
				forms.submit(function () {
					// show loader
					CMS.API.Toolbar._loader(true);
					// we cannot use disabled as the name action will be ignored
					$('input[type="submit"]').bind('click', function (e) {
						e.preventDefault();
					}).css('opacity', 0.5);
				});
		},

		// fixes csrf behaviour
		csrf: function (csrf_token) {
			$.ajaxSetup({
				beforeSend: function (xhr) {
					// set csrf_token
					xhr.setRequestHeader("X-CSRFToken", csrf_token);
				}
			});
		},

		// handles the tooltip for the plugins
		showTooltip: function (name, id) {
			var tooltip = $('.cms_tooltip');

			// change css and attributes
			tooltip.css('visibility', 'visible')
				.data('plugin_id', id || null)
				.show()
				.find('span').html(name);

			// attaches move event
			// this sets the correct position for the edit tooltip
			$('body').bind('mousemove.cms', function (e) {
				// so lets figure out where we are
				var offset = 20;
				var bound = $(document).width();
				var pos = e.pageX + tooltip.outerWidth(true) + offset;

				tooltip.css({
					'left': (pos >= bound) ? e.pageX - tooltip.outerWidth(true) - offset : e.pageX + offset,
					'top': e.pageY - 12
				});
			});

			// attach tooltip event for touch devices
			tooltip.bind('touchstart.cms', function () {
				$('.cms_plugin-' + $(this).data('plugin_id')).trigger('dblclick');
			});
		},

		hideTooltip: function () {
			var tooltip = $('.cms_tooltip');

			// change css
			tooltip.css('visibility', 'hidden').hide();

			// unbind events
			$('body').unbind('mousemove.cms');
			tooltip.unbind('touchstart.cms');
		},

		// sends or retrieves a JSON from localStorage or the session if local storage is not available
		setSettings: function (settings) {
			var that = this;
			// merge settings
			settings = JSON.stringify($.extend({}, CMS.config.settings, settings));
			// set loader
			if(CMS.API.Toolbar) CMS.API.Toolbar._loader(true);

			// use local storage or session
			if(window.localStorage) {
				// save within local storage
				localStorage.setItem('cms_cookie', settings);
				if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
			} else {
				// save within session
				CMS.API.locked = true;

				$.ajax({
					'async': false,
					'type': 'POST',
					'url': CMS.config.urls.settings,
					'data': {
						'csrfmiddlewaretoken': this.config.csrf,
						'settings': settings
					},
					'success': function (data) {
						CMS.API.locked = false;
						// determine if logged in or not
						settings = (data) ? JSON.parse(data) : CMS.config.settings;
						if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
					},
					'error': function (jqXHR) {
						that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
					}
				});
			}

			// save settings
			CMS.settings = JSON.parse(settings);

			// ensure new settings are returned
			return CMS.settings;
		},

		getSettings: function () {
			var that = this;
			var settings;
			// set loader
			if(CMS.API.Toolbar) CMS.API.Toolbar._loader(true);

			// use local storage or session
			if(window.localStorage) {
				// get from local storage
				settings = JSON.parse(localStorage.getItem('cms_cookie'));
				if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
			} else {
				CMS.API.locked = true;
				// get from session
				$.ajax({
					'async': false,
					'type': 'GET',
					'url': CMS.config.urls.settings,
					'success': function (data) {
						CMS.API.locked = false;
						// determine if logged in or not
						settings = (data) ? JSON.parse(data) : CMS.config.settings;
						if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
					},
					'error': function (jqXHR) {
						that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
					}
				});
			}

			if(settings === null) settings = this.setSettings(CMS.config.settings);

			// save settings
			CMS.settings = settings;

			// ensure new settings are returned
			return CMS.settings;
		},

		// prevents scrolling when another scrollbar is used (for better ux)
		preventScroll: function (disable) {
			// TODO: currently disabled
/*
			// cancel if scrollbar is not visible
			if($(document).height() <= $(window).height()) return false;

			var scrollTop = $(window).scrollTop();
			var html = $('html');

			if(disable) {
				html.addClass('cms_toolbar-noscroll').css('top',-scrollTop).data('scroll', scrollTop);
			} else {
				html.removeClass('cms_toolbar-noscroll');
				$(window).scrollTop(html.data('scroll'));
			}
*/
		}

	};

	// autoinits
	CMS.API.Helpers.preventSubmit();

});
})(CMS.$);<commit_msg>fix for issue #3413<commit_after>/*##################################################|*/
/* #CMS# */

// ensuring django namespace is set correctly
window.django = window.django || undefined;

// ensuring jQuery namespace is set correctly
window.jQuery = (django && django.jQuery) ? django.jQuery : window.jQuery || undefined;

// ensuring Class namespace is set correctly
window.Class = window.Class || undefined;

// ensuring CMS namespace is set correctly
var CMS = {
	'$': (jQuery) ? jQuery.noConflict() : undefined,
	'Class': (Class) ? Class.noConflict() : undefined,
	'API': {}
};

/*##################################################|*/
/* #CMS.API# */
(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {
	/*!
	 * CNS.API.Helpers
	 * Multiple helpers used accross all CMS features
	 */
	CMS.API.Helpers = {

		// redirects to a specific url or reloads browser
		reloadBrowser: function (url, timeout, ajax) {
			var that = this;
			// is there a parent window?
			var parent = (window.parent) ? window.parent : window;

			// if there is an ajax reload, prioritize
			if(ajax) {
				parent.CMS.API.locked = true;
				// check if the url has changed, if true redirect to the new path
				// this requires an ajax request
				$.ajax({
					'async': false,
					'type': 'GET',
					'url': parent.CMS.config.request.url,
					'data': {
						'model': parent.CMS.config.request.model,
						'pk': parent.CMS.config.request.pk
					},
					'success': function (response) {
						parent.CMS.API.locked = false;

						if(response === '' && !url) {
							// cancel if response is empty
							return false;
						} else if(parent.location.pathname !== response) {
							// api call to the backend to check if the current path is still the same
							that.reloadBrowser(response);
						} else if(url === 'REFRESH_PAGE') {
							// if on_close provides REFRESH_PAGE, only do a reload
							that.reloadBrowser();
						} else if(url) {
							// on_close can also provide a url, reload to the new destination
							that.reloadBrowser(url);
						}
					}
				});

				// cancel further operations
				return false;
			}

			// add timeout if provided
			parent.setTimeout(function () {
				if (url) { parent.location.href = url; }
				// ensure page is always reloaded #3413
				parent.location.reload()
			}, timeout || 0);
		},

		// disable multiple form submissions
		preventSubmit: function () {
			var forms = $('#cms_toolbar').find('form');
				forms.submit(function () {
					// show loader
					CMS.API.Toolbar._loader(true);
					// we cannot use disabled as the name action will be ignored
					$('input[type="submit"]').bind('click', function (e) {
						e.preventDefault();
					}).css('opacity', 0.5);
				});
		},

		// fixes csrf behaviour
		csrf: function (csrf_token) {
			$.ajaxSetup({
				beforeSend: function (xhr) {
					// set csrf_token
					xhr.setRequestHeader("X-CSRFToken", csrf_token);
				}
			});
		},

		// handles the tooltip for the plugins
		showTooltip: function (name, id) {
			var tooltip = $('.cms_tooltip');

			// change css and attributes
			tooltip.css('visibility', 'visible')
				.data('plugin_id', id || null)
				.show()
				.find('span').html(name);

			// attaches move event
			// this sets the correct position for the edit tooltip
			$('body').bind('mousemove.cms', function (e) {
				// so lets figure out where we are
				var offset = 20;
				var bound = $(document).width();
				var pos = e.pageX + tooltip.outerWidth(true) + offset;

				tooltip.css({
					'left': (pos >= bound) ? e.pageX - tooltip.outerWidth(true) - offset : e.pageX + offset,
					'top': e.pageY - 12
				});
			});

			// attach tooltip event for touch devices
			tooltip.bind('touchstart.cms', function () {
				$('.cms_plugin-' + $(this).data('plugin_id')).trigger('dblclick');
			});
		},

		hideTooltip: function () {
			var tooltip = $('.cms_tooltip');

			// change css
			tooltip.css('visibility', 'hidden').hide();

			// unbind events
			$('body').unbind('mousemove.cms');
			tooltip.unbind('touchstart.cms');
		},

		// sends or retrieves a JSON from localStorage or the session if local storage is not available
		setSettings: function (settings) {
			var that = this;
			// merge settings
			settings = JSON.stringify($.extend({}, CMS.config.settings, settings));
			// set loader
			if(CMS.API.Toolbar) CMS.API.Toolbar._loader(true);

			// use local storage or session
			if(window.localStorage) {
				// save within local storage
				localStorage.setItem('cms_cookie', settings);
				if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
			} else {
				// save within session
				CMS.API.locked = true;

				$.ajax({
					'async': false,
					'type': 'POST',
					'url': CMS.config.urls.settings,
					'data': {
						'csrfmiddlewaretoken': this.config.csrf,
						'settings': settings
					},
					'success': function (data) {
						CMS.API.locked = false;
						// determine if logged in or not
						settings = (data) ? JSON.parse(data) : CMS.config.settings;
						if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
					},
					'error': function (jqXHR) {
						that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
					}
				});
			}

			// save settings
			CMS.settings = JSON.parse(settings);

			// ensure new settings are returned
			return CMS.settings;
		},

		getSettings: function () {
			var that = this;
			var settings;
			// set loader
			if(CMS.API.Toolbar) CMS.API.Toolbar._loader(true);

			// use local storage or session
			if(window.localStorage) {
				// get from local storage
				settings = JSON.parse(localStorage.getItem('cms_cookie'));
				if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
			} else {
				CMS.API.locked = true;
				// get from session
				$.ajax({
					'async': false,
					'type': 'GET',
					'url': CMS.config.urls.settings,
					'success': function (data) {
						CMS.API.locked = false;
						// determine if logged in or not
						settings = (data) ? JSON.parse(data) : CMS.config.settings;
						if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
					},
					'error': function (jqXHR) {
						that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
					}
				});
			}

			if(settings === null) settings = this.setSettings(CMS.config.settings);

			// save settings
			CMS.settings = settings;

			// ensure new settings are returned
			return CMS.settings;
		},

		// prevents scrolling when another scrollbar is used (for better ux)
		preventScroll: function (disable) {
			// TODO: currently disabled
/*
			// cancel if scrollbar is not visible
			if($(document).height() <= $(window).height()) return false;

			var scrollTop = $(window).scrollTop();
			var html = $('html');

			if(disable) {
				html.addClass('cms_toolbar-noscroll').css('top',-scrollTop).data('scroll', scrollTop);
			} else {
				html.removeClass('cms_toolbar-noscroll');
				$(window).scrollTop(html.data('scroll'));
			}
*/
		}

	};

	// autoinits
	CMS.API.Helpers.preventSubmit();

});
})(CMS.$);<|endoftext|>


<commit_before>/*##################################################|*/
/* #CMS# */

// ensuring django namespace is set correctly
window.django = window.django || undefined;

// ensuring jQuery namespace is set correctly
window.jQuery = (django) ? django.jQuery : window.jQuery || undefined;

// ensuring Class namespace is set correctly
window.Class = window.Class || undefined;

// ensuring CMS namespace is set correctly
var CMS = {
	'$': (jQuery) ? jQuery.noConflict() : undefined,
	'Class': (Class) ? Class.noConflict() : undefined,
	'API': {}
};

/*##################################################|*/
/* #CMS.API# */
(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {
	/*!
	 * CNS.API.Helpers
	 * Multiple helpers used accross all CMS features
	 */
	CMS.API.Helpers = {

		// redirects to a specific url or reloads browser
		reloadBrowser: function (url, timeout, ajax) {
			var that = this;
			// is there a parent window?
			var parent = (window.parent) ? window.parent : window;

			// if there is an ajax reload, prioritize
			if(ajax) {
				parent.CMS.API.locked = true;
				// check if the url has changed, if true redirect to the new path
				// this requires an ajax request
				$.ajax({
					'async': false,
					'type': 'GET',
					'url': parent.CMS.config.request.url,
					'data': {
						'model': parent.CMS.config.request.model,
						'pk': parent.CMS.config.request.pk
					},
					'success': function (response) {
						parent.CMS.API.locked = false;

						if(response === '' && !url) {
							// cancel if response is empty
							return false;
						} else if(parent.location.pathname !== response) {
							// api call to the backend to check if the current path is still the same
							that.reloadBrowser(response);
						} else if(url === 'REFRESH_PAGE') {
							// if on_close provides REFRESH_PAGE, only do a reload
							that.reloadBrowser();
						} else if(url) {
							// on_close can also provide a url, reload to the new destination
							that.reloadBrowser(url);
						}
					}
				});

				// cancel further operations
				return false;
			}

			// add timeout if provided
			parent.setTimeout(function () {
				(url) ? parent.location.href = url : parent.location.reload();
			}, timeout || 0);
		},

		// disable multiple form submissions
		preventSubmit: function () {
			var forms = $('#cms_toolbar').find('form');
				forms.submit(function () {
					// show loader
					CMS.API.Toolbar._loader(true);
					// we cannot use disabled as the name action will be ignored
					$('input[type="submit"]').bind('click', function (e) {
						e.preventDefault();
					}).css('opacity', 0.5);
				});
		},

		// fixes csrf behaviour
		csrf: function (csrf_token) {
			$.ajaxSetup({
				beforeSend: function (xhr) {
					// set csrf_token
					xhr.setRequestHeader("X-CSRFToken", csrf_token);
				}
			});
		},

		// handles the tooltip for the plugins
		showTooltip: function (name, id) {
			var tooltip = $('.cms_tooltip');

			// change css and attributes
			tooltip.css('visibility', 'visible')
				.data('plugin_id', id || null)
				.show()
				.find('span').html(name);

			// attaches move event
			// this sets the correct position for the edit tooltip
			$('body').bind('mousemove.cms', function (e) {
				// so lets figure out where we are
				var offset = 20;
				var bound = $(document).width();
				var pos = e.pageX + tooltip.outerWidth(true) + offset;

				tooltip.css({
					'left': (pos >= bound) ? e.pageX - tooltip.outerWidth(true) - offset : e.pageX + offset,
					'top': e.pageY - 12
				});
			});

			// attach tooltip event for touch devices
			tooltip.bind('touchstart.cms', function () {
				$('#cms_plugin-' + $(this).data('plugin_id')).trigger('dblclick');
			});
		},

		hideTooltip: function () {
			var tooltip = $('.cms_tooltip');

			// change css
			tooltip.css('visibility', 'hidden').hide();

			// unbind events
			$('body').unbind('mousemove.cms');
			tooltip.unbind('touchstart.cms');
		},

		// sends or retrieves a JSON from localStorage or the session if local storage is not available
		setSettings: function (settings) {
			var that = this;
			// merge settings
			settings = JSON.stringify($.extend({}, CMS.config.settings, settings));
			// set loader
			if(CMS.API.Toolbar) CMS.API.Toolbar._loader(true);

			// use local storage or session
			if(window.localStorage) {
				// save within local storage
				localStorage.setItem('cms_cookie', settings);
				if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
			} else {
				// save within session
				CMS.API.locked = true;

				$.ajax({
					'async': false,
					'type': 'POST',
					'url': CMS.config.urls.settings,
					'data': {
						'csrfmiddlewaretoken': this.config.csrf,
						'settings': settings
					},
					'success': function (data) {
						CMS.API.locked = false;
						// determine if logged in or not
						settings = (data) ? JSON.parse(data) : CMS.config.settings;
						if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
					},
					'error': function (jqXHR) {
						that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
					}
				});
			}

			// save settings
			CMS.settings = JSON.parse(settings);

			// ensure new settings are returned
			return CMS.settings;
		},

		getSettings: function () {
			var that = this;
			var settings;
			// set loader
			if(CMS.API.Toolbar) CMS.API.Toolbar._loader(true);

			// use local storage or session
			if(window.localStorage) {
				// get from local storage
				settings = JSON.parse(localStorage.getItem('cms_cookie'));
				if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
			} else {
				CMS.API.locked = true;
				// get from session
				$.ajax({
					'async': false,
					'type': 'GET',
					'url': CMS.config.urls.settings,
					'success': function (data) {
						CMS.API.locked = false;
						// determine if logged in or not
						settings = (data) ? JSON.parse(data) : CMS.config.settings;
						if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
					},
					'error': function (jqXHR) {
						that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
					}
				});
			}

			if(settings === null) settings = this.setSettings(CMS.config.settings);

			// save settings
			CMS.settings = settings;

			// ensure new settings are returned
			return CMS.settings;
		},

		// prevents scrolling when another scrollbar is used (for better ux)
		preventScroll: function (disable) {
			// TODO: currently disabled
/*
			// cancel if scrollbar is not visible
			if($(document).height() <= $(window).height()) return false;

			var scrollTop = $(window).scrollTop();
			var html = $('html');

			if(disable) {
				html.addClass('cms_toolbar-noscroll').css('top',-scrollTop).data('scroll', scrollTop);
			} else {
				html.removeClass('cms_toolbar-noscroll');
				$(window).scrollTop(html.data('scroll'));
			}
*/
		}

	};

	// autoinits
	CMS.API.Helpers.preventSubmit();

});
})(CMS.$);<commit_msg>check for django.jQuery existence before using it<commit_after>/*##################################################|*/
/* #CMS# */

// ensuring django namespace is set correctly
window.django = window.django || undefined;

// ensuring jQuery namespace is set correctly
window.jQuery = (django && django.jQuery) ? django.jQuery : window.jQuery || undefined;

// ensuring Class namespace is set correctly
window.Class = window.Class || undefined;

// ensuring CMS namespace is set correctly
var CMS = {
	'$': (jQuery) ? jQuery.noConflict() : undefined,
	'Class': (Class) ? Class.noConflict() : undefined,
	'API': {}
};

/*##################################################|*/
/* #CMS.API# */
(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {
	/*!
	 * CNS.API.Helpers
	 * Multiple helpers used accross all CMS features
	 */
	CMS.API.Helpers = {

		// redirects to a specific url or reloads browser
		reloadBrowser: function (url, timeout, ajax) {
			var that = this;
			// is there a parent window?
			var parent = (window.parent) ? window.parent : window;

			// if there is an ajax reload, prioritize
			if(ajax) {
				parent.CMS.API.locked = true;
				// check if the url has changed, if true redirect to the new path
				// this requires an ajax request
				$.ajax({
					'async': false,
					'type': 'GET',
					'url': parent.CMS.config.request.url,
					'data': {
						'model': parent.CMS.config.request.model,
						'pk': parent.CMS.config.request.pk
					},
					'success': function (response) {
						parent.CMS.API.locked = false;

						if(response === '' && !url) {
							// cancel if response is empty
							return false;
						} else if(parent.location.pathname !== response) {
							// api call to the backend to check if the current path is still the same
							that.reloadBrowser(response);
						} else if(url === 'REFRESH_PAGE') {
							// if on_close provides REFRESH_PAGE, only do a reload
							that.reloadBrowser();
						} else if(url) {
							// on_close can also provide a url, reload to the new destination
							that.reloadBrowser(url);
						}
					}
				});

				// cancel further operations
				return false;
			}

			// add timeout if provided
			parent.setTimeout(function () {
				(url) ? parent.location.href = url : parent.location.reload();
			}, timeout || 0);
		},

		// disable multiple form submissions
		preventSubmit: function () {
			var forms = $('#cms_toolbar').find('form');
				forms.submit(function () {
					// show loader
					CMS.API.Toolbar._loader(true);
					// we cannot use disabled as the name action will be ignored
					$('input[type="submit"]').bind('click', function (e) {
						e.preventDefault();
					}).css('opacity', 0.5);
				});
		},

		// fixes csrf behaviour
		csrf: function (csrf_token) {
			$.ajaxSetup({
				beforeSend: function (xhr) {
					// set csrf_token
					xhr.setRequestHeader("X-CSRFToken", csrf_token);
				}
			});
		},

		// handles the tooltip for the plugins
		showTooltip: function (name, id) {
			var tooltip = $('.cms_tooltip');

			// change css and attributes
			tooltip.css('visibility', 'visible')
				.data('plugin_id', id || null)
				.show()
				.find('span').html(name);

			// attaches move event
			// this sets the correct position for the edit tooltip
			$('body').bind('mousemove.cms', function (e) {
				// so lets figure out where we are
				var offset = 20;
				var bound = $(document).width();
				var pos = e.pageX + tooltip.outerWidth(true) + offset;

				tooltip.css({
					'left': (pos >= bound) ? e.pageX - tooltip.outerWidth(true) - offset : e.pageX + offset,
					'top': e.pageY - 12
				});
			});

			// attach tooltip event for touch devices
			tooltip.bind('touchstart.cms', function () {
				$('#cms_plugin-' + $(this).data('plugin_id')).trigger('dblclick');
			});
		},

		hideTooltip: function () {
			var tooltip = $('.cms_tooltip');

			// change css
			tooltip.css('visibility', 'hidden').hide();

			// unbind events
			$('body').unbind('mousemove.cms');
			tooltip.unbind('touchstart.cms');
		},

		// sends or retrieves a JSON from localStorage or the session if local storage is not available
		setSettings: function (settings) {
			var that = this;
			// merge settings
			settings = JSON.stringify($.extend({}, CMS.config.settings, settings));
			// set loader
			if(CMS.API.Toolbar) CMS.API.Toolbar._loader(true);

			// use local storage or session
			if(window.localStorage) {
				// save within local storage
				localStorage.setItem('cms_cookie', settings);
				if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
			} else {
				// save within session
				CMS.API.locked = true;

				$.ajax({
					'async': false,
					'type': 'POST',
					'url': CMS.config.urls.settings,
					'data': {
						'csrfmiddlewaretoken': this.config.csrf,
						'settings': settings
					},
					'success': function (data) {
						CMS.API.locked = false;
						// determine if logged in or not
						settings = (data) ? JSON.parse(data) : CMS.config.settings;
						if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
					},
					'error': function (jqXHR) {
						that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
					}
				});
			}

			// save settings
			CMS.settings = JSON.parse(settings);

			// ensure new settings are returned
			return CMS.settings;
		},

		getSettings: function () {
			var that = this;
			var settings;
			// set loader
			if(CMS.API.Toolbar) CMS.API.Toolbar._loader(true);

			// use local storage or session
			if(window.localStorage) {
				// get from local storage
				settings = JSON.parse(localStorage.getItem('cms_cookie'));
				if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
			} else {
				CMS.API.locked = true;
				// get from session
				$.ajax({
					'async': false,
					'type': 'GET',
					'url': CMS.config.urls.settings,
					'success': function (data) {
						CMS.API.locked = false;
						// determine if logged in or not
						settings = (data) ? JSON.parse(data) : CMS.config.settings;
						if(CMS.API.Toolbar) CMS.API.Toolbar._loader(false);
					},
					'error': function (jqXHR) {
						that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
					}
				});
			}

			if(settings === null) settings = this.setSettings(CMS.config.settings);

			// save settings
			CMS.settings = settings;

			// ensure new settings are returned
			return CMS.settings;
		},

		// prevents scrolling when another scrollbar is used (for better ux)
		preventScroll: function (disable) {
			// TODO: currently disabled
/*
			// cancel if scrollbar is not visible
			if($(document).height() <= $(window).height()) return false;

			var scrollTop = $(window).scrollTop();
			var html = $('html');

			if(disable) {
				html.addClass('cms_toolbar-noscroll').css('top',-scrollTop).data('scroll', scrollTop);
			} else {
				html.removeClass('cms_toolbar-noscroll');
				$(window).scrollTop(html.data('scroll'));
			}
*/
		}

	};

	// autoinits
	CMS.API.Helpers.preventSubmit();

});
})(CMS.$);<|endoftext|>