<commit_before>
(function(){
//The idea of using Multiple canvases
	var d = document,
		canvas = d.body.appendChild( d.createElement( 'canvas' ) ),
		context = canvas.getContext( '2d' ),
		 time = 1,
		 w = 10,
		 h = 10,
		 cos = Math.cos,
		 sin = Math.sin,
		 PI = Math.PI;

	function resize() {
		canvas.width = w = innerWidth;
		canvas.height = h = innerHeight;
	}

	// Browser Size Response
	addEventListener( 'resize', resize, false );

	// Initial size
	resize();

	// The main animation loop
	setInterval( function() {
		context.clearRect( 0, 0, w, h );
		context.fillStyle = 'rgba(255, 102, 0,.5)';
		context.globalCompositeOperation = 'lighter';
		context.fillstyle = 'rgba(0, 255, 0, .5)';
		context.globalCompositeOperation = 'color-burn';
		time += .1;

		// The number of particles to generate
		i = 7500;

		while( i-- ) {
			// Where Math happens lol(Makes stuff go in circles)
			r = ( ( w + h ) * 0.4 ) * ( cos( ( time + i ) * ( .05 + ( ( sin(time*0.00030) / PI ) * .4 ) ) ) / PI );

			context.fillRect( sin(i) * r + (w/2),
							  cos(i) * r + (h/2),
							  4,
							  4 );
		}
	}, 32 );

    function keyControls(e) {
        switch(e.keyCode) {
            case 32:
                // spacebar pressed
                loader.directStream('toggle');
                break;
            case 37:
                // left key pressed
                loader.directStream('backward');
                break;
            case 39:
                // right key pressed
                loader.directStream('forward');
                break;
        }
    }

})()<commit_msg>SoundCloud Elements/Sphere Morphing<commit_after>var SoundCloudAudioSource = function(player) {
    var self = this;
    var analyser;
    var audioCtx = new (window.AudioContext || window.webkitAudioContext);
    analyser = audioCtx.createAnalyser();
    analyser.fftSize = 256;
    player.crossOrigin = "anonymous";
    var source = audioCtx.createMediaElementSource(player);
    source.connect(analyser);
    analyser.connect(audioCtx.destination);
    var sampleAudioStream = function() {
        analyser.getByteFrequencyData(self.streamData);
        // calculate an overall volume value
        var total = 0;
        for (var i = 0; i < 80; i++) { // get the volume from the first 80 bins, else it gets too loud with treble
            total += self.streamData[i];
        }
        self.volume = total;
    };
    setInterval(sampleAudioStream, 20);
    // public properties and methods
    this.volume = 0;
    this.streamData = new Uint8Array(128);
    this.playStream = function(streamUrl) {
        // get the input stream from the audio element
        player.addEventListener('ended', function(){
            self.directStream('coasting');
        });
        player.setAttribute('src', streamUrl);
        player.play();
    }
};
/**
 * The Visualizer object, after being instantiated, must be initialized with the init() method,
 * which takes an options object specifying the element to append the canvases to and the audiosource which will
 * provide the data to be visualized.
 */
var Visualizer = function() {
    var tileSize;
    var tiles = [];
    var stars = [];
    // canvas vars
    var fgCanvas;
    var fgCtx;
    var fgRotation = 0.001;
    var bgCanvas;
    var bgCtx;
    var sfCanvas;
    var sfCtx;
    var audioSource;

    function Polygon(sides, x, y, tileSize, ctx, num) {
        this.sides = sides;
        this.tileSize = tileSize;
        this.ctx = ctx;
        this.num = num; // the number of the tile, starting at 0
        this.high = 0; // the highest colour value, which then fades out
        this.decay = this.num > 42 ? 1.5 : 2; // increase this value to fade out faster.
        this.highlight = 0; // for highlighted stroke effect;
        // figure out the x and y coordinates of the center of the polygon based on the
        // 60 degree XY axis coordinates passed in
        var step = Math.round(Math.cos(Math.PI/6)*tileSize*2);
        this.y = Math.round(step * Math.sin(Math.PI/3) * -y  );
        this.x = Math.round(x * step + y * step/2 );

        // calculate the vertices of the polygon
        this.vertices = [];
        for (var i = 1; i <= this.sides;i += 1) {
            x = this.x + this.tileSize * Math.cos(i * 2 * Math.PI / this.sides + Math.PI/6);
            y = this.y + this.tileSize * Math.sin(i * 2 * Math.PI / this.sides + Math.PI/6);
            this.vertices.push([x, y]);
        }
    }
    Polygon.prototype.rotateVertices = function() {
        // rotate all the vertices to achieve the overall rotational effect
        var rotation = fgRotation;
        rotation -= audioSource.volume > 10000 ? Math.sin(audioSource.volume/800000) : 0;
        for (var i = 0; i <= this.sides-1;i += 1) {
            this.vertices[i][0] = this.vertices[i][0] -  this.vertices[i][1] * Math.sin(rotation);
            this.vertices[i][1] = this.vertices[i][1] +  this.vertices[i][0] * Math.sin(rotation);
        }
    };
    var minMental = 0, maxMental = 0;
    Polygon.prototype.calculateOffset = function(coords) {
        var angle = Math.atan(coords[1]/coords[0]);
        var distance = Math.sqrt(Math.pow(coords[0], 2) + Math.pow(coords[1], 2)); // a bit of pythagoras
        var mentalFactor = Math.min(Math.max((Math.tan(audioSource.volume/6000) * 0.5), -20), 2); // this factor makes the visualization go crazy wild

        var offsetFactor = Math.pow(distance/3, 2) * (audioSource.volume/2000000) * (Math.pow(this.high, 1.3)/300) * mentalFactor;
        var offsetX = Math.cos(angle) * offsetFactor;
        var offsetY = Math.sin(angle) * offsetFactor;
        offsetX *= (coords[0] < 0) ? -1 : 1;
        offsetY *= (coords[0] < 0) ? -1 : 1;
        return [offsetX, offsetY];
    };
    Polygon.prototype.drawPolygon = function() {
        var bucket = Math.ceil(audioSource.streamData.length/tiles.length*this.num);
        var val = Math.pow((audioSource.streamData[bucket]/255),2)*255;
        val *= this.num > 42 ? 1.1 : 1;
        // establish the value for this tile
        if (val > this.high) {
            this.high = val;
        } else {
            this.high -= this.decay;
            val = this.high;
        }

        // figure out what colour to fill it and then draw the polygon
        var r, g, b, a;
        if (val > 0) {
            this.ctx.beginPath();
            var offset = this.calculateOffset(this.vertices[0]);
            this.ctx.moveTo(this.vertices[0][0] + offset[0], this.vertices[0][1] + offset[1]);
            // draw the polygon
            for (var i = 1; i <= this.sides-1;i += 1) {
                offset = this.calculateOffset(this.vertices[i]);
                this.ctx.lineTo (this.vertices[i][0] + offset[0], this.vertices[i][1] + offset[1]);
            }
            this.ctx.closePath();

            if (val > 128) {
                r = (val-128)*2;
                g = ((Math.cos((2*val/128*Math.PI/2)- 4*Math.PI/3)+1)*128);
                b = (val-105)*3;
            }
            else if (val > 175) {
                r = (val-128)*2;
                g = 255;
                b = (val-105)*3;
            }
            else {
                r = ((Math.cos((2*val/128*Math.PI/2))+1)*128);
                g = ((Math.cos((2*val/128*Math.PI/2)- 4*Math.PI/3)+1)*128);
                b = ((Math.cos((2.4*val/128*Math.PI/2)- 2*Math.PI/3)+1)*128);
            }
            if (val > 210) {
                this.cubed = val; // add the cube effect if it's really loud
            }
            if (val > 120) {
                this.highlight = 100; // add the highlight effect if it's pretty loud
            }
            // set the alpha
            var e = 2.7182;
            a = (0.5/(1 + 40 * Math.pow(e, -val/8))) + (0.5/(1 + 40 * Math.pow(e, -val/20)));

            this.ctx.fillStyle = "rgba(" +
                Math.round(r) + ", " +
                Math.round(g) + ", " +
                Math.round(b) + ", " +
                a + ")";
            this.ctx.fill();
            // stroke
            if (val > 20) {
                var strokeVal = 20;
                this.ctx.strokeStyle =  "rgba(" + strokeVal + ", " + strokeVal + ", " + strokeVal + ", 0.5)";
                this.ctx.lineWidth = 1;
                this.ctx.stroke();
            }
        }
        // display the tile number for debug purposes
        /*this.ctx.font = "bold 12px sans-serif";
         this.ctx.fillStyle = 'grey';
         this.ctx.fillText(this.num, this.vertices[0][0], this.vertices[0][1]);*/
    };
    Polygon.prototype.drawHighlight = function() {
        this.ctx.beginPath();
        // draw the highlight
        var offset = this.calculateOffset(this.vertices[0]);
        this.ctx.moveTo(this.vertices[0][0] + offset[0], this.vertices[0][1] + offset[1]);
        // draw the polygon
        for (var i = 0; i <= this.sides-1;i += 1) {
            offset = this.calculateOffset(this.vertices[i]);
            this.ctx.lineTo (this.vertices[i][0] + offset[0], this.vertices[i][1] + offset[1]);
        }
        this.ctx.closePath();
        var a = this.highlight/100;
        this.ctx.strokeStyle =  "rgba(255, 255, 255, " + a + ")";
        this.ctx.lineWidth = 1;
        this.ctx.stroke();
        this.highlight -= 0.5;
    };

    var makePolygonArray = function() {
        tiles = [];
        /**
         * Arrange into a grid x, y, with the y axis at 60 degrees to the x, rather than
         * the usual 90.
         * @type {number}
         */
        var i = 0; // unique number for each tile
        tiles.push(new Polygon(6, 0, 0, tileSize, fgCtx, i)); // the centre tile
        i++;
        for (var layer = 1; layer < 7; layer++) {
            tiles.push(new Polygon(6, 0, layer, tileSize, fgCtx, i)); i++;
            tiles.push(new Polygon(6, 0, -layer, tileSize, fgCtx, i)); i++;
            for(var x = 1; x < layer; x++) {
                tiles.push(new Polygon(6, x, -layer, tileSize, fgCtx, i)); i++;
                tiles.push(new Polygon(6, -x, layer, tileSize, fgCtx, i)); i++;
                tiles.push(new Polygon(6, x, layer-x, tileSize, fgCtx, i)); i++;
                tiles.push(new Polygon(6, -x, -layer+x, tileSize, fgCtx, i)); i++;
            }
            for(var y = -layer; y <= 0; y++) {
                tiles.push(new Polygon(6, layer, y, tileSize, fgCtx, i)); i++;
                tiles.push(new Polygon(6, -layer, -y, tileSize, fgCtx, i)); i++;
            }
        }
    };

    function Star(x, y, starSize, ctx) {
        this.x = x;
        this.y = y;
        this.angle = Math.atan(Math.abs(y)/Math.abs(x));
        this.starSize = starSize;
        this.ctx = ctx;
        this.high = 0;
    }
    Star.prototype.drawStar = function() {
        var distanceFromCentre = Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));

        // stars as lines
        var brightness = 200 + Math.min(Math.round(this.high * 5), 55);
        this.ctx.lineWidth= 0.5 + distanceFromCentre/2000 * Math.max(this.starSize/2, 1);
        this.ctx.strokeStyle='rgba(' + brightness + ', ' + brightness + ', ' + brightness + ', 1)';
        this.ctx.beginPath();
        this.ctx.moveTo(this.x,this.y);
        var lengthFactor = 1 + Math.min(Math.pow(distanceFromCentre,2)/30000 * Math.pow(audioSource.volume, 2)/6000000, distanceFromCentre);
        var toX = Math.cos(this.angle) * -lengthFactor;
        var toY = Math.sin(this.angle) * -lengthFactor;
        toX *= this.x > 0 ? 1 : -1;
        toY *= this.y > 0 ? 1 : -1;
        this.ctx.lineTo(this.x + toX, this.y + toY);
        this.ctx.stroke();
        this.ctx.closePath();

        // starfield movement coming towards the camera
        var speed = lengthFactor/20 * this.starSize;
        this.high -= Math.max(this.high - 0.0001, 0);
        if (speed > this.high) {
            this.high = speed;
        }
        var dX = Math.cos(this.angle) * this.high;
        var dY = Math.sin(this.angle) * this.high;
        this.x += this.x > 0 ? dX : -dX;
        this.y += this.y > 0 ? dY : -dY;

        var limitY = fgCanvas.height/2 + 500;
        var limitX = fgCanvas.width/2 + 500;
        if ((this.y > limitY || this.y < -limitY) || (this.x > limitX || this.x < -limitX)) {
            // it has gone off the edge so respawn it somewhere near the middle.
            this.x = (Math.random() - 0.5) * fgCanvas.width/3;
            this.y = (Math.random() - 0.5) * fgCanvas.height/3;
            this.angle = Math.atan(Math.abs(this.y)/Math.abs(this.x));
        }
    };

    var makeStarArray = function() {
        var x, y, starSize;
        stars = [];
        var limit = fgCanvas.width / 15; // how many stars?
        for (var i = 0; i < limit; i ++) {
            x = (Math.random() - 0.5) * fgCanvas.width;
            y = (Math.random() - 0.5) * fgCanvas.height;
            starSize = (Math.random()+0.1)*3;
            stars.push(new Star(x, y, starSize, sfCtx));
        }
    };

    var drawBg = function() {
        bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
        var r, g, b, a;
        var val = audioSource.volume/1000;
        r = 200 + (Math.sin(val) + 1) * 28;
        g = val * 2;
        b = val * 8;
        a = Math.sin(val+3*Math.PI/2) + 1;
        bgCtx.beginPath();
        bgCtx.rect(0, 0, bgCanvas.width, bgCanvas.height);
        // create radial gradient
        var grd = bgCtx.createRadialGradient(bgCanvas.width/2, bgCanvas.height/2, val, bgCanvas.width/2, bgCanvas.height/2, bgCanvas.width-Math.min(Math.pow(val, 2.7), bgCanvas.width - 20));
        grd.addColorStop(0, 'rgba(0,0,0,0)');// centre is transparent black
        grd.addColorStop(0.8, "rgba(" +
            Math.round(r) + ", " +
            Math.round(g) + ", " +
            Math.round(b) + ", 0.4)"); // edges are reddish

        bgCtx.fillStyle = grd;
        bgCtx.fill();
    };

    this.resizeCanvas = function() {
        if (fgCanvas) {
            // resize the foreground canvas
            fgCanvas.width = window.innerWidth;
            fgCanvas.height = window.innerHeight;
            fgCtx.translate(fgCanvas.width/2,fgCanvas.height/2);

            // resize the bg canvas
            bgCanvas.width = window.innerWidth;
            bgCanvas.height = window.innerHeight;
            // resize the starfield canvas
            sfCanvas.width = window.innerWidth;
            sfCanvas.height = window.innerHeight;
            sfCtx.translate(fgCanvas.width/2,fgCanvas.height/2);

            tileSize = fgCanvas.width > fgCanvas.height ? fgCanvas.width / 25 : fgCanvas.height / 25;

            drawBg();
            makePolygonArray();
            makeStarArray()
        }
    };

    var rotateForeground = function() {
        tiles.forEach(function(tile) {
            tile.rotateVertices();
        });
    };

    var draw = function() {
        fgCtx.clearRect(-fgCanvas.width, -fgCanvas.height, fgCanvas.width*2, fgCanvas.height *2);
        sfCtx.clearRect(-fgCanvas.width/2, -fgCanvas.height/2, fgCanvas.width, fgCanvas.height);

        stars.forEach(function(star) {
            star.drawStar();
        });
        tiles.forEach(function(tile) {
            tile.drawPolygon();
        });
        tiles.forEach(function(tile) {
            if (tile.highlight > 0) {
                tile.drawHighlight();
            }
        });

        // debug
        /* fgCtx.font = "bold 24px sans-serif";
         fgCtx.fillStyle = 'grey';
         fgCtx.fillText("minMental:" + minMental, 10, 10);
         fgCtx.fillText("maxMental:" + maxMental, 10, 40);*/
        requestAnimationFrame(draw);
    };

    this.init = function(options) {
        audioSource = options.audioSource;
        var container = document.getElementById(options.containerId);

        // foreground hexagons layer
        fgCanvas = document.createElement('canvas');
        fgCanvas.setAttribute('style', 'position: absolute; z-index: 10');
        fgCtx = fgCanvas.getContext("2d");
        container.appendChild(fgCanvas);

        // middle starfield layer
        sfCanvas = document.createElement('canvas');
        sfCtx = sfCanvas.getContext("2d");
        sfCanvas.setAttribute('style', 'position: absolute; z-index: 5');
        container.appendChild(sfCanvas);

        // background image layer
        bgCanvas = document.createElement('canvas');
        bgCtx = bgCanvas.getContext("2d");
        container.appendChild(bgCanvas);

        makePolygonArray();
        makeStarArray();

        this.resizeCanvas();
        draw();

        setInterval(drawBg, 100);
        setInterval(rotateForeground, 20);
        // resize the canvas to fill browser window dynamically
        window.addEventListener('resize', this.resizeCanvas, false);
    };
};

