<commit_before>
/* Copyright (C) 2013 Justin Windle, http://soulwire.co.uk */

(function (root, factory) {
    if (typeof exports === 'object') {

        // CommonJS like
        module.exports = factory(root, root.document);

    } else if (typeof define === 'function' && define.amd) {

        // AMD
        define(function() { return factory(root, root.document); });

    } else {

        // Browser global
        root.Sketch = factory(root, root.document);

    }

}(this, function (window, document) {

    var Sketch = (function(window, document) {

        "use strict";

        /*
        ----------------------------------------------------------------------

            Config

        ----------------------------------------------------------------------
        */

        var MATH_PROPS = 'E LN10 LN2 LOG2E LOG10E PI SQRT1_2 SQRT2 abs acos asin atan ceil cos exp floor log round sin sqrt tan atan2 pow max min'.split( ' ' );
        var HAS_SKETCH = '__hasSketch';
        var M = Math;

        var CANVAS = 'canvas';
        var WEBGL = 'webgl';
        var DOM = 'dom';

        var doc = document;
        var win = window;

        var instances = [];

        var defaults = {

            fullscreen: true,
            autostart: true,
            autoclear: true,
            autopause: true,
            container: doc.body,
            interval: 1,
            globals: true,
            retina: false,
            type: CANVAS
        };

        var keyMap = {

             8: 'BACKSPACE',
             9: 'TAB',
            13: 'ENTER',
            16: 'SHIFT',
            27: 'ESCAPE',
            32: 'SPACE',
            37: 'LEFT',
            38: 'UP',
            39: 'RIGHT',
            40: 'DOWN'
        };

        /*
        ----------------------------------------------------------------------

            Utilities

        ----------------------------------------------------------------------
        */

        function isArray( object ) {

            return Object.prototype.toString.call( object ) == '[object Array]';
        }

        function isFunction( object ) {

            return typeof object == 'function';
        }

        function isNumber( object ) {

            return typeof object == 'number';
        }

        function isString( object ) {

            return typeof object == 'string';
        }

        function keyName( code ) {

            return keyMap[ code ] || String.fromCharCode( code );
        }

        function extend( target, source, overwrite ) {

            for ( var key in source )

                if ( overwrite || !( key in target ) )

                    target[ key ] = source[ key ];

            return target;
        }

        function proxy( method, context ) {

            return function() {

                method.apply( context, arguments );
            };
        }

        function clone( target ) {

            var object = {};

            for ( var key in target ) {

                if ( isFunction( target[ key ] ) )

                    object[ key ] = proxy( target[ key ], target );

                else

                    object[ key ] = target[ key ];
            }

            return object;
        }

        /*
        ----------------------------------------------------------------------

            Constructor

        ----------------------------------------------------------------------
        */

        function constructor( context ) {

            var request, handler, target, parent, bounds, index, suffix, clock, node, copy, type, key, val, min, max, w, h;

            var counter = 0;
            var touches = [];
            var resized = false;
            var setup = false;
            var ratio = win.devicePixelRatio;
            var isDiv = context.type == DOM;
            var is2D = context.type == CANVAS;

            var mouse = {
                x:  0.0, y:  0.0,
                ox: 0.0, oy: 0.0,
                dx: 0.0, dy: 0.0
            };

            var eventMap = [

                context.element,

                    pointer, 'mousedown', 'touchstart',
                    pointer, 'mousemove', 'touchmove',
                    pointer, 'mouseup', 'touchend',
                    pointer, 'click',

                doc,

                    keypress, 'keydown', 'keyup',

                win,

                    active, 'focus', 'blur',
                    resize, 'resize'
            ];

            var keys = {}; for ( key in keyMap ) keys[ keyMap[ key ] ] = false;

            function trigger( method ) {

                if ( isFunction( method ) )

                    method.apply( context, [].splice.call( arguments, 1 ) );
            }

            function bind( on ) {

                for ( index = 0; index < eventMap.length; index++ ) {

                    node = eventMap[ index ];

                    if ( isString( node ) )

                        target[ ( on ? 'add' : 'remove' ) + 'EventListener' ].call( target, node, handler, false );

                    else if ( isFunction( node ) )

                        handler = node;

                    else target = node;
                }
            }

            function update() {

                cAF( request );
                request = rAF( update );

                if ( !setup ) {

                    trigger( context.setup );
                    setup = isFunction( context.setup );
                }

                if ( !resized ) {
                    trigger( context.resize );
                    resized = isFunction( context.resize );
                }

                if ( context.running && !counter ) {

                    context.dt = ( clock = +new Date() ) - context.now;
                    context.millis += context.dt;
                    context.now = clock;

                    trigger( context.update );

                    if ( context.autoclear && is2D )

                        context.clear();

                    trigger( context.draw );
                }

                counter = ++counter % context.interval;
            }

            function resize() {

                target = isDiv ? context.style : context.canvas;
                suffix = isDiv ? 'px' : '';

                w = context.width;
                h = context.height;

                if ( context.fullscreen ) {

                    h = context.height = win.innerHeight;
                    w = context.width = win.innerWidth;
                }

                if ( context.retina && is2D && ratio ) {

                    target.style.height = h + 'px';
                    target.style.width = w + 'px';

                    w *= ratio;
                    h *= ratio;

                    context.scale( ratio, ratio );
                }

                if ( target.height !== h )

                    target.height = h + suffix;

                if ( target.width !== w )

                    target.width = w + suffix;

                if ( setup ) trigger( context.resize );
            }

            function align( touch, target ) {

                bounds = target.getBoundingClientRect();

                touch.x = touch.pageX - bounds.left - win.scrollX;
                touch.y = touch.pageY - bounds.top - win.scrollY;

                return touch;
            }

            function augment( touch, target ) {

                align( touch, context.element );

                target = target || {};

                target.ox = target.x || touch.x;
                target.oy = target.y || touch.y;

                target.x = touch.x;
                target.y = touch.y;

                target.dx = target.x - target.ox;
                target.dy = target.y - target.oy;

                return target;
            }

            function process( event ) {

                event.preventDefault();

                copy = clone( event );
                copy.originalEvent = event;

                if ( copy.touches ) {

                    touches.length = copy.touches.length;

                    for ( index = 0; index < copy.touches.length; index++ )

                        touches[ index ] = augment( copy.touches[ index ], touches[ index ] );

                } else {

                    touches.length = 0;
                    touches[0] = augment( copy, mouse );
                }

                extend( mouse, touches[0], true );

                return copy;
            }

            function pointer( event ) {

                event = process( event );

                min = ( max = eventMap.indexOf( type = event.type ) ) - 1;

                context.dragging =

                    /down|start/.test( type ) ? true :

                    /up|end/.test( type ) ? false :

                    context.dragging;

                while( min )

                    isString( eventMap[ min ] ) ?

                        trigger( context[ eventMap[ min-- ] ], event ) :

                    isString( eventMap[ max ] ) ?

                        trigger( context[ eventMap[ max++ ] ], event ) :

                    min = 0;
            }

            function keypress( event ) {

                key = event.keyCode;
                val = event.type == 'keyup';
                keys[ key ] = keys[ keyName( key ) ] = !val;

                trigger( context[ event.type ], event );
            }

            function active( event ) {

                if ( context.autopause )

                    ( event.type == 'blur' ? stop : start )();

                trigger( context[ event.type ], event );
            }

            // Public API

            function start() {

                context.now = +new Date();
                context.running = true;
            }

            function stop() {

                context.running = false;
            }

            function toggle() {

                ( context.running ? stop : start )();
            }

            function clear() {

                if ( is2D )

                    context.clearRect( 0, 0, context.width, context.height );
            }

            function destroy() {

                parent = context.element.parentNode;
                index = instances.indexOf( context );

                if ( parent ) parent.removeChild( context.element );
                if ( ~index ) instances.splice( index, 1 );

                bind( false );
                stop();
            }

            extend( context, {

                touches: touches,
                mouse: mouse,
                keys: keys,

                dragging: false,
                running: false,
                millis: 0,
                now: NaN,
                dt: NaN,

                destroy: destroy,
                toggle: toggle,
                clear: clear,
                start: start,
                stop: stop
            });

            instances.push( context );

            return ( context.autostart && start(), bind( true ), resize(), update(), context );
        }

        /*
        ----------------------------------------------------------------------

            Global API

        ----------------------------------------------------------------------
        */

        var element, context, Sketch = {

            CANVAS: CANVAS,
            WEB_GL: WEBGL,
            WEBGL: WEBGL,
            DOM: DOM,

            instances: instances,

            install: function( context ) {

                if ( !context[ HAS_SKETCH ] ) {

                    for ( var i = 0; i < MATH_PROPS.length; i++ )

                        context[ MATH_PROPS[i] ] = M[ MATH_PROPS[i] ];

                    extend( context, {

                        TWO_PI: M.PI * 2,
                        HALF_PI: M.PI / 2,
                        QUATER_PI: M.PI / 4,

                        random: function( min, max ) {

                            if ( isArray( min ) )

                                return min[ ~~( M.random() * min.length ) ];

                            if ( !isNumber( max ) )

                                max = min || 1, min = 0;

                            return min + M.random() * ( max - min );
                        },

                        lerp: function( min, max, amount ) {

                            return min + amount * ( max - min );
                        },

                        map: function( num, minA, maxA, minB, maxB ) {

                            return ( num - minA ) / ( maxA - minA ) * ( maxB - minB ) + minB;
                        }
                    });

                    context[ HAS_SKETCH ] = true;
                }
            },

            create: function( options ) {

                options = extend( options || {}, defaults );

                if ( options.globals ) Sketch.install( self );

                element = options.element = options.element || doc.createElement( options.type === DOM ? 'div' : 'canvas' );

                context = options.context = options.context || (function() {

                    switch( options.type ) {

                        case CANVAS:

                            return element.getContext( '2d', options );

                        case WEBGL:

                            return element.getContext( 'webgl', options ) || element.getContext( 'experimental-webgl', options );

                        case DOM:

                            return element.canvas = element;
                    }

                })();

                ( options.container || doc.body ).appendChild( element );

                return Sketch.augment( context, options );
            },

            augment: function( context, options ) {

                options = extend( options || {}, defaults );

                options.element = context.canvas || context;
                options.element.className += ' sketch';

                extend( context, options, true );

                return constructor( context );
            }
        };

        /*
        ----------------------------------------------------------------------

            Shims

        ----------------------------------------------------------------------
        */

        var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
        var scope = self;
        var then = 0;

        var a = 'AnimationFrame';
        var b = 'request' + a;
        var c = 'cancel' + a;

        var rAF = scope[ b ];
        var cAF = scope[ c ];

        for ( var i = 0; i < vendors.length && !rAF; i++ ) {

            rAF = scope[ vendors[ i ] + 'Request' + a ];
            cAF = scope[ vendors[ i ] + 'Cancel' + a ];
        }

        scope[ b ] = rAF = rAF || function( callback ) {

            var now = +new Date();
            var dt = M.max( 0, 16 - ( now - then ) );
            var id = setTimeout( function() {
                callback( now + dt );
            }, dt );

            then = now + dt;
            return id;
        };

        scope[ c ] = cAF = cAF || function( id ) {
            clearTimeout( id );
        };

        /*
        ----------------------------------------------------------------------

            Output

        ----------------------------------------------------------------------
        */

        return Sketch;

})(window, document);

    return Sketch;

}));
<commit_msg>Fix closing function indent<commit_after>
/* Copyright (C) 2013 Justin Windle, http://soulwire.co.uk */

