<commit_before>(function ($, audiojs) {
    'use strict';

    $.fn.addPlayer = function (preload) {
        if ($(this).length !== 1) {
            throw new Error('Cannot instantiate player on ' +
                            'multiple/null selector');
        }
        if (!$(this).data('js-player')) {
            $(this).data('js-player', new Player($(this), preload));
        }
        return $(this).data('js-player');
    };

    var Track = function (src, title, dur, poster_src, pod_id, last_pos, played) {
        return {
            src: src,
            title: title,
            duration: dur,
            poster: poster_src,
            podcast: Number(pod_id),
            last_pos: (last_pos) ? last_pos : 0,
            played: (played) ? played : false
        };
    };

    var TrackElement = function (track) {
        var el = $('

' +
                   '
' +
                   '  ' +
                   '

' + track.title +
                   '

');
        return el;
    };

    var PlayMode = {
        continue: 0x01,
        repeat: 0x02
    };

    var Player = function (parentElement, preload) {
        if (!preload) preload = {};
        var P = {
            _dom: $('

'),
            _mode: (preload.mode) ? preload.mode : 0,
            header: new Header(),
            audio: new AudioPlayer(),
            playlist: new PlayList(preload.playlist),

            init: function (volume) {
                this.audio.init(this, volume);
                this._dom.find('.player-list ol').click(function (e) {
                    var li = ($(e.target).is('li')) ? $(e.target) :
                            $(e.target).closest('li'),
                        index = li.index(),
                        div = ($(e.target).is('div'))? $(e.target) :
                            $(e.target).closest('div');
                    if (div.hasClass('pl-btn-del')) {
                        P.delete(index);
                    }
                    else {
                        P.load(index);
                        P.play();
                    }
                });
            },
            error: function (e) {
                console.log(e);
                this.header.loadError(this.playlist.getTrack());
                this._showIcon('error');
            },
            load: function (index) {
                var track = this.playlist.load(index);
                this._showIcon('load');
                this.audio.load(track);
                this.header.load(track);
            },
            unload: function () {
                this._showIcon();
            },
            add: function (src, title, dur, poster_src, pod_id) {
                var i = this.playlist.add(
                    src, title, dur, poster_src, pod_id);
                if (i === 0) this.load(i);
                console.log('Added ' + title + ' to index ' + i);
            },
            delete: function (index) {
                console.log('deelete: ' + index);
                var c = this.playlist._cur;
                if (c === index) {
                    this.stop();
                    if (this.playlist.count() > 1) this.nextTrack(true);
                    else this.unload();
                }
                this.playlist.delete(index);
            },
            addAndPlay: function (src, title, dur, poster_src, pod_id) {
                var i = this.playlist.insert(
                    src, title, dur, poster_src, pod_id);
                console.log('Added ' + title + ' to index ' + i);
                this.load(i);
                this.play();
            },
            stop: function () {
                this.pause();
                this.reset();
            },
            play: function () {
                if (this.playlist.getTrack()) {
                    this.audio.play();
                    this._showIcon('pause');
                }
            },
            pause: function () {
                if (this.playlist.getTrack()) {
                    this.audio.pause();
                    this._showIcon('play');
                }
            },
            trackFinished: function () {
                this.playlist.finished();
                if (this.isMode(PlayMode.continue)) {
                    var t = this.playlist.next();
                    if (t !== -1 || this.isMode(PlayMode.repeat)) {
                        this.nextTrack();
                    }
                }
                else if (this.isMode(PlayMode.repeat)) {
                    this.reset();
                    this.play();
                }
            },
            reset: function () {
                this.audio.reset();
            },
            nextTrack: function (noplay) {
                var t = this.playlist.next();
                if (t === -1) t = 0;
                this.load(t);
                if (!noplay) this.play();
            },
            prevTrack: function () {
                var t = this.playlist.prev();
                if (t === -1) t = this.playlist.count() - 1;
                this.load(t);
                this.play();
            },
            skipAhead: function (sec) {
                this.audio.skipAhead(sec);
            },
            skipBack: function (sec) {
                this.audio.skipBack(sec);
            },
            addMode: function (mode) {
                mode = (Number(mode) == mode) ? mode : Modes[mode];
                this._mode = this._mode | mode;
            },
            remMode: function (mode) {
                mode = (Number(mode) == mode) ? mode : Modes[mode];
                this._mode = this._mode & ~mode;
            },
            isMode: function () {
                var i;
                if (arguments.length < 1) return false;
                for (i = 0; i < arguments.length; i++) {
                    if (!(this._mode & arguments[i])) return false;
                }
                return true;
            },
            setVolume: function (vol) {
                this.audio.setVolume(vol);
            },
            _showIcon: function (type) {
                var all = 'p-play p-pause p-load p-error',
                    pp = this._dom.find('.play-pause'),
                    Types = {
                    play: 'p-play',
                    pause: 'p-pause',
                    load: 'p-load',
                    error: 'p-error'
                };
                if (!type) pp.removeClass(all);
                else if (!Types[type]) throw new Error('Cannot display icon: ' + type);
                else if (!pp.hasClass(Types[type])) {
                    pp.removeClass(all);
                    pp.addClass(Types[type]);
                }
            }
        };
        P.header._dom.append(P.audio._dom);
        P._dom.append(P.header._dom);
        P._dom.append(P.playlist._dom);
        parentElement.append(P._dom);
        P.init(preload.volume);
        return P;
    };

    var Header = function () {
        var H = {
            _dom: $('

'),

            load: function (track) {
                if (!track) this._unload();
                else {
                }
            },

            loadError: function (track) {

            },

            _unload: function () {
            }
        };
        return H;
    };

    var AudioPlayer = function () {
        var AP = {
            _dom: $('
<audio preload></audio>
'),
            _audio: false,

            init: function (player, volume) {
                if (!volume) volume = 0.75;
                if ($(this._dom.getUnique()).length < 1) {
                    throw new Error('Cannot initialize AudioPlayer that is ' +
                                    'not attached to the current DOM.');
                }
                this._audio = audiojs.newInstance(this._dom.find('audio')[0], {
                    trackEnded: function () {
                        player.trackFinished();
                    }
                });
                this._audio.onError = function (e) {
                    player.error(e);
                };
                this._dom.find('.play-pause').click(function () {
                    console.log('playpause: \n\t');
                    console.log($(this));
                    if ($(this).hasClass('p-play')) {
                        player.pause();
                    }
                    else if ($(this).hasClass('p-pause')) {
                        player.play();
                    }
                });
                this._dom.find('.skip.flip-glyph').click(function () {
                    player.skipBack(15);
                });
                this._dom.find('.skip.flip-glyph').click(function () {
                    player.skipAhead(30);
                });
                this._dom.find('.volume').click(function () {
                    var time = $(this).closest('.audiojs').find('.time');
                    if (time.find('span').css('display') != 'none') {
                        $(this).newTip(true, 'Close');
                        time.find('span').css('display', 'none');
                        time.find('.slider').css('display', 'block');
                        $(this).css('color', '#ccc');
                    }
                    else {
                        $(this).newTip(true, 'Adjust Volume');
                        time.find('span').css('display', 'block');
                        time.find('.slider').css('display', 'none');
                        $(this).css('color', '#777');
                    }
                });
                this._dom.find('.slider').slider({
                    range: "min",
                    min: 0,
                    max: 40,
                    value: volume * 40,
                    slide: function (event, ui) {
                        player.setVolume(ui.value/40);
                    }
                });
                player.setVolume(this._dom.find('.slider').slider('value')/40);
                this._dom.find('[title]').newTip();
            },

            load: function (src) {
                if (!src) this._unload();
                else {
                    if (typeof(src) === 'object') src = src.src;
                    this._audio.load(src);
                }
            },

            _unload: function () {
            },

            play: function () {
                this._audio.play();
            },

            pause: function () {
                this._audio.pause();
            },

            playPause: function () {
                this._audio.playPause();
            },

            skipTo: function (position) {
                var percent, a = this._dom.find('audio')[0];
                position = (position < 0) ? 0 :
                        (position > a.duration) ? a.duration : position;
                percent = position / a.duration;
                this._audio.skipTo(percent);
            },

            skipAhead: function (seconds) {
                var a = this._dom.find('audio')[0];
                this.skipTo(a.currentTime + seconds);
            },

            skipBack: function (seconds) {
                this.skipAhead(seconds * -1);
            },

            reset: function () {
                this.skipTo(0);
            },

            isPlaying: function () {
                return this._audio.playing;
            },

            getPosition: function () {
                return Math.floor(this._dom.find('audio')[0].currentTime);
            },

            setVolume: function (vol) {
                var el = this._dom.find('.volume');
                if (vol === this._dom.find('audio')[0].volume) return;
                this._audio.setVolume(vol);
                el.find('.glyphicon').css('display', 'none');
                if (vol === 0) {
                    el.find('.glyphicon-volume-off').css('display', 'block');
                }
                else if (vol === 1) {
                    el.find('.glyphicon-volume-up').css('display', 'block');
                }
                else {
                    el.find('.glyphicon-volume-down').css('display', 'block');
                }
            },

        };
        return AP;
    };

    var PlayList = function (list) {
        var PL = {
            _dom: $('

'),
            _list: [],
            _cur: 0,

            add: function (src, title, dur, poster_src, pod_id) {
                var track, played, index, el;
                if (typeof(src) === 'object') {
                    track = src;
                    autoload = title;
                }
                else {
                    track = new Track(src, title, dur, poster_src, pod_id);
                }
                if (this.hasTrack(track)) {
                    throw new Error('Track already in playlist.');
                }
                el = new TrackElement(track);
                this._list.push(track);
                this._appendElement(el);
                index = this.count() - 1;
                if (track.played) this._markPlayed(index);
                return index;
            },

            insert: function (src, title, dur, poster_src, pod_id) {
                var track, played, el;
                if (typeof(src) === 'object') {
                    track = src;
                    autoload = title;
                }
                else {
                    track = new Track(src, title, dur, poster_src, pod_id);
                }
                if (this.hasTrack(track)) {
                    throw new Error('Track already in playlist.');
                }
                el = new TrackElement(track);
                this._list.unshift(track);
                this._insertElement(el);
                if (track.played) this._markPlayed(0);
                if (this.count() !== 1) this._cur++;
                return 0;
            },

            delete: function (index) {
                var rem, element;
                if (this._list[index]) {
                    element = $(this._dom.find('li')[index]);
                    this._list.splice(index, 1);
                    this._removeElement(element);
                }
                if (index <= this._cur) this._cur--;
            },

            load: function (index) {
                var item, element;
                if (index < 0) index = this.count() - 1;
                if (index >= this.count()) index = 0;
                if (!this.getTrack(index)) {
                    return false;
                }
                this._cur = index;
                item = this.getTrack();
                element = $(this._dom.find('li')[index]);
                item.played = false;
                $(element).parent().find('.loaded').removeClass('loaded');
                $(element).removeClass('played');
                $(element).addClass('loaded');
                return item;
            },

            getTrack: function (index) {
                index = (Number(index) === index) ? index : this._cur;
                if (this.count() === 0 || !this._list[index]) {
                    return false;
                }
                return this._list[index];
            },

            hasTrack: function (track_or_src) {
                var src = track_or_src, filter;
                if (typeof(src) !== 'string') {
                    src = src.src;
                }
                filter = this._list.filter(function (track) {
                    return track.src === src;
                })[0];
                return (typeof(filter) !== 'undefined');
            },

            next: function () {
                if (!this._cur || this._cur === this.count() - 1) return -1;
                return this._cur + 1;
            },

            prev: function () {
                if (this._cur === 0) return -1;
                return this._cur - 1;
            },

            finished: function (index) {
                if (!index) index = this._cur;
                if (this._list[index]) {
                    this._list[index].played = true;
                    this._markPlayed(index);
                }
            },

            _markPlayed: function (index) {
                if (this._list[index]) {
                    $(this._list[index].selector).addClass('played');
                }
            },

            count: function () { return this._list.length; },

            _insertElement: function (el) {
                $(this._dom).find('ol').prepend(el);
                el.animate({opacity: 1}, 500);
            },

            _appendElement: function (el) {
                $(this._dom).find('ol').append(el);
                el.animate({opacity: 1}, 500);
            },

            _removeElement: function (el) {
                el.animate({height: '0px', opacity: 0}, 250, function () {
                    el.remove();
                });
            }
        };
        while (list && list.length > 0) {
            PL.insert(list.pop(), false);
        }
        return PL;
    };

}(jQuery, audiojs));<commit_msg>[Fix] Audioplayer click events<commit_after>(function ($, audiojs) {
    'use strict';

    $.fn.addPlayer = function (preload) {
        if ($(this).length !== 1) {
            throw new Error('Cannot instantiate player on ' +
                            'multiple/null selector');
        }
        if (!$(this).data('js-player')) {
            $(this).data('js-player', new Player($(this), preload));
        }
        return $(this).data('js-player');
    };

    var Track = function (src, title, dur, poster_src, pod_id, last_pos, played) {
        return {
            src: src,
            title: title,
            duration: dur,
            poster: poster_src,
            podcast: Number(pod_id),
            last_pos: (last_pos) ? last_pos : 0,
            played: (played) ? played : false
        };
    };

    var TrackElement = function (track) {
        var el = $('

' +
                   '
' +
                   '  ' +
                   '

' + track.title +
                   '

');
        return el;
    };

    var PlayMode = {
        continue: 0x01,
        repeat: 0x02
    };

    var Player = function (parentElement, preload) {
        if (!preload) preload = {};
        var P = {
            _dom: $('

'),
            _mode: (preload.mode) ? preload.mode : 0,
            header: new Header(),
            audio: new AudioPlayer(),
            playlist: new PlayList(preload.playlist),

            init: function (volume) {
                this.audio.init(this, volume);
                this._dom.find('.player-list ol').click(function (e) {
                    var li = ($(e.target).is('li')) ? $(e.target) :
                            $(e.target).closest('li'),
                        index = li.index(),
                        div = ($(e.target).is('div'))? $(e.target) :
                            $(e.target).closest('div');
                    if (div.hasClass('pl-btn-del')) {
                        P.delete(index);
                    }
                    else {
                        P.load(index);
                        P.play();
                    }
                });
            },
            error: function (e) {
                console.log(e);
                this.header.loadError(this.playlist.getTrack());
                this._showState('error');
            },
            load: function (index) {
                var track = this.playlist.load(index);
                this._showState('load');
                this.audio.load(track);
                this.header.load(track);
            },
            unload: function () {
                this._showIcon();
            },
            add: function (src, title, dur, poster_src, pod_id) {
                var i = this.playlist.add(
                    src, title, dur, poster_src, pod_id);
                if (i === 0) this.load(i);
                console.log('Added ' + title + ' to index ' + i);
            },
            delete: function (index) {
                console.log('deelete: ' + index);
                var c = this.playlist._cur;
                if (c === index) {
                    this.stop();
                    if (this.playlist.count() > 1) this.nextTrack(true);
                    else this.unload();
                }
                this.playlist.delete(index);
            },
            addAndPlay: function (src, title, dur, poster_src, pod_id) {
                var i = this.playlist.insert(
                    src, title, dur, poster_src, pod_id);
                console.log('Added ' + title + ' to index ' + i);
                this.load(i);
                this.play();
            },
            stop: function () {
                this.pause();
                this.reset();
            },
            play: function () {
                if (this.playlist.getTrack()) {
                    this.audio.play();
                    this._showState('play');
                }
            },
            pause: function () {
                if (this.playlist.getTrack()) {
                    this.audio.pause();
                    this._showState('pause');
                }
            },
            trackFinished: function () {
                this.playlist.finished();
                if (this.isMode(PlayMode.continue)) {
                    var t = this.playlist.next();
                    if (t !== -1 || this.isMode(PlayMode.repeat)) {
                        this.nextTrack();
                    }
                }
                else if (this.isMode(PlayMode.repeat)) {
                    this.reset();
                    this.play();
                }
            },
            reset: function () {
                this.audio.reset();
            },
            nextTrack: function (noplay) {
                var t = this.playlist.next();
                if (t === -1) t = 0;
                this.load(t);
                if (!noplay) this.play();
            },
            prevTrack: function () {
                var t = this.playlist.prev();
                if (t === -1) t = this.playlist.count() - 1;
                this.load(t);
                this.play();
            },
            skipAhead: function (sec) {
                this.audio.skipAhead(sec);
            },
            skipBack: function (sec) {
                this.audio.skipBack(sec);
            },
            addMode: function (mode) {
                mode = (Number(mode) == mode) ? mode : Modes[mode];
                this._mode = this._mode | mode;
            },
            remMode: function (mode) {
                mode = (Number(mode) == mode) ? mode : Modes[mode];
                this._mode = this._mode & ~mode;
            },
            isMode: function () {
                var i;
                if (arguments.length < 1) return false;
                for (i = 0; i < arguments.length; i++) {
                    if (!(this._mode & arguments[i])) return false;
                }
                return true;
            },
            setVolume: function (vol) {
                this.audio.setVolume(vol);
            },
            _showState: function (type) {
                var all = 'p-play p-pause p-load p-error',
                    pp = this._dom.find('.play-pause'),
                    Types = {
                    play: 'p-play',
                    pause: 'p-pause',
                    load: 'p-load',
                    error: 'p-error'
                };
                if (!type) pp.removeClass(all);
                else if (!Types[type]) throw new Error('Cannot display state: ' + type);
                else if (!pp.hasClass(Types[type])) {
                    pp.removeClass(all);
                    pp.addClass(Types[type]);
                }
            }
        };
        P.header._dom.append(P.audio._dom);
        P._dom.append(P.header._dom);
        P._dom.append(P.playlist._dom);
        parentElement.append(P._dom);
        P.init(preload.volume);
        return P;
    };

    var Header = function () {
        var H = {
            _dom: $('

'),

            load: function (track) {
                if (!track) this._unload();
                else {
                }
            },

            loadError: function (track) {

            },

            _unload: function () {
            }
        };
        return H;
    };

    var AudioPlayer = function () {
        var AP = {
            _dom: $('
<audio preload></audio>
'),
            _audio: false,

            init: function (player, volume) {
                if (!volume) volume = 0.75;
                if ($(this._dom.getUnique()).length < 1) {
                    throw new Error('Cannot initialize AudioPlayer that is ' +
                                    'not attached to the current DOM.');
                }
                this._audio = audiojs.newInstance(this._dom.find('audio')[0], {
                    trackEnded: function () {
                        player.trackFinished();
                    }
                });
                this._audio.onError = function (e) {
                    player.error(e);
                };
                this._dom.find('.play-pause').click(function () {
                    console.log('playpause: \n\t');
                    console.log($(this));
                    if ($(this).hasClass('p-play')) {
                        player.pause();
                    }
                    else if ($(this).hasClass('p-pause')) {
                        player.play();
                    }
                });
                this._dom.find('.skip.ahead').click(function () {
                    player.skipAhead(30);
                });
                this._dom.find('.skip.back').click(function () {
                    player.skipBack(15);
                });
                this._dom.find('.volume').click(function () {
                    var time = $(this).closest('.audiojs').find('.time');
                    if (time.find('span').css('display') != 'none') {
                        $(this).newTip(true, 'Close');
                        time.find('span').css('display', 'none');
                        time.find('.slider').css('display', 'block');
                        $(this).css('color', '#ccc');
                    }
                    else {
                        $(this).newTip(true, 'Adjust Volume');
                        time.find('span').css('display', 'block');
                        time.find('.slider').css('display', 'none');
                        $(this).css('color', '#777');
                    }
                });
                this._dom.find('.slider').slider({
                    range: "min",
                    min: 0,
                    max: 40,
                    value: volume * 40,
                    slide: function (event, ui) {
                        player.setVolume(ui.value/40);
                    }
                });
                player.setVolume(this._dom.find('.slider').slider('value')/40);
                this._dom.find('[title]').newTip();
            },

            load: function (src) {
                if (!src) this._unload();
                else {
                    if (typeof(src) === 'object') src = src.src;
                    this._audio.load(src);
                }
            },

            _unload: function () {
            },

            play: function () {
                this._audio.play();
            },

            pause: function () {
                this._audio.pause();
            },

            playPause: function () {
                this._audio.playPause();
            },

            skipTo: function (position) {
                var percent, a = this._dom.find('audio')[0];
                position = (position < 0) ? 0 :
                        (position > a.duration) ? a.duration : position;
                percent = Math.floor(position / a.duration * 100) / 100;
                this._audio.skipTo(percent);
            },

            skipAhead: function (seconds) {
                var a = this._dom.find('audio')[0];
                this.skipTo(a.currentTime + seconds);
            },

            skipBack: function (seconds) {
                this.skipAhead(seconds * -1);
            },

            reset: function () {
                this.skipTo(0);
            },

            isPlaying: function () {
                return this._audio.playing;
            },

            getPosition: function () {
                return Math.floor(this._dom.find('audio')[0].currentTime);
            },

            setVolume: function (vol) {
                var el = this._dom.find('.volume');
                if (vol === this._dom.find('audio')[0].volume) return;
                this._audio.setVolume(vol);
                el.find('.glyphicon').css('display', 'none');
                if (vol === 0) {
                    el.find('.glyphicon-volume-off').css('display', 'block');
                }
                else if (vol === 1) {
                    el.find('.glyphicon-volume-up').css('display', 'block');
                }
                else {
                    el.find('.glyphicon-volume-down').css('display', 'block');
                }
            },

        };
        return AP;
    };

    var PlayList = function (list) {
        var PL = {
            _dom: $('

'),
            _list: [],
            _cur: 0,

            add: function (src, title, dur, poster_src, pod_id) {
                var track, played, index, el;
                if (typeof(src) === 'object') {
                    track = src;
                    autoload = title;
                }
                else {
                    track = new Track(src, title, dur, poster_src, pod_id);
                }
                if (this.hasTrack(track)) {
                    throw new Error('Track already in playlist.');
                }
                el = new TrackElement(track);
                this._list.push(track);
                this._appendElement(el);
                index = this.count() - 1;
                if (track.played) this._markPlayed(index);
                return index;
            },

            insert: function (src, title, dur, poster_src, pod_id) {
                var track, played, el;
                if (typeof(src) === 'object') {
                    track = src;
                    autoload = title;
                }
                else {
                    track = new Track(src, title, dur, poster_src, pod_id);
                }
                if (this.hasTrack(track)) {
                    throw new Error('Track already in playlist.');
                }
                el = new TrackElement(track);
                this._list.unshift(track);
                this._insertElement(el);
                if (track.played) this._markPlayed(0);
                if (this.count() !== 1) this._cur++;
                return 0;
            },

            delete: function (index) {
                var rem, element;
                if (this._list[index]) {
                    element = $(this._dom.find('li')[index]);
                    this._list.splice(index, 1);
                    this._removeElement(element);
                }
                if (index <= this._cur) this._cur--;
            },

            load: function (index) {
                var item, element;
                if (index < 0) index = this.count() - 1;
                if (index >= this.count()) index = 0;
                if (!this.getTrack(index)) {
                    return false;
                }
                this._cur = index;
                item = this.getTrack();
                element = $(this._dom.find('li')[index]);
                item.played = false;
                $(element).parent().find('.loaded').removeClass('loaded');
                $(element).removeClass('played');
                $(element).addClass('loaded');
                return item;
            },

            getTrack: function (index) {
                index = (Number(index) === index) ? index : this._cur;
                if (this.count() === 0 || !this._list[index]) {
                    return false;
                }
                return this._list[index];
            },

            hasTrack: function (track_or_src) {
                var src = track_or_src, filter;
                if (typeof(src) !== 'string') {
                    src = src.src;
                }
                filter = this._list.filter(function (track) {
                    return track.src === src;
                })[0];
                return (typeof(filter) !== 'undefined');
            },

            next: function () {
                if (!this._cur || this._cur === this.count() - 1) return -1;
                return this._cur + 1;
            },

            prev: function () {
                if (this._cur === 0) return -1;
                return this._cur - 1;
            },

            finished: function (index) {
                if (!index) index = this._cur;
                if (this._list[index]) {
                    this._list[index].played = true;
                    this._markPlayed(index);
                }
            },

            _markPlayed: function (index) {
                if (this._list[index]) {
                    $(this._list[index].selector).addClass('played');
                }
            },

            count: function () { return this._list.length; },

            _insertElement: function (el) {
                $(this._dom).find('ol').prepend(el);
                el.animate({opacity: 1}, 500);
            },

            _appendElement: function (el) {
                $(this._dom).find('ol').append(el);
                el.animate({opacity: 1}, 500);
            },

            _removeElement: function (el) {
                el.animate({height: '0px', opacity: 0}, 250, function () {
                    el.remove();
                });
            }
        };
        while (list && list.length > 0) {
            PL.insert(list.pop(), false);
        }
        return PL;
    };

}(jQuery, audiojs));<|endoftext|>


<commit_before>// *** Express Server Setup ***

var express = require("express");
var app = express();

//Enable compression
var compression = require("compression");
app.use(compression());

// body-parser for the json
var bodyParser = require( 'body-parser' );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded( { extended: true } ))

// *** Security ***

var express_enforces_ssl = require('express-enforces-ssl');
// Do not use SSL in the localhost because there's no certificate there.
/*
if ( process.env.NODE_ENV ) {
  app.enable('trust proxy');
  app.use(express_enforces_ssl());
}
*/
/*
var helmet = require('helmet');
app.use(helmet());
app.use(helmet.referrerPolicy());
*/
var cors = require('cors');
var whitelist = [
    process.env.ALLOWED_ORIGIN
];
var corsOptions = {
    origin: function(origin, callback){
      if (whitelist.indexOf(origin) !== -1) {
        callback(null, true)
      } else {
        console.log("Origin not allowed by CORS:" + origin);
        callback(new Error('Origin not allowed by CORS.  The origin is ' + origin), false);
      }
    },
    methods: "POST"
};

// *** Mailgun ***

var mailgun = require('mailgun-js') ({
  apiKey: process.env.MAILGUN_API_KEY,
  domain: process.env.MAILGUN_DOMAIN
} );

// *** reCAPTCHA ***

var recaptcha = require('express-recaptcha');
recaptcha.init( process.env.RECAPTCHA_SITE_KEY, process.env.RECAPTCHA_SECRET_KEY );

app.post('/mail', [recaptcha.middleware.verify, cors(corsOptions)], function(req, res) {

  console.log("Received data:");
  console.log(req.body);
  console.log("Response from reCAPTCHA:");
  console.log(req.recaptcha);

  req.body.to = process.env.EMAIL;

  if ( req.recaptcha.error ) {
    console.log("Recaptcha Error");
    return res.status(403).send( { message: "Error From ReCAPTCHA: "+req.recaptcha.error.toString() } );
  }
  else {
    mailgun.messages().send( req.body, function sendReply (error, body) {
      console.log("Response from Mailgun:");
      console.log(body);
      if ( !error ) {
        console.log("Message Sent");
        return res.status(200).send( { message: "Your message has been sent." });
      }
      else {
        console.log("Cannot send message due to errors.");
        console.log(error);
        return res.status(404).send( { message: "Cannot send message due to server error." } );
      }
    });
  }
});

app.get('/cors', cors(corsOptions), function(req, res) {
    res.send('I am CORS alive! :)');
})

app.get('/', function(req, res) {
    res.send('I am alive! :)');
})

//Turn on the web server listening on a specific port
app.listen( process.env.PORT );
<commit_msg>Debug staging<commit_after>// *** Express Server Setup ***

var express = require("express");
var app = express();

//Enable compression
var compression = require("compression");
app.use(compression());

// body-parser for the json
var bodyParser = require( 'body-parser' );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded( { extended: true } ))

// *** Security ***

/*
var helmet = require('helmet');
app.use(helmet());
app.use(helmet.referrerPolicy());
*/
var cors = require('cors');
var whitelist = [
    process.env.ALLOWED_ORIGIN
];
var corsOptions = {
    origin: function(origin, callback){
      if (whitelist.indexOf(origin) !== -1) {
        callback(null, true)
      } else {
        console.log("Origin not allowed by CORS:" + origin);
        callback(new Error('Origin not allowed by CORS.  The origin is ' + origin), false);
      }
    },
    methods: "POST"
};

// *** Mailgun ***

var mailgun = require('mailgun-js') ({
  apiKey: process.env.MAILGUN_API_KEY,
  domain: process.env.MAILGUN_DOMAIN
} );

// *** reCAPTCHA ***

var recaptcha = require('express-recaptcha');
recaptcha.init( process.env.RECAPTCHA_SITE_KEY, process.env.RECAPTCHA_SECRET_KEY );

app.post('/mail', [recaptcha.middleware.verify, cors(corsOptions)], function(req, res) {

  console.log("Received data:");
  console.log(req.body);
  console.log("Response from reCAPTCHA:");
  console.log(req.recaptcha);

  req.body.to = process.env.EMAIL;

  if ( req.recaptcha.error ) {
    console.log("Recaptcha Error");
    return res.status(403).send( { message: "Error From ReCAPTCHA: "+req.recaptcha.error.toString() } );
  }
  else {
    mailgun.messages().send( req.body, function sendReply (error, body) {
      console.log("Response from Mailgun:");
      console.log(body);
      if ( !error ) {
        console.log("Message Sent");
        return res.status(200).send( { message: "Your message has been sent." });
      }
      else {
        console.log("Cannot send message due to errors.");
        console.log(error);
        return res.status(404).send( { message: "Cannot send message due to server error." } );
      }
    });
  }
});

app.get('/cors', cors(corsOptions), function(req, res) {
    res.send('I am CORS alive! :)');
})

app.get('/', function(req, res) {
    res.send('I am alive! :)');
})

//Turn on the web server listening on a specific port
app.listen( process.env.PORT );
<|endoftext|>


<commit_before>class CatmullClark
{
    // Constructor
    constructor(vertice, edges, polygones)
    {
        this.vertice = vertice;
        this.edges = edges;
        this.polygones = polygones;

        this.catmullClarkVertice = [];
        this.catmullClarkEdges = [];
        this.catmullClarkPolygones = [];
    }

    // Setter
    setVertice(vertice)
    {
        this.vertice = vertice;
    }
    setEdges(edges)
    {
        this.edges = edges;
    }
    setVertice(polygones)
    {
        this.polygones = polygones;

    }

    computeCatmullClarkPoints()
    {
        // Calcul des tous les face points
        for(var i = 0; i < this.polygones.length; ++i)
            this.polygones[i].computeFacePoint();

        // Calcul des tous les edge points
        for(var i = 0; i < this.edges.length; ++i)
            this.edges[i].computeEdgePoint();

        // Calcul des tous les vertice points
        for(var i = 0; i < this.vertice.length; ++i)
            this.vertice[i].computeVertexPoint();
    }

    pushCatmullClarkVertex(vertex)
    {
        this.catmullClarkVertice.push(vertex);
    }

    pushCatmullClarkEdge(edge)
    {
        this.catmullClarkEdges.push(edge);

        // Ajout de l'edge adjacente aux vertice de l'edge
        edge.v1.adjacentEdges.(edge);
        edge.v2.adjacentEdges.(edge);
    }

    pushCatmullClarkPolygone(polygone)
    {
        this.catmullClarkPolygones.push(polygone);

        // Ajout du polygone (gauche ou droit) aux edges composant le polygone
        var edges = this.polygones.edges;
        for(var i = 0; i < edges.length; ++i)
            edges[i].setPolygone(polygone);
    }

    linkFacePointsToEdgePoints()
    {
        var tmpFacePoint = null;
        var tmpEdges = null;

        var tmpEdgePoint = null;

        var newEdge = null;

        // Parcout de toutes les faces pour lier le face point aux edge point de chaque edge de la face
        for(var i = 0; i < this.polygones.length; ++i)
        {
            tmpFacePoint = this.polygones[i].facePoint;
            tmpEdges = this.polygones[i].edges;

            this.catmullClarkVertice.push(tmpFacePoint);

            // Parcout des edges du polygone pour ajouter les edgesPoints et les nouvelles edges
            for(var j = 0; j < tmpEdges.length; ++j)
            {
                tmpEdgePoint = tmpEdges[j].edgePoint;
                this.catmullClarkVertice.push(tmpEdgePoint);

                newEdge = new Edge(tmpFacePoint, tmpEdgePoint);
                this.catmullClarkEdges.push(newEdge);
            }
        }
    }

    linkVertexPointsToEdgePoints()
    {
        var tmpVertex = null;
        var tmpIncidentEdges = null
        var tmpVertexPoint = null;

        var tmpEdgePoint = null;
        var newEdge = null;

        for(var i = 0; i < this.vertice.length; ++i)
        {
            tmpVertex = this.vertice[i];
            tmpVertexPoint = tmpVertex.vertexPoint;
            tmpIncidentEdges = tmpVertex.incidentEdges;

            this.catmullClarkVertice.push(tmpVertexPoint);

            // Création des edges du nouveau points
            for(var j = 0; j < tmpIncidentEdges.length; ++j)
            {
                tmpEdgePoint = tmpIncidentEdges[j].EdgePoint;

                newEdge = new Edge(tmpVertexPoint, tmpEdgePoint);
                this.catmullClarkEdges.push(newEdge);
            }
        }
    }

    findEdge(v1, v2)
    {
        var tmpEdge = null;
        for(var i = 0; i < this.catmullClarkEdges.length; ++i)
        {
            tmpEdge = this.catmullClarkEdges[i];
            if((tmpEdge.v1 == v1 || tmpEdge.v2 == v1) && (tmpEdge.v1 == v2 || tmpEdge.v2 == v2))
                return tmpEdge;
        }
        return null;
    }

    hasPolygone(edge1, edge2, edge3, edge4)
    {
        var tmpPlygone = null:
        var tmpEdges = null;

        var tmpEdge = null;

        var hasEdge = true;

        var arrayLength = 0;

        for(var i = 0; i < this.catmullClarkPolygones.length; ++i)
        {
            tmpPolygone = this.catmullClarkPolygones[i];
            tmpEdges = tmpPolygone.edges;
            arrayLength = tmpEdges.length;

            if(arrayLength == 4)
            {
                hasEdge = true;

                for(var j = 0; j < tmpEdges.length; ++j)
                {
                    tmpEdge = tmpEdges[j];
                    if(tmpEdge != edge1 || tmpEdge != edge2 || tmpEdge != edge3 || tmpEdge != edge4)
                    {
                        hasEdge = false;
                    }
                }

                if(hasAllEdges)
                    return true;
            }
        }
        return false;
    }

    findEdgesToPushCatmullClarkPolygone(facePoint, polygoneEdges, polygoneEdge1, vertex)
    {
        var polygoneEdge2 = null;

        var edgePoint1 = null;
        var edgePoint2 = null;

        var edge1 = null;
        var edge2 = null;
        var edge3 = null;
        var edge4 = null;

        var vertexPoint = vertex.vertexPoint;

        for(var i = 0; i < polygoneEdges.length; ++i)
        {
            // Edge 2
            polygoneEdge2 = polygoneEdges[i];

            if(polygoneEdge1 != polygoneEdge2)
            {
                if(vertex == polygoneEdge2.v1 || vertex == polygoneEdge2.v2)
                {
                    // Edge point 1 et 2
                    edgePoint1 = polygoneEdge1.edgePoint;
                    edgePoint2 = polygoneEdge2.edgePoint;

                    edge1 = findEdge(facePoint, edgePoint1);
                    edge2 = findEdge(edgePoint1, vertexPoint);
                    edge3 = findEdge(vertexPoint, edgePoint2);
                    edge4 = findEdge(edgePoint2, facePoint);

                    if(edge1 != null && edge2 != null && edge3 != null && edge4 != null)
                    {
                        if(this.hasPolygone(edge1, edge2, edge3, edge4)
                        {
                            newPolygone = new Polygone(edge1, edge2, edge3, edge4);
                            pushCatmullClarkPolygone(newPolygone);
                        }
                        break;
                    }
                }
            }
        }
    }

    generateCatmullClarkPolygones()
    {
        var tmpPolygone = null;
        var tmpPolygoneEdges = null;
        var tmpPolygoneFacePoint = null;

        for(var i = 0; i < this.polygones.length; ++i)
        {
            tmpPolygone = this.polygones[i];
            tmpPolygoneEdges = tmpPolygone.edges;
            tmpPolygoneFacePoint = tmpPolygone.facePoint;

            for(var j = 0; j < tmpPolygoneEdges.length; ++j)
            {
                tmpPolygoneEdge1 = tmpPolygoneEdges[j];

                this.findEdgesToPushCatmullClarkPolygones(tmpPolygoneFacePoint, tmpPolygoneEdges, tmpPolygoneEdge1, tmpPolygoneEdge1.v1);
                this.findEdgesToPushCatmullClarkPolygones(tmpPolygoneFacePoint, tmpPolygoneEdges, tmpPolygoneEdge1, tmpPolygoneEdge1.v2);
            }
        }
    }

    // Lancer l'algo de subdivision Catmull-Clark
    launchCatmullClark()
    {
        this.computeCatmullClarkPoints();

        this.linkFacePointsToEdgePoints();

        this.linkVertexPointsToEdgePoints();

        this.generateCatmullClarkPolygones();
    }
}<commit_msg>modif find poly et edge<commit_after>class CatmullClark
{
    // Constructor
    constructor(vertice, edges, polygones)
    {
        this.vertice = vertice;
        this.edges = edges;
        this.polygones = polygones;

        this.catmullClarkVertice = [];
        this.catmullClarkEdges = [];
        this.catmullClarkPolygones = [];
    }

    // Setter
    setVertice(vertice)
    {
        this.vertice = vertice;
    }
    setEdges(edges)
    {
        this.edges = edges;
    }
    setVertice(polygones)
    {
        this.polygones = polygones;

    }

    computeCatmullClarkPoints()
    {
        // Calcul des tous les face points
        for(var i = 0; i < this.polygones.length; ++i)
            this.polygones[i].computeFacePoint();

        // Calcul des tous les edge points
        for(var i = 0; i < this.edges.length; ++i)
            this.edges[i].computeEdgePoint();

        // Calcul des tous les vertice points
        for(var i = 0; i < this.vertice.length; ++i)
            this.vertice[i].computeVertexPoint();
    }

    pushCatmullClarkVertex(vertex)
    {
        this.catmullClarkVertice.push(vertex);
    }

    pushCatmullClarkEdge(edge)
    {
        this.catmullClarkEdges.push(edge);

        // Ajout de l'edge adjacente aux vertice de l'edge
        edge.v1.adjacentEdges.(edge);
        edge.v2.adjacentEdges.(edge);
    }

    pushCatmullClarkPolygone(polygone)
    {
        this.catmullClarkPolygones.push(polygone);

        // Ajout du polygone (gauche ou droit) aux edges composant le polygone
        var edges = this.polygones.edges;
        for(var i = 0; i < edges.length; ++i)
            edges[i].setPolygone(polygone);
    }

    linkFacePointsToEdgePoints()
    {
        var tmpFacePoint = null;
        var tmpEdges = null;

        var tmpEdgePoint = null;

        var newEdge = null;

        // Parcout de toutes les faces pour lier le face point aux edge point de chaque edge de la face
        for(var i = 0; i < this.polygones.length; ++i)
        {
            tmpFacePoint = this.polygones[i].facePoint;
            tmpEdges = this.polygones[i].edges;

            this.catmullClarkVertice.push(tmpFacePoint);

            // Parcout des edges du polygone pour ajouter les edgesPoints et les nouvelles edges
            for(var j = 0; j < tmpEdges.length; ++j)
            {
                tmpEdgePoint = tmpEdges[j].edgePoint;
                this.catmullClarkVertice.push(tmpEdgePoint);

                newEdge = new Edge(tmpFacePoint, tmpEdgePoint);
                this.catmullClarkEdges.push(newEdge);
            }
        }
    }

    linkVertexPointsToEdgePoints()
    {
        var tmpVertex = null;
        var tmpIncidentEdges = null
        var tmpVertexPoint = null;

        var tmpEdgePoint = null;
        var newEdge = null;

        for(var i = 0; i < this.vertice.length; ++i)
        {
            tmpVertex = this.vertice[i];
            tmpVertexPoint = tmpVertex.vertexPoint;
            tmpIncidentEdges = tmpVertex.incidentEdges;

            this.catmullClarkVertice.push(tmpVertexPoint);

            // Création des edges du nouveau points
            for(var j = 0; j < tmpIncidentEdges.length; ++j)
            {
                tmpEdgePoint = tmpIncidentEdges[j].EdgePoint;

                newEdge = new Edge(tmpVertexPoint, tmpEdgePoint);
                this.catmullClarkEdges.push(newEdge);
            }
        }
    }

    findEdge(v1, v2)
    {
        var tmpEdge = null;
        for(var i = 0; i < this.catmullClarkEdges.length; ++i)
        {
            tmpEdge = this.catmullClarkEdges[i];

            if((tmpEdge.v1.id == v1.id || tmpEdge.v2.id == v1.id)
               && (tmpEdge.v1.id == v2.id || tmpEdge.v2.id == v2.id))
                return tmpEdge;
        }
        return null;
    }

    hasPolygone(edge1, edge2, edge3, edge4)
    {
        var tmpPlygone = null:
        var tmpEdges = null;

        var arrayLength = 0;

        var hasEdge = true;

        var tmpEdge = null;

        for(var i = 0; i < this.catmullClarkPolygones.length; ++i)
        {
            tmpPolygone = this.catmullClarkPolygones[i];
            tmpEdges = tmpPolygone.edges;

            arrayLength = tmpEdges.length;

            if(arrayLength == 4)
            {
                hasEdge = true;

                for(var j = 0; j < tmpEdges.length; ++j)
                {
                    tmpEdge = tmpEdges[j];
                    if(tmpEdge.id != edge1.id || tmpEdge.id != edge2.id || tmpEdge.id != edge3.id || tmpEdge.id != edge4.id)
                    {
                        hasEdge = false;
                    }
                }

                if(hasAllEdges)
                    return true;
            }
        }
        return false;
    }

    findEdgesToPushCatmullClarkPolygone(facePoint, polygoneEdges, polygoneEdge1, vertex)
    {
        var polygoneEdge2 = null;

        var edgePoint1 = null;
        var edgePoint2 = null;

        var edge1 = null;
        var edge2 = null;
        var edge3 = null;
        var edge4 = null;

        var vertexPoint = vertex.vertexPoint;

        for(var i = 0; i < polygoneEdges.length; ++i)
        {
            // Edge 2
            polygoneEdge2 = polygoneEdges[i];

            if(polygoneEdge1.id != polygoneEdge2.id)
            {
                if(vertex.id == polygoneEdge2.v1.id || vertex.id == polygoneEdge2.v2.id)
                {
                    // Edge point 1 et 2
                    edgePoint1 = polygoneEdge1.edgePoint;
                    edgePoint2 = polygoneEdge2.edgePoint;

                    edge1 = findEdge(facePoint, edgePoint1);
                    edge2 = findEdge(edgePoint1, vertexPoint);
                    edge3 = findEdge(vertexPoint, edgePoint2);
                    edge4 = findEdge(edgePoint2, facePoint);

                    if(edge1 != null && edge2 != null && edge3 != null && edge4 != null)
                    {
                        if(this.hasPolygone(edge1, edge2, edge3, edge4)
                        {
                            newPolygone = new Polygone(edge1, edge2, edge3, edge4);
                            pushCatmullClarkPolygone(newPolygone);
                        }
                        break;
                    }
                }
            }
        }
    }

    generateCatmullClarkPolygones()
    {
        var tmpPolygone = null;
        var tmpPolygoneEdges = null;
        var tmpPolygoneFacePoint = null;

        for(var i = 0; i < this.polygones.length; ++i)
        {
            tmpPolygone = this.polygones[i];
            tmpPolygoneEdges = tmpPolygone.edges;
            tmpPolygoneFacePoint = tmpPolygone.facePoint;

            for(var j = 0; j < tmpPolygoneEdges.length; ++j)
            {
                tmpPolygoneEdge1 = tmpPolygoneEdges[j];

                this.findEdgesToPushCatmullClarkPolygones(tmpPolygoneFacePoint, tmpPolygoneEdges, tmpPolygoneEdge1, tmpPolygoneEdge1.v1);
                this.findEdgesToPushCatmullClarkPolygones(tmpPolygoneFacePoint, tmpPolygoneEdges, tmpPolygoneEdge1, tmpPolygoneEdge1.v2);
            }
        }
    }

    // Lancer l'algo de subdivision Catmull-Clark
    launchCatmullClark()
    {
        this.computeCatmullClarkPoints();

        this.linkFacePointsToEdgePoints();

        this.linkVertexPointsToEdgePoints();

        this.generateCatmullClarkPolygones();
    }
}<|endoftext|>


<commit_before>var ty = require('../lib/types');
var asmAssert = require('../lib/asmAssert');

exports.testModuloIntish1 = asmAssert.one(
    "% doesn't return int",
    function f() {
        var x = 0, y = 0;
        x = (x|0)%(y|0);
    },
    { pass: false });

exports.testModuleIntish2 = asmAssert.one(
    "% returns intish",
    function f() {
        var x = 0, y = 0;
        x = ((x|0)%(y|0))|0;
    },
    { pass: true });

exports.testIntCoercionRequiresDouble1 = asmAssert.one(
    "~~ requires double",
    function f() {
        var x = 0.0, y = 0;
        y = ~~HF64[0];
    },
    { pass: false });

exports.testIntCoercionRequiresDouble2 = asmAssert.one(
    "~~ requires double",
    function f() {
        var x = 0.0, y = 0;
        y = ~~+HF64[0];
    },
    { pass: true });

exports.testNot = asmAssert.one(
    "! operator",
    function f() {
        var x = 0;
        x = !((x|0) > 0);
    },
    { pass: true });

exports.testParamTypes = asmAssert.one(
    "different parameter types",
    function f(x, y) {
        x = x|0;
        y = +y;
    }, {
        pass: true,
        types: {
            f: ty.Arrow([ty.Int, ty.Double], ty.Void)
        }
    });

exports.testAdd = asmAssert.one(
    "addition",
    function add1(x) {
        x = x|0;
        return ((x|0)+1)|0;
    }, {
        pass: true,
        types: {
            add1: ty.Arrow([ty.Int], ty.Signed)
        }
    });

exports.testImul = asmAssert.one(
    "Math.imul",
    function double(x) {
        x = x|0;
        return imul(x, 2)|0;
    }, {
        pass: true,
        double: ty.Arrow([ty.Int], ty.Signed)
    });

exports.testLoad = asmAssert.one(
    "heap load",
    function get(i) {
        i = i|0;
        return H32[i>>2]|0;
    }, {
        pass: true,
        types: {
            get: ty.Arrow([ty.Int], ty.Signed)
        }
    });

exports.testStore = asmAssert.one(
    "heap store",
    function set(i, x) {
        i = i|0;
        x = x|0;
        H32[i>>2] = x|0;
    }, {
        pass: true,
        types: {
            set: ty.Arrow([ty.Int, ty.Int], ty.Void)
        }
    });

exports.testCall1 = asmAssert(
    "function call",
    function call(stdlib, foreign, heap) {
        "use asm";
        __ALL__
        function f(x) {
            x = +x;
            return +(x + 1.0);
        }
        function g() {
            var x = 0.0;
            x = +f(x);
            return +x;
        }
        return {};
    }, { pass: true });

exports.testCall2 = asmAssert(
    "function call",
    function call(stdlib, foreign, heap) {
        "use asm";
        __ALL__
        function f(x) {
            x = x|0;
            return (x + 1)|0;
        }
        function g() {
            var x = 0.0;
            x = +f(x);
            return +x;
        }
        return {};
    }, { pass: false });

exports.testVoid1 = asmAssert(
    "void function call in expression statement",
    function void_(stdlib) {
        "use asm";
        __PURE__
        function f() { }
        function g() {
            f();
        }
        return {}
    }, { pass: true });

exports.testVoid2 = asmAssert(
    "void function call in comma expression",
    function void_(stdlib) {
        "use asm";
        __PURE__
        function f() { }
        function g() {
            var x = 0.0;
            x = (f(), f(), 1.0);
        }
        return {};
    }, { pass: true });

exports.testEval1 = asmAssert(
    "module named eval",
    function eval() {
        "use asm";
        __PURE__
        function empty () { }
        return empty;
    }, { pass: false });

exports.testEval2 = asmAssert(
    "function named eval",
    function m() {
        "use asm";
        __PURE__
        function eval() { }
        return eval;
    }, { pass: false });

exports.testEval3 = asmAssert(
    "local named eval",
    function m() {
        "use asm";
        __PURE__
        function f() {
            var eval = 0;
        }
        return f;
    }, { pass: false });

exports.testAbs = asmAssert(
    "abs returns signed",
    function call(stdlib, foreign, heap) {
        "use asm";
        __PURE__
        var abs = stdlib.Math.abs;
        function f() {
            return abs(1)|0;
        }
        return f;
    }, { pass: true });

exports.testIf = asmAssert(
    "if condition is Int",
    function m(){
        "use asm";
        function f(x,y) {
            x = x|0;
            y = y|0;
            if (x) {
                y = 3;
            }
        }
        return f;
    }, { pass: true });

exports.testEmpty = asmAssert(
    "empty statements",
    function m(){
        "use asm";
        function f() {
            ;
            ;
            ;
            {};
            if (0);
            if (0) {};
        }
        return f;
    }, { pass: true });

exports.testMinMax = asmAssert(
    "min and max validate",
    function m(stdlib, foreign, heap) {
        "use asm";
        var max = stdlib.Math.max;
        var min = stdlib.Math.max;
        function f(i0, i1, d0, d1) {
            i0 = i0|0;
            i1 = i1|0;
            d0 = +d0;
            d1 = +d1;
            var ia = 0;
            var ib = 0;
            var da = 0.0;
            var db = 0.0;
            ia = max(i0, i1)|0;
            ib = min(i0, i1)|0;
            da = +max(d0, d1);
            db = +min(d0, d1);
            return +(+(+(ia + ib|0) + d0) + d1);
        }
        return f;
    }, { pass: true });
<commit_msg>Add more min/max tests<commit_after>var ty = require('../lib/types');
var asmAssert = require('../lib/asmAssert');

exports.testModuloIntish1 = asmAssert.one(
    "% doesn't return int",
    function f() {
        var x = 0, y = 0;
        x = (x|0)%(y|0);
    },
    { pass: false });

exports.testModuleIntish2 = asmAssert.one(
    "% returns intish",
    function f() {
        var x = 0, y = 0;
        x = ((x|0)%(y|0))|0;
    },
    { pass: true });

exports.testIntCoercionRequiresDouble1 = asmAssert.one(
    "~~ requires double",
    function f() {
        var x = 0.0, y = 0;
        y = ~~HF64[0];
    },
    { pass: false });

exports.testIntCoercionRequiresDouble2 = asmAssert.one(
    "~~ requires double",
    function f() {
        var x = 0.0, y = 0;
        y = ~~+HF64[0];
    },
    { pass: true });

exports.testNot = asmAssert.one(
    "! operator",
    function f() {
        var x = 0;
        x = !((x|0) > 0);
    },
    { pass: true });

exports.testParamTypes = asmAssert.one(
    "different parameter types",
    function f(x, y) {
        x = x|0;
        y = +y;
    }, {
        pass: true,
        types: {
            f: ty.Arrow([ty.Int, ty.Double], ty.Void)
        }
    });

exports.testAdd = asmAssert.one(
    "addition",
    function add1(x) {
        x = x|0;
        return ((x|0)+1)|0;
    }, {
        pass: true,
        types: {
            add1: ty.Arrow([ty.Int], ty.Signed)
        }
    });

exports.testImul = asmAssert.one(
    "Math.imul",
    function double(x) {
        x = x|0;
        return imul(x, 2)|0;
    }, {
        pass: true,
        double: ty.Arrow([ty.Int], ty.Signed)
    });

exports.testLoad = asmAssert.one(
    "heap load",
    function get(i) {
        i = i|0;
        return H32[i>>2]|0;
    }, {
        pass: true,
        types: {
            get: ty.Arrow([ty.Int], ty.Signed)
        }
    });

exports.testStore = asmAssert.one(
    "heap store",
    function set(i, x) {
        i = i|0;
        x = x|0;
        H32[i>>2] = x|0;
    }, {
        pass: true,
        types: {
            set: ty.Arrow([ty.Int, ty.Int], ty.Void)
        }
    });

exports.testCall1 = asmAssert(
    "function call",
    function call(stdlib, foreign, heap) {
        "use asm";
        __ALL__
        function f(x) {
            x = +x;
            return +(x + 1.0);
        }
        function g() {
            var x = 0.0;
            x = +f(x);
            return +x;
        }
        return {};
    }, { pass: true });

exports.testCall2 = asmAssert(
    "function call",
    function call(stdlib, foreign, heap) {
        "use asm";
        __ALL__
        function f(x) {
            x = x|0;
            return (x + 1)|0;
        }
        function g() {
            var x = 0.0;
            x = +f(x);
            return +x;
        }
        return {};
    }, { pass: false });

exports.testVoid1 = asmAssert(
    "void function call in expression statement",
    function void_(stdlib) {
        "use asm";
        __PURE__
        function f() { }
        function g() {
            f();
        }
        return {}
    }, { pass: true });

exports.testVoid2 = asmAssert(
    "void function call in comma expression",
    function void_(stdlib) {
        "use asm";
        __PURE__
        function f() { }
        function g() {
            var x = 0.0;
            x = (f(), f(), 1.0);
        }
        return {};
    }, { pass: true });

exports.testEval1 = asmAssert(
    "module named eval",
    function eval() {
        "use asm";
        __PURE__
        function empty () { }
        return empty;
    }, { pass: false });

exports.testEval2 = asmAssert(
    "function named eval",
    function m() {
        "use asm";
        __PURE__
        function eval() { }
        return eval;
    }, { pass: false });

exports.testEval3 = asmAssert(
    "local named eval",
    function m() {
        "use asm";
        __PURE__
        function f() {
            var eval = 0;
        }
        return f;
    }, { pass: false });

exports.testAbs = asmAssert(
    "abs returns signed",
    function call(stdlib, foreign, heap) {
        "use asm";
        __PURE__
        var abs = stdlib.Math.abs;
        function f() {
            return abs(1)|0;
        }
        return f;
    }, { pass: true });

exports.testIf = asmAssert(
    "if condition is Int",
    function m(){
        "use asm";
        function f(x,y) {
            x = x|0;
            y = y|0;
            if (x) {
                y = 3;
            }
        }
        return f;
    }, { pass: true });

exports.testEmpty = asmAssert(
    "empty statements",
    function m(){
        "use asm";
        function f() {
            ;
            ;
            ;
            {};
            if (0);
            if (0) {};
        }
        return f;
    }, { pass: true });

exports.testMinMax = asmAssert(
    "min and max validate",
    function m(stdlib, foreign, heap) {
        "use asm";
        var max = stdlib.Math.max;
        var min = stdlib.Math.min;
        function f(i0, i1, d0, d1) {
            i0 = i0|0;
            i1 = i1|0;
            d0 = +d0;
            d1 = +d1;
            var ia = 0;
            var ib = 0;
            var da = 0.0;
            var db = 0.0;
            ia = max(i0, i1)|0;
            ib = min(i0, i1)|0;
            da = +max(d0, d1);
            db = +min(d0, d1);
            return +(+(+(ia + ib|0) + d0) + d1);
        }
        return f;
    }, { pass: true });

exports.testMinWrongArgumentType = asmAssert(
    "min argument types don't match",
    function m(stdlib, foreign, heap) {
        "use asm";
        var min = stdlib.Math.min;
        function f(i0, d1) {
            i0 = i0|0;
            d1 = +d1;
            min(i0, d1)|0;
        }
        return f;
    }, { pass: false });

exports.testMaxWrongArgumentType = asmAssert(
    "min argument types don't match",
    function m(stdlib, foreign, heap) {
        "use asm";
        var max = stdlib.Math.max;
        function f(d0, i1) {
            d0 = +d0;
            i1 = i1|0;
            +max(d0, i1);
        }
        return f;
    }, { pass: false });

exports.testMaxWrongReturnType = asmAssert(
    "min argument types don't match",
    function m(stdlib, foreign, heap) {
        "use asm";
        var max = stdlib.Math.max;
        function f(i0, i1) {
            i0 = i0|0;
            i1 = i1|0;
            +max(i0, i1);
        }
        return f;
    }, { pass: false });
<|endoftext|>


<commit_before>'use strict';

function checkAbortTransition(context, transitionArgument) {
	const transitionVariable = context.getScope().set.get(transitionArgument.name);
	const transitionAbortCall = transitionVariable.references.find((ref) =>
		ref.identifier.parent.parent.type === 'CallExpression' && ref.identifier.parent.parent.callee.property.name === 'abort'
	);

	if (transitionAbortCall) {
		context.report({
			node: transitionAbortCall.identifier.parent.parent,
			message: 'avoid `transition.abort` on route hooks, use an abort with fallback method instead'
		});
	}
}

module.exports = {
	meta: {
		type: 'suggestion',
		docs: {
			description: '`transition.abort` can lead to navigation problems if executed on route hooks while the page refreshes',
			recommended: false
		},
		fixable: null,
		schema: [],
	},

	create(context) {
		const filename = context.getFilename();

		if (filename.endsWith('route.js') || filename.includes('routes') || filename.includes('mixins')) {
			return {
				'Property[key.name=beforeModel] > FunctionExpression[params.length=1]'(node) {
					checkAbortTransition(context, node.params[0]);
				},
				'Property[key.name=willTransition] > FunctionExpression[params.length=1]'(node) {
					checkAbortTransition(context, node.params[0]);
				},
				'Property[key.name=loading] > FunctionExpression[params.length>=2]'(node) {
					checkAbortTransition(context, node.params[0]);
				},
				'Property[key.name=model] > FunctionExpression[params.length=2]'(node) {
					checkAbortTransition(context, node.params[1]);
				},
				'Property[key.name=afterModel] > FunctionExpression[params.length=2]'(node) {
					checkAbortTransition(context, node.params[1]);
				},
				'Property[key.name=redirect] > FunctionExpression[params.length=2]'(node) {
					checkAbortTransition(context, node.params[1]);
				},
				'Property[key.name=error] > FunctionExpression[params.length=2]'(node) {
					checkAbortTransition(context, node.params[1]);
				},
				'Property[key.name=resetController] > FunctionExpression[params.length=3]'(node) {
					checkAbortTransition(context, node.params[2]);
				}
			};
		}

		return {};
	}
};
<commit_msg>feat(no-transition-abort-in-routes): better doc<commit_after>'use strict';

function checkAbortTransition(context, transitionArgument) {
	const transitionVariable = context.getScope().set.get(transitionArgument.name);
	const transitionAbortCall = transitionVariable.references.find((ref) =>
		ref.identifier.parent.parent.type === 'CallExpression' && ref.identifier.parent.parent.callee.property.name === 'abort'
	);

	if (transitionAbortCall) {
		context.report({
			node: transitionAbortCall.identifier.parent.parent,
			message: 'avoid aborting the transition on route hooks, use an abort with fallback method instead'
		});
	}
}

module.exports = {
	meta: {
		type: 'suggestion',
		docs: {
			description: '`transition.abort` can lead to navigation problems if executed on route hooks while the page refreshes',
			recommended: false
		},
		fixable: null,
		schema: [],
	},

	create(context) {
		const filename = context.getFilename();

		if (filename.endsWith('route.js') || filename.includes('routes') || filename.includes('mixins')) {
			return {
				'Property[key.name=beforeModel] > FunctionExpression[params.length=1]'(node) {
					checkAbortTransition(context, node.params[0]);
				},
				'Property[key.name=willTransition] > FunctionExpression[params.length=1]'(node) {
					checkAbortTransition(context, node.params[0]);
				},
				'Property[key.name=loading] > FunctionExpression[params.length>=2]'(node) {
					checkAbortTransition(context, node.params[0]);
				},
				'Property[key.name=model] > FunctionExpression[params.length=2]'(node) {
					checkAbortTransition(context, node.params[1]);
				},
				'Property[key.name=afterModel] > FunctionExpression[params.length=2]'(node) {
					checkAbortTransition(context, node.params[1]);
				},
				'Property[key.name=redirect] > FunctionExpression[params.length=2]'(node) {
					checkAbortTransition(context, node.params[1]);
				},
				'Property[key.name=error] > FunctionExpression[params.length=2]'(node) {
					checkAbortTransition(context, node.params[1]);
				},
				'Property[key.name=resetController] > FunctionExpression[params.length=3]'(node) {
					checkAbortTransition(context, node.params[2]);
				}
			};
		}

		return {};
	}
};
<|endoftext|>


<commit_before>'use strict'

const tap = require('tap')
const fs = require('fs')
const parseResults = require('../lib/parse-results')

tap.test('parseResults requires data', test => {
  const data = false
  const expectedErrorMessage = 'Missing required input: data'
  tap.throws(() => {
    parseResults(data)
  }, { message: expectedErrorMessage })
  test.done()
})

tap.test('parseResults reports not valid for result_fail.html', function (test) {
  const result = fs.readFileSync('test/data/result_fail.html').toString()
  const data = parseResults(result)
  tap.equal(data.pdfIsValid, false)
  test.done()
})

tap.test('parseResults reports valid for result_pass.html', function (test) {
  const result = fs.readFileSync('test/data/result_pass.html').toString()
  const data = parseResults(result)
  tap.equal(data.pdfIsValid, true)
  test.done()
})
<commit_msg>Changes test.done to test.end (patch)<commit_after>'use strict'

const tap = require('tap')
const fs = require('fs')
const parseResults = require('../lib/parse-results')

tap.test('parseResults requires data', test => {
  const data = false
  const expectedErrorMessage = 'Missing required input: data'
  tap.throws(() => {
    parseResults(data)
  }, { message: expectedErrorMessage })
  test.end()
})

tap.test('parseResults reports not valid for result_fail.html', function (test) {
  const result = fs.readFileSync('test/data/result_fail.html').toString()
  const data = parseResults(result)
  tap.equal(data.pdfIsValid, false)
  test.end()
})

tap.test('parseResults reports valid for result_pass.html', function (test) {
  const result = fs.readFileSync('test/data/result_pass.html').toString()
  const data = parseResults(result)
  tap.equal(data.pdfIsValid, true)
  test.end()
})
<|endoftext|>


<commit_before>var Filter = (function() {
  function Filter(options) {
    options = options || {};
    this.list = options.emptyList && [] || Array.prototype.concat.apply(require('./lang.json').words, [require('badwords-list').array, options.list || []]);
    this.placeHolder = options.placeHolder || '*';
    this.regex = options.regex || /[^a-zA-z0-9|\$|\@]|\^/g;
  }

  Filter.prototype.isProfane = function isProfane(string) {
    var words = string.split(' ');
    for (var j = 0; j < words.length; j++) {
      var word = words[j].toLowerCase().replace(this.regex, '');
      if (~this.list.indexOf(word)) {
        return true;
      }
    }
    return false;
  };

  Filter.prototype.replaceWord = function replaceWord(string) {
    return string.replace(this.regex, '').replace(/\w/g, this.placeHolder);
  };

  Filter.prototype.clean = function clean(string) {
    return string.split(' ').map(function(word) {
      return this.isProfane(word) ? this.replaceWord(word) : word;
    }.bind(this)).join(' ');
  };

  Filter.prototype.addWords = function addWords(words) {
    words = (words instanceof Array) ? words : [words];
    this.list = this.list.concat(words);
  };

  Filter.prototype.removeWords = function removeWords() {
    words = Array.prototype.slice.call(arguments);
    words.map(function(word) {
      return this.list.indexOf(word);
    }, this).filter(function(index) {
      return !!~index;
    }).forEach(function(index){
      this.list.splice(index, 1);
    }, this);
  };

  return Filter;
})();

module.exports = Filter;<commit_msg>syntax fix<commit_after>var Filter = (function() {
  function Filter(options) {
    options = options || {};
    this.list = options.emptyList && [] || Array.prototype.concat.apply(require('./lang.json').words, [require('badwords-list').array, options.list || []]);
    this.placeHolder = options.placeHolder || '*';
    this.regex = options.regex || /[^a-zA-z0-9|\$|\@]|\^/g;
  }

  Filter.prototype.isProfane = function isProfane(string) {
    var words = string.split(' ');
    for (var j = 0; j < words.length; j++) {
      var word = words[j].toLowerCase().replace(this.regex, '');
      if (~this.list.indexOf(word)) {
        return true;
      }
    }
    return false;
  };

  Filter.prototype.replaceWord = function replaceWord(string) {
    return string.replace(this.regex, '').replace(/\w/g, this.placeHolder);
  };

  Filter.prototype.clean = function clean(string) {
    return string.split(' ').map(function(word) {
      return this.isProfane(word) ? this.replaceWord(word) : word;
    }.bind(this)).join(' ');
  };

  Filter.prototype.addWords = function addWords(words) {
    words = (words instanceof Array) ? words : [words];
    this.list = this.list.concat(words);
  };

  Filter.prototype.removeWords = function removeWords() {
    var words = Array.prototype.slice.call(arguments);
    words.map(function(word) {
      return this.list.indexOf(word);
    }, this).filter(function(index) {
      return !!~index;
    }).forEach(function(index){
      this.list.splice(index, 1);
    }, this);
  };

  return Filter;
})();

module.exports = Filter;<|endoftext|>


<commit_before>;
(function ($, window, document, undefined) {
    "use strict";

    var pluginName = 'addField',
        defaults = {
            addFieldContainerClass: 'addFieldContainer',
            addFieldClass: 'addField',
            generalMultipleFieldsContainerParentsClass: 'generalMultipleFieldsContainer',
            firstMultipleFieldsContainerParentsClass: 'firstMultipleFieldsContainer',
            firstWrapperClass: 'firstWrapper',
            firstPrefix: 'firstPrefix',
            secondMultipleFieldsContainerParentsClass: null,
            secondWrapperClass: null,
            secondPrefix: null,
            thirdMultipleFieldsContainerParentsClass: null,
            thirdWrapperClass: null,
            thirdPrefix: null,
            fourthMultipleFieldsContainerParentsClass: null,
            fourthWrapperClass: null,
            fourthPrefix: null,
            fifthMultipleFieldsContainerParentsClass: null,
            fifthWrapperClass: null,
            fifthPrefix: null,
            sixthMultipleFieldsContainerParentsClass: null,
            sixthWrapperClass: null,
            sixthPrefix: null,
            mustacheTemplateId: 'addFieldTemplate',
            maxFieldsNumber: 10
        };

    //constructor
    function plugin(element, options) {
        this.elem = element;
        this.$elem = $(element);
        this.options = $.extend({}, defaults, options);

        this.$addField = this.$elem.find('.' + this.options.addFieldClass);
        this.elecInputCount = 1;
        this.gasInputCount = 1;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    plugin.prototype = {
        constructor: plugin,
        addField: function (event) {
            var pluginThis = event.data.pluginThis,
                $this = $(this),
                $thisParents = $this.parents('.' + pluginThis.options.generalMultipleFieldsContainerParentsClass),
                max_fields = pluginThis.options.maxFieldsNumber,
                counter = 0,
                prefix,
                $wrapper;

            event.preventDefault();

            if ($thisParents.hasClass(pluginThis.options.firstMultipleFieldsContainerParentsClass)) {
                $wrapper = $thisParents.find('.' + pluginThis.options.firstWrapperClass);
                prefix = pluginThis.options.firstPrefix;
                pluginThis.elecInputCount = pluginThis.elecInputCount + 1;
                counter = pluginThis.elecInputCount;
            } else if ($thisParents.hasClass(pluginThis.options.secondMultipleFieldsContainerParentsClass)) {
                $wrapper = $thisParents.find('.' + pluginThis.options.secondWrapperClass);
                prefix = pluginThis.options.secondPrefix;
                pluginThis.gasInputCount = pluginThis.gasInputCount + 1;
                counter = pluginThis.gasInputCount;
            }

            if (counter <= max_fields) {
//				$wrapper.append('\
//
\
//
\
//							kWhs\
//							<input id="' + prefix + 'kWh-' + counter + '" name="' + prefix + 'kWh-' + counter + '" type="text" class="formField">\
//
\
//
\
//							Per\
//							<input name="' + prefix + 'PerYear" type="text" class="formField" value="Per Year" disabled="disabled">\
//
\
//						\
//							\
//						\
//
\
//				');

                /* Mustache.js template rendering */
                var view = {
                    counter: counter,
                    prefix: prefix
                };

                var output = Mustache.render($('#' + pluginThis.options.mustacheTemplateId).html(), view);

                $wrapper.append(output);
                /* End Mustache.js template rendering */

                $wrapper.find('[data-' + prefix + '-field-remove="' + (counter - 1) + '"]').addClass('is-hidden');

                if (counter == max_fields) {
                    $wrapper.siblings('.' + pluginThis.options.addFieldContainerClass).addClass('is-hidden');
                }
            }

            $wrapper.find('.removeField[data-' + prefix + '-field-remove="' + counter + '"]').on('click', function (e) {
                var $this = $(this);

                e.preventDefault();
                e.stopPropagation();
                $this.parents('[data-' + prefix + '-field-count="' + counter + '"]').remove();

                if (prefix == pluginThis.options.firstPrefix) {
                    pluginThis.elecInputCount = pluginThis.elecInputCount - 1;
                    counter = pluginThis.elecInputCount;
                } else if (prefix == pluginThis.options.secondPrefix) {
                    pluginThis.gasInputCount = pluginThis.gasInputCount - 1;
                    counter = pluginThis.gasInputCount;
                }

                $wrapper.find('[data-' + prefix + '-field-remove="' + counter + '"]').removeClass('is-hidden');
                $wrapper.siblings('.' + pluginThis.options.addFieldContainerClass).removeClass('is-hidden');
            });
        },
        eventBindings: function () {
            this.$addField.on('click', {pluginThis: this}, this.addField);
        },
        init: function () {
            this.eventBindings();
        }
    };

    $.fn[pluginName] = function (option) {
        return this.each(function () {
            var data = $.data(this, 'ObjPlugin_' + pluginName),
                options = typeof option === 'object' && option;

            if (!data) $.data(this, 'ObjPlugin_' + pluginName, (data = new plugin(this, options)));
            if (typeof option === 'string') data[option]();
        });
    };

    $.fn[pluginName].defaults = defaults;
    $.fn[pluginName].constructor = plugin;

    $(document).addField();

})(jQuery, window, document);<commit_msg>input counts till 6 different block of add fields possible<commit_after>;
(function ($, window, document, undefined) {
    "use strict";

    var pluginName = 'addField',
        defaults = {
            addFieldContainerClass: 'addFieldContainer',
            addFieldClass: 'addField',
            generalMultipleFieldsContainerParentsClass: 'generalMultipleFieldsContainer',
            firstMultipleFieldsContainerParentsClass: 'firstMultipleFieldsContainer',
            firstWrapperClass: 'firstWrapper',
            firstPrefix: 'firstPrefix',
            secondMultipleFieldsContainerParentsClass: null,
            secondWrapperClass: null,
            secondPrefix: null,
            thirdMultipleFieldsContainerParentsClass: null,
            thirdWrapperClass: null,
            thirdPrefix: null,
            fourthMultipleFieldsContainerParentsClass: null,
            fourthWrapperClass: null,
            fourthPrefix: null,
            fifthMultipleFieldsContainerParentsClass: null,
            fifthWrapperClass: null,
            fifthPrefix: null,
            sixthMultipleFieldsContainerParentsClass: null,
            sixthWrapperClass: null,
            sixthPrefix: null,
            mustacheTemplateId: 'addFieldTemplate',
            maxFieldsNumber: 10
        };

    //constructor
    function plugin(element, options) {
        this.elem = element;
        this.$elem = $(element);
        this.options = $.extend({}, defaults, options);

        this.$addField = this.$elem.find('.' + this.options.addFieldClass);
        this.firstInputCount = 1;
        this.secondInputCount = 1;
        this.thirdInputCount = 1;
        this.fourthInputCount = 1;
        this.fifthInputCount = 1;
        this.sixthInputCount = 1;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    plugin.prototype = {
        constructor: plugin,
        addField: function (event) {
            var pluginThis = event.data.pluginThis,
                $this = $(this),
                $thisParents = $this.parents('.' + pluginThis.options.generalMultipleFieldsContainerParentsClass),
                max_fields = pluginThis.options.maxFieldsNumber,
                counter = 0,
                prefix,
                $wrapper;

            event.preventDefault();

            if ($thisParents.hasClass(pluginThis.options.firstMultipleFieldsContainerParentsClass)) {
                $wrapper = $thisParents.find('.' + pluginThis.options.firstWrapperClass);
                prefix = pluginThis.options.firstPrefix;
                pluginThis.firstInputCount = pluginThis.firstInputCount + 1;
                counter = pluginThis.firstInputCount;
            } else if ($thisParents.hasClass(pluginThis.options.secondMultipleFieldsContainerParentsClass)) {
                $wrapper = $thisParents.find('.' + pluginThis.options.secondWrapperClass);
                prefix = pluginThis.options.secondPrefix;
                pluginThis.secondInputCount = pluginThis.secondInputCount + 1;
                counter = pluginThis.secondInputCount;
            } else if ($thisParents.hasClass(pluginThis.options.secondMultipleFieldsContainerParentsClass)) {
                $wrapper = $thisParents.find('.' + pluginThis.options.secondWrapperClass);
                prefix = pluginThis.options.secondPrefix;
                pluginThis.thirdInputCount = pluginThis.thirdInputCount + 1;
                counter = pluginThis.thirdInputCount;
            } else if ($thisParents.hasClass(pluginThis.options.secondMultipleFieldsContainerParentsClass)) {
                $wrapper = $thisParents.find('.' + pluginThis.options.secondWrapperClass);
                prefix = pluginThis.options.secondPrefix;
                pluginThis.fourthInputCount = pluginThis.fourthInputCount + 1;
                counter = pluginThis.fourthInputCount;
            } else if ($thisParents.hasClass(pluginThis.options.secondMultipleFieldsContainerParentsClass)) {
                $wrapper = $thisParents.find('.' + pluginThis.options.secondWrapperClass);
                prefix = pluginThis.options.secondPrefix;
                pluginThis.fifthInputCount = pluginThis.fifthInputCount + 1;
                counter = pluginThis.fifthInputCount;
            } else if ($thisParents.hasClass(pluginThis.options.secondMultipleFieldsContainerParentsClass)) {
                $wrapper = $thisParents.find('.' + pluginThis.options.secondWrapperClass);
                prefix = pluginThis.options.secondPrefix;
                pluginThis.sixthInputCount = pluginThis.sixthInputCount + 1;
                counter = pluginThis.sixthInputCount;
            }

            if (counter <= max_fields) {
//				$wrapper.append('\
//
\
//
\
//							kWhs\
//							<input id="' + prefix + 'kWh-' + counter + '" name="' + prefix + 'kWh-' + counter + '" type="text" class="formField">\
//
\
//
\
//							Per\
//							<input name="' + prefix + 'PerYear" type="text" class="formField" value="Per Year" disabled="disabled">\
//
\
//						\
//							\
//						\
//
\
//				');

                /* Mustache.js template rendering */
                var view = {
                    counter: counter,
                    prefix: prefix
                };

                var output = Mustache.render($('#' + pluginThis.options.mustacheTemplateId).html(), view);

                $wrapper.append(output);
                /* End Mustache.js template rendering */

                $wrapper.find('[data-' + prefix + '-field-remove="' + (counter - 1) + '"]').addClass('is-hidden');

                if (counter == max_fields) {
                    $wrapper.siblings('.' + pluginThis.options.addFieldContainerClass).addClass('is-hidden');
                }
            }

            $wrapper.find('.removeField[data-' + prefix + '-field-remove="' + counter + '"]').on('click', function (e) {
                var $this = $(this);

                e.preventDefault();
                e.stopPropagation();
                $this.parents('[data-' + prefix + '-field-count="' + counter + '"]').remove();

                if (prefix == pluginThis.options.firstPrefix) {
                    pluginThis.firstInputCount = pluginThis.firstInputCount - 1;
                    counter = pluginThis.firstInputCount;
                } else if (prefix == pluginThis.options.secondPrefix) {
                    pluginThis.secondInputCount = pluginThis.secondInputCount - 1;
                    counter = pluginThis.secondInputCount;
                } else if (prefix == pluginThis.options.secondPrefix) {
                    pluginThis.thirdInputCount = pluginThis.thirdInputCount - 1;
                    counter = pluginThis.thirdInputCount;
                } else if (prefix == pluginThis.options.secondPrefix) {
                    pluginThis.fourthInputCount = pluginThis.fourthInputCount - 1;
                    counter = pluginThis.fourthInputCount;
                } else if (prefix == pluginThis.options.secondPrefix) {
                    pluginThis.fifthInputCount = pluginThis.fifthInputCount - 1;
                    counter = pluginThis.fifthInputCount;
                } else if (prefix == pluginThis.options.secondPrefix) {
                    pluginThis.sixthInputCount = pluginThis.sixthInputCount - 1;
                    counter = pluginThis.sixthInputCount;
                }

                $wrapper.find('[data-' + prefix + '-field-remove="' + counter + '"]').removeClass('is-hidden');
                $wrapper.siblings('.' + pluginThis.options.addFieldContainerClass).removeClass('is-hidden');
            });
        },
        eventBindings: function () {
            this.$addField.on('click', {pluginThis: this}, this.addField);
        },
        init: function () {
            this.eventBindings();
        }
    };

    $.fn[pluginName] = function (option) {
        return this.each(function () {
            var data = $.data(this, 'ObjPlugin_' + pluginName),
                options = typeof option === 'object' && option;

            if (!data) $.data(this, 'ObjPlugin_' + pluginName, (data = new plugin(this, options)));
            if (typeof option === 'string') data[option]();
        });
    };

    $.fn[pluginName].defaults = defaults;
    $.fn[pluginName].constructor = plugin;

    $(document).addField();

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