/**
 * Makes a request to the Soundcloud API and returns the JSON data.
 */
var SoundcloudLoader = function(player,uiUpdater) {
    var self = this;
    var client_id = "YOUR_SOUNDCLOUD_CLIENT_ID"; // to get an ID go to http://developers.soundcloud.com/
    this.sound = {};
    this.streamUrl = "";
    this.errorMessage = "";
    this.player = player;
    this.uiUpdater = uiUpdater;

    /**
     * Loads the JSON stream data object from the URL of the track (as given in the location bar of the browser when browsing Soundcloud),
     * and on success it calls the callback passed to it (for example, used to then send the stream_url to the audiosource object).
     * @param track_url
     * @param callback
     */
    this.loadStream = function(track_url, successCallback, errorCallback) {
        SC.initialize({
            client_id: client_id
        });
        SC.get('/resolve', { url: track_url }, function(sound) {
            if (sound.errors) {
                self.errorMessage = "";
                for (var i = 0; i < sound.errors.length; i++) {
                    self.errorMessage += sound.errors[i].error_message + '<br>';
                }
                self.errorMessage += 'Make sure the URL has the correct format: https://soundcloud.com/user/title-of-the-track';
                errorCallback();
            } else {

                if(sound.kind=="playlist"){
                    self.sound = sound;
                    self.streamPlaylistIndex = 0;
                    self.streamUrl = function(){
                        return sound.tracks[self.streamPlaylistIndex].stream_url + '?client_id=' + client_id;
                    };
                    successCallback();
                }else{
                    self.sound = sound;
                    self.streamUrl = function(){ return sound.stream_url + '?client_id=' + client_id; };
                    successCallback();
                }
            }
        });
    };

    this.directStream = function(direction){
        if(direction=='toggle'){
            if (this.player.paused) {
                this.player.play();
            } else {
                this.player.pause();
            }
        }
        else if(this.sound.kind=="playlist"){
            if(direction=='coasting') {
                this.streamPlaylistIndex++;
            }else if(direction=='forward') {
                if(this.streamPlaylistIndex>=this.sound.track_count-1) this.streamPlaylistIndex = 0;
                else this.streamPlaylistIndex++;
            }else{
                if(this.streamPlaylistIndex<=0) this.streamPlaylistIndex = this.sound.track_count-1;
                else this.streamPlaylistIndex--;
            }
            if(this.streamPlaylistIndex>=0 && this.streamPlaylistIndex<=this.sound.track_count-1) {
               this.player.setAttribute('src',this.streamUrl());
               this.uiUpdater.update(this);
               this.player.play();
            }
        }
    }

};

/**
 * Class to update the UI when a new sound is loaded
 * @constructor
 */