(function (root, factory) {
    if (typeof exports === 'object') {

        // CommonJS like
        module.exports = factory(root, root.document);

    } else if (typeof define === 'function' && define.amd) {

        // AMD
        define(function() { return factory(root, root.document); });

    } else {

        // Browser global
        root.Sketch = factory(root, root.document);

    }

}(this, function (window, document) {

    var Sketch = (function(window, document) {

        "use strict";

        /*
        ----------------------------------------------------------------------

            Config

        ----------------------------------------------------------------------
        */

        var MATH_PROPS = 'E LN10 LN2 LOG2E LOG10E PI SQRT1_2 SQRT2 abs acos asin atan ceil cos exp floor log round sin sqrt tan atan2 pow max min'.split( ' ' );
        var HAS_SKETCH = '__hasSketch';
        var M = Math;

        var CANVAS = 'canvas';
        var WEBGL = 'webgl';
        var DOM = 'dom';

        var doc = document;
        var win = window;

        var instances = [];

        var defaults = {

            fullscreen: true,
            autostart: true,
            autoclear: true,
            autopause: true,
            container: doc.body,
            interval: 1,
            globals: true,
            retina: false,
            type: CANVAS
        };

        var keyMap = {

             8: 'BACKSPACE',
             9: 'TAB',
            13: 'ENTER',
            16: 'SHIFT',
            27: 'ESCAPE',
            32: 'SPACE',
            37: 'LEFT',
            38: 'UP',
            39: 'RIGHT',
            40: 'DOWN'
        };

        /*
        ----------------------------------------------------------------------

            Utilities

        ----------------------------------------------------------------------
        */

        function isArray( object ) {

            return Object.prototype.toString.call( object ) == '[object Array]';
        }

        function isFunction( object ) {

            return typeof object == 'function';
        }

        function isNumber( object ) {

            return typeof object == 'number';
        }

        function isString( object ) {

            return typeof object == 'string';
        }

        function keyName( code ) {

            return keyMap[ code ] || String.fromCharCode( code );
        }

        function extend( target, source, overwrite ) {

            for ( var key in source )

                if ( overwrite || !( key in target ) )

                    target[ key ] = source[ key ];

            return target;
        }

        function proxy( method, context ) {

            return function() {

                method.apply( context, arguments );
            };
        }

        function clone( target ) {

            var object = {};

            for ( var key in target ) {

                if ( isFunction( target[ key ] ) )

                    object[ key ] = proxy( target[ key ], target );

                else

                    object[ key ] = target[ key ];
            }

            return object;
        }

        /*
        ----------------------------------------------------------------------

            Constructor

        ----------------------------------------------------------------------
        */

        function constructor( context ) {

            var request, handler, target, parent, bounds, index, suffix, clock, node, copy, type, key, val, min, max, w, h;

            var counter = 0;
            var touches = [];
            var resized = false;
            var setup = false;
            var ratio = win.devicePixelRatio;
            var isDiv = context.type == DOM;
            var is2D = context.type == CANVAS;

            var mouse = {
                x:  0.0, y:  0.0,
                ox: 0.0, oy: 0.0,
                dx: 0.0, dy: 0.0
            };

            var eventMap = [

                context.element,

                    pointer, 'mousedown', 'touchstart',
                    pointer, 'mousemove', 'touchmove',
                    pointer, 'mouseup', 'touchend',
                    pointer, 'click',

                doc,

                    keypress, 'keydown', 'keyup',

                win,

                    active, 'focus', 'blur',
                    resize, 'resize'
            ];

            var keys = {}; for ( key in keyMap ) keys[ keyMap[ key ] ] = false;

            function trigger( method ) {

                if ( isFunction( method ) )

                    method.apply( context, [].splice.call( arguments, 1 ) );
            }

            function bind( on ) {

                for ( index = 0; index < eventMap.length; index++ ) {

                    node = eventMap[ index ];

                    if ( isString( node ) )

                        target[ ( on ? 'add' : 'remove' ) + 'EventListener' ].call( target, node, handler, false );

                    else if ( isFunction( node ) )

                        handler = node;

                    else target = node;
                }
            }

            function update() {

                cAF( request );
                request = rAF( update );

                if ( !setup ) {

                    trigger( context.setup );
                    setup = isFunction( context.setup );
                }

                if ( !resized ) {
                    trigger( context.resize );
                    resized = isFunction( context.resize );
                }

                if ( context.running && !counter ) {

                    context.dt = ( clock = +new Date() ) - context.now;
                    context.millis += context.dt;
                    context.now = clock;

                    trigger( context.update );

                    if ( context.autoclear && is2D )

                        context.clear();

                    trigger( context.draw );
                }

                counter = ++counter % context.interval;
            }

            function resize() {

                target = isDiv ? context.style : context.canvas;
                suffix = isDiv ? 'px' : '';

                w = context.width;
                h = context.height;

                if ( context.fullscreen ) {

                    h = context.height = win.innerHeight;
                    w = context.width = win.innerWidth;
                }

                if ( context.retina && is2D && ratio ) {

                    target.style.height = h + 'px';
                    target.style.width = w + 'px';

                    w *= ratio;
                    h *= ratio;

                    context.scale( ratio, ratio );
                }

                if ( target.height !== h )

                    target.height = h + suffix;

                if ( target.width !== w )

                    target.width = w + suffix;

                if ( setup ) trigger( context.resize );
            }

            function align( touch, target ) {

                bounds = target.getBoundingClientRect();

                touch.x = touch.pageX - bounds.left - win.scrollX;
                touch.y = touch.pageY - bounds.top - win.scrollY;

                return touch;
            }

            function augment( touch, target ) {

                align( touch, context.element );

                target = target || {};

                target.ox = target.x || touch.x;
                target.oy = target.y || touch.y;

                target.x = touch.x;
                target.y = touch.y;

                target.dx = target.x - target.ox;
                target.dy = target.y - target.oy;

                return target;
            }

            function process( event ) {

                event.preventDefault();

                copy = clone( event );
                copy.originalEvent = event;

                if ( copy.touches ) {

                    touches.length = copy.touches.length;

                    for ( index = 0; index < copy.touches.length; index++ )

                        touches[ index ] = augment( copy.touches[ index ], touches[ index ] );

                } else {

                    touches.length = 0;
                    touches[0] = augment( copy, mouse );
                }

                extend( mouse, touches[0], true );

                return copy;
            }

            function pointer( event ) {

                event = process( event );

                min = ( max = eventMap.indexOf( type = event.type ) ) - 1;

                context.dragging =

                    /down|start/.test( type ) ? true :

                    /up|end/.test( type ) ? false :

                    context.dragging;

                while( min )

                    isString( eventMap[ min ] ) ?

                        trigger( context[ eventMap[ min-- ] ], event ) :

                    isString( eventMap[ max ] ) ?

                        trigger( context[ eventMap[ max++ ] ], event ) :

                    min = 0;
            }

            function keypress( event ) {

                key = event.keyCode;
                val = event.type == 'keyup';
                keys[ key ] = keys[ keyName( key ) ] = !val;

                trigger( context[ event.type ], event );
            }

            function active( event ) {

                if ( context.autopause )

                    ( event.type == 'blur' ? stop : start )();

                trigger( context[ event.type ], event );
            }

            // Public API

            function start() {

                context.now = +new Date();
                context.running = true;
            }

            function stop() {

                context.running = false;
            }

            function toggle() {

                ( context.running ? stop : start )();
            }

            function clear() {

                if ( is2D )

                    context.clearRect( 0, 0, context.width, context.height );
            }

            function destroy() {

                parent = context.element.parentNode;
                index = instances.indexOf( context );

                if ( parent ) parent.removeChild( context.element );
                if ( ~index ) instances.splice( index, 1 );

                bind( false );
                stop();
            }

            extend( context, {

                touches: touches,
                mouse: mouse,
                keys: keys,

                dragging: false,
                running: false,
                millis: 0,
                now: NaN,
                dt: NaN,

                destroy: destroy,
                toggle: toggle,
                clear: clear,
                start: start,
                stop: stop
            });

            instances.push( context );

            return ( context.autostart && start(), bind( true ), resize(), update(), context );
        }

        /*
        ----------------------------------------------------------------------

            Global API

        ----------------------------------------------------------------------
        */

        var element, context, Sketch = {

            CANVAS: CANVAS,
            WEB_GL: WEBGL,
            WEBGL: WEBGL,
            DOM: DOM,

            instances: instances,

            install: function( context ) {

                if ( !context[ HAS_SKETCH ] ) {

                    for ( var i = 0; i < MATH_PROPS.length; i++ )

                        context[ MATH_PROPS[i] ] = M[ MATH_PROPS[i] ];

                    extend( context, {

                        TWO_PI: M.PI * 2,
                        HALF_PI: M.PI / 2,
                        QUATER_PI: M.PI / 4,

                        random: function( min, max ) {

                            if ( isArray( min ) )

                                return min[ ~~( M.random() * min.length ) ];

                            if ( !isNumber( max ) )

                                max = min || 1, min = 0;

                            return min + M.random() * ( max - min );
                        },

                        lerp: function( min, max, amount ) {

                            return min + amount * ( max - min );
                        },

                        map: function( num, minA, maxA, minB, maxB ) {

                            return ( num - minA ) / ( maxA - minA ) * ( maxB - minB ) + minB;
                        }
                    });

                    context[ HAS_SKETCH ] = true;
                }
            },

            create: function( options ) {

                options = extend( options || {}, defaults );

                if ( options.globals ) Sketch.install( self );

                element = options.element = options.element || doc.createElement( options.type === DOM ? 'div' : 'canvas' );

                context = options.context = options.context || (function() {

                    switch( options.type ) {

                        case CANVAS:

                            return element.getContext( '2d', options );

                        case WEBGL:

                            return element.getContext( 'webgl', options ) || element.getContext( 'experimental-webgl', options );

                        case DOM:

                            return element.canvas = element;
                    }

                })();

                ( options.container || doc.body ).appendChild( element );

                return Sketch.augment( context, options );
            },

            augment: function( context, options ) {

                options = extend( options || {}, defaults );

                options.element = context.canvas || context;
                options.element.className += ' sketch';

                extend( context, options, true );

                return constructor( context );
            }
        };

        /*
        ----------------------------------------------------------------------

            Shims

        ----------------------------------------------------------------------
        */

        var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
        var scope = self;
        var then = 0;

        var a = 'AnimationFrame';
        var b = 'request' + a;
        var c = 'cancel' + a;

        var rAF = scope[ b ];
        var cAF = scope[ c ];

        for ( var i = 0; i < vendors.length && !rAF; i++ ) {

            rAF = scope[ vendors[ i ] + 'Request' + a ];
            cAF = scope[ vendors[ i ] + 'Cancel' + a ];
        }

        scope[ b ] = rAF = rAF || function( callback ) {

            var now = +new Date();
            var dt = M.max( 0, 16 - ( now - then ) );
            var id = setTimeout( function() {
                callback( now + dt );
            }, dt );

            then = now + dt;
            return id;
        };

        scope[ c ] = cAF = cAF || function( id ) {
            clearTimeout( id );
        };

        /*
        ----------------------------------------------------------------------

            Output

        ----------------------------------------------------------------------
        */

        return Sketch;

    })(window, document);

    return Sketch;

}));
<|endoftext|>