var UiUpdater = function() {
    var controlPanel = document.getElementById('controlPanel');
    var trackInfoPanel = document.getElementById('trackInfoPanel');
    var infoImage = document.getElementById('infoImage');
    var infoArtist = document.getElementById('infoArtist');
    var infoTrack = document.getElementById('infoTrack');
    var messageBox = document.getElementById('messageBox');

    this.clearInfoPanel = function() {
        // first clear the current contents
        infoArtist.innerHTML = "";
        infoTrack.innerHTML = "";
        trackInfoPanel.className = 'hidden';
    };
    this.update = function(loader) {
        // update the track and artist into in the controlPanel
        var artistLink = document.createElement('a');
        artistLink.setAttribute('href', loader.sound.user.permalink_url);
        artistLink.innerHTML = loader.sound.user.username;
        var trackLink = document.createElement('a');
        trackLink.setAttribute('href', loader.sound.permalink_url);

        if(loader.sound.kind=="playlist"){
            trackLink.innerHTML = "<p>" + loader.sound.tracks[loader.streamPlaylistIndex].title + "</p>" + "<p>"+loader.sound.title+"</p>";
        }else{
            trackLink.innerHTML = loader.sound.title;
        }

        var image = loader.sound.artwork_url ? loader.sound.artwork_url : loader.sound.user.avatar_url; // if no track artwork exists, use the user's avatar.
        infoImage.setAttribute('src', image);

        infoArtist.innerHTML = '';
        infoArtist.appendChild(artistLink);

        infoTrack.innerHTML = '';
        infoTrack.appendChild(trackLink);

        // display the track info panel
        trackInfoPanel.className = '';

        // add a hash to the URL so it can be shared or saved
        var trackToken = loader.sound.permalink_url.substr(22);
        window.location = '#' + trackToken;
    };
    this.toggleControlPanel = function() {
        if (controlPanel.className.indexOf('hidden') === 0) {
            controlPanel.className = '';
        } else {
            controlPanel.className = 'hidden';
        }
    };
    this.displayMessage = function(title, message) {
        messageBox.innerHTML = ''; // reset the contents

        var titleElement = document.createElement('h3');
        titleElement.innerHTML = title;

        var messageElement = document.createElement('p');
        messageElement.innerHTML = message;

        var closeButton = document.createElement('a');
        closeButton.setAttribute('href', '#');
        closeButton.innerHTML = 'close';
        closeButton.addEventListener('click', function(e) {
            e.preventDefault();
            messageBox.className = 'hidden';
        });

        messageBox.className = '';
        // stick them into the container div
        messageBox.appendChild(titleElement);
        messageBox.appendChild(messageElement);
        messageBox.appendChild(closeButton);
    };
};

window.onload = function init() {

    var visualizer = new Visualizer();
    var player =  document.getElementById('player');
    var uiUpdater = new UiUpdater();
    var loader = new SoundcloudLoader(player,uiUpdater);

    var audioSource = new SoundCloudAudioSource(player);
    var form = document.getElementById('form');
    var loadAndUpdate = function(trackUrl) {
        loader.loadStream(trackUrl,
            function() {
                uiUpdater.clearInfoPanel();
                audioSource.playStream(loader.streamUrl());
                uiUpdater.update(loader);
                setTimeout(uiUpdater.toggleControlPanel, 3000); // auto-hide the control panel
            },
            function() {
                uiUpdater.displayMessage("Error", loader.errorMessage);
            });
    };

    visualizer.init({
        containerId: 'visualizer',
        audioSource: audioSource
    });

    uiUpdater.toggleControlPanel();
    // on load, check to see if there is a track token in the URL, and if so, load that automatically
    if (window.location.hash) {
        var trackUrl = 'https://soundcloud.com/' + window.location.hash.substr(1);
        loadAndUpdate(trackUrl);
    }

    // handle the form submit event to load the new URL
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        var trackUrl = document.getElementById('input').value;
        loadAndUpdate(trackUrl);
    });
    var toggleButton = document.getElementById('toggleButton')
    toggleButton.addEventListener('click', function(e) {
        e.preventDefault();
        uiUpdater.toggleControlPanel();
    });
    var aboutButton = document.getElementById('credit');
    aboutButton.addEventListener('click', function(e) {
        e.preventDefault();
        var message = document.getElementById('info').innerHTML;
        uiUpdater.displayMessage("About", message);
    });

    window.addEventListener("keydown", keyControls, false);

    function keyControls(e) {
        switch(e.keyCode) {
            case 32:
                // spacebar pressed
                loader.directStream('toggle');
                break;
            case 37:
                // left key pressed
                loader.directStream('backward');
                break;
            case 39:
                // right key pressed
                loader.directStream('forward');
                break;
        }
    }

};<|endoftext|>


<commit_before>var canvas;