<commit_before>splasha.innerHTML = "Prossimo incontro: 31 maggio - prof. Frolli
NewMateriali della dott.ssa Galzerano e Badge Operatori della scuola";
splashb.innerHTML = "Prossimo incontro: 31 maggio - prof. Frolli
NewMateriali della dott.ssa Galzerano e Badge Operatori della scuola";
splashc.innerHTML = "Prossimo incontro: 31 maggio - prof. Frolli
NewMateriali della dott.ssa Galzerano e Badge Operatori della scuola";
<commit_msg>Update splash.js<commit_after>splasha.innerHTML = "NewBadge internauta";
splashb.innerHTML = "NewMateriali della dott.ssa Galzerano e Badge Operatori della scuola";
splashc.innerHTML = "NewMateriali della dott.ssa Galzerano e Badge Operatori della scuola";
<|endoftext|>


<commit_before>/**
 * Created by Mark on 2014/8/19.
 */

// 点击选项
var bar,p;
// 判断选择是否正确
function check(a) {
    //暂停进度条
    clearInterval(bar);
    clearInterval(p);

    var ans = $('audio').data('name'); //获得正确答案
    var op = $(a).text(); //获得所选项
    var point = +$('.pointsDelta').text(); //获得当时分数
    var scoreNode = $('#score').find('span');
    var score = +scoreNode.text();//得到当前的总分数
    if(ans === op) { //判断是否正确
        //弹出正确对话框
        $('#correct-box').css('display','inherit');
        $('.label-success').text('+' +point+'pts');
        scoreNode.text(score+point);
        if(score+point > 0) { //分数大于0 设置其为绿色
            scoreNode.removeClass('negative');
        }
    } else {
        //弹出错误对话框
        $('#wrong-box').css('display','inherit');
        $('.label-error').text('-'+(150-point)+'pts');
        scoreNode.text(score-150+point);
        if(score-150+point < 0) { //分数小于0， 设置其为红色
            scoreNode.addClass('negative');
        }
    }

    // 为了 在弹出对话框后，防止鼠标与其他页面元素进行交互 设置背景图片
    $('.fancybox-overlay').css('display','block');

}

// progressbar
$(document).ready(function(){
    var len = 400; //进度条长度
    var point = 100;//分数
    // 进度条缩短到0的时间应该与分数减少到0的时间差不多
    //所以 400*30 约等于 100*130 因为有误差，所以不是绝对相等的，具体看效果
    function setProgressBar() { // 设置进度条
        bar = setInterval(function(){ //定时缩短进度条，每30毫秒，缩短1px
            $('#choiceProgressBar').css('width',(len--)+'px');
        },30);
    }
    function setPoint() { //设置分数
        p = setInterval(function () { //定时减少分数，每130毫秒，分数减少1
            point--;
            var pd = $('.pointsDelta');
            pd.text(point);
            if (point <= 0) { //如果分数小于0了，则弹出错误对话框
                clear();
            }
        }, 130);
    }
    function clear() { //
        clearInterval(bar);
        clearInterval(p);
        $('#wrong-box').css('display','inherit');
        $('.label-error').text('-100pts');
    }

    function getData() {
        //以Ajax方式向服务器取数据
        $.ajax('test',{
            type:'POST', //POST类型
            dataType:'json',//设置服务器发送过来的数据为json格式
            //contentType:'application/json',//设置发送给服务器的数据为json个数
            data:{'isAjax':'true'},//发送给服务器的参数数据
            success:function(response){//服务器成功返回数据时 执行的函数
                var ops = response.ops; //服务器端传过来的选项数据
                var ans = response.ans;// 服务器端传过来的正确答案
                $('.box').css('display','none'); // 隐藏弹出框
                var audio = $('#music');
                audio.attr('src','music/'+ans.name+'.mp3');//设置歌曲
                audio.data('name',ans.name); //给 data-name属性设置值
                $('#box-ans').text(ans.name);// 给 wrong-box设置正确的答案
                var options = $('.lead');
                options.children().remove(); //清除原先的选项
                $('.fancybox-overlay').css('display','none');//隐藏 阻止鼠标与页面进行交互的 图片
                for(var i=0; i<ops.length; i++) {// 设置选项
                    var opt = $('');
                    opt.append(ops[i].name);
                    options.append(opt);
                }
                //重新设置进度条和分数
                len = 400;
                point = 100;
                setProgressBar();
                setPoint();
            }
        });
    }

    function setData(){
        var ops =[];
        var ans ;
        for (var i=0; i<4; i++) {
            var tmp = Math.floor(Math.random()*songs.length);
            var cnu = false;
            for(var j=0; j<i; j++) {
                if (tmp == ops[j]) {
                    cnu = true; break;
                }
            }
            if(cnu) continue;
            ops[i] = songs[tmp];
        }
        ans = ops[Math.floor(Math.random()*4)];
        $('.box').css('display','none'); // 隐藏弹出框
        var audio = $('#music');
        audio.attr('src','music/'+ans+'.mp3');//设置歌曲
        audio.data('name',ans); //给 data-name属性设置值
        $('#box-ans').text(ans);// 给 wrong-box设置正确的答案
        var options = $('.lead');
        options.children().remove(); //清除原先的选项
        $('.fancybox-overlay').css('display','none');//隐藏 阻止鼠标与页面进行交互的 图片
        for(var i=0; i<ops.length; i++) {// 设置选项
            var opt = $('');
            opt.append(ops[i]);
            options.append(opt);
        }
        //重新设置进度条和分数
        len = 400;
        point = 100;
        setProgressBar();
        setPoint();
    }

    setProgressBar();
    setPoint();
    setData();//初始化选项
    $('.nextSong').on('click',setData); //设置 下一首的 点击事件

});
<commit_msg>解决点击选项，进度条还在走的bug<commit_after>/**
 * Created by Mark on 2014/8/19.
 */

// 点击选项
var bar ,p ;
// 判断选择是否正确
function check(a) {
    //暂停进度条
    clearInterval(bar);
    clearInterval(p);

    var ans = $('audio').data('name'); //获得正确答案
    var op = $(a).text(); //获得所选项
    var point = +$('.pointsDelta').text(); //获得当时分数
    var scoreNode = $('#score').find('span');
    var score = +scoreNode.text();//得到当前的总分数
    if(ans === op) { //判断是否正确
        //弹出正确对话框
        $('#correct-box').css('display','inherit');
        $('.label-success').text('+' +point+'pts');
        scoreNode.text(score+point);
        if(score+point > 0) { //分数大于0 设置其为绿色
            scoreNode.removeClass('negative');
        }
    } else {
        //弹出错误对话框
        $('#wrong-box').css('display','inherit');
        $('.label-error').text('-'+(150-point)+'pts');
        scoreNode.text(score-150+point);
        if(score-150+point < 0) { //分数小于0， 设置其为红色
            scoreNode.addClass('negative');
        }
    }

    // 为了 在弹出对话框后，防止鼠标与其他页面元素进行交互 设置背景图片
    $('.fancybox-overlay').css('display','block');

}

function setData(){
    var ops =[];
    var ans ;
    for (var i=0; i<4; i++) {
        var tmp = Math.floor(Math.random()*songs.length);
        var cnu = false;
        for(var j=0; j<i; j++) {
            if (tmp == ops[j]) {
                cnu = true; break;
            }
        }
        if(cnu) continue;
        ops[i] = songs[tmp];
    }
    ans = ops[Math.floor(Math.random()*4)];
    $('.box').css('display','none'); // 隐藏弹出框
    var audio = $('#music');
    audio.attr('src','music/'+ans+'.mp3');//设置歌曲
    audio.data('name',ans); //给 data-name属性设置值
    $('#box-ans').text(ans);// 给 wrong-box设置正确的答案
    var options = $('.lead');
    options.children().remove(); //清除原先的选项
    $('.fancybox-overlay').css('display','none');//隐藏 阻止鼠标与页面进行交互的 图片
    for(var i=0; i<ops.length; i++) {// 设置选项
        var opt = $('');
        opt.append(ops[i]);
        options.append(opt);
    }
    //重新设置进度条和分数
    len = 400;
    point = 100;

    setProgressBar();
    setPoint();
}

var len = 400; //进度条长度
var point = 100;//分数
// 进度条缩短到0的时间应该与分数减少到0的时间差不多
//所以 400*30 约等于 100*130 因为有误差，所以不是绝对相等的，具体看效果
function setProgressBar() { // 设置进度条
    clearInterval(bar); //为了防止在下面的设置之前，清除前一次的设置，没有这句会出现，点击了选项，进度条还是走的情况
    bar = setInterval(function(){ //定时缩短进度条，每30毫秒，缩短1px
        $('#choiceProgressBar').css('width',(len--)+'px');
    },30);

}
function setPoint() { //设置分数
    clearInterval(p); //为了防止在下面的设置之前，清除前一次的设置，没有这句会出现，点击了选项，分数还是走的情况
    p = setInterval(function () { //定时减少分数，每130毫秒，分数减少1
        point--;
        var pd = $('.pointsDelta');
        pd.text(point);
        if (point <= 0) { //如果分数小于0了，则弹出错误对话框
            clear();
        }
    }, 130);

}

function clear() { //
    clearInterval(bar);
    clearInterval(p);
    $('#wrong-box').css('display','inherit');
    $('.label-error').text('-100pts');
}

// progressbar
$(document).ready(function(){
    setProgressBar();
    setPoint();
    setData();//初始化选项
    //$('.nextSong').on('click',setData); //设置 下一首的 点击事件
});

<|endoftext|>