function clearScreen(ctx) {
	ctx.setTransform(1, 0, 0, 1, 0, 0);
	ctx.clearRect(0,0,canvas.width,canvas.height);
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

function getRandomColor() {
	var r = Math.round(Math.random() * 255);
    var g = Math.round(Math.random() * 255);
    var b = Math.round(Math.random() * 255);

    return 'rgb(' + r +',' + g + ',' + b + ')';
}

function box(x,y,width,height,mass) {
	this.x = x;
	this.y = y;
	this.width = width;
	this.height = height;

	if(mass == undefined)
		this.mass = 0;
	else
		this.mass = mass;

	this.color = getRandomColor();

	this.draw = function(ctx) {
						ctx.fillStyle=this.color;
						ctx.fillRect(this.x,this.y,this.width,this.height);
					};

	this.isPointInBox = function(x,y) {
						if(x < this.x)
							return false;
						if(y < this.y)
							return false;
						if(x > this.x + this.width)
							return false;
						if(y > this.y + this.height)
							return false;

						return true;
					};

	this.overLapsBox = function(box) {
						if(box.isPointInBox(this.x, this.y))
							return true;
						if(box.isPointInBox(this.x + this.width, this.y))
							return true;
						if(box.isPointInBox(this.x, this.y + this.height))
							return true;
						if(box.isPointInBox(this.x + this.width, this.y + this.height))
							return true;

						return false;
					};

	this.overLapsBoxes = function(boxes) {

						for(var i = 0; i < boxes.length; i++) {
							if(boxes[i].overLapsBox(this))
								return true;
						}

						return false;
					};
}

function spring(fixedX,fixedY,startX,startY,k) {
	this.fixedX = fixedX;
	this.fixedY = fixedY;
	this.moveX = startX;
	this.moveY = startY;

	var dx = this.moveX - this.fixedX;
	var dy = this.moveY - this.fixedY;

	this.unstretchedLength = Math.sqrt(dx * dx + dy * dy);
	this.k = k;

	var width = 0.5 * this.unstretchedLength;

	this.dx = function() {
		return this.moveX - this.fixedX;
	};

	this.dy = function() {
		return this.moveY - this.fixedY;
	};

	this.length = function() {
		var dx = this.dx();
		var dy = this.dy();

		return Math.sqrt(dx * dx + dy * dy);
	};

	this.displacement = function() {
		return this.length() - this.unstretchedLength;
	};

	this.force = function()	{
		return - this.k * this.displacement();
	};

	this.draw = function(ctx) {
		var dx = this.dx();
		var dy = this.dy();

		var size = Math.sqrt(dx * dx + dy * dy);

		var rotation;

		if(dy == 0)	{
			if(dx >= 0)	{
				rotation = 0;
			} else {
				rotation = Math.PI;
			}
		} else if(dy > 0) {
			rotation = Math.PI / 2 - Math.atan(dx / dy);
		} else {
			rotation = Math.atan(- dx / dy) - Math.PI / 2;
		}

		ctx.save();

		ctx.setTransform(1, 0, 0, 1, 0, 0);
		ctx.translate(this.fixedX,this.fixedY);
		ctx.rotate(rotation);

		ctx.lineWidth="1";
		ctx.strokeStyle="black";
		ctx.moveTo(0,0);
		ctx.beginPath();

		var x = 0;
		var y = 0;

		ctx.lineTo(x,y);

		x = 1 / 20;
		y = 1.0;

		ctx.lineTo(x * size,y * width);

		x += 1 / 10;
		y = -1.0;

		for(var i = 0; i < 9; i++) {
			ctx.lineTo(x * size,y * width);

			x += 1 / 10;
			y = - 1 * y;
		}

		y = 0.0;
		x -= 1 / 20;

		ctx.lineTo(x * size,y * width);
		ctx.stroke();
		ctx.restore();
	};
}

function drawEverything(array, ctx) {
	for(var i = 0; i < array.length; i++) {
		array[i].draw(ctx);
	}
}

$(document).ready(function() {
	var timer = null;

	var everything = new Array();

	canvas = $("#spring").get(0);
	var ctx = canvas.getContext('2d');

	var mouseDown = false;

	var prevMousePos;

	var boxWidth = 50;
	var boxHeight = 50;

	var topBoxX = canvas.width / 2 - boxWidth / 2;
	var topBoxY = canvas.height / 4;

	var topBox = new box(topBoxX,topBoxY,boxWidth,boxHeight);
	everything.push(topBox);

	var bottomBoxX = topBoxX;
	var bottomBoxY = topBoxY + boxHeight * 2;

	var hangingBox = new box(bottomBoxX, bottomBoxY, boxWidth, boxHeight, 50);
	everything.push(hangingBox);

	var springTopX = topBoxX + boxWidth / 2;
	var springTopY = topBoxY + boxHeight;

	var springBottomX = springTopX;
	var springBottomY = bottomBoxY;

	var theSpring = new spring(springTopX,springTopY,springBottomX,springBottomY,0.5);
	everything.push(theSpring);

	drawEverything(everything, ctx);

	$("#spring").mousedown(function(e) {
		var mousePos = getMousePos(canvas, e);

		if(hangingBox.isPointInBox(mousePos.x, mousePos.y))	{
			window.clearInterval(timer);
			mouseDown = true;
			prevMousePos = mousePos;
		}
	});

	$("#spring").mousemove(function(e) {
		if(mouseDown) {
			var mousePos = getMousePos(canvas, e);
			var dx = mousePos.x - prevMousePos.x;
			var dy = mousePos.y - prevMousePos.y;
			prevMousePos = mousePos;

			hangingBox.x = hangingBox.x + dx;
			hangingBox.y = hangingBox.y + dy;

			theSpring.moveX = theSpring.moveX + dx;
			theSpring.moveY = theSpring.moveY + dy;

			var springForce = - theSpring.force();

			$("#length").html(theSpring.length().toString());
			$("#force").html(springForce.toString());

			clearScreen(ctx);
			drawEverything(everything, ctx);
		}
	});

	$(window).mouseup(function() {
		mouseDown = false;

		var velocity = 0;
		var velocity_x = 0;
		var velocity_y = 0;
		var time = 1000 / 60;

		timer = window.setInterval(function() {
			var springForce = theSpring.force();
			var dampingForce = 1.0 * velocity;
			//springForce -= dampingForce;

			var acceleration = springForce / hangingBox.mass;
			velocity += acceleration;

			if(theSpring.dx() != 0 && theSpring.dy() != 0) {
				velocity_x = theSpring.dx() * velocity / theSpring.length();
				velocity_y = theSpring.dy() * velocity / theSpring.length();
			} else if(theSpring.dx() == 0 && theSpring.dy() != 0) {
				velocity_x = 0;
				velocity_y = velocity;
			} else if(theSpring.dx() != 0 && theSpring.dy() == 0) {
				velocity_x = velocity;
				velocity_y = 0;
			}

			hangingBox.x += velocity_x;
			theSpring.moveX += velocity_x;
			hangingBox.y += velocity_y;
			theSpring.moveY += velocity_y;

			$("#length").html(theSpring.length().toString());
			$("#force").html(springForce.toString());
			$("#acc").html(acceleration.toString());
			$("#velocity").html(velocity.toString());

			clearScreen(ctx);
			drawEverything(everything, ctx);
		},

		time);
	});
});
<commit_msg>Update spring.js<commit_after>var canvas;

function clearScreen(ctx) {
	ctx.setTransform(1, 0, 0, 1, 0, 0);
	ctx.clearRect(0,0,canvas.width,canvas.height);
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

function getRandomColor() {
	var r = Math.round(Math.random() * 255);
    var g = Math.round(Math.random() * 255);
    var b = Math.round(Math.random() * 255);

    return 'rgb(' + r +',' + g + ',' + b + ')';
}

function box(x,y,width,height,mass) {
	this.x = x;
	this.y = y;
	this.width = width;
	this.height = height;

	if(mass == undefined)
		this.mass = 0;
	else
		this.mass = mass;

	this.color = getRandomColor();

	this.draw = function(ctx) {
		ctx.fillStyle=this.color;
		ctx.fillRect(this.x,this.y,this.width,this.height);
	};

	this.isPointInBox = function(x,y) {
		if(x < this.x)
			return false;
		if(y < this.y)
			return false;
		if(x > this.x + this.width)
			return false;
		if(y > this.y + this.height)
			return false;

		return true;
	};

	this.overLapsBox = function(box) {
		if(box.isPointInBox(this.x, this.y))
			return true;
		if(box.isPointInBox(this.x + this.width, this.y))
			return true;
		if(box.isPointInBox(this.x, this.y + this.height))
			return true;
		if(box.isPointInBox(this.x + this.width, this.y + this.height))
			return true;

		return false;
	};

	this.overLapsBoxes = function(boxes) {
		for(var i = 0; i < boxes.length; i++) {
			if(boxes[i].overLapsBox(this))
				return true;
		}

		return false;
	};
}

function spring(fixedX,fixedY,startX,startY,k) {
	this.fixedX = fixedX;
	this.fixedY = fixedY;
	this.moveX = startX;
	this.moveY = startY;

	var dx = this.moveX - this.fixedX;
	var dy = this.moveY - this.fixedY;

	this.unstretchedLength = Math.sqrt(dx * dx + dy * dy);
	this.k = k;

	var width = 0.5 * this.unstretchedLength;

	this.dx = function() {
		return this.moveX - this.fixedX;
	};

	this.dy = function() {
		return this.moveY - this.fixedY;
	};

	this.length = function() {
		var dx = this.dx();
		var dy = this.dy();

		return Math.sqrt(dx * dx + dy * dy);
	};

	this.displacement = function() {
		return this.length() - this.unstretchedLength;
	};

	this.force = function()	{
		return - this.k * this.displacement();
	};

	this.draw = function(ctx) {
		var dx = this.dx();
		var dy = this.dy();

		var size = Math.sqrt(dx * dx + dy * dy);

		var rotation;

		if(dy == 0)	{
			if(dx >= 0)	{
				rotation = 0;
			} else {
				rotation = Math.PI;
			}
		} else if(dy > 0) {
			rotation = Math.PI / 2 - Math.atan(dx / dy);
		} else {
			rotation = Math.atan(- dx / dy) - Math.PI / 2;
		}

		ctx.save();

		ctx.setTransform(1, 0, 0, 1, 0, 0);
		ctx.translate(this.fixedX,this.fixedY);
		ctx.rotate(rotation);

		ctx.lineWidth="1";
		ctx.strokeStyle="black";
		ctx.moveTo(0,0);
		ctx.beginPath();

		var x = 0;
		var y = 0;

		ctx.lineTo(x,y);

		x = 1 / 20;
		y = 1.0;

		ctx.lineTo(x * size,y * width);

		x += 1 / 10;
		y = -1.0;

		for(var i = 0; i < 9; i++) {
			ctx.lineTo(x * size,y * width);

			x += 1 / 10;
			y = - 1 * y;
		}

		y = 0.0;
		x -= 1 / 20;

		ctx.lineTo(x * size,y * width);
		ctx.stroke();
		ctx.restore();
	};
}

function drawEverything(array, ctx) {
	for(var i = 0; i < array.length; i++) {
		array[i].draw(ctx);
	}
}

$(document).ready(function() {
	var timer = null;

	var everything = new Array();

	canvas = $("#spring").get(0);
	var ctx = canvas.getContext('2d');

	var mouseDown = false;

	var prevMousePos;

	var boxWidth = 50;
	var boxHeight = 50;

	var topBoxX = canvas.width / 2 - boxWidth / 2;
	var topBoxY = canvas.height / 4;

	var topBox = new box(topBoxX,topBoxY,boxWidth,boxHeight);
	everything.push(topBox);

	var bottomBoxX = topBoxX;
	var bottomBoxY = topBoxY + boxHeight * 2;

	var hangingBox = new box(bottomBoxX, bottomBoxY, boxWidth, boxHeight, 50);
	everything.push(hangingBox);

	var springTopX = topBoxX + boxWidth / 2;
	var springTopY = topBoxY + boxHeight;

	var springBottomX = springTopX;
	var springBottomY = bottomBoxY;

	var theSpring = new spring(springTopX,springTopY,springBottomX,springBottomY,0.5);
	everything.push(theSpring);

	drawEverything(everything, ctx);

	$("#spring").mousedown(function(e) {
		var mousePos = getMousePos(canvas, e);

		if(hangingBox.isPointInBox(mousePos.x, mousePos.y))	{
			window.clearInterval(timer);
			mouseDown = true;
			prevMousePos = mousePos;
		}
	});

	$("#spring").mousemove(function(e) {
		if(mouseDown) {
			var mousePos = getMousePos(canvas, e);
			var dx = mousePos.x - prevMousePos.x;
			var dy = mousePos.y - prevMousePos.y;
			prevMousePos = mousePos;

			hangingBox.x = hangingBox.x + dx;
			hangingBox.y = hangingBox.y + dy;

			theSpring.moveX = theSpring.moveX + dx;
			theSpring.moveY = theSpring.moveY + dy;

			var springForce = - theSpring.force();

			$("#length").html(theSpring.length().toString());
			$("#force").html(springForce.toString());

			clearScreen(ctx);
			drawEverything(everything, ctx);
		}
	});

	$(window).mouseup(function() {
		mouseDown = false;

		var velocity = 0;
		var velocity_x = 0;
		var velocity_y = 0;
		var time = 1000 / 60;

		timer = window.setInterval(function() {
			var springForce = theSpring.force();
			var dampingForce = 1.0 * velocity;
			//springForce -= dampingForce;

			var acceleration = springForce / hangingBox.mass;
			velocity += acceleration;

			if(theSpring.dx() != 0 && theSpring.dy() != 0) {
				velocity_x = theSpring.dx() * velocity / theSpring.length();
				velocity_y = theSpring.dy() * velocity / theSpring.length();
			} else if(theSpring.dx() == 0 && theSpring.dy() != 0) {
				velocity_x = 0;
				velocity_y = velocity;
			} else if(theSpring.dx() != 0 && theSpring.dy() == 0) {
				velocity_x = velocity;
				velocity_y = 0;
			}

			hangingBox.x += velocity_x;
			theSpring.moveX += velocity_x;
			hangingBox.y += velocity_y;
			theSpring.moveY += velocity_y;

			$("#length").html(theSpring.length().toString());
			$("#force").html(springForce.toString());
			$("#acc").html(acceleration.toString());
			$("#velocity").html(velocity.toString());

			clearScreen(ctx);
			drawEverything(everything, ctx);
		},

		time);
	});
});
<|endoftext|>


<commit_before>'use strict'

var url = require('url')
  , crypto = require('crypto')
var qs = require('qs')
  , uuid = require('node-uuid')
  , _oauth = require('oauth-sign')

function oauth (req, options) {
  var form
    , query
    , contentType = options.headers.get('content-type') || ''
    , formContentType = 'application/x-www-form-urlencoded'
    , transport = options.oauth.transport_method || 'header'

  if (contentType.slice(0, formContentType.length) === formContentType) {
    contentType = formContentType
    form = options.body
  }
  // should store somewhere the parse URL
  var uri = options.uri || {}
  if (uri.query) {
    query = uri.query
  }
  if (transport === 'body' &&
    (options.method !== 'POST' || contentType !== formContentType)) {
    // self.request.emit('error',
    //   new Error('oauth: transport_method of body requires POST ' +
    //   'and content-type ' + formContentType))
  }

  if (!form && typeof options.oauth.body_hash === 'boolean') {
    options.oauth.body_hash =
      buildBodyHash(options.oauth, options.body.toString())
  }

  var oa = buildParams(options.oauth, uri, options.method, query, form)

  if (transport === 'header') {
    options.headers.set('authorization', 'OAuth ' + concatParams(oa, ',', '"'))
  }
  else if (transport === 'query') {
    var href = options.uri.href += (query ? '&' : '?') + concatParams(oa, '&')

    // options.uri = url.parse(href)
    // self.request.path = self.request.uri.path
  }
  else if (transport === 'body') {
    options.body = (form ? form + '&' : '') + concatParams(oa, '&')
  }
}

function buildParams (oauth, uri, method, query, form) {
  var oa = {}
  for (var key in oauth) {
    var param = (!/^oauth_/.test(key)) ? ('oauth_' + key) : key
    oa[param] = oauth[key]
  }
  if (!oa.oauth_version) {
    oa.oauth_version = '1.0'
  }
  if (!oa.oauth_timestamp) {
    oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString()
  }
  if (!oa.oauth_nonce) {
    oa.oauth_nonce = uuid().replace(/-/g, '')
  }
  if (!oa.oauth_signature_method) {
    oa.oauth_signature_method = 'HMAC-SHA1'
  }

  var consumer_secret_or_private_key =
    oa.oauth_consumer_secret || oa.oauth_private_key
  delete oa.oauth_consumer_secret
  delete oa.oauth_private_key

  var token_secret = oa.oauth_token_secret
  delete oa.oauth_token_secret

  var realm = oa.oauth_realm
  delete oa.oauth_realm
  delete oa.oauth_transport_method

  var baseurl = uri.protocol + '//' + uri.host + uri.pathname
  var params = qs.parse([].concat(query, form, qs.stringify(oa)).join('&'))

  oa.oauth_signature = _oauth.sign(
    oa.oauth_signature_method,
    method,
    baseurl,
    params,
    consumer_secret_or_private_key,
    token_secret)

  if (realm) {
    oa.realm = realm
  }

  return oa
}

function buildBodyHash (oauth, body) {
  if (['HMAC-SHA1', 'RSA-SHA1']
    .indexOf(oauth.signature_method || 'HMAC-SHA1') < 0) {
    // this.request.emit('error',
    //   new Error('oauth: ' + oauth.signature_method +
    //   ' signature_method not supported with body_hash signing.'))
  }

  var shasum = crypto.createHash('sha1')
  shasum.update(body || '')
  var sha1 = shasum.digest('hex')

  return new Buffer(sha1).toString('base64')
}

function concatParams (oa, sep, wrap) {
  wrap = wrap || ''

  var params = Object.keys(oa).filter(function (i) {
    return i !== 'realm' && i !== 'oauth_signature'
  }).sort()

  if (oa.realm) {
    params.splice(0, 0, 'realm')
  }
  params.push('oauth_signature')

  return params.map(function (i) {
    return i + '=' + wrap + _oauth.rfc3986(oa[i]) + wrap
  }).join(sep)
}

module.exports = oauth
<commit_msg>Move the oauth logic into external module<commit_after>'use strict'

var url = require('url')
var _oauth = require('request-oauth')

function oauth (req, options) {

  var form, contentType = options.headers.get('content-type')
  if (options.form || /^application\/x-www-form-urlencoded/.test(contentType)) {
    form = options.body.toString()
  }

  var result = _oauth({
    oauth: options.oauth, uri: options.uri, method: options.method,
    query: options.uri.query, form: form, body: options.body
  })

  if (result instanceof Error) {
    req.emit('error', result.error)
    return
  }

  var transport = options.oauth.transport_method || 'header'
  if (transport === 'header') {
    options.headers.set('authorization', result)
  }
  else if (transport === 'query') {
    var href = options.uri.href += result
    options.uri = url.parse(href)
    options.path = options.uri.path
  }
  else if (transport === 'body') {
    options.body += result
  }
}

module.exports = oauth
<|endoftext|>


<commit_before>var MAX_TIMER_COUNT = 9;

function openPanel() {
    var elements = document.querySelectorAll("#timerConfig :not(div)");
    for (i=0; i<elements.length; ++i) {
        elements[i].classList.remove("hidden");
    }
    document.getElementById("addtimerbutton").classList.remove("hidden");
    document.getElementById("timerConfig").dataset.state = "open";
    document.getElementById("timerConfig").classList.add("timerConfigAnimateIn");
    document.getElementById("timerConfig").classList.remove("timerConfigAnimateOut");
}

function closePanel() {
    var timers = document.querySelectorAll(".timer");
    Array.prototype.forEach.call(timers, function(item){
        item.dataset.state="un-selected";
    });
    document.getElementById("timerConfig").classList.add("timerConfigAnimateOut");
    document.getElementById("timerConfig").classList.remove("timerConfigAnimateIn");
}

function hideConfigElements() {

    if (document.getElementById("timerConfig").classList.contains("timerConfigAnimateIn")) {
    } else {
        document.getElementById("timerConfig").dataset.state = "closed";
    }
}

function toggleTimer(){
    if (this.dataset.state == "selected" || this.dataset.state == "un-selected") {
        var timers = document.getElementsByClassName("timer");
        var toggle = this.dataset.state == "selected";
        Array.prototype.forEach.call(timers, function(item){
            item.dataset.state="un-selected";
        });
        this.dataset.state = toggle ? "un-selected" : "selected";
    }
}

var currentTimerCount=0;
function addTimer(title, minute, second) {
    currentTimerCount++;
    var timers = document.getElementById("timers");
    if (timers.children.length < MAX_TIMER_COUNT) {
        var newtimer = document.createElement("div");
        newtimer.classList.add("timer");
        newtimer.addEventListener("click", toggleTimer);

        var timerContents = document.createElement("span");
        timerContents.classList.add("timerContents");

        var timerTitle = document.createElement("span");
        if(title != null) {
            timerTitle.innerHTML = title;
        }
        else{
            timerTitle.innerHTML = "Title";
        }
        timerTitle.setAttribute("contenteditable","true");
        timerTitle.addEventListener("keypress", function(e){
            if(e.keyCode === 13){
                e.preventDefault();
                this.blur();
            }
        });
        timerTitle.classList.add("timerTitle");
        timerTitle.addEventListener("click",function(){
            this.parentNode.dataset.state = "un-selected";
        });

        var timerCountdown = document.createElement("div");
        timerCountdown.classList.add("timerCountdown");
        if(minute != null && second != null) {
            timerCountdown.innerHTML = minute+":"+second;
        }
        else{
            timerCountdown.innerHTML = "00:00";
        }
        var timerTime = document.createElement("span");
        timerTime.classList.add("timerTime");
        timerTime.addEventListener("change", function(){
                setTimer(newtimer, "true");
        }, false);
        /*timerTime.addEventListener("keydown", function(e){
            if(e.keyCode === 13){
                setTimer(newtimer);
            }
        }, false);*/

        var timerTimeMin = document.createElement("input");
        timerTimeMin.classList.add("timerTimeMin");
        timerTimeMin.type="number";
        if(minute != null){
            timerTimeMin.value=minute;
        }
        else{
            timerTimeMin.value="00";
        }
        timerTimeMin.max=500;

        var timerColon = document.createElement("span");
        timerColon.classList.add("timerColon");
        timerColon.innerHTML=":";

        var timerTimeSec = document.createElement("input");
        timerTimeSec.classList.add("timerTimeSec");
        timerTimeSec.type="number";
        if(second != null){
            timerTimeSec.value=second;
        }
        else{
            timerTimeSec.value="00";
        }
        timerTimeSec.max=59;

        timerTime.appendChild(timerTimeMin);
        timerTime.appendChild(timerColon);
        timerTime.appendChild(timerTimeSec);

        var addMinuteButton = document.createElement("button");
        addMinuteButton.classList.add("addMinuteButton");
        addMinuteButton.innerHTML="+ min";
        addMinuteButton.addEventListener("click", function(){
            var timerTimeMinadd = this.parentNode.querySelectorAll(".timerTimeMin").item(0);
            timerTimeMinadd.value = parseInt(timerTimeMinadd.value)+1;
            fireEvent(timerTimeMinadd,"change");
            this.parentNode.dataset.state = "un-selected";
        }, false);
        var cancelTimerButton = document.createElement("button");
        cancelTimerButton.classList.add("cancelTimerButton");
        cancelTimerButton.innerHTML="Cancel";
        cancelTimerButton.addEventListener("click", function(){
            this.parentNode.dataset.state = "un-selected";
            clearInterval(timerMap[this.id]);
            document.getElementById("timers").removeChild(this.parentNode);
        }, false);

        timerCountdown.id="timer"+currentTimerCount;
        newtimer.appendChild(timerTitle);
        newtimer.appendChild(timerTime);
        newtimer.appendChild(timerCountdown);
        newtimer.appendChild(addMinuteButton);
        newtimer.appendChild(cancelTimerButton);

            newtimer.dataset.state="un-selected";
        timers.appendChild(newtimer);
        if(minute != "00" && second != "00") {
        }
        else {
            fireEvent(timerTime, "change");
        }
    }
}
function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}
function setTimer(newtimer){
    var time = newtimer.querySelectorAll(".timerTime").item(0);
    var countDown = newtimer.querySelectorAll(".timerCountdown").item(0);
    var minute = parseInt(time.querySelectorAll(".timerTimeMin").item(0).value);
    var second = parseInt(time.querySelectorAll(".timerTimeSec").item(0).value);
    var display = document.getElementById(countDown.id);
    var duration = 60*minute+second;
    startTimer(duration, display);
}
function removeAllTimers(){
    var el = document.getElementById('timers');
    while( el.hasChildNodes() ){
        el.removeChild(el.lastChild);
    }
}

function togglePanel() {
    if (document.getElementById("timerConfig").dataset.state == "closed") {
        openPanel();
    } else {
        closePanel();
    }
}

window.addEventListener("DOMContentLoaded", function() {
    document.getElementById("timerConfigButton").addEventListener('click', togglePanel);
    document.getElementById("closeConfigButton").addEventListener('click', togglePanel);
    document.getElementById("timerConfig").addEventListener("transitionend", hideConfigElements, true);
    var add_buttons = document.querySelectorAll("[data-action='add_timer']");
    for (i=0; i<add_buttons.length; ++i) {
        add_buttons[i].addEventListener("click", function(){
            if (this.dataset.title) {
                addTimer(this.dataset.title,this.dataset.minutes||"00",this.dataset.seconds||"00");
            } else {
                addTimer("title","00","00");
            }
        });
    }
    var clear_timers = document.querySelectorAll("[data-action='clear_timers']");
    for (i=0; i<clear_timers.length; ++i) {
        clear_timers[i].addEventListener("click", removeAllTimers);
    }

});
function startTimer(duration, display) {

    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        if(minutes <= 60) {
            display.textContent = minutes + ":" + seconds;
        }
        else{
            display.textContent = parseInt(minutes/60)+":"+parseInt(minutes%60) + ":" + seconds;
        }
        var timerMin = display.parentNode.querySelectorAll(".timerTime .timerTimeMin").item(0);
        var timerSec = display.parentNode.querySelectorAll(".timerTime .timerTimeSec").item(0);
        if(timerMin != document.activeElement){
        timerMin.value=minutes;}
        if(timerSec != document.activeElement){
        timerSec.value=seconds;}
        if(duration > 0 && minutes == "00" && seconds =="00"){
            clearInterval(timerMap[display.id]);
                display.parentNode.classList.add("completed");
        }
        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    if(timerMap[display.id]!=null) {
        clearInterval(timerMap[display.id]);
    }
    timerMap[display.id]=setInterval(timer, 1000);
}
var timerMap ={};
<commit_msg>fixed timer stay open on change title and on blur<commit_after>var MAX_TIMER_COUNT = 9;

function openPanel() {
    var elements = document.querySelectorAll("#timerConfig :not(div)");
    for (i=0; i<elements.length; ++i) {
        elements[i].classList.remove("hidden");
    }
    document.getElementById("addtimerbutton").classList.remove("hidden");
    document.getElementById("timerConfig").dataset.state = "open";
    document.getElementById("timerConfig").classList.add("timerConfigAnimateIn");
    document.getElementById("timerConfig").classList.remove("timerConfigAnimateOut");
}

function closePanel() {
    var timers = document.querySelectorAll(".timer");
    Array.prototype.forEach.call(timers, function(item){
        item.dataset.state="un-selected";
    });
    document.getElementById("timerConfig").classList.add("timerConfigAnimateOut");
    document.getElementById("timerConfig").classList.remove("timerConfigAnimateIn");
}

function hideConfigElements() {

    if (document.getElementById("timerConfig").classList.contains("timerConfigAnimateIn")) {
    } else {
        document.getElementById("timerConfig").dataset.state = "closed";
    }
}

function toggleTimer(){
    if (this.dataset.state == "selected" || this.dataset.state == "un-selected") {
        var timers = document.getElementsByClassName("timer");
        var toggle = this.dataset.state == "selected";
        Array.prototype.forEach.call(timers, function(item){
            item.dataset.state="un-selected";
        });
        this.dataset.state = toggle ? "un-selected" : "selected";
    }
}

var currentTimerCount=0;
function addTimer(title, minute, second) {
    currentTimerCount++;
    var timers = document.getElementById("timers");
    if (timers.children.length < MAX_TIMER_COUNT) {
        var newtimer = document.createElement("div");
        newtimer.classList.add("timer");
        newtimer.addEventListener("click", toggleTimer);

        var timerContents = document.createElement("span");
        timerContents.classList.add("timerContents");

        var timerTitle = document.createElement("span");
        if(title != null) {
            timerTitle.innerHTML = title;
        }
        else{
            timerTitle.innerHTML = "Title";
        }
        timerTitle.setAttribute("contenteditable","true");
        timerTitle.addEventListener("keypress", function(e){
            if(e.keyCode === 13){
                e.preventDefault();
                this.blur();
            }
        });
        timerTitle.classList.add("timerTitle");
        timerTitle.addEventListener("click",function(){
            this.parentNode.dataset.state = "un-selected";
        });
        timerTitle.addEventListener("blur",function(){
            this.parentNode.dataset.state = "un-selected";
        });

        var timerCountdown = document.createElement("div");
        timerCountdown.classList.add("timerCountdown");
        if(minute != null && second != null) {
            timerCountdown.innerHTML = minute+":"+second;
        }
        else{
            timerCountdown.innerHTML = "00:00";
        }
        var timerTime = document.createElement("span");
        timerTime.classList.add("timerTime");
        timerTime.addEventListener("change", function(){
                setTimer(newtimer, "true");
        }, false);
        /*timerTime.addEventListener("keydown", function(e){
            if(e.keyCode === 13){
                setTimer(newtimer);
            }
        }, false);*/

        var timerTimeMin = document.createElement("input");
        timerTimeMin.classList.add("timerTimeMin");
        timerTimeMin.type="number";
        if(minute != null){
            timerTimeMin.value=minute;
        }
        else{
            timerTimeMin.value="00";
        }
        timerTimeMin.max=500;

        var timerColon = document.createElement("span");
        timerColon.classList.add("timerColon");
        timerColon.innerHTML=":";

        var timerTimeSec = document.createElement("input");
        timerTimeSec.classList.add("timerTimeSec");
        timerTimeSec.type="number";
        if(second != null){
            timerTimeSec.value=second;
        }
        else{
            timerTimeSec.value="00";
        }
        timerTimeSec.max=59;

        timerTime.appendChild(timerTimeMin);
        timerTime.appendChild(timerColon);
        timerTime.appendChild(timerTimeSec);

        var addMinuteButton = document.createElement("button");
        addMinuteButton.classList.add("addMinuteButton");
        addMinuteButton.innerHTML="+ min";
        addMinuteButton.addEventListener("click", function(){
            var timerTimeMinadd = this.parentNode.querySelectorAll(".timerTimeMin").item(0);
            timerTimeMinadd.value = parseInt(timerTimeMinadd.value)+1;
            fireEvent(timerTimeMinadd,"change");
            this.parentNode.dataset.state = "un-selected";
        }, false);
        var cancelTimerButton = document.createElement("button");
        cancelTimerButton.classList.add("cancelTimerButton");
        cancelTimerButton.innerHTML="Cancel";
        cancelTimerButton.addEventListener("click", function(){
            this.parentNode.dataset.state = "un-selected";
            clearInterval(timerMap[this.id]);
            document.getElementById("timers").removeChild(this.parentNode);
        }, false);

        timerCountdown.id="timer"+currentTimerCount;
        newtimer.appendChild(timerTitle);
        newtimer.appendChild(timerTime);
        newtimer.appendChild(timerCountdown);
        newtimer.appendChild(addMinuteButton);
        newtimer.appendChild(cancelTimerButton);

            newtimer.dataset.state="un-selected";
        timers.appendChild(newtimer);
        if(minute != "00" && second != "00") {
        }
        else {
            fireEvent(timerTime, "change");
        }
    }
}
function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}
function setTimer(newtimer){
    var time = newtimer.querySelectorAll(".timerTime").item(0);
    var countDown = newtimer.querySelectorAll(".timerCountdown").item(0);
    var minute = parseInt(time.querySelectorAll(".timerTimeMin").item(0).value);
    var second = parseInt(time.querySelectorAll(".timerTimeSec").item(0).value);
    var display = document.getElementById(countDown.id);
    var duration = 60*minute+second;
    startTimer(duration, display);
}
function removeAllTimers(){
    var el = document.getElementById('timers');
    while( el.hasChildNodes() ){
        el.removeChild(el.lastChild);
    }
}