<commit_before>/*
* jQuery UI Tag-it!
*
* @version v2.0 (06/2011)
*
* Copyright 2011, Levy Carneiro Jr.
* Released under the MIT license.
* http://aehlke.github.com/tag-it/LICENSE
*
* Homepage:
*   http://aehlke.github.com/tag-it/
*
* Authors:
*   Levy Carneiro Jr.
*   Martin Rehfeld
*   Tobias Schmidt
*   Skylar Challand
*   Alex Ehlke
*
* Maintainer:
*   Alex Ehlke - Twitter: @aehlke
*
* Dependencies:
*   jQuery v1.4+
*   jQuery UI v1.8+
*/
(function($) {

    $.widget('ui.tagit', {
        options: {
            itemName          : 'item',
            fieldName         : 'tags',
            availableTags     : [],
            tagSource         : null,
            removeConfirmation: false,
            caseSensitive     : true,

            // When enabled, quotes are not neccesary
            // for inputting multi-word tags.
            allowSpaces: false,

            // The below options are for using a single field instead of several
            // for our form values.
            //
            // When enabled, will use a single hidden field for the form,
            // rather than one per tag. It will delimit tags in the field
            // with singleFieldDelimiter.
            singleField: false,

            singleFieldDelimiter: ',',

            // Set this to an input DOM node to use an existing form field.
            // Any text in it will be erased on init. But it will be
            // populated with the text of tags as they are created,
            // delimited by singleFieldDelimiter.
            // If this is not set, we create an input node for it,
            // with the name // given in settings.fieldName,
            // ignoring settings.itemName.
            singleFieldNode: null,

            // Optionally set a tabindex attribute on the input that gets
            // created for tag-it.
            tabIndex: null,

            // Event callbacks.
            onTagAdded  : null,
            onTagRemoved: null,
            onTagClicked: null
        },

        _create: function() {
            // for handling static scoping inside callbacks
            var that = this;

            // There are 2 kinds of DOM nodes this widget can be instantiated on:
            //     1. UL, OL, or some element containing either of these.
            //     2. INPUT, in which case 'singleField' is overridden to true,
            //        a UL is created and the INPUT is hidden.
            if (this.element.is('input')) {
                this.tagList = $('

').insertAfter(this.element);
                this.options.singleField = true;
                this.options.singleFieldNode = this.element;
                this.element.css('display', 'none');
            } else {
                this.tagList = this.element.find('ul, ol').andSelf().last();
            }

            this._tagInput = $('<input type="text">').addClass('ui-widget-content');
            if (this.options.tabIndex) {
                this._tagInput.attr('tabindex', this.options.tabIndex);
            }

            this.options.tagSource = this.options.tagSource || function(search, showChoices) {
                var filter = search.term.toLowerCase();
                var choices = $.grep(that.options.availableTags, function(element) {
                    // Only match autocomplete options that begin with the search term.
                    // (Case insensitive.)
                    return (element.toLowerCase().indexOf(filter) === 0);
                });
                showChoices(that._subtractArray(choices, that.assignedTags()));
            };

            this.tagList
                .addClass('tagit')
                .addClass('ui-widget ui-widget-content ui-corner-all')
                // Create the input field.
                .append($('

').append(this._tagInput))
                .click(function(e) {
                    var target = $(e.target);
                    if (target.hasClass('tagit-label')) {
                        that._trigger('onTagClicked', e, target.closest('.tagit-choice'));
                    } else {
                        // Sets the focus() to the input field, if the user
                        // clicks anywhere inside the UL. This is needed
                        // because the input field needs to be of a small size.
                        that._tagInput.focus();
                    }
                });

            // Add existing tags from the list, if any.
            this.tagList.children('li').each(function() {
                if (!$(this).hasClass('tagit-new')) {
                    that.createTag($(this).html(), $(this).attr('class'));
                    $(this).remove();
                }
            });

            // Single field support.
            if (this.options.singleField) {
                if (this.options.singleFieldNode) {
                    // Add existing tags from the input field.
                    var node = $(this.options.singleFieldNode);
                    var tags = node.val().split(this.options.singleFieldDelimiter);
                    node.val('');
                    $.each(tags, function(index, tag) {
                        that.createTag(tag);
                    });
                } else {
                    // Create our single field input after our list.
                    this.options.singleFieldNode = this.tagList.after('<input type="hidden" style="display:none;" value="" name="' + this.options.fieldName + '">');
                }
            }

            // Events.
            this._tagInput
                .keydown(function(event) {
                    // Backspace is not detected within a keypress, so it must use keydown.
                    if (event.which == $.ui.keyCode.BACKSPACE && that._tagInput.val() === '') {
                        var tag = that._lastTag();
                        if (!that.options.removeConfirmation || tag.hasClass('remove')) {
                            // When backspace is pressed, the last tag is deleted.
                            that.removeTag(tag);
                        } else if (that.options.removeConfirmation) {
                            tag.addClass('remove ui-state-highlight');
                        }
                    } else if (that.options.removeConfirmation) {
                        that._lastTag().removeClass('remove ui-state-highlight');
                    }

                    // Comma/Space/Enter are all valid delimiters for new tags,
                    // except when there is an open quote or if setting allowSpaces = true.
                    // Tab will also create a tag, unless the tag input is empty, in which case it isn't caught.
                    if (
                        event.which == $.ui.keyCode.COMMA ||
                        event.which == $.ui.keyCode.ENTER ||
                        (
                            event.which == $.ui.keyCode.TAB &&
                            that._tagInput.val() !== ''
                        ) ||
                        (
                            event.which == $.ui.keyCode.SPACE &&
                            that.options.allowSpaces !== true &&
                            (
                                $.trim(that._tagInput.val()).replace( /^s*/, '' ).charAt(0) != '"' ||
                                (
                                    $.trim(that._tagInput.val()).charAt(0) == '"' &&
                                    $.trim(that._tagInput.val()).charAt($.trim(that._tagInput.val()).length - 1) == '"' &&
                                    $.trim(that._tagInput.val()).length - 1 !== 0
                                )
                            )
                        )
                    ) {
                        event.preventDefault();
                        that.createTag(that._cleanedInput());

                        // The autocomplete doesn't close automatically when TAB is pressed.
                        // So let's ensure that it closes.
                        that._tagInput.autocomplete('close');
                    }
                }).blur(function(e){
                    // Create a tag when the element loses focus (unless it's empty).
                    that.createTag(that._cleanedInput());
                });

            // Autocomplete.
            if (this.options.availableTags || this.options.tagSource) {
                this._tagInput.autocomplete({
                    source: this.options.tagSource,
                    select: function(event, ui) {
                        // Delete the last tag if we autocomplete something despite the input being empty
                        // This happens because the input's blur event causes the tag to be created when
                        // the user clicks an autocomplete item.
                        // The only artifact of this is that while the user holds down the mouse button
                        // on the selected autocomplete item, a tag is shown with the pre-autocompleted text,
                        // and is changed to the autocompleted text upon mouseup.
                        if (that._tagInput.val() === '') {
                            that.removeTag(that._lastTag(), false);
                        }
                        that.createTag(ui.item.value);
                        // Preventing the tag input to be updated with the chosen value.
                        return false;
                    }
                });
            }
        },

        _cleanedInput: function() {
            // Returns the contents of the tag input, cleaned and ready to be passed to createTag
            return $.trim(this._tagInput.val().replace(/^"(.*)"$/, '$1'));
        },

        _lastTag: function() {
            return this.tagList.children('.tagit-choice:last');
        },

        assignedTags: function() {
            // Returns an array of tag string values
            var that = this;
            var tags = [];
            if (this.options.singleField) {
                tags = $(this.options.singleFieldNode).val().split(this.options.singleFieldDelimiter);
                if (tags[0] === '') {
                    tags = [];
                }
            } else {
                this.tagList.children('.tagit-choice').each(function() {
                    tags.push(that.tagLabel(this));
                });
            }
            return tags;
        },

        _updateSingleTagsField: function(tags) {
            // Takes a list of tag string values, updates this.options.singleFieldNode.val to the tags delimited by this.options.singleFieldDelimiter
            $(this.options.singleFieldNode).val(tags.join(this.options.singleFieldDelimiter));
        },

        _subtractArray: function(a1, a2) {
            var result = [];
            for (var i = 0; i < a1.length; i++) {
                if ($.inArray(a1[i], a2) == -1) {
                    result.push(a1[i]);
                }
            }
            return result;
        },

        tagLabel: function(tag) {
            // Returns the tag's string label.
            if (this.options.singleField) {
                return $(tag).children('.tagit-label').text();
            } else {
                return $(tag).children('input').val();
            }
        },

        _isNew: function(value) {
            var that = this;
            var isNew = true;
            this.tagList.children('.tagit-choice').each(function(i) {
                if (that._formatStr(value) == that._formatStr(that.tagLabel(this))) {
                    isNew = false;
                    return;
                }
            });
            return isNew;
        },

        _formatStr: function(str) {
            if (this.options.caseSensitive) {
                return str;
            }
            return $.trim(str.toLowerCase());
        },

        createTag: function(value, additionalClass) {
            that = this;
            // Automatically trims the value of leading and trailing whitespace.
            value = $.trim(value);

            if (!this._isNew(value) || value === '') {
                return false;
            }

            var label = $(this.options.onTagClicked ? '' : '').text(value);

            // Create tag.
            var tag = $('

')
                .addClass('tagit-choice ui-widget-content ui-state-default ui-corner-all')
                .addClass(additionalClass)
                .append(label);

            // Button for removing the tag.
            var removeTagIcon = $('')
                .addClass('ui-icon ui-icon-close');
            var removeTag = $('\xd7') // \xd7 is an X
                .addClass('close')
                .append(removeTagIcon)
                .click(function(e) {
                    // Removes a tag when the little 'x' is clicked.
                    that.removeTag(tag);
                });
            tag.append(removeTag);

            // Unless options.singleField is set, each tag has a hidden input field inline.
            if (this.options.singleField) {
                var tags = this.assignedTags();
                tags.push(value);
                this._updateSingleTagsField(tags);
            } else {
                var escapedValue = label.html();
                tag.append('<input type="hidden" style="display:none;" value="' + escapedValue + '" name="' + this.options.itemName + '[' + this.options.fieldName + '][]">');
            }

            this._trigger('onTagAdded', null, tag);

            // Cleaning the input.
            this._tagInput.val('');

            // insert tag
            this._tagInput.parent().before(tag);
        },

        removeTag: function(tag, animate) {
            if (typeof animate === 'undefined') { animate = true; }

            tag = $(tag);

            this._trigger('onTagRemoved', null, tag);

            if (this.options.singleField) {
                var tags = this.assignedTags();
                var removedTagLabel = this.tagLabel(tag);
                tags = $.grep(tags, function(el){
                    return el != removedTagLabel;
                });
                this._updateSingleTagsField(tags);
            }
            // Animate the removal.
            if (animate) {
                tag.fadeOut('fast').hide('blind', {direction: 'horizontal'}, 'fast', function(){
                    tag.remove();
                }).dequeue();
            } else {
                tag.remove();
            }
        },

        removeAll: function() {
            // Removes all tags. Takes an optional `animate` argument.
            var that = this;
            this.tagList.children('.tagit-choice').each(function(index, tag) {
                that.removeTag(tag, false);
            });
        }

    });

})(jQuery);

<commit_msg>comment cleanup<commit_after>/*
* jQuery UI Tag-it!
*
* @version v2.0 (06/2011)
*
* Copyright 2011, Levy Carneiro Jr.
* Released under the MIT license.
* http://aehlke.github.com/tag-it/LICENSE
*
* Homepage:
*   http://aehlke.github.com/tag-it/
*
* Authors:
*   Levy Carneiro Jr.
*   Martin Rehfeld
*   Tobias Schmidt
*   Skylar Challand
*   Alex Ehlke
*
* Maintainer:
*   Alex Ehlke - Twitter: @aehlke
*
* Dependencies:
*   jQuery v1.4+
*   jQuery UI v1.8+
*/
(function($) {

    $.widget('ui.tagit', {
        options: {
            itemName          : 'item',
            fieldName         : 'tags',
            availableTags     : [],
            tagSource         : null,
            removeConfirmation: false,
            caseSensitive     : true,

            // When enabled, quotes are not neccesary
            // for inputting multi-word tags.
            allowSpaces: false,

            // The below options are for using a single field instead of several
            // for our form values.
            //
            // When enabled, will use a single hidden field for the form,
            // rather than one per tag. It will delimit tags in the field
            // with singleFieldDelimiter.
            singleField: false,

            singleFieldDelimiter: ',',

            // Set this to an input DOM node to use an existing form field.
            // Any text in it will be erased on init. But it will be
            // populated with the text of tags as they are created,
            // delimited by singleFieldDelimiter.
            //
            // If this is not set, we create an input node for it,
            // with the name given in settings.fieldName,
            // ignoring settings.itemName.
            singleFieldNode: null,

            // Optionally set a tabindex attribute on the input that gets
            // created for tag-it.
            tabIndex: null,

            // Event callbacks.
            onTagAdded  : null,
            onTagRemoved: null,
            onTagClicked: null
        },

        _create: function() {
            // for handling static scoping inside callbacks
            var that = this;

            // There are 2 kinds of DOM nodes this widget can be instantiated on:
            //     1. UL, OL, or some element containing either of these.
            //     2. INPUT, in which case 'singleField' is overridden to true,
            //        a UL is created and the INPUT is hidden.
            if (this.element.is('input')) {
                this.tagList = $('

').insertAfter(this.element);
                this.options.singleField = true;
                this.options.singleFieldNode = this.element;
                this.element.css('display', 'none');
            } else {
                this.tagList = this.element.find('ul, ol').andSelf().last();
            }

            this._tagInput = $('<input type="text">').addClass('ui-widget-content');
            if (this.options.tabIndex) {
                this._tagInput.attr('tabindex', this.options.tabIndex);
            }

            this.options.tagSource = this.options.tagSource || function(search, showChoices) {
                var filter = search.term.toLowerCase();
                var choices = $.grep(that.options.availableTags, function(element) {
                    // Only match autocomplete options that begin with the search term.
                    // (Case insensitive.)
                    return (element.toLowerCase().indexOf(filter) === 0);
                });
                showChoices(that._subtractArray(choices, that.assignedTags()));
            };

            this.tagList
                .addClass('tagit')
                .addClass('ui-widget ui-widget-content ui-corner-all')
                // Create the input field.
                .append($('

').append(this._tagInput))
                .click(function(e) {
                    var target = $(e.target);
                    if (target.hasClass('tagit-label')) {
                        that._trigger('onTagClicked', e, target.closest('.tagit-choice'));
                    } else {
                        // Sets the focus() to the input field, if the user
                        // clicks anywhere inside the UL. This is needed
                        // because the input field needs to be of a small size.
                        that._tagInput.focus();
                    }
                });

            // Add existing tags from the list, if any.
            this.tagList.children('li').each(function() {
                if (!$(this).hasClass('tagit-new')) {
                    that.createTag($(this).html(), $(this).attr('class'));
                    $(this).remove();
                }
            });

            // Single field support.
            if (this.options.singleField) {
                if (this.options.singleFieldNode) {
                    // Add existing tags from the input field.
                    var node = $(this.options.singleFieldNode);
                    var tags = node.val().split(this.options.singleFieldDelimiter);
                    node.val('');
                    $.each(tags, function(index, tag) {
                        that.createTag(tag);
                    });
                } else {
                    // Create our single field input after our list.
                    this.options.singleFieldNode = this.tagList.after('<input type="hidden" style="display:none;" value="" name="' + this.options.fieldName + '">');
                }
            }

            // Events.
            this._tagInput
                .keydown(function(event) {
                    // Backspace is not detected within a keypress, so it must use keydown.
                    if (event.which == $.ui.keyCode.BACKSPACE && that._tagInput.val() === '') {
                        var tag = that._lastTag();
                        if (!that.options.removeConfirmation || tag.hasClass('remove')) {
                            // When backspace is pressed, the last tag is deleted.
                            that.removeTag(tag);
                        } else if (that.options.removeConfirmation) {
                            tag.addClass('remove ui-state-highlight');
                        }
                    } else if (that.options.removeConfirmation) {
                        that._lastTag().removeClass('remove ui-state-highlight');
                    }

                    // Comma/Space/Enter are all valid delimiters for new tags,
                    // except when there is an open quote or if setting allowSpaces = true.
                    // Tab will also create a tag, unless the tag input is empty, in which case it isn't caught.
                    if (
                        event.which == $.ui.keyCode.COMMA ||
                        event.which == $.ui.keyCode.ENTER ||
                        (
                            event.which == $.ui.keyCode.TAB &&
                            that._tagInput.val() !== ''
                        ) ||
                        (
                            event.which == $.ui.keyCode.SPACE &&
                            that.options.allowSpaces !== true &&
                            (
                                $.trim(that._tagInput.val()).replace( /^s*/, '' ).charAt(0) != '"' ||
                                (
                                    $.trim(that._tagInput.val()).charAt(0) == '"' &&
                                    $.trim(that._tagInput.val()).charAt($.trim(that._tagInput.val()).length - 1) == '"' &&
                                    $.trim(that._tagInput.val()).length - 1 !== 0
                                )
                            )
                        )
                    ) {
                        event.preventDefault();
                        that.createTag(that._cleanedInput());

                        // The autocomplete doesn't close automatically when TAB is pressed.
                        // So let's ensure that it closes.
                        that._tagInput.autocomplete('close');
                    }
                }).blur(function(e){
                    // Create a tag when the element loses focus (unless it's empty).
                    that.createTag(that._cleanedInput());
                });

            // Autocomplete.
            if (this.options.availableTags || this.options.tagSource) {
                this._tagInput.autocomplete({
                    source: this.options.tagSource,
                    select: function(event, ui) {
                        // Delete the last tag if we autocomplete something despite the input being empty
                        // This happens because the input's blur event causes the tag to be created when
                        // the user clicks an autocomplete item.
                        // The only artifact of this is that while the user holds down the mouse button
                        // on the selected autocomplete item, a tag is shown with the pre-autocompleted text,
                        // and is changed to the autocompleted text upon mouseup.
                        if (that._tagInput.val() === '') {
                            that.removeTag(that._lastTag(), false);
                        }
                        that.createTag(ui.item.value);
                        // Preventing the tag input to be updated with the chosen value.
                        return false;
                    }
                });
            }
        },

        _cleanedInput: function() {
            // Returns the contents of the tag input, cleaned and ready to be passed to createTag
            return $.trim(this._tagInput.val().replace(/^"(.*)"$/, '$1'));
        },

        _lastTag: function() {
            return this.tagList.children('.tagit-choice:last');
        },

        assignedTags: function() {
            // Returns an array of tag string values
            var that = this;
            var tags = [];
            if (this.options.singleField) {
                tags = $(this.options.singleFieldNode).val().split(this.options.singleFieldDelimiter);
                if (tags[0] === '') {
                    tags = [];
                }
            } else {
                this.tagList.children('.tagit-choice').each(function() {
                    tags.push(that.tagLabel(this));
                });
            }
            return tags;
        },

        _updateSingleTagsField: function(tags) {
            // Takes a list of tag string values, updates this.options.singleFieldNode.val to the tags delimited by this.options.singleFieldDelimiter
            $(this.options.singleFieldNode).val(tags.join(this.options.singleFieldDelimiter));
        },

        _subtractArray: function(a1, a2) {
            var result = [];
            for (var i = 0; i < a1.length; i++) {
                if ($.inArray(a1[i], a2) == -1) {
                    result.push(a1[i]);
                }
            }
            return result;
        },

        tagLabel: function(tag) {
            // Returns the tag's string label.
            if (this.options.singleField) {
                return $(tag).children('.tagit-label').text();
            } else {
                return $(tag).children('input').val();
            }
        },

        _isNew: function(value) {
            var that = this;
            var isNew = true;
            this.tagList.children('.tagit-choice').each(function(i) {
                if (that._formatStr(value) == that._formatStr(that.tagLabel(this))) {
                    isNew = false;
                    return;
                }
            });
            return isNew;
        },

        _formatStr: function(str) {
            if (this.options.caseSensitive) {
                return str;
            }
            return $.trim(str.toLowerCase());
        },

        createTag: function(value, additionalClass) {
            that = this;
            // Automatically trims the value of leading and trailing whitespace.
            value = $.trim(value);

            if (!this._isNew(value) || value === '') {
                return false;
            }

            var label = $(this.options.onTagClicked ? '' : '').text(value);

            // Create tag.
            var tag = $('

')
                .addClass('tagit-choice ui-widget-content ui-state-default ui-corner-all')
                .addClass(additionalClass)
                .append(label);

            // Button for removing the tag.
            var removeTagIcon = $('')
                .addClass('ui-icon ui-icon-close');
            var removeTag = $('\xd7') // \xd7 is an X
                .addClass('close')
                .append(removeTagIcon)
                .click(function(e) {
                    // Removes a tag when the little 'x' is clicked.
                    that.removeTag(tag);
                });
            tag.append(removeTag);

            // Unless options.singleField is set, each tag has a hidden input field inline.
            if (this.options.singleField) {
                var tags = this.assignedTags();
                tags.push(value);
                this._updateSingleTagsField(tags);
            } else {
                var escapedValue = label.html();
                tag.append('<input type="hidden" style="display:none;" value="' + escapedValue + '" name="' + this.options.itemName + '[' + this.options.fieldName + '][]">');
            }

            this._trigger('onTagAdded', null, tag);

            // Cleaning the input.
            this._tagInput.val('');

            // insert tag
            this._tagInput.parent().before(tag);
        },

        removeTag: function(tag, animate) {
            if (typeof animate === 'undefined') { animate = true; }

            tag = $(tag);

            this._trigger('onTagRemoved', null, tag);

            if (this.options.singleField) {
                var tags = this.assignedTags();
                var removedTagLabel = this.tagLabel(tag);
                tags = $.grep(tags, function(el){
                    return el != removedTagLabel;
                });
                this._updateSingleTagsField(tags);
            }
            // Animate the removal.
            if (animate) {
                tag.fadeOut('fast').hide('blind', {direction: 'horizontal'}, 'fast', function(){
                    tag.remove();
                }).dequeue();
            } else {
                tag.remove();
            }
        },

        removeAll: function() {
            // Removes all tags. Takes an optional `animate` argument.
            var that = this;
            this.tagList.children('.tagit-choice').each(function(index, tag) {
                that.removeTag(tag, false);
            });
        }

    });

})(jQuery);

<|endoftext|>


<commit_before>const URLResolver = require('./urlResolver');
const FigshareAPIHandler = require('../sourceHandlers/figshare');

const stripHttp = /^(https?:\/\/)?(www\.)?/;
const urlRegex = /^figshare\.com\/articles(\/\w+)?\/\d+$/;

const apiBaseUrl = 'https://api.figshare.com/v2/';

/**
 * Creates the supported source handlers for a given URL.
 * @class
 * @memberof urlResolvers
 * @augments urlResolvers.URLResolver
 */
class FigshareResolver extends URLResolver {
  static getSourceHandlers(url) {
    const sourceHandlers = [];
    const strippedURL = url.replace(stripHttp, '');

    if (urlRegex.exec(strippedURL)) {
      sourceHandlers.push(new FigshareAPIHandler(apiBaseUrl, /\d+$/.exec(strippedURL)));
    }

    return sourceHandlers;
  }
}

module.exports = FigshareResolver;
<commit_msg>Added dashes to regex for figshare source<commit_after>const URLResolver = require('./urlResolver');
const FigshareAPIHandler = require('../sourceHandlers/figshare');

const stripHttp = /^(https?:\/\/)?(www\.)?/;
const urlRegex = /^figshare\.com\/articles(\/[\w-]+)?\/\d+$/;

const apiBaseUrl = 'https://api.figshare.com/v2/';

/**
 * Creates the supported source handlers for a given URL.
 * @class
 * @memberof urlResolvers
 * @augments urlResolvers.URLResolver
 */
class FigshareResolver extends URLResolver {
  static getSourceHandlers(url) {
    const sourceHandlers = [];
    const strippedURL = url.replace(stripHttp, '');

    if (urlRegex.exec(strippedURL)) {
      sourceHandlers.push(new FigshareAPIHandler(apiBaseUrl, /\d+$/.exec(strippedURL)));
    }

    return sourceHandlers;
  }
}

module.exports = FigshareResolver;
<|endoftext|>


<commit_before>
(function($) {

    $.fn.tagit = function(options) {

        var settings = {
            'itemName'          : 'item',
            'fieldName'         : 'tags',
            'availableTags'     : [],
            // callback: called when a tag is added
            'onTagAdded'        : null,
            // callback: called when a tag is removed
            'onTagRemoved'      : null,
            // callback: called when a tag is clicked
    	    'onTagClicked'      : null,
            'tagSource':
                function(search, show_choices) {
                    var filter = new RegExp(search.term, 'i');
                    var choices = settings.availableTags.filter(function(element) {
                        return (element.search(filter) != -1);
                    });
                    show_choices(subtract_array(choices, assigned_tags()));
                },
            'removeConfirmation': false,
            'caseSensitive': true,
            'allowSpaces': false, // when enabled, quotes are not neccesary for inputting multi-word tags

            'singleField': false, // When enabled, will use a single hidden field for the form, rather than one per tag.
                                  // It will delimit tags in the field with singleFieldDelimiter.
            'singleFieldDelimiter': ','
        };

        if (options) {
            $.extend(settings, options);
        }

        var tagList = $(this),
            tagInput  = $('<input class="tagit-input" type="text" />');
            BACKSPACE = 8,
            ENTER     = 13,
            SPACE     = 32,
            COMMA     = 44,
            TAB       = 9;

        tagList
            // add the tagit CSS class.
            .addClass('tagit')
            // create the input field.
            .append($('

\n').append(tagInput))
            .click(function(e) {
                if (e.target.className == 'close') {
                    // Removes a tag when the little 'x' is clicked.
                    // Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it.
                    remove_tag($(e.target).parent());
                } else if (e.target.className == 'tagLabel' && settings.onTagClicked) {
                    settings.onTagClicked($(e.target).parent());
                } else {
                    // Sets the focus() to the input field, if the user clicks anywhere inside the UL.
                    // This is needed because the input field needs to be of a small size.
                    tagInput.focus();
                }
            })
            // add existing tags
            .children('li')
                .each(function() {
                    if (!$(this).hasClass('tagit-new')) {
                        create_tag($(this).html(), $(this).attr('class'));
                        $(this).remove();
                    }
                });

        tagInput
            .keydown(function(event) {
                var keyCode = event.keyCode || event.which;
                // Backspace is not detected within a keypress, so using a keydown
                if (keyCode == BACKSPACE && tagInput.val() == '') {
                    var tag = tagList.children('.tagit-choice:last');
                    if (!settings.removeConfirmation || tag.hasClass('remove')) {
                        // When backspace is pressed, the last tag is deleted.
                        remove_tag(tag);
                    } else if (settings.removeConfirmation) {
                        tag.addClass('remove');
                    }
                }
            })
            .keypress(function(event) {
                var keyCode = event.keyCode || event.which;
                // Comma/Space/Enter are all valid delimiters for new tags. except when there is an open quote or if setting allowSpaces = true
                if (
                    keyCode == COMMA ||
                    keyCode == ENTER ||
                    keyCode == TAB ||
                    (
             	        keyCode == SPACE &&
             	        settings.allowSpaces != true &&
				        (
					        (tagInput.val().trim().replace( /^s*/, '' ).charAt(0) != '"') ||
					        (
					            tagInput.val().trim().charAt(0) == '"' &&
					            tagInput.val().trim().charAt(tagInput.val().trim().length - 1) == '"' &&
					            tagInput.val().trim().length - 1 != 0
					        )
				        )
                    )
                ) {

                    event.preventDefault();
                    create_tag(tagInput.val().replace(/^"|"$|,+$/g, '').trim());
                }
                if (settings.removeConfirmation) {
                    tagList.children('.tagit-choice:last').removeClass('remove');
                }
            });

        if (options.availableTags || options.tagSource) {
            tagInput.autocomplete({
                source: settings.tagSource,
                select: function(event, ui) {
                    create_tag(ui.item.value);
                    // Preventing the tag input to be updated with the chosen value.
                    return false;
                }
            });
        }

        function assigned_tags() {
            var tags = [];
            tagList.children('.tagit-choice').each(function() {
                tags.push($(this).children('input').val());
            });
            return tags;
        }

        function subtract_array(a1, a2) {
            var result = new Array();
            for (var i = 0; i < a1.length; i++) {
                if (a2.indexOf(a1[i]) == -1) {
                    result.push(a1[i]);
                }
            }
            return result;
        }

        function is_new(value) {
            var isNew = true;
            tagList.children('.tagit-choice').each(function(i) {
                if (format_str(value) == format_str($(this).children('input').val())) {
                    isNew = false;
                    return;
                }
            });
            return isNew;
        }
	    function format_str(str) {
		    if(settings.caseSensitive)
			    return str;
		    return str.toLowerCase();
	    }
        function create_tag(value, additionalClass) {
            // Cleaning the input.
            tagInput.val('');

            if (!is_new(value) || value == '') {
                return false;
            }
            var linkValue = value;
            if (settings.onTagClicked) {
      	        linkValue = '' + value + '';
            }
            // create tag
            var tag = $('
')
                .addClass('tagit-choice')
                .addClass(additionalClass)
                .append(linkValue)
                .append('x');
            if (settings.singleField) {
                //TODO
            } else {
                tag.append('<input type="hidden" style="display:none;" value="' + value + '" name="' + settings.itemName + '[' + settings.fieldName + '][]">');
            }

            if (settings.onTagAdded) {
                settings.onTagAdded(tag);
            }

            // insert tag
            tagInput.parent().before(tag);
        }
        function remove_tag(tag) {
            if (settings.onTagRemoved) {
                settings.onTagRemoved(tag);
            }
            if (settings.singleField) {
                //TODO
            }
            tag.remove();
        }

        // maintaining chainability
        return this;
    };

    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };

})(jQuery);

<commit_msg>use jquery's native string trim instead of adding to the string prototype<commit_after>
(function($) {

    $.fn.tagit = function(options) {

        var settings = {
            'itemName'          : 'item',
            'fieldName'         : 'tags',
            'availableTags'     : [],
            // callback: called when a tag is added
            'onTagAdded'        : null,
            // callback: called when a tag is removed
            'onTagRemoved'      : null,
            // callback: called when a tag is clicked
    	    'onTagClicked'      : null,
            'tagSource':
                function(search, show_choices) {
                    var filter = new RegExp(search.term, 'i');
                    var choices = settings.availableTags.filter(function(element) {
                        return (element.search(filter) != -1);
                    });
                    show_choices(subtract_array(choices, assigned_tags()));
                },
            'removeConfirmation': false,
            'caseSensitive': true,
            'allowSpaces': false, // when enabled, quotes are not neccesary for inputting multi-word tags

            'singleField': false, // When enabled, will use a single hidden field for the form, rather than one per tag.
                                  // It will delimit tags in the field with singleFieldDelimiter.
            'singleFieldDelimiter': ','
        };

        if (options) {
            $.extend(settings, options);
        }

        var tagList = $(this),
            tagInput  = $('<input class="tagit-input" type="text" />');
            BACKSPACE = 8,
            ENTER     = 13,
            SPACE     = 32,
            COMMA     = 44,
            TAB       = 9;

        tagList
            // add the tagit CSS class.
            .addClass('tagit')
            // create the input field.
            .append($('

\n').append(tagInput))
            .click(function(e) {
                if (e.target.className == 'close') {
                    // Removes a tag when the little 'x' is clicked.
                    // Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it.
                    remove_tag($(e.target).parent());
                } else if (e.target.className == 'tagLabel' && settings.onTagClicked) {
                    settings.onTagClicked($(e.target).parent());
                } else {
                    // Sets the focus() to the input field, if the user clicks anywhere inside the UL.
                    // This is needed because the input field needs to be of a small size.
                    tagInput.focus();
                }
            })
            // add existing tags
            .children('li')
                .each(function() {
                    if (!$(this).hasClass('tagit-new')) {
                        create_tag($(this).html(), $(this).attr('class'));
                        $(this).remove();
                    }
                });

        tagInput
            .keydown(function(event) {
                var keyCode = event.keyCode || event.which;
                // Backspace is not detected within a keypress, so using a keydown
                if (keyCode == BACKSPACE && tagInput.val() == '') {
                    var tag = tagList.children('.tagit-choice:last');
                    if (!settings.removeConfirmation || tag.hasClass('remove')) {
                        // When backspace is pressed, the last tag is deleted.
                        remove_tag(tag);
                    } else if (settings.removeConfirmation) {
                        tag.addClass('remove');
                    }
                }
            })
            .keypress(function(event) {
                var keyCode = event.keyCode || event.which;
                // Comma/Space/Enter are all valid delimiters for new tags. except when there is an open quote or if setting allowSpaces = true
                if (
                    keyCode == COMMA ||
                    keyCode == ENTER ||
                    keyCode == TAB ||
                    (
             	        keyCode == SPACE &&
             	        settings.allowSpaces != true &&
				        (
					        ($.trim(tagInput.val()).replace( /^s*/, '' ).charAt(0) != '"') ||
					        (
					            $.trim(tagInput.val()).charAt(0) == '"' &&
					            $.trim(tagInput.val()).charAt(tagInput.val().trim().length - 1) == '"' &&
					            $.trim(tagInput.val()).length - 1 != 0
					        )
				        )
                    )
                ) {

                    event.preventDefault();
                    $.trim(create_tag(tagInput.val().replace(/^'|"$|,+$/g, ''));
                }
                if (settings.removeConfirmation) {
                    tagList.children('.tagit-choice:last').removeClass('remove');
                }
            });

        if (options.availableTags || options.tagSource) {
            tagInput.autocomplete({
                source: settings.tagSource,
                select: function(event, ui) {
                    create_tag(ui.item.value);
                    // Preventing the tag input to be updated with the chosen value.
                    return false;
                }
            });
        }

        function assigned_tags() {
            var tags = [];
            tagList.children('.tagit-choice').each(function() {
                tags.push($(this).children('input').val());
            });
            return tags;
        }

        function subtract_array(a1, a2) {
            var result = new Array();
            for (var i = 0; i < a1.length; i++) {
                if (a2.indexOf(a1[i]) == -1) {
                    result.push(a1[i]);
                }
            }
            return result;
        }

        function is_new(value) {
            var isNew = true;
            tagList.children('.tagit-choice').each(function(i) {
                if (format_str(value) == format_str($(this).children('input').val())) {
                    isNew = false;
                    return;
                }
            });
            return isNew;
        }
	    function format_str(str) {
		    if(settings.caseSensitive)
			    return str;
		    return str.toLowerCase();
	    }
        function create_tag(value, additionalClass) {
            // Cleaning the input.
            tagInput.val('');

            if (!is_new(value) || value == '') {
                return false;
            }
            var linkValue = value;
            if (settings.onTagClicked) {
      	        linkValue = '' + value + '';
            }
            // create tag
            var tag = $('
')
                .addClass('tagit-choice')
                .addClass(additionalClass)
                .append(linkValue)
                .append('x');
            if (settings.singleField) {
                //TODO
            } else {
                tag.append('<input type="hidden" style="display:none;" value="' + value + '" name="' + settings.itemName + '[' + settings.fieldName + '][]">');
            }

            if (settings.onTagAdded) {
                settings.onTagAdded(tag);
            }

            // insert tag
            tagInput.parent().before(tag);
        }
        function remove_tag(tag) {
            if (settings.onTagRemoved) {
                settings.onTagRemoved(tag);
            }
            if (settings.singleField) {
                //TODO
            }
            tag.remove();
        }

        // maintaining chainability
        return this;
    };

})(jQuery);

<|endoftext|>