function togglePanel() {
    if (document.getElementById("timerConfig").dataset.state == "closed") {
        openPanel();
    } else {
        closePanel();
    }
}

window.addEventListener("DOMContentLoaded", function() {
    document.getElementById("timerConfigButton").addEventListener('click', togglePanel);
    document.getElementById("closeConfigButton").addEventListener('click', togglePanel);
    document.getElementById("timerConfig").addEventListener("transitionend", hideConfigElements, true);
    var add_buttons = document.querySelectorAll("[data-action='add_timer']");
    for (i=0; i<add_buttons.length; ++i) {
        add_buttons[i].addEventListener("click", function(){
            if (this.dataset.title) {
                addTimer(this.dataset.title,this.dataset.minutes||"00",this.dataset.seconds||"00");
            } else {
                addTimer("title","00","00");
            }
        });
    }
    var clear_timers = document.querySelectorAll("[data-action='clear_timers']");
    for (i=0; i<clear_timers.length; ++i) {
        clear_timers[i].addEventListener("click", removeAllTimers);
    }

});
function startTimer(duration, display) {

    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        if(minutes <= 60) {
            display.textContent = minutes + ":" + seconds;
        }
        else{
            display.textContent = parseInt(minutes/60)+":"+parseInt(minutes%60) + ":" + seconds;
        }
        var timerMin = display.parentNode.querySelectorAll(".timerTime .timerTimeMin").item(0);
        var timerSec = display.parentNode.querySelectorAll(".timerTime .timerTimeSec").item(0);
        if(timerMin != document.activeElement){
        timerMin.value=minutes;}
        if(timerSec != document.activeElement){
        timerSec.value=seconds;}
        if(duration > 0 && minutes == "00" && seconds =="00"){
            clearInterval(timerMap[display.id]);
                display.parentNode.classList.add("completed");
        }
        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    if(timerMap[display.id]!=null) {
        clearInterval(timerMap[display.id]);
    }
    timerMap[display.id]=setInterval(timer, 1000);
}
var timerMap ={};
<|endoftext|>


<commit_before>//http://www.hongkiat.com/blog/node-js-server-side-javascript/
//http://stackoverflow.com/questions/6084360/node-js-as-a-simple-web-server
//https://github.com/requirejs/example-jquery-cdn/blob/master/tools/server.js

//Install: add --debug=8081 in Node parameters

var http = require('http'),
    path = require('path'),
    url = require('url'),
    fs = require('fs'),
    port = parseInt(process.argv[3], 10) || parseInt(process.argv[2], 10) || 8080,
    types = {
        'html'  : 'text/html',
        'txt'   : 'text/plain',
        'css'   : 'text/css',
        'js'    : 'text/javascript',
        'ico'   : 'image/x-icon',
        'jpg'   : 'image/jpeg',
        'png'   : 'image/png',
        'gif'   : 'image/gif',
        'svg'   : 'image/svg+xml',
        'json'  : 'application/json',
        'xml'   : 'text/xml',
        'bin'   : 'application/octet-stream',
        'ttf'  : 'font/ttf',
        'woff'  : 'font/woff'

    };

console.log('Server Running on port ' + port.toString() + '\n');

module.exports = http.createServer(function(request,response){
    //debugger;
    var uri = url.parse(request.url).pathname,
        filename = path.join(process.cwd(),uri);
    console.log(request.url); //basic console.log
    console.log(filename);
    fs.exists(filename,function(exists){
        if(!exists){
            response.writeHeader(404, {'Content-Type': 'text/plain'});
            response.write('404 Not Found\n');
            response.end();
            return;
        }
        if(fs.lstatSync(filename).isDirectory()) {
            response.writeHead(301, {'Location': path.join(process.cwd(),'index.html') });
            response.end();
            return;
        }
        var type = filename.split('.');
        type = type[type.length - 1];
        response.writeHead(200, { 'Content-Type': (types[type] || types['bin']) + '; charset=utf-8' });
        fs.createReadStream(filename).pipe(response);
    });
}).listen(parseInt(port, 10));
<commit_msg>Added audio and video media types<commit_after>//http://www.hongkiat.com/blog/node-js-server-side-javascript/
//http://stackoverflow.com/questions/6084360/node-js-as-a-simple-web-server
//https://github.com/requirejs/example-jquery-cdn/blob/master/tools/server.js

//Install: add --debug=8081 in Node parameters

var http = require('http'),
    path = require('path'),
    url = require('url'),
    fs = require('fs'),
    port = parseInt(process.argv[3], 10) || parseInt(process.argv[2], 10) || 8080,
    types = {
        'html'  : 'text/html',
        'txt'   : 'text/plain',
        'css'   : 'text/css',
        'js'    : 'text/javascript',
        'ico'   : 'image/x-icon',
        'jpg'   : 'image/jpeg',
        'png'   : 'image/png',
        'gif'   : 'image/gif',
        'svg'   : 'image/svg+xml',
        'json'  : 'application/json',
        'xml'   : 'text/xml',
        'bin'   : 'application/octet-stream',
        'mp3'   : 'audio/mpeg',
        'ogg'   : 'audio/ogg',
        'mp4'   : 'video/mpeg',
        'ogv'   : 'video/ogg',
        'webm'   : 'video/webm',
        'ttf'  : 'font/ttf',
        'woff'  : 'font/woff'
    };

console.log('Server Running on port ' + port.toString() + '\n');

module.exports = http.createServer(function(request,response){
    //debugger;
    var uri = url.parse(request.url).pathname,
        filename = path.join(process.cwd(),uri);
    console.log(request.url); //basic console.log
    console.log(filename);
    fs.exists(filename,function(exists){
        if(!exists){
            response.writeHeader(404, {'Content-Type': 'text/plain'});
            response.write('404 Not Found\n');
            response.end();
            return;
        }
        if(fs.lstatSync(filename).isDirectory()) {
            response.writeHead(301, {'Location': path.join(process.cwd(),'index.html') });
            response.end();
            return;
        }
        var type = filename.split('.');
        type = type[type.length - 1];
        response.writeHead(200, { 'Content-Type': (types[type] || types['bin']) + '; charset=utf-8' });
        fs.createReadStream(filename).pipe(response);
    });
}).listen(parseInt(port, 10));
<|endoftext|>


<commit_before>function transformState(activity, lastBuildStatus) {
    var state = '';
    if (lastBuildStatus == 'Success') {
        state = 'healthy';
    } else if (lastBuildStatus == 'Failure') {
        state = 'sick';
    } else if (lastBuildStatus == 'Sleeping') {
        state = 'waiting';
    } else if (lastBuildStatus == 'Unknown') {
        state = 'unknown';
    }
    if ((state == 'unknown') && activity == "Building") {
        state = 'healthy-building';
    } else if ((state != 'unknown') && activity == "Building") {
        state = state + '-building';
    }
    return state;
}

function updateCache(pipelines, hiddenPrefix, defautHiddenSteps, cache, asynCall) {
    $.each(pipelines, function(pipelineName, pipeline) {
        var hiddenSteps = pipeline['hiddenSteps'];
        var cctrayUrl = pipeline['cctrayUrl'];
        var guiURL = pipeline['guiUrl'];
        var guiURL = pipeline['visibleWaitingSteps'];
        $.ajax({
                    type: 'GET',
                    url: cctrayUrl,
                    success: function (response) {
                        var newProjectCache = new Array();
                        $(response).find('Project').each(function (project) {
                            var name = $(this).attr('name');
                            var activity = $(this).attr('activity');
                            var lastBuildStatus = $(this).attr('lastBuildStatus');
                            var newState = transformState(activity, lastBuildStatus);
                            var cacheEntry = [];
                            //var keyName = pipeline['displayName'] + '-' + name;
                            cacheEntry['stepName'] = name;
                            cacheEntry['pipelineName'] = pipelineName;
                            cacheEntry['state'] = newState;
                            cacheEntry['visible'] = ($.inArray(name, hiddenSteps) == -1) &&
                                                    ($.inArray(name, defautHiddenSteps) == -1) &&
                                                    !(name.startsWith(hiddenPrefix)) &&
                                                    ($.inArray(name, visibleWaitingSteps) != -1);
                            cacheEntry['guiURL'] = guiURL;
                            newProjectCache.push(cacheEntry);
                        });
                        cache[pipelineName] = newProjectCache;
                    },
                    error: function (response) {
                        var newProjectCache = new Array();
                        var cacheEntry = [];
                        cacheEntry['stepName'] = '';
                        cacheEntry['pipelineName'] = pipelineName;
                        cacheEntry['state'] = 'sick';
                        cacheEntry['visible'] = true;
                        cacheEntry['guiURL'] = guiURL;
                        newProjectCache.push(cacheEntry);
                        cache[pipelineName] = newProjectCache;
                    }
                    ,
                    dataType: 'xml',
                    crossDomain: true,
                    async: asynCall
                }
        )
        ;
    });
}<commit_msg>fix variable name<commit_after>function transformState(activity, lastBuildStatus) {
    var state = '';
    if (lastBuildStatus == 'Success') {
        state = 'healthy';
    } else if (lastBuildStatus == 'Failure') {
        state = 'sick';
    } else if (lastBuildStatus == 'Sleeping') {
        state = 'waiting';
    } else if (lastBuildStatus == 'Unknown') {
        state = 'unknown';
    }
    if ((state == 'unknown') && activity == "Building") {
        state = 'healthy-building';
    } else if ((state != 'unknown') && activity == "Building") {
        state = state + '-building';
    }
    return state;
}

function updateCache(pipelines, hiddenPrefix, defautHiddenSteps, cache, asynCall) {
    $.each(pipelines, function(pipelineName, pipeline) {
        var hiddenSteps = pipeline['hiddenSteps'];
        var cctrayUrl = pipeline['cctrayUrl'];
        var guiURL = pipeline['guiUrl'];
        var visibleWaitingSteps = pipeline['visibleWaitingSteps'];
        $.ajax({
                    type: 'GET',
                    url: cctrayUrl,
                    success: function (response) {
                        var newProjectCache = new Array();
                        $(response).find('Project').each(function (project) {
                            var name = $(this).attr('name');
                            var activity = $(this).attr('activity');
                            var lastBuildStatus = $(this).attr('lastBuildStatus');
                            var newState = transformState(activity, lastBuildStatus);
                            var cacheEntry = [];
                            //var keyName = pipeline['displayName'] + '-' + name;
                            cacheEntry['stepName'] = name;
                            cacheEntry['pipelineName'] = pipelineName;
                            cacheEntry['state'] = newState;
                            cacheEntry['visible'] = ($.inArray(name, hiddenSteps) == -1) &&
                                                    ($.inArray(name, defautHiddenSteps) == -1) &&
                                                    !(name.startsWith(hiddenPrefix)) &&
                                                    ($.inArray(name, visibleWaitingSteps) != -1);
                            cacheEntry['guiURL'] = guiURL;
                            newProjectCache.push(cacheEntry);
                        });
                        cache[pipelineName] = newProjectCache;
                    },
                    error: function (response) {
                        var newProjectCache = new Array();
                        var cacheEntry = [];
                        cacheEntry['stepName'] = '';
                        cacheEntry['pipelineName'] = pipelineName;
                        cacheEntry['state'] = 'sick';
                        cacheEntry['visible'] = true;
                        cacheEntry['guiURL'] = guiURL;
                        newProjectCache.push(cacheEntry);
                        cache[pipelineName] = newProjectCache;
                    }
                    ,
                    dataType: 'xml',
                    crossDomain: true,
                    async: asynCall
                }
        )
        ;
    });
}<|endoftext|>


<commit_before>var Upvote = (function (window, document) {

	that = this;

	// endEvent = hasTouch ? 'touchend' : 'mouseup',

	Upvote = function (opts) {

		that = this;

		this.current_category = 'us';

		// ---------------------------------------------------------
		// Muench launch
		// ---------------------------------------------------------

		// Options from user
		for (i in opts) this.options[i] = opts[i];

		// ---------------------------------------------------------
		// Skimmin launch
		// ---------------------------------------------------------

        	$('.upvote-container').on('click', this.fn_tap_upvote.bind(this));
        	$('.category-container').on('click', this.fn_change_category.bind(this));

		window.addEventListener('load', function() {
		    FastClick.attach(document.body);
		}, false);

		this.fn_hide_rendering_icons();
		this.fn_loading();
       		this.fn_reveal_content();

    	};

	Upvote.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        	// primarily used to hide slow rendering
        	fn_loading: function() {

            	that = this;

            	$('#L').fadeIn(0);
            	$('#L').addClass('animated zoomIn');

            	setTimeout(function() {
            		$('#O').fadeIn(0);
            		$('#O').addClass('animated zoomIn');
            	}, 65);

            	setTimeout(function() {
            		$('#A').fadeIn(0);
            		$('#A').addClass('animated zoomIn');
            	}, 130);

            	setTimeout(function() {
            		$('#D').fadeIn(0);
            		$('#D').addClass('animated zoomIn');
            	}, 195);

            	setTimeout(function() {
            		$('#I').fadeIn(0);
            		$('#I').addClass('animated zoomIn');
            	}, 260);

            	setTimeout(function() {
            		$('#N').fadeIn(0);
            		$('#N').addClass('animated zoomIn');
            	}, 325);

            	setTimeout(function() {
            		$('#G').fadeIn(0);
            		$('#G').addClass('animated zoomIn');
            	}, 390);

            	/*setTimeout(function(){
            		$('#L').css('opacity', '.5');
            	}, 1200);

            	setTimeout(function() {
            		$('#L').css('opacity', '1');
            		$('#O').css('opacity', '.5');
            	}, 1400);

            	setTimeout(function() {
            		$('#O').css('opacity', '1');
            		$('#A').css('opacity', '.5');
            	}, 1600);

            	setTimeout(function() {
            		$('#A').css('opacity', '1');
            		$('#D').css('opacity', '.5');
            	}, 1800);

            	setTimeout(function() {
            		$('#D').css('opacity', '1');
            		$('#I').css('opacity', '.5');
            	}, 2000);

            	setTimeout(function() {
            		$('#I').css('opacity', '1');
            		$('#N').css('opacity', '.5');
            	}, 2200);

            	setTimeout(function() {
            		$('#N').css('opacity', '1');
            		$('#G').css('opacity', '.5');
            	}, 2400);

            	setTimeout(function() {
            		$('#G').css('opacity', '1');
            	}, 2600);*/

            	setTimeout(function(){
            		$('#loading-container').css('opacity', '.3');
            	}, 1300);
        	setTimeout(function(){
        		$('#loading-container').css('opacity', '1');
       		}, 2500);

       		setTimeout(function(){
            		$('#loading-container').css('opacity', '.3');
            	}, 3700);
        	setTimeout(function(){
        		$('#loading-container').css('opacity', '1');
       		}, 4900);

       		setTimeout(function(){
            		$('#loading-container').css('opacity', '.3');
            	}, 6100);
        	setTimeout(function(){
        		$('#loading-container').css('opacity', '1');
       		}, 7300);

            	setTimeout(function() {
        		$('#loading-container').fadeOut(300);
        	}, 8500);
        	setTimeout(function() {
        		$('#content').fadeIn(0);
        		$('#content').addClass('animated bounceInUp');
        	}, 8750);

        	},

        	fn_reveal_content: function() {

        		/*setTimeout(function() {
        			$('#loading-circle').addClass('animated zoomOut');
        			$('#content').addClass('animated slideInUp');
        		}, 300);*/

        	},

        	fn_hide_rendering_icons: function() {

        		setTimeout(function() {
        			$('.rendering-container').addClass('display-none');
        		}, 3000);

        	},

        	fn_change_category: function(e) {

        		if (this.current_category == 'world') {
        			$('#category-container').removeClass('world')
        			$('#category-container').addClass('us');
        			$('#category-text').html('us');
        			this.current_category = 'us';
        		}

        		else if (this.current_category == 'us') {
        			$('#category-container').removeClass('us')
        			$('#category-container').addClass('sports');
        			$('#category-text').html('sports');
        			this.current_category = 'sports';
        		}

        		else if (this.current_category == 'sports') {
        			$('#category-container').removeClass('sports')
        			$('#category-container').addClass('business');
        			$('#category-text').html('business');
        			this.current_category = 'business';
        		}

        		else if (this.current_category == 'business') {
        			$('#category-container').removeClass('business')
        			$('#category-container').addClass('technology');
        			$('#category-text').html('technology');
        			this.current_category = 'technology';
        		}

        		else if (this.current_category == 'technology') {
        			$('#category-container').removeClass('technology')
        			$('#category-container').addClass('entertainment');
        			$('#category-text').html('entertainment');
        			this.current_category = 'entertainment';
        		}

        		else {
        			$('#category-container').removeClass('entertainment')
        			$('#category-container').addClass('world');
        			$('#category-text').html('world');
        			this.current_category = 'world';
        		}

        		if ($('.upvote-container').hasClass('upvoted') == true) {
        			$('.upvote-container').removeClass('us world sports business technology entertainment');
        			$('.upvote-text').removeClass('us world sports business technology entertainment');
        			$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			$('.upvote-container').addClass(this.current_category);
        			$('.upvote-text').addClass(this.current_category);
        			$('.upvote-icon').addClass(this.current_category);
        		}

        	},

		fn_tap_upvote: function() {

			if ($('.upvote-container').hasClass('upvoted') == true) {

				$('.upvote-container').removeClass('upvoted');

				setTimeout(function() {
        				$('.upvote-container').removeClass('tapped us world sports business technology entertainment');
        				$('.upvote-text').removeClass('us world sports business technology entertainment');
        				$('.upvote-text').html(30);
        				$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			}, 300);
        		}

			else {

				$('.upvote-container').addClass('upvoted');
    				setTimeout(function() {
        				$('.upvote-container').addClass('tapped ' + that.current_category);
        				$('.upvote-text').addClass(that.current_category);
        				$('.upvote-text').html(31);
        				$('.upvote-icon').addClass(that.current_category);
    				}, 300);
			}

		},

	};

	return Upvote;

})(window, document);
<commit_msg>Update upvote.js<commit_after>var Upvote = (function (window, document) {

	that = this;

	// endEvent = hasTouch ? 'touchend' : 'mouseup',

	Upvote = function (opts) {

		that = this;

		this.current_category = 'us';

		// ---------------------------------------------------------
		// Muench launch
		// ---------------------------------------------------------

		// Options from user
		for (i in opts) this.options[i] = opts[i];

		// ---------------------------------------------------------
		// Skimmin launch
		// ---------------------------------------------------------

        	$('.upvote-container').on('click', this.fn_tap_upvote.bind(this));
        	$('.category-container').on('click', this.fn_change_category.bind(this));

		window.addEventListener('load', function() {
		    FastClick.attach(document.body);
		}, false);

		this.fn_hide_rendering_icons();
		this.fn_loading();
       		this.fn_reveal_content();

    	};

	Upvote.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        	// primarily used to hide slow rendering
        	fn_loading: function() {

            	that = this;

            	$('#L').fadeIn(0);
            	$('#L').addClass('animated zoomIn');

            	setTimeout(function() {
            		$('#O').fadeIn(0);
            		$('#O').addClass('animated zoomIn');
            	}, 65);

            	setTimeout(function() {
            		$('#A').fadeIn(0);
            		$('#A').addClass('animated zoomIn');
            	}, 130);

            	setTimeout(function() {
            		$('#D').fadeIn(0);
            		$('#D').addClass('animated zoomIn');
            	}, 195);

            	setTimeout(function() {
            		$('#I').fadeIn(0);
            		$('#I').addClass('animated zoomIn');
            	}, 260);

            	setTimeout(function() {
            		$('#N').fadeIn(0);
            		$('#N').addClass('animated zoomIn');
            	}, 325);

            	setTimeout(function() {
            		$('#G').fadeIn(0);
            		$('#G').addClass('animated zoomIn');
            	}, 390);

            	/*setTimeout(function(){
            		$('#L').css('opacity', '.5');
            	}, 1200);

            	setTimeout(function() {
            		$('#L').css('opacity', '1');
            		$('#O').css('opacity', '.5');
            	}, 1400);

            	setTimeout(function() {
            		$('#O').css('opacity', '1');
            		$('#A').css('opacity', '.5');
            	}, 1600);

            	setTimeout(function() {
            		$('#A').css('opacity', '1');
            		$('#D').css('opacity', '.5');
            	}, 1800);

            	setTimeout(function() {
            		$('#D').css('opacity', '1');
            		$('#I').css('opacity', '.5');
            	}, 2000);

            	setTimeout(function() {
            		$('#I').css('opacity', '1');
            		$('#N').css('opacity', '.5');
            	}, 2200);

            	setTimeout(function() {
            		$('#N').css('opacity', '1');
            		$('#G').css('opacity', '.5');
            	}, 2400);

            	setTimeout(function() {
            		$('#G').css('opacity', '1');
            	}, 2600);*/

            	setTimeout(function(){
            		$('#loading-container').css('opacity', '.3');
            	}, 1300);
        	setTimeout(function(){
        		$('#loading-container').css('opacity', '1');
       		}, 2500);

       		setTimeout(function(){
            		$('#loading-container').css('opacity', '.3');
            	}, 3700);
        	setTimeout(function(){
        		$('#loading-container').css('opacity', '1');
       		}, 4900);

       		setTimeout(function(){
            		$('#loading-container').css('opacity', '.3');
            	}, 6100);
        	setTimeout(function(){
        		$('#loading-container').css('opacity', '1');
       		}, 7300);

            	setTimeout(function() {
        		// $('#loading-container').fadeOut(300);
        		$('#loading-container').addClass('animated zoomOut');
        	}, 8500);
        	setTimeout(function() {
        		$('#content').fadeIn(0);
        		$('#content').addClass('animated bounceInUp');
        	}, 8750);

        	},

        	fn_reveal_content: function() {

        		/*setTimeout(function() {
        			$('#loading-circle').addClass('animated zoomOut');
        			$('#content').addClass('animated slideInUp');
        		}, 300);*/

        	},

        	fn_hide_rendering_icons: function() {

        		setTimeout(function() {
        			$('.rendering-container').addClass('display-none');
        		}, 3000);

        	},

        	fn_change_category: function(e) {

        		if (this.current_category == 'world') {
        			$('#category-container').removeClass('world')
        			$('#category-container').addClass('us');
        			$('#category-text').html('us');
        			this.current_category = 'us';
        		}

        		else if (this.current_category == 'us') {
        			$('#category-container').removeClass('us')
        			$('#category-container').addClass('sports');
        			$('#category-text').html('sports');
        			this.current_category = 'sports';
        		}

        		else if (this.current_category == 'sports') {
        			$('#category-container').removeClass('sports')
        			$('#category-container').addClass('business');
        			$('#category-text').html('business');
        			this.current_category = 'business';
        		}

        		else if (this.current_category == 'business') {
        			$('#category-container').removeClass('business')
        			$('#category-container').addClass('technology');
        			$('#category-text').html('technology');
        			this.current_category = 'technology';
        		}

        		else if (this.current_category == 'technology') {
        			$('#category-container').removeClass('technology')
        			$('#category-container').addClass('entertainment');
        			$('#category-text').html('entertainment');
        			this.current_category = 'entertainment';
        		}

        		else {
        			$('#category-container').removeClass('entertainment')
        			$('#category-container').addClass('world');
        			$('#category-text').html('world');
        			this.current_category = 'world';
        		}

        		if ($('.upvote-container').hasClass('upvoted') == true) {
        			$('.upvote-container').removeClass('us world sports business technology entertainment');
        			$('.upvote-text').removeClass('us world sports business technology entertainment');
        			$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			$('.upvote-container').addClass(this.current_category);
        			$('.upvote-text').addClass(this.current_category);
        			$('.upvote-icon').addClass(this.current_category);
        		}

        	},

		fn_tap_upvote: function() {

			if ($('.upvote-container').hasClass('upvoted') == true) {

				$('.upvote-container').removeClass('upvoted');

				setTimeout(function() {
        				$('.upvote-container').removeClass('tapped us world sports business technology entertainment');
        				$('.upvote-text').removeClass('us world sports business technology entertainment');
        				$('.upvote-text').html(30);
        				$('.upvote-icon').removeClass('us world sports business technology entertainment');
        			}, 300);
        		}

			else {

				$('.upvote-container').addClass('upvoted');
    				setTimeout(function() {
        				$('.upvote-container').addClass('tapped ' + that.current_category);
        				$('.upvote-text').addClass(that.current_category);
        				$('.upvote-text').html(31);
        				$('.upvote-icon').addClass(that.current_category);
    				}, 300);
			}

		},

	};

	return Upvote;

})(window, document);
<|endoftext|>