<commit_before>var Queue = {
	manualList: [],
    autoList: [],
    manualPlayIndex: null,
    autoPlayIndex: null,
    init: function() {

    },
    addManual: function(video) {
        Queue.manualList.push(video);
        Queue.updateView();
    },
    setAutoQueue: function(videoList) {
        Queue.autoPlayIndex = 0;
        Queue.autoList = videoList;
        Queue.updateView();
    },
    manualPlay: function(index) {
        console.log('manual ' + index);
        if (Queue.manualList.length === 0) {
            return false;
        }

        if (index < 0 || index > Queue.manualList.length -1) {
            return false;
        } else {
            Queue.manualPlayIndex = index;
        }
        Queue.manualList[Queue.manualPlayIndex].play();
        Queue.autoPlayIndex = null;
        Queue.updateView();
        return true;
    },
    autoPlay: function(index) {
        console.log('auto ' + index);
        if (Queue.autoList.length === 0) {
            return false;
        }

        if (index < 0 || index > Queue.autoList.length -1) {
            return false;
        } else {
            Queue.autoPlayIndex = index;
        }
        Queue.autoList[Queue.autoPlayIndex].play();
        Queue.updateView();
        return true;
    },
    playNext: function() {
        if ((Queue.manualList.length + Queue.autoList.length) === 0) {
            return false;
        }

        if (Queue.manualList.length > 0 && Queue.manualPlayIndex === null) {
            return Queue.manualPlay(0);
        } else if (Queue.manualList.length > 0 && Queue.manualPlayIndex + 1 < Queue.manualList.length) {
            return Queue.manualPlay(Queue.manualPlayIndex + 1);
        } else if (Queue.autoList.length > 0 && Queue.autoPlayIndex === null) {
            return Queue.autoPlay(0);
        } else if (Queue.autoList.length > 0 && Queue.autoPlayIndex + 1 < Queue.autoList.length) {
            return Queue.autoPlay(Queue.autoPlayIndex + 1);
        } else {
            return false;
        }
    },
    playPrev: function() {
        if ((Queue.manualList.length + Queue.autoList.length) === 0) {
            return false;
        }

        if (Queue.autoPlayIndex !== null && Queue.autoPlayIndex > 0) {
            return Queue.autoPlay(Queue.autoPlayIndex - 1);
        } else if (Queue.autoPlayIndex !== null && Queue.autoPlayIndex === 0) {
            return Queue.manualPlay(Queue.manualList.length - 1);
        } else if (Queue.manualPlayIndex !== null && Queue.manualPlayIndex > 0) {
            return Queue.manualPlay(Queue.manualPlayIndex - 1);
        } else {
            return false;
        }
    },
	updateView: function() {
        var view = Menu.find('queue').findTab('queue').paneView;

        view.html('');
        $.each(Queue.manualList, function(index, video) {
			var clone = video.listView.clone(),
                play = function() {
                    Queue.manualPlay(index);
                };

            /* Clean */
            clone.removeClass('selected').removeClass('playing');

            /* Is Playing? */
            if (index === Queue.manualPlayIndex && Queue.autoPlayIndex === null) {
                clone.addClass('playing');
            }

            /* Bind actions */
            clone.dblclick(play);
            clone.find('.play').click(play);
            clone.bind('contextmenu', showResultsItemContextMenu);
            clone.click(function(event){video.listViewSelect(event, clone);});

            /* Only display the last 3 */
            if (Queue.manualPlayIndex !== null && index - Queue.manualPlayIndex < -2) {
                clone.hide();
            }
            clone.appendTo(view);
		});
        $.each(Queue.autoList, function(index, video) {
			var clone = video.listView.clone(),
                play = function() {
                    Queue.autoPlay(index);
                };

            /* Clean */
            clone.removeClass('selected').removeClass('playing');

            /* Is Playing? */
            if (index === Queue.autoPlayIndex) {
                clone.addClass('playing');
            }

            /* Bind actions */
            clone.dblclick(play);
            clone.find('.play').click(play);
            clone.bind('contextmenu', showResultsItemContextMenu);
            clone.click(function(event){video.listViewSelect(event, clone);});

            /* Make movable */
            clone.data('model', video);
            clone.addClass('draggable');

            clone.appendTo(view);
		});
	},

    addSiblingsToPlayorder: function(startElem) {
        if (startElem === undefined) {
			return;
        }
		var list = [];

		if ($('#bottom .shuffle').hasClass('on')) {
            /* Add all videos */
            $(startElem).siblings('.video').each(function(index, item) {
                list.push($(item).data('model'));
            });
			$.shuffle(list);
		} else {
            /* Add videos after this */
            $(startElem).nextAll('.video').each(function(index, item) {
                list.push($(item).data('model'));
            });
        }
        list.unshift($(startElem).data('model'));
        Queue.setAutoQueue(list);
	}
};
<commit_msg>Fix bug with menu buttons in Play Queue<commit_after>var Queue = {
	manualList: [],
    autoList: [],
    manualPlayIndex: null,
    autoPlayIndex: null,
    init: function() {

    },
    addManual: function(video) {
        Queue.manualList.push(video);
        Queue.updateView();
    },
    setAutoQueue: function(videoList) {
        Queue.autoPlayIndex = 0;
        Queue.autoList = videoList;
        Queue.updateView();
    },
    manualPlay: function(index) {
        console.log('manual ' + index);
        if (Queue.manualList.length === 0) {
            return false;
        }

        if (index < 0 || index > Queue.manualList.length -1) {
            return false;
        } else {
            Queue.manualPlayIndex = index;
        }
        Queue.manualList[Queue.manualPlayIndex].play();
        Queue.autoPlayIndex = null;
        Queue.updateView();
        return true;
    },
    autoPlay: function(index) {
        console.log('auto ' + index);
        if (Queue.autoList.length === 0) {
            return false;
        }

        if (index < 0 || index > Queue.autoList.length -1) {
            return false;
        } else {
            Queue.autoPlayIndex = index;
        }
        Queue.autoList[Queue.autoPlayIndex].play();
        Queue.updateView();
        return true;
    },
    playNext: function() {
        if ((Queue.manualList.length + Queue.autoList.length) === 0) {
            return false;
        }

        if (Queue.manualList.length > 0 && Queue.manualPlayIndex === null) {
            return Queue.manualPlay(0);
        } else if (Queue.manualList.length > 0 && Queue.manualPlayIndex + 1 < Queue.manualList.length) {
            return Queue.manualPlay(Queue.manualPlayIndex + 1);
        } else if (Queue.autoList.length > 0 && Queue.autoPlayIndex === null) {
            return Queue.autoPlay(0);
        } else if (Queue.autoList.length > 0 && Queue.autoPlayIndex + 1 < Queue.autoList.length) {
            return Queue.autoPlay(Queue.autoPlayIndex + 1);
        } else {
            return false;
        }
    },
    playPrev: function() {
        if ((Queue.manualList.length + Queue.autoList.length) === 0) {
            return false;
        }

        if (Queue.autoPlayIndex !== null && Queue.autoPlayIndex > 0) {
            return Queue.autoPlay(Queue.autoPlayIndex - 1);
        } else if (Queue.autoPlayIndex !== null && Queue.autoPlayIndex === 0) {
            return Queue.manualPlay(Queue.manualList.length - 1);
        } else if (Queue.manualPlayIndex !== null && Queue.manualPlayIndex > 0) {
            return Queue.manualPlay(Queue.manualPlayIndex - 1);
        } else {
            return false;
        }
    },
	updateView: function() {
        var view = Menu.find('queue').findTab('queue').paneView;

        view.html('');
        $.each(Queue.manualList, function(index, video) {
			var clone = video.listView.clone(),
                play = function() {
                    Queue.manualPlay(index);
                };

            /* Clean */
            clone.removeClass('selected').removeClass('playing');

            /* Is Playing? */
            if (index === Queue.manualPlayIndex && Queue.autoPlayIndex === null) {
                clone.addClass('playing');
            }

            /* Bind actions */
            clone.dblclick(play);
            clone.find('.play').click(play);
            clone.bind('contextmenu', showResultsItemContextMenu);
            clone.click(function(event){video.listViewSelect(event, clone);});
            clone.find('.menu').click(function(event) {
                showResultsItemContextMenu(event, clone);
            });

            /* Only display the last 3 */
            if (Queue.manualPlayIndex !== null && index - Queue.manualPlayIndex < -2) {
                clone.hide();
            }
            clone.appendTo(view);
		});
        $.each(Queue.autoList, function(index, video) {
			var clone = video.listView.clone(),
                play = function() {
                    Queue.autoPlay(index);
                };

            /* Clean */
            clone.removeClass('selected').removeClass('playing');

            /* Is Playing? */
            if (index === Queue.autoPlayIndex) {
                clone.addClass('playing');
            }

            /* Bind actions */
            clone.dblclick(play);
            clone.find('.play').click(play);
            clone.bind('contextmenu', showResultsItemContextMenu);
            clone.click(function(event){video.listViewSelect(event, clone);});
            clone.find('.menu').click(function(event) {
                showResultsItemContextMenu(event, clone);
            });

            /* Make movable */
            clone.data('model', video);
            clone.addClass('draggable');

            clone.appendTo(view);
		});
	},

    addSiblingsToPlayorder: function(startElem) {
        if (startElem === undefined) {
			return;
        }
		var list = [];

		if ($('#bottom .shuffle').hasClass('on')) {
            /* Add all videos */
            $(startElem).siblings('.video').each(function(index, item) {
                list.push($(item).data('model'));
            });
			$.shuffle(list);
		} else {
            /* Add videos after this */
            $(startElem).nextAll('.video').each(function(index, item) {
                list.push($(item).data('model'));
            });
        }
        list.unshift($(startElem).data('model'));
        Queue.setAutoQueue(list);
	}
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs-extra');
var async = require('async');
var exec = require('child_process').exec;
var colors = require('colors');

function doExec(text) {
    return function (done) {
        exec(text, function (err, stdout, stderr) {
            if (stdout) console.log(stdout.grey);
            if (stderr) console.log(stderr.red);
            done(err);
        });
    };
}

// Let's get started
console.log('starting build...'.bgMagenta);

// Copy assets to www
require('./copy-assets');

// Clean
fs.removeSync('./platforms');
fs.removeSync('./plugins');

async.series([
    doExec('cordova platform add android firefoxos ios'),
    doExec('cordova plugin add org.apache.cordova.contacts'),
    // bug fix in progress for com.rjfun.cordova.sms
    doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-sms.git'),
    // PR in progress for org.apache.cordova.camera to add dataURIs for ffos
    doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-camera.git')
], function (err) {
    // Done!
    if (err) return console.log('finished build, but there were errors!'.bgMagenta);
    console.log('finished build with no errors.'.bgMagenta);
});

<commit_msg>Add social sharing plugin and remove contacts and SMS plugins<commit_after>#!/usr/bin/env node

var fs = require('fs-extra');
var async = require('async');
var exec = require('child_process').exec;
var colors = require('colors');

function doExec(text) {
    return function (done) {
        exec(text, function (err, stdout, stderr) {
            if (stdout) console.log(stdout.grey);
            if (stderr) console.log(stderr.red);
            done(err);
        });
    };
}

// Let's get started
console.log('starting build...'.bgMagenta);

// Copy assets to www
require('./copy-assets');

// Clean
fs.removeSync('./platforms');
fs.removeSync('./plugins');

async.series([
    doExec('cordova platform add android firefoxos ios'),
    doExec('cordova plugin add https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin.git'),
    // PR in progress for org.apache.cordova.camera to add dataURIs for ffos
    doExec('cordova plugin add https://github.com/k88hudson/cordova-plugin-camera.git')
], function (err) {
    // Done!
    if (err) return console.log('finished build, but there were errors!'.bgMagenta);
    console.log('finished build with no errors.'.bgMagenta);
});

<|endoftext|>


<commit_before>#!/usr/bin/env node
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
import shell from 'shelljs'
import { getSubPackages } from './utils/helpers.js'

const __dirname = path.dirname(url.fileURLToPath(import.meta.url))

const args = process.argv.slice(2)
const HAS_WATCH_FLAG = args[0] === '--watch'
const TSCONFIG_FILE = process.env.NODE_ENV === 'production' ? 'tsconfig.prod.json' : 'tsconfig.json'

if (HAS_WATCH_FLAG) {
    args.shift()
}

// Order of packages:
// 1. root packages
// 2. core packages (e.g. wdio-cli)
// 3. plugins (e.g. wdio-allure-reporter)
const ROOT_PACKAGES = [
    'wdio-types',
    'wdio-protocols',
    'wdio-logger',
    'wdio-utils',
    'wdio-config',
    'wdio-repl',
    'webdriver',
    'devtools',
    'webdriverio',
    'wdio-globals',
    'wdio-runner',
    'wdio-local-runner',
    'wdio-browser-runner'
]

const packages = getSubPackages()
    /**
     * Filter out packages that don't need compiling
     */
    .filter((pkg) => {
        try {
            fs.accessSync(`packages/${pkg}/${TSCONFIG_FILE}`)
            return true
        } catch (err) {
            return false
        }
    })

    /**
     * Deduplicate root packages
     */
    .filter((pkg) => !ROOT_PACKAGES.includes(pkg))

    /**
     * Divide packages into core (e.g. wdio-cli) and
     * plugins (wdio-allure-reporter)
     */
    .reduce((acc, pkg) => {
        const tokens = pkg.split('-')
        acc[tokens.length > 2 ? 1 : 0].push(pkg)
        return acc
    }, [[], []])

    /**
     * Concat all groups of packages, with root packages as first
     */
    .reduce((acc, collection) => acc.concat(collection), ROOT_PACKAGES)

    /**
     * Only build packages that are passed in as params
     */
    .filter((pkg) => args.length === 0 || args.includes(pkg))

shell.cd(path.join(__dirname, '..'))

const cmd = `npx tsc -b ${packages.map((pkg) => `packages/${pkg}/${TSCONFIG_FILE}`).join(' ')}${HAS_WATCH_FLAG ? ' --watch' : ''}`

console.log(cmd)
const { code } = shell.exec(cmd)

if (!HAS_WATCH_FLAG) {
    console.log('Remove `export {}` from CJS files')
    for (const pkg of ['webdriver', 'devtools', 'webdriverio']) {
        const filePath = path.join(__dirname, '..', 'packages', pkg, 'build', 'cjs', 'index.js')
        const fileContent = await fs.readFileSync(filePath, 'utf8')
        await fs.writeFileSync(filePath, fileContent.toString().replace('export {};', ''), 'utf8')
    }
}

if (code) {
    throw new Error('Failed compiling TypeScript files!')
}
<commit_msg>fix compiling<commit_after>#!/usr/bin/env node
import fs from 'node:fs'
import url from 'node:url'
import path from 'node:path'
import shell from 'shelljs'
import { getSubPackages } from './utils/helpers.js'

const __dirname = path.dirname(url.fileURLToPath(import.meta.url))

const args = process.argv.slice(2)
const HAS_WATCH_FLAG = args[0] === '--watch'
const TSCONFIG_FILE = process.env.NODE_ENV === 'production' ? 'tsconfig.prod.json' : 'tsconfig.json'

if (HAS_WATCH_FLAG) {
    args.shift()
}

// Order of packages:
// 1. root packages
// 2. core packages (e.g. wdio-cli)
// 3. plugins (e.g. wdio-allure-reporter)
const ROOT_PACKAGES = [
    'wdio-types',
    'wdio-protocols',
    'wdio-logger',
    'wdio-utils',
    'wdio-config',
    'wdio-repl',
    'webdriver',
    'devtools',
    'webdriverio',
    'wdio-globals',
    'wdio-runner',
    'wdio-local-runner',
    'wdio-mocha-framework',
    'wdio-browser-runner'
]

const packages = getSubPackages()
    /**
     * Filter out packages that don't need compiling
     */
    .filter((pkg) => {
        try {
            fs.accessSync(`packages/${pkg}/${TSCONFIG_FILE}`)
            return true
        } catch (err) {
            return false
        }
    })

    /**
     * Deduplicate root packages
     */
    .filter((pkg) => !ROOT_PACKAGES.includes(pkg))

    /**
     * Divide packages into core (e.g. wdio-cli) and
     * plugins (wdio-allure-reporter)
     */
    .reduce((acc, pkg) => {
        const tokens = pkg.split('-')
        acc[tokens.length > 2 ? 1 : 0].push(pkg)
        return acc
    }, [[], []])

    /**
     * Concat all groups of packages, with root packages as first
     */
    .reduce((acc, collection) => acc.concat(collection), ROOT_PACKAGES)

    /**
     * Only build packages that are passed in as params
     */
    .filter((pkg) => args.length === 0 || args.includes(pkg))

shell.cd(path.join(__dirname, '..'))

const cmd = `npx tsc -b ${packages.map((pkg) => `packages/${pkg}/${TSCONFIG_FILE}`).join(' ')}${HAS_WATCH_FLAG ? ' --watch' : ''}`

console.log(cmd)
const { code } = shell.exec(cmd)

if (!HAS_WATCH_FLAG) {
    console.log('Remove `export {}` from CJS files')
    for (const pkg of ['webdriver', 'devtools', 'webdriverio']) {
        const filePath = path.join(__dirname, '..', 'packages', pkg, 'build', 'cjs', 'index.js')
        const fileContent = await fs.readFileSync(filePath, 'utf8')
        await fs.writeFileSync(filePath, fileContent.toString().replace('export {};', ''), 'utf8')
    }
}

if (code) {
    throw new Error('Failed compiling TypeScript files!')
}
<|endoftext|>


<commit_before>// CONSTANTS
var fieldWidth = 54, // the width of every of the 24 fields
    offsetBetweenFields = 5, // between small field(white) and big field(dark)
    boardSide = 324, // the width of one side of the board
    boardBar = 34, // the thing between the board sides in pixels
    boardFrameOffset = 18, // the offset in the corners between the board itself and the frame in pixels
    checkerHeight = 42, // the height of the checker after being fully drawn in pixels
    checkerRadius = 21, // full width = 44; outer stroke 1px
    checkerInnerCircleRadius = 10,
    initialDiceValue = 6;

// GAME ELEMENTS - canvas, ctx, keystate, etc.
var canvas,
    ctx,
    diceCanvas,
    diceCtx,
    clickedField,
    firstPlayer,
    secondPlayer,
    firstDice,
    secondDice,
    firstDiceThrow,
    firstPlayerOnTurn,
    mustThrowDices;

// DEFINING GAME OBJECTS - player, checker, dice, board(not if it is just a background) ...
var player = (function () {
    var player = {
        init: function (name, color) {
            this.name = name;
            this.color = color;
            this.currentCheckersCount = 15;
            this.hasHitChecker = false;
            this.hitCheckersCount = 0;
            this.canTakeChecker = false;
            return this;
        },
        tookChecker: function () {
            // TODO: Validate depending on call.
            this.currentCheckersCount -= 1;
        }
    };

    Object.defineProperty(player, 'name', {
        get: function () {
            return this._name;
        },
        set: function (value) {
            //TODO: Validate
            this._name = value;
        }
    });

    Object.defineProperty(player, 'currentCheckersCount', {
        get: function () {
            return this._currentCheckersCount;
        },
        set: function (value) {
            //TODO: Validate
            this._currentCheckersCount = value;
        }
    });

    Object.defineProperty(player, 'color', {
        get: function () {
            return this._color;
        },
        set: function (value) {
            // TODO: Validate
            this._color = value;
        }
    });

    Object.defineProperty(player, 'hasHitChecker', {
        get: function () {
            return this._hasHitChecker;
        },
        set: function (value) {
            // TODO: Validate
            this._hasHitChecker = value;
        }
    });

    Object.defineProperty(player, 'hitCheckersCount', {
        get: function () {
            return this._hitCheckersCount;
        },
        set: function (value) {
            // TODO: Validate
            this._hitCheckersCount = value;
        }
    });

    Object.defineProperty(player, 'canTakeChecker', {
        get: function () {
            return this._canTakeChecker;
        },
        set: function (value) {
            // TODO: Validate
            this._canTakeChecker = value;
        }
    });

    return player;
}());

var field = (function () { /* the board is filled with 24 fields,
 IT IS A RESPONSIBILITY OF THE FIELDS TO GIVE COORDINATES TO THE CHECKERS, WITH RESPECT TO THEIR OWN X,Y COORDINATES
 IN THIS WAY WE DON'T CARE HOW TO STACK CHECKERS AND TO TAKE INTO ACCOUNT THEIR Xs AND Ys,
 THE FIELD JUST STACKS THEM DEPENDING ON THE COUNT IT IS HOLDING, GIVING HIS OWN X, Y */
    var field = {
        init: function (x, y) {
            this.checkers = [];
            this.x = x;
            this.y = y;
            /* if field is 0~11 y = canvas.height - boardFrameOffset; else y = boardFrameOffset;
             this is needed only for knowing at which side are we, so we can draw the checkers properly */
            return this;
        },
        addChecker: function (checker) {
            this.checkers.push(checker);
        },
        removeChecker: function () {
            this.checkers.pop();
        },
        draw: function () {
            var count = this.checkers.length, // count checkers, if more than 5 draw stacked
                i,
                fieldCenter;
            for (i = 0; i < count; i += 1) {
                if (i > 4) {
                    // draw stacked
                    ctx.save();
                    ctx.fillStyle = 'red';
                    ctx.font = "12px Verdana";
                    ctx.fillText('x' + (i - 3), (this.x - 6) + fieldWidth / 2, this.y + checkerRadius + 4);
                    // x2 for the 6th checker because it represents how many checkers are stacked
                    // 6 and 4 are just a magic numbers to position the text in the center of the checker, because the text has also its own offset
                    ctx.restore();
                } else {
                    if (this.y < canvas.height / 2) { // if field is in the upper half of the board, should stack them up to bottom
                        fieldCenter = this.x + (fieldWidth / 2); // x coordinate for the checker center
                        this.checkers[i].draw(fieldCenter, this.y + i * checkerHeight + checkerRadius + 2);
                        /* +2 just to look better,
                         the checker from the board frame */
                    } else { // when the field is in the lower part, should stack them from bottom to up
                        fieldCenter = this.x + (fieldWidth / 2); // x coordinate for the checker center
                        this.checkers[i].draw(fieldCenter, this.y - i * checkerHeight + checkerRadius - 2); // -2 just to look better
                    }
                }
            }
        }
    };

    Object.defineProperty(field, 'checkers', {
        get: function () {
            return this._checkers;
        },
        set: function (value) {
            this._checkers = value;
        }
    });

    Object.defineProperty(field, 'x', {
        get: function () {
            return this._x;
        },
        set: function (value) {
            this._x = value;
        }
    });

    Object.defineProperty(field, 'y', {
        get: function () {
            return this._y;
        },
        set: function (value) {
            this._y = value;
        }
    });

    return field;
}());

var checker = (function () {
    var checker = {
        init: function (color) {
            this.color = color; // can be only 'black' or 'white'
            return this;
        },
        draw: function (x, y) {
            ctx.save();
            if (this.color === 'black') {
                ctx.strokeStyle = 'white';
            }
            // outer circle
            ctx.beginPath();
            ctx.fillStyle = this.color;
            ctx.lineWidth = 1;
            ctx.arc(x, y, checkerRadius, 0, 2 * Math.PI);
            ctx.fill();
            ctx.stroke();

            // inner circle
            ctx.beginPath();
            ctx.strokeStyle = '#808080';
            ctx.lineWidth = 2;
            ctx.arc(x, y, checkerInnerCircleRadius, 0, 2 * Math.PI);
            ctx.stroke();

            ctx.restore();
        }
    };

    Object.defineProperty(checker, 'color', {
        get: function () {
            return this._color;
        },
        set: function (value) {
            this._color = value;
        }
    });

    return checker;
}());

var board = (function () {
    var bottomSideAllSet, // flag to indicate that we must start with a field having 5 checkers in it(the 12th field)
    // at bottom we start with  12. 5 3 5 2 .23
    // at top we start with     11. 5 3 5 2 .0
        patternToPutColors = []; // colors are inverted in the opposite sides of the field, sorry it truly looks ugly..

    var gameboard = {
        init: function () {
            this.fields = [];
            bottomSideAllSet = false;
            patternToPutColors[0] = 1;
            patternToPutColors[5] = 0;
            patternToPutColors[7] = 0;
            patternToPutColors[11] = 1;
            var self = this;
            setupHalfGameBoard(self, bottomSideAllSet);
            bottomSideAllSet = true;
            setupHalfGameBoard(self, bottomSideAllSet);
            return this;
        },
        addField: function (value) {
            this.fields.push(value);
        }
    };

    function setupHalfGameBoard(self, bottomSideAllSet) {
        var i,
            len,
            x,
            y,
            currentField,
            patternOfTheNumberOfCheckersToPut = [2, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 5],// on 0 field put 2, on field 1 put 0, etc.. the setup rules..
            j,  // needed to go trough the patternToPutCheckers
            colorToPut,
            countPassedFields = 0; // needed to add a boardBar offset to the X coordinate

        if (bottomSideAllSet) {
            i = 12;
            j = 11;
        } else {
            i = 0;
            j = 0;
        }
        for (len = i + 12; i < len; i += 1, (i >= 12) ? j -= 1 : j += 1, countPassedFields += 1) {
            if (countPassedFields >= 6) {  // after every 6 fields we must consider the boardBar also, in both the upper and the lower side of the board
                x = (!bottomSideAllSet) * canvas.width - boardFrameOffset - ((countPassedFields + !bottomSideAllSet) * fieldWidth) - boardBar;
            } else {
                x = (!bottomSideAllSet) * canvas.width - boardFrameOffset - ((countPassedFields + !bottomSideAllSet) * fieldWidth);
                // if we are at the bottom we must consider the canvas width and to subtract from it
            }
            y = (!bottomSideAllSet) * (canvas.height - checkerHeight) - boardFrameOffset;

            if (x < 0) { // because we are extracting everything from the canvas width or height
                x *= -1; // when we are at the bottom side, we start from the MOST-RIGHT field(our 0 field) so canvas height, and width must be considered,
            }            // while when we are at the upper side of the board, the MOST-LEFT field(the 12th field) must be filled first,
            if (y < 0) { // so canvas width and height in the upper side are 0, and we get a negative number but we actually need that number to be positive,
                y *= -1; // to go to the right.. to fill the rest of the fields.. it's all because of how the fields position in backgammon
            }
            if (patternToPutColors[j] === 1) {
                colorToPut = 'white';
                patternToPutColors[j] = 0; // swapping the pattern for the next half of the board
            } else if (patternToPutColors[j] === 0) {
                colorToPut = 'black';
                patternToPutColors[j] = 1;
            }
            currentField = Object.create(field).init(x, y); // creating one of the 24 fields in the board
            putCheckersOnField(patternOfTheNumberOfCheckersToPut[j], currentField, colorToPut); // assigning checkers to it with respect to the Backgammon setup rules
            self.addField(currentField); // adding the field to the board, used 'self' because the scope of this has changed
        }
    }

    function putCheckersOnField(checkersToPut, givenField, color) {
        var i;
        for (i = 0; i < checkersToPut; i += 1) {
            givenField.addChecker(Object.create(checker).init(color));
        }
    }

    return gameboard;
}());

var dice = (function () {
    var dice = {
        init: function () {
            this.number = initialDiceValue;
            return this;
        }
    };

    Object.defineProperty(dice, 'number', {
        get: function () {
            return this._number;
        },
        set: function (value) {
            checkIfDiceValueIsValid(value);
            this._number = value;
        }
    });

    Object.defineProperty(dice, 'generateNewNumber', {
        value: function () {
            return this.number = Math.floor(Math.random() * 6) + 1;
        }
    });

    function checkIfDiceValueIsValid(number) {
        if (isNaN(number) || number % 1 != 0 || number < 1 || number > 6) {
            // throw new Error('Dice number is invalid!');
        }
    }

    return dice;
}());

// function newGame() or main()
// create initiate and append game canvas
// INITIATE GAME OBJECTS;
function newGame() {
    canvas = document.getElementById('board-canvas');
    ctx = canvas.getContext('2d');

    // INIT GAME OBJECTS, SETS UP GAME
    board.init();
    firstDice = Object.create(dice).init();
    secondDice = Object.create(dice).init();
    firstDiceThrow = true;
}
newGame();

function play() {
    // GAME LOOP - game logic, updating the fields, players turns, dices etc. Update update update
    // change fields depending on how the player interact(key presses)
    canvas.addEventListener('click', findPressedField);

    //LOGIC NEEDS TO BE IMPLEMENTED FOR CURRENT PLAYER

    //THROW DICE - at first time, throw to see who will be playing first
    if (firstDiceThrow) {
        firstDiceThrow = false;
        firstDice.generateNewNumber();
        secondDice.generateNewNumber();
        if (firstDice.number > secondDice.number) {
            firstPlayerOnTurn = true;
        } else if (firstDice.number < secondDice.number) {
            firstPlayerOnTurn = false;
        } else {
            firstDiceThrow = true;
            play();
        }
    } else {
        firstDice.generateNewNumber();
        secondDice.generateNewNumber();
    }

    //CHECK IF ANY POSSIBLE MOVE

    //IF ANY POSSIBLE MOVES AVAILABLE  -->  CHECK FOR NEW CLICKS AND CATCH START POSITION , else change player
    //IF ANY POSSIBLE MOVES AVAILABLE  -->  CHECK IF NEW SET/CLICKED POSITION IS CORRECT AND MOVE PULL , else try again

    // DRAW
    // draws every time and if we have changes its ok
    draw();

    // CHANGE PLAYER
    firstPlayerOnTurn ? firstPlayerOnTurn = false : firstPlayerOnTurn = true;

    requestAnimationFrame(play);
}
play();

function findPressedField(event) {
    var x = event.offsetX;
    var y = event.offsetY;
    if (((x < canvas.width - boardFrameOffset && x > boardFrameOffset + boardSide + boardBar) ||
        (x < boardFrameOffset + boardSide && x > boardFrameOffset)) &&
        (y < canvas.height - boardFrameOffset && y > boardFrameOffset)) { // ignoring every piece of the frame
        var i = 0,
            len,
            foundField,
            upperSide = false;
        // determining in which quadrant are we exactly
        if (y < canvas.height / 2 && y > boardFrameOffset) {
            i = 12; // last field of the upper side, last because if we take the first our condition in the for-loop will be achieved every time
            upperSide = true;
        } else {
            i = 0; // first field of the lower side
        }
        if (x < boardSide + boardFrameOffset && x > boardFrameOffset) { // left side of the board
            if (i === 0) { // bottom left side
                i = 6;
            } else { // upper left side
                i = 12;
            }
        } else { // right side of the board
            if (i === 0) { // bottom right side
                i = 0;
            } else { // upper left side
                i = 18; // again last of the array
            }
        }
        for (len = i + 6; i < len; i += 1) {
            var currentField = board.fields[i];
            if (upperSide) { /* its all because of the fields..
             the start position of the lower side is most-right and it starts from 0,
             while the start position of the upper side is the most-left which confuses the algorithm */
                var previousField = board.fields[i - 1];
                if (currentField.x > x) {
                    foundField = previousField;
                    break;
                }
            } else {
                if (x > currentField.x) {
                    foundField = currentField;
                    break;
                }
            }
        }
        if (typeof foundField === 'undefined') { // when we are going out of the for-in and the condition for the upperSide is not met,
            // because we take the previous field element we could not get to check the last one
            foundField = board.fields[len - 1];
        }
        clickedField = foundField;
        console.log(clickedField); // testing purposes
    }
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // refresh canvas

    board.fields.forEach(function (field) {
        field.draw(); // redraw every field again
    });
}<commit_msg>dice roll revert<commit_after>// CONSTANTS
var fieldWidth = 54, // the width of every of the 24 fields
    offsetBetweenFields = 5, // between small field(white) and big field(dark)
    boardSide = 324, // the width of one side of the board
    boardBar = 34, // the thing between the board sides in pixels
    boardFrameOffset = 18, // the offset in the corners between the board itself and the frame in pixels
    checkerHeight = 42, // the height of the checker after being fully drawn in pixels
    checkerRadius = 21, // full width = 44; outer stroke 1px
    checkerInnerCircleRadius = 10,
    initialDiceValue = 6;

// GAME ELEMENTS - canvas, ctx, keystate, etc.
var canvas,
    ctx,
    diceCanvas,
    diceCtx,
    clickedField,
    firstPlayer,
    secondPlayer,
    firstDice,
    secondDice,
    firstDiceThrow,
    firstPlayerOnTurn,
    mustThrowDices;

// DEFINING GAME OBJECTS - player, checker, dice, board(not if it is just a background) ...
var player = (function () {
    var player = {
        init: function (name, color) {
            this.name = name;
            this.color = color;
            this.currentCheckersCount = 15;
            this.hasHitChecker = false;
            this.hitCheckersCount = 0;
            this.canTakeChecker = false;
            return this;
        },
        tookChecker: function () {
            // TODO: Validate depending on call.
            this.currentCheckersCount -= 1;
        }
    };

    Object.defineProperty(player, 'name', {
        get: function () {
            return this._name;
        },
        set: function (value) {
            //TODO: Validate
            this._name = value;
        }
    });

    Object.defineProperty(player, 'currentCheckersCount', {
        get: function () {
            return this._currentCheckersCount;
        },
        set: function (value) {
            //TODO: Validate
            this._currentCheckersCount = value;
        }
    });

    Object.defineProperty(player, 'color', {
        get: function () {
            return this._color;
        },
        set: function (value) {
            // TODO: Validate
            this._color = value;
        }
    });

    Object.defineProperty(player, 'hasHitChecker', {
        get: function () {
            return this._hasHitChecker;
        },
        set: function (value) {
            // TODO: Validate
            this._hasHitChecker = value;
        }
    });

    Object.defineProperty(player, 'hitCheckersCount', {
        get: function () {
            return this._hitCheckersCount;
        },
        set: function (value) {
            // TODO: Validate
            this._hitCheckersCount = value;
        }
    });

    Object.defineProperty(player, 'canTakeChecker', {
        get: function () {
            return this._canTakeChecker;
        },
        set: function (value) {
            // TODO: Validate
            this._canTakeChecker = value;
        }
    });

    return player;
}());

var field = (function () { /* the board is filled with 24 fields,
 IT IS A RESPONSIBILITY OF THE FIELDS TO GIVE COORDINATES TO THE CHECKERS, WITH RESPECT TO THEIR OWN X,Y COORDINATES
 IN THIS WAY WE DON'T CARE HOW TO STACK CHECKERS AND TO TAKE INTO ACCOUNT THEIR Xs AND Ys,
 THE FIELD JUST STACKS THEM DEPENDING ON THE COUNT IT IS HOLDING, GIVING HIS OWN X, Y */
    var field = {
        init: function (x, y) {
            this.checkers = [];
            this.x = x;
            this.y = y;
            /* if field is 0~11 y = canvas.height - boardFrameOffset; else y = boardFrameOffset;
             this is needed only for knowing at which side are we, so we can draw the checkers properly */
            return this;
        },
        addChecker: function (checker) {
            this.checkers.push(checker);
        },
        removeChecker: function () {
            this.checkers.pop();
        },
        draw: function () {
            var count = this.checkers.length, // count checkers, if more than 5 draw stacked
                i,
                fieldCenter;
            for (i = 0; i < count; i += 1) {
                if (i > 4) {
                    // draw stacked
                    ctx.save();
                    ctx.fillStyle = 'red';
                    ctx.font = "12px Verdana";
                    ctx.fillText('x' + (i - 3), (this.x - 6) + fieldWidth / 2, this.y + checkerRadius + 4);
                    // x2 for the 6th checker because it represents how many checkers are stacked
                    // 6 and 4 are just a magic numbers to position the text in the center of the checker, because the text has also its own offset
                    ctx.restore();
                } else {
                    if (this.y < canvas.height / 2) { // if field is in the upper half of the board, should stack them up to bottom
                        fieldCenter = this.x + (fieldWidth / 2); // x coordinate for the checker center
                        this.checkers[i].draw(fieldCenter, this.y + i * checkerHeight + checkerRadius + 2);
                        /* +2 just to look better,
                         the checker from the board frame */
                    } else { // when the field is in the lower part, should stack them from bottom to up
                        fieldCenter = this.x + (fieldWidth / 2); // x coordinate for the checker center
                        this.checkers[i].draw(fieldCenter, this.y - i * checkerHeight + checkerRadius - 2); // -2 just to look better
                    }
                }
            }
        }
    };

    Object.defineProperty(field, 'checkers', {
        get: function () {
            return this._checkers;
        },
        set: function (value) {
            this._checkers = value;
        }
    });

    Object.defineProperty(field, 'x', {
        get: function () {
            return this._x;
        },
        set: function (value) {
            this._x = value;
        }
    });

    Object.defineProperty(field, 'y', {
        get: function () {
            return this._y;
        },
        set: function (value) {
            this._y = value;
        }
    });

    return field;
}());

var checker = (function () {
    var checker = {
        init: function (color) {
            this.color = color; // can be only 'black' or 'white'
            return this;
        },
        draw: function (x, y) {
            ctx.save();
            if (this.color === 'black') {
                ctx.strokeStyle = 'white';
            }
            // outer circle
            ctx.beginPath();
            ctx.fillStyle = this.color;
            ctx.lineWidth = 1;
            ctx.arc(x, y, checkerRadius, 0, 2 * Math.PI);
            ctx.fill();
            ctx.stroke();

            // inner circle
            ctx.beginPath();
            ctx.strokeStyle = '#808080';
            ctx.lineWidth = 2;
            ctx.arc(x, y, checkerInnerCircleRadius, 0, 2 * Math.PI);
            ctx.stroke();

            ctx.restore();
        }
    };

    Object.defineProperty(checker, 'color', {
        get: function () {
            return this._color;
        },
        set: function (value) {
            this._color = value;
        }
    });

    return checker;
}());

var board = (function () {
    var bottomSideAllSet, // flag to indicate that we must start with a field having 5 checkers in it(the 12th field)
    // at bottom we start with  12. 5 3 5 2 .23
    // at top we start with     11. 5 3 5 2 .0
        patternToPutColors = []; // colors are inverted in the opposite sides of the field, sorry it truly looks ugly..

    var gameboard = {
        init: function () {
            this.fields = [];
            bottomSideAllSet = false;
            patternToPutColors[0] = 1;
            patternToPutColors[5] = 0;
            patternToPutColors[7] = 0;
            patternToPutColors[11] = 1;
            var self = this;
            setupHalfGameBoard(self, bottomSideAllSet);
            bottomSideAllSet = true;
            setupHalfGameBoard(self, bottomSideAllSet);
            return this;
        },
        addField: function (value) {
            this.fields.push(value);
        }
    };

    function setupHalfGameBoard(self, bottomSideAllSet) {
        var i,
            len,
            x,
            y,
            currentField,
            patternOfTheNumberOfCheckersToPut = [2, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 5],// on 0 field put 2, on field 1 put 0, etc.. the setup rules..
            j,  // needed to go trough the patternToPutCheckers
            colorToPut,
            countPassedFields = 0; // needed to add a boardBar offset to the X coordinate

        if (bottomSideAllSet) {
            i = 12;
            j = 11;
        } else {
            i = 0;
            j = 0;
        }
        for (len = i + 12; i < len; i += 1, (i >= 12) ? j -= 1 : j += 1, countPassedFields += 1) {
            if (countPassedFields >= 6) {  // after every 6 fields we must consider the boardBar also, in both the upper and the lower side of the board
                x = (!bottomSideAllSet) * canvas.width - boardFrameOffset - ((countPassedFields + !bottomSideAllSet) * fieldWidth) - boardBar;
            } else {
                x = (!bottomSideAllSet) * canvas.width - boardFrameOffset - ((countPassedFields + !bottomSideAllSet) * fieldWidth);
                // if we are at the bottom we must consider the canvas width and to subtract from it
            }
            y = (!bottomSideAllSet) * (canvas.height - checkerHeight) - boardFrameOffset;

            if (x < 0) { // because we are extracting everything from the canvas width or height
                x *= -1; // when we are at the bottom side, we start from the MOST-RIGHT field(our 0 field) so canvas height, and width must be considered,
            }            // while when we are at the upper side of the board, the MOST-LEFT field(the 12th field) must be filled first,
            if (y < 0) { // so canvas width and height in the upper side are 0, and we get a negative number but we actually need that number to be positive,
                y *= -1; // to go to the right.. to fill the rest of the fields.. it's all because of how the fields position in backgammon
            }
            if (patternToPutColors[j] === 1) {
                colorToPut = 'white';
                patternToPutColors[j] = 0; // swapping the pattern for the next half of the board
            } else if (patternToPutColors[j] === 0) {
                colorToPut = 'black';
                patternToPutColors[j] = 1;
            }
            currentField = Object.create(field).init(x, y); // creating one of the 24 fields in the board
            putCheckersOnField(patternOfTheNumberOfCheckersToPut[j], currentField, colorToPut); // assigning checkers to it with respect to the Backgammon setup rules
            self.addField(currentField); // adding the field to the board, used 'self' because the scope of this has changed
        }
    }

    function putCheckersOnField(checkersToPut, givenField, color) {
        var i;
        for (i = 0; i < checkersToPut; i += 1) {
            givenField.addChecker(Object.create(checker).init(color));
        }
    }

    return gameboard;
}());

var dice = (function () {
    var dice = {
        init: function () {
            this.number = initialDiceValue;
            return this;
        }
    };

    Object.defineProperty(dice, 'number', {
        get: function () {
            return this._number;
        },
        set: function (value) {
            checkIfDiceValueIsValid(value);
            this._number = value;
        }
    });

    Object.defineProperty(dice, 'generateNewNumber', {
        value: function () {
            return this.number = Math.round(Math.random() * 5) + 1;
        }
    });

    function checkIfDiceValueIsValid(number) {
        if (isNaN(number) || number % 1 != 0 || number < 1 || number > 6) {
            throw new Error('Dice number is invalid!');
        }
    }

    return dice;
}());

// function newGame() or main()
// create initiate and append game canvas
// INITIATE GAME OBJECTS;
function newGame() {
    canvas = document.getElementById('board-canvas');
    ctx = canvas.getContext('2d');

    // INIT GAME OBJECTS, SETS UP GAME
    board.init();
    firstDice = Object.create(dice).init();
    secondDice = Object.create(dice).init();
    firstDiceThrow = true;
}
newGame();

function play() {
    // GAME LOOP - game logic, updating the fields, players turns, dices etc. Update update update
    // change fields depending on how the player interact(key presses)
    canvas.addEventListener('click', findPressedField);

    //LOGIC NEEDS TO BE IMPLEMENTED FOR CURRENT PLAYER

    //THROW DICE - at first time, throw to see who will be playing first
    if (firstDiceThrow) {
        firstDiceThrow = false;
        firstDice.generateNewNumber();
        secondDice.generateNewNumber();
        if (firstDice.number > secondDice.number) {
            firstPlayerOnTurn = true;
        } else if (firstDice.number < secondDice.number) {
            firstPlayerOnTurn = false;
        } else {
            firstDiceThrow = true;
            play();
        }
    } else {
        firstDice.generateNewNumber();
        secondDice.generateNewNumber();
    }

    //CHECK IF ANY POSSIBLE MOVE

    //IF ANY POSSIBLE MOVES AVAILABLE  -->  CHECK FOR NEW CLICKS AND CATCH START POSITION , else change player
    //IF ANY POSSIBLE MOVES AVAILABLE  -->  CHECK IF NEW SET/CLICKED POSITION IS CORRECT AND MOVE PULL , else try again

    // DRAW
    // draws every time and if we have changes its ok
    draw();

    // CHANGE PLAYER
    firstPlayerOnTurn ? firstPlayerOnTurn = false : firstPlayerOnTurn = true;

    requestAnimationFrame(play);
}
play();

function findPressedField(event) {
    var x = event.offsetX;
    var y = event.offsetY;
    if (((x < canvas.width - boardFrameOffset && x > boardFrameOffset + boardSide + boardBar) ||
        (x < boardFrameOffset + boardSide && x > boardFrameOffset)) &&
        (y < canvas.height - boardFrameOffset && y > boardFrameOffset)) { // ignoring every piece of the frame
        var i = 0,
            len,
            foundField,
            upperSide = false;
        // determining in which quadrant are we exactly
        if (y < canvas.height / 2 && y > boardFrameOffset) {
            i = 12; // last field of the upper side, last because if we take the first our condition in the for-loop will be achieved every time
            upperSide = true;
        } else {
            i = 0; // first field of the lower side
        }
        if (x < boardSide + boardFrameOffset && x > boardFrameOffset) { // left side of the board
            if (i === 0) { // bottom left side
                i = 6;
            } else { // upper left side
                i = 12;
            }
        } else { // right side of the board
            if (i === 0) { // bottom right side
                i = 0;
            } else { // upper left side
                i = 18; // again last of the array
            }
        }
        for (len = i + 6; i < len; i += 1) {
            var currentField = board.fields[i];
            if (upperSide) { /* its all because of the fields..
             the start position of the lower side is most-right and it starts from 0,
             while the start position of the upper side is the most-left which confuses the algorithm */
                var previousField = board.fields[i - 1];
                if (currentField.x > x) {
                    foundField = previousField;
                    break;
                }
            } else {
                if (x > currentField.x) {
                    foundField = currentField;
                    break;
                }
            }
        }
        if (typeof foundField === 'undefined') { // when we are going out of the for-in and the condition for the upperSide is not met,
            // because we take the previous field element we could not get to check the last one
            foundField = board.fields[len - 1];
        }
        clickedField = foundField;
        console.log(clickedField); // testing purposes
    }
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // refresh canvas

    board.fields.forEach(function (field) {
        field.draw(); // redraw every field again
    });
}<|endoftext|>


<commit_before>$(document).ready(function() {
  // 注意事项！
  // 因为各部分代码处于同一个js文件里，因此尽量都创建局部变量，非不得已时避免创建全局变量，这样代码性能也更好
  // 在创建变量或函数时需要加上自己部分的前缀名: head、on_show、coming_soon
  // 例： var head_count = 0; const on_show_name = 'movie'; function coming_soon_find_movie() {}

  const build_api = {
    head: 'http://192.168.199.105/resource/movie/popular?count=3',
    on_show: 'http://192.168.199.105/resource/movie/on_show',
    coming_soon: 'http://192.168.199.105/resource/movie/coming_soon',
  }

  const global_api = {
    head: 'http://120.25.76.106/resource/movie/popular?count=3',
    on_show: 'http://120.25.76.106/resource/movie/on_show',
    coming_soon: 'http://120.25.76.106/resource/movie/coming_soon',
  }
  /*顶部电影热图 js代码部分开始*/
  let head_popular_images = $('.head_popular_movies_img');

  /*模拟api动态添加图片*/
  const head_popular_movies_properties = {
    "count":3,
    "data":[
      {
        "id":1,
        "uri":"https://raw.githubusercontent.com/AwesomeTickets/Dashboard/master/img/poster/large/1.png"
      },
      {
        "id":2,
        "uri":"https://raw.githubusercontent.com/AwesomeTickets/Dashboard/master/img/poster/large/2.png"
      },
      {
        "id":3,
        "uri":"https://raw.githubusercontent.com/AwesomeTickets/Dashboard/master/img/poster/large/3.png"
      },
    ],
  }

  for (let i = 0; i < 3; i++) {
    head_popular_images[i].src = head_popular_movies_properties.data[i].uri;
  }
  /*模拟api动态添加图片*/

  /*使用ajax根据api来拿照片信息*/
  // $.get(build_api.head, function(data, textStatus) {
  //   for (let i = 0; i < 3; i++) {
  //     head_popular_images[i].src = data.data[i].uri;
  //   }
  // })
  /*使用ajax根据api来拿照片信息*/
  /*顶部电影热图 js代码部分结束*/

  /*正在热映 js代码部分开始*/

  // 模拟api接口
  var on_show_data = {
    "count": 9,
    "data": [1, 2, 3, 4, 5, 6, 7, 8, 9]
  };
  function on_show_obj(_id) {
    this.id = _id;
    this.title = "";
    this.pubdate = "";
  };
  var on_show_set = new Array();
  for (var i = 0; i < on_show_data.count; i++)
    on_show_set.push(new on_show_obj(i+1));

  //  动态添加海报
  var pic_num = on_show_data.count;
  function slick_temp(i) {
      return "
"+
        "
"+
          "text
<button>goto buy</button>"+
          ""+
        "
"+
      "
";
    };
  var on_show_html = "";
  for(var i = 0; i < pic_num; i++)
    on_show_html += slick_temp(i+1);
  $(".on_show").html(on_show_html);

  //  动态修改海报地址
  var on_show_location = "/static/pictures/resource/poster/on_show/";
  var i = 0;
  $(".on_show_img").each(function(){
    $(this).attr("data-lazy", on_show_location + "hot" + on_show_set[i].id + ".jpg");
    i++;
  });
  $(".on_show_hover").each(function() {
    $(this).bind("mouseover", function() {
      $(this).find("span").css("display", "block").css("z-index", 9);
      $(this).find("img").css("opacity", "0.4");
    });
    $(this).bind("mouseout", function() {
      $(this).find("span").css("display", "none").css("z-index", 0);
      $(this).find("img").css("opacity", "1");
    });
  });
  /*正在热映 js代码部分结束*/

  /*即将上映 js代码部分开始*/

  // 模拟api接口
  var coming_soon_data = {
    "count": 9,
    "data": [1, 2, 3, 4, 5, 6, 7, 8, 9]
  };
  var coming_soon_pic = [
    "p1596755313",
    "p2256580955",
    "p2441815392",
    "p2443765210",
    "p2445601403",
    "p2446525065",
    "p2448692606",
    "p2450444730",
    "p2450800270"
  ]
  function coming_soon_obj(_id) {
    this.id = _id;
    this.title = "";
    this.pubdate = "";
  };
  var coming_soon_set = new Array();
  for (var i = 0; i < coming_soon_data.count; i++)
    coming_soon_set.push(new coming_soon_obj(i+1));

  //  动态添加海报
  var coming_soon_pic_num = coming_soon_data.count;
  function coming_soon_slick_temp(i) {
      return "
"+
        "
"+
          "text
<button>goto buy</button>"+
          ""+
        "
"+
      "
";
    };
  var coming_soon_html = "";
  for(var i = 0; i < coming_soon_pic_num; i++)
    coming_soon_html += coming_soon_slick_temp(i+1);
  $(".coming_soon").html(coming_soon_html);

//  动态修改海报地址
  var coming_soon_location = "/static/pictures/resource/poster/coming_soon/";
  var i = 0;
  $(".coming_soon_img").each(function(){
    $(this).attr("data-lazy", coming_soon_location + coming_soon_pic[i] + ".jpg");
    i++;
  });
  $(".coming_soon_hover").each(function() {
    $(this).bind("mouseover", function() {
      $(this).find("span").css("display", "block").css("z-index", 9);
      $(this).find("img").css("opacity", "0.4");
    });
    $(this).bind("mouseout", function() {
      $(this).find("span").css("display", "none").css("z-index", 0);
      $(this).find("img").css("opacity", "1");
    });
  });

  /*即将上映 js代码部分结束*/

  //  滑动组件
  $('.lazy').slick({
    lazyLoad: 'ondemand',
    slidesToShow: 6,
    slidesToScroll: 1,
    infinite:false
  });

});<commit_msg>use ajax to get popular images<commit_after>$(document).ready(function() {
  // 注意事项！
  // 因为各部分代码处于同一个js文件里，因此尽量都创建局部变量，非不得已时避免创建全局变量，这样代码性能也更好
  // 在创建变量或函数时需要加上自己部分的前缀名: head、on_show、coming_soon
  // 例： var head_count = 0; const on_show_name = 'movie'; function coming_soon_find_movie() {}

  const global_api = {
    head: 'http://120.25.76.106/resource/movie/popular?count=3',
    on_show: 'http://120.25.76.106/resource/movie/on_show',
    coming_soon: 'http://120.25.76.106/resource/movie/coming_soon',
  }

  /*顶部电影热图 js代码部分开始*/
  let head_popular_images = $('.head_popular_movies_img');

  /*使用ajax根据api来拿照片信息*/
  $.get(global_api.head, function(data, textStatus) {
    for (let i = 0; i < 3; i++) {
      head_popular_images[i].src = data.data[i].uri;
    }
  })
  /*顶部电影热图 js代码部分结束*/

  /*正在热映 js代码部分开始*/
  // 模拟api接口
  var on_show_data = {
    "count": 9,
    "data": [1, 2, 3, 4, 5, 6, 7, 8, 9]
  };
  function on_show_obj(_id) {
    this.id = _id;
    this.title = "";
    this.pubdate = "";
  };
  var on_show_set = new Array();
  for (var i = 0; i < on_show_data.count; i++)
    on_show_set.push(new on_show_obj(i+1));

  //  动态添加海报
  var pic_num = on_show_data.count;
  function slick_temp(i) {
      return "
"+
        "
"+
          "text
<button>goto buy</button>"+
          ""+
        "
"+
      "
";
    };
  var on_show_html = "";
  for(var i = 0; i < pic_num; i++)
    on_show_html += slick_temp(i+1);
  $(".on_show").html(on_show_html);

  //  动态修改海报地址
  var on_show_location = "/static/pictures/resource/poster/on_show/";
  var i = 0;
  $(".on_show_img").each(function(){
    $(this).attr("data-lazy", on_show_location + "hot" + on_show_set[i].id + ".jpg");
    i++;
  });
  $(".on_show_hover").each(function() {
    $(this).bind("mouseover", function() {
      $(this).find("span").css("display", "block").css("z-index", 9);
      $(this).find("img").css("opacity", "0.4");
    });
    $(this).bind("mouseout", function() {
      $(this).find("span").css("display", "none").css("z-index", 0);
      $(this).find("img").css("opacity", "1");
    });
  });
  /*正在热映 js代码部分结束*/

  /*即将上映 js代码部分开始*/

  // 模拟api接口
  var coming_soon_data = {
    "count": 9,
    "data": [1, 2, 3, 4, 5, 6, 7, 8, 9]
  };
  var coming_soon_pic = [
    "p1596755313",
    "p2256580955",
    "p2441815392",
    "p2443765210",
    "p2445601403",
    "p2446525065",
    "p2448692606",
    "p2450444730",
    "p2450800270"
  ]
  function coming_soon_obj(_id) {
    this.id = _id;
    this.title = "";
    this.pubdate = "";
  };
  var coming_soon_set = new Array();
  for (var i = 0; i < coming_soon_data.count; i++)
    coming_soon_set.push(new coming_soon_obj(i+1));

  //  动态添加海报
  var coming_soon_pic_num = coming_soon_data.count;
  function coming_soon_slick_temp(i) {
      return "
"+
        "
"+
          "text
<button>goto buy</button>"+
          ""+
        "
"+
      "
";
    };
  var coming_soon_html = "";
  for(var i = 0; i < coming_soon_pic_num; i++)
    coming_soon_html += coming_soon_slick_temp(i+1);
  $(".coming_soon").html(coming_soon_html);

//  动态修改海报地址
  var coming_soon_location = "/static/pictures/resource/poster/coming_soon/";
  var i = 0;
  $(".coming_soon_img").each(function(){
    $(this).attr("data-lazy", coming_soon_location + coming_soon_pic[i] + ".jpg");
    i++;
  });
  $(".coming_soon_hover").each(function() {
    $(this).bind("mouseover", function() {
      $(this).find("span").css("display", "block").css("z-index", 9);
      $(this).find("img").css("opacity", "0.4");
    });
    $(this).bind("mouseout", function() {
      $(this).find("span").css("display", "none").css("z-index", 0);
      $(this).find("img").css("opacity", "1");
    });
  });

  /*即将上映 js代码部分结束*/

  //  滑动组件
  $('.lazy').slick({
    lazyLoad: 'ondemand',
    slidesToShow: 6,
    slidesToScroll: 1,
    infinite:false
  });

});<|endoftext|>


<commit_before>global_url="";

function remove_port(url){
    if(url.substr(-4)==':80/'){
        url=url.substring(0,url.length-4);
    }
    return url;
}

function remove_wbm(url){
    var pos=url.indexOf('/http');
    if(pos!=-1){
        var new_url=url.substring(pos+1);
    }else{
        var pos=url.indexOf('/www');
        var new_url=url.substring(pos+1);
    }
    return remove_port(new_url);
}

function remove_alexa(url){
    var pos=url.indexOf('/siteinfo/');
    var new_url=url.substring(pos+10);
    return remove_port(new_url);
}

function remove_whois(url){
    var pos=url.indexOf('/whois/');
    var new_url=url.substring(pos+7);
    return remove_port(new_url);
}
/* Common method used everywhere to retrieve cleaned up URL */
function retrieve_url(){
    var search_term = document.getElementById('search_input').value;
    if(search_term == ""){
        var url=global_url;
    }else{
        var url=search_term;
    }
    return url;
}

function get_clean_url() {
    var url=retrieve_url();
    if (url.includes('web.archive.org')) {
        url=remove_wbm(url);
    } else if (url.includes('www.alexa.com')) {
        url=remove_alexa(url);
    } else if (url.includes('www.whois.com')) {
        url=remove_whois(url);
    }
    return url;
}

function save_now(){
	  chrome.runtime.sendMessage({message: "openurl",
                                wayback_url: "https://web.archive.org/save/",
                                page_url: get_clean_url(),
                                method:'save' }).then(handleResponse, handleError);
}

function recent_capture(){
	  chrome.runtime.sendMessage({message: "openurl",
                                wayback_url: "https://web.archive.org/web/2/",
                                page_url: get_clean_url(),
                                method:'recent'});
}

function first_capture(){
	  chrome.runtime.sendMessage({message: "openurl",
                                wayback_url: "https://web.archive.org/web/0/",
                                page_url: get_clean_url(),
                                method:'first'});
}

function view_all(){
	  chrome.runtime.sendMessage({message: "openurl",
                                wayback_url: "https://web.archive.org/web/*/",
                                page_url: get_clean_url(),
                                method:'viewall'});
}

function get_url(){
    chrome.tabs.query({active: true,currentWindow:true},function(tabs){
        global_url=tabs[0].url;
    });
}

function social_share(eventObj){
    var parent=eventObj.target.parentNode;
    var id=parent.getAttribute('id');
    var sharing_url="";
    var url=retrieve_url();
    var overview_url="https://web.archive.org/web/*/";
    if (url.includes('web.archive.org')){
        sharing_url=url; //If the user is already at a playback page,share that URL
    }
    else{
        sharing_url=overview_url+get_clean_url(); //When not on a playback page,share the overview version of that URL
    }
    var open_url="";
    if(!(url.includes('chrome://') || url.includes('chrome-extension://'))){ //Prevents sharing some unnecessary page
        if(id.includes('fb')){
            open_url="https://www.facebook.com/sharer/sharer.php?u="+sharing_url; //Share the wayback machine's overview of the URL
        }else if(id.includes('twit')){
            open_url="https://twitter.com/home?status="+sharing_url;
        }else if(id.includes('gplus')){
            open_url="https://plus.google.com/share?url="+sharing_url;
        }else if(id.includes('linkedin')){
            open_url="https://www.linkedin.com/shareArticle?url="+sharing_url;
        }
        window.open(open_url, 'newwindow', 'width=800, height=280,left=0');
    }
}

function statistics(eventObj) {  //Common Function for alexa and whois statistics
    var target=eventObj.target;
    var id=target.getAttribute('id');
    var url=get_clean_url();
    url = url.replace(/^https?:\/\//,'');
    var length=url.length;
    var last_index=url.indexOf('/');
    url=url.slice(0,last_index);
    if(id.includes("alexa")){
        var open_url="http://www.alexa.com/siteinfo/" + url;
        window.open(open_url, 'newwindow', 'width=1000, height=1000,left=0');
    }else if(id.includes("whois")){
        var open_url="https://www.whois.com/whois/" + url;
        window.open(open_url, 'newwindow', 'width=1000, height=1000,left=0');
    }
}

function search_tweet(eventObj){
    var url = get_clean_url();
    url = url.replace(/^https?:\/\//,'');
    if(url.slice(-1)=='/') url=url.substring(0,url.length-1);
    var open_url="https://twitter.com/search?q="+url;
    window.open(open_url, 'newwindow', 'width=1000, height=1000,left=0');
}

function display_list(key_word){
    $sbox = document.getElementById('suggestion-box');
    $sbox.style.display='none';
    $sbox.innerHTML="";
    var xhr = new XMLHttpRequest();
    xhr.open('GET', "https://web.archive.org/__wb/search/host?q="+key_word, true);
    xhr.onload=function(){
        $sbox.style.display='none';
        $sbox.innerHTML="";
        var data=JSON.parse(xhr.response);
        var n=data.hosts.length;
        if(n>0 && document.getElementById('search_input').value!=''){
            $sbox.style.display='block';
            for(var i=0;i<n;i++){
                var a=document.createElement('a');
                a.onclick=function(event){
                    document.getElementById('search_input').value=event.target.innerHTML;
                    $sbox.style.display='none';
                    $sbox.innerHTML="";
                };
                a.setAttribute('role','button');
                a.innerHTML=data.hosts[i].display_name;
                var li=document.createElement('li');
                li.appendChild(a);
                $sbox.appendChild(li);
            }
        }
    };
    xhr.send(null);
}

function display_suggestions(e){
    document.getElementById('suggestion-box').style.display='none';
    document.getElementById('suggestion-box').innerHTML="";
    if(e.keyCode==13){
        e.preventDefault();
    }else {
        //setTimeout is used to get the text in the text field after key has been pressed
        window.setTimeout(function(){
            var len=document.getElementById('search_input').value.length;
            if((len)>=3){
                display_list(document.getElementById('search_input').value);
            }else{
                document.getElementById('suggestion-box').style.display='none';
                document.getElementById('suggestion-box').innerHTML="";
            }
        },0.1);
    }
}
function open_feedback_page(){
    var feedback_url="https://chrome.google.com/webstore/detail/wayback-machine/fpnmgdkabkmnadcjpehmlllkndpkmiak/reviews?hl=en";
    chrome.tabs.create({ url: feedback_url });
}

function about_support(){
    window.open('about.html', 'newwindow', 'width=1200, height=900,left=0').focus();
}

function makeModal(){
    var url = get_clean_url();
    console.log("Making RT for "+url);
    chrome.runtime.sendMessage({message: "makemodal",rturl:url});
}

function settings(){
    window.open('settings.html','newwindow', 'width=590, height=740,left=0');
}

function auto_archive_url(){
    var tab_url="";
    chrome.tabs.query({active: true,currentWindow:true},function(tabs){
        tab_url=tabs[0].url;
        tabId=tabs[0].id;
        console.log(tab_url);
        chrome.storage.sync.get(['auto_archive'],function(event){
            if(event.auto_archive==true){
                if(!((tab_url.includes("https://web.archive.org/web/")) || (tab_url.includes("chrome://newtab")))){
                    check_url(tab_url,function(){
                        var wayback_url = "https://web.archive.org/save/";
                        chrome.browserAction.getBadgeText({tabId:tabId}, function (result){
                            if((result=="S")){
                                tab_url = wayback_url+tab_url;
                                console.log(tab_url);
                                wm_save_URL(tab_url, function(){
                                    var tabId=tabs[0].id;
                                    console.log(tabId);
                                    chrome.runtime.sendMessage({message:"changeBadge",tabId:tabId});
                                });
                            }
                        });
                    });
                }
            }
        });
    });
}

function wm_save_URL(url, callback) {
    var http=new XMLHttpRequest();
    var new_url=url;
    http.open("GET",new_url,true);
    http.send(null);
    http.onreadystatechange = function() {
        if (this.readyState==4 && this.status==200) {
            console.log("Archived");
        }
    }
    callback();
}

function check_url(url,callback){
    var xhr=new XMLHttpRequest();
    var new_url="http://archive.org/wayback/available?url="+url;
    xhr.open("GET",new_url,true);
    xhr.send(null);
    xhr.onload = function() {
        var response = JSON.parse(xhr.response);
        console.log(response);
        if(response.archived_snapshots.closest){
            console.log("available");
            chrome.tabs.query({active: true,currentWindow:true},function(tabs){
                var tab_id=tabs[0].id;
                chrome.browserAction.getBadgeText({tabId:tab_id}, function (result){
                    if(result=="S"){
                        chrome.runtime.sendMessage({message:"changeBadge",tabId:tab_id});
                    }
                });
            });
        }else{
            console.log("not available");
            callback();
        }
    }
}

function show_all_screens(){
    var url=get_clean_url();
    chrome.runtime.sendMessage({message:"showall",url:url});
}

function borrow_books(){
    chrome.tabs.query({active: true,currentWindow:true},function(tabs){
        url=tabs[0].url;
        tabId=tabs[0].id;
        chrome.browserAction.getBadgeText({tabId:tabId}, function (result){
            if(result=="B"){
                if(url.includes("www.amazon") && url.includes('/dp/')){
                    var xhr=new XMLHttpRequest();
                    var new_url="https://wwwb-api.archive.org/services/context/book?url="+url;
                    console.log(new_url);
                    xhr.open("GET",new_url,true);
                    xhr.send(null);
                    xhr.onload=function(){
                        var response = JSON.parse(xhr.response);
                        if(response.success==true && response.error==undefined){
                          var responses=response.responses;
                          for(var propName in responses) {
                            if(responses.hasOwnProperty(propName)) {
                              var propValue = responses[propName];
                            }
                          }
                          var identifier=propValue.identifier;
                        }
                        if(identifier!=undefined||null){
                        document.getElementById('borrow_books_tr').style.display="block";
                        }
                        document.getElementById('borrow_books_tr').onclick=function(){
                            chrome.tabs.create({url:"https://archive.org/details/"+identifier});
                        }
                    }
                }
            }
        });

    });
}

function show_news(){
    chrome.tabs.query({active: true,currentWindow:true},function(tabs){
        url=tabs[0].url;
        tabId=tabs[0].id;
        console.log("hey");
        if(url.includes("https://www.huffingtonpost"||"https://www.nytimes"||"https://www.forbes"||"https://www.washingtonpost")){
            console.log("also here");
            document.getElementById('news_recommend_tr').style.display="block";
            document.getElementById('news_recommend_tr').onclick=function(){
                chrome.tabs.create({url:chrome.runtime.getURL("recommendations.html")+"?url="+url});
            }
        }
    });
}

/** Disabled code for the autosave feature **/
//function restoreSettings() {
//  chrome.storage.sync.get({
//    as:false
//  }, function(items) {
//    document.getElementById('as').checked = items.as;
//      if(items.as){
//          chrome.runtime.sendMessage({message: "start_as"}, function(response) {});
//      }
//     });
//}
//
//function saveSettings(){
//    var as = document.getElementById('as').checked;
//      chrome.storage.sync.set({
//      as: as
//  });
//}
//function showSettings(eventObj){
//    var target=eventObj.target;
//    if(target.getAttribute('toggle')=='off'){
//        document.getElementById('settings_btn').setAttribute('toggle','on');
//    document.getElementById('settings_div').style.display="block";
//    }else{
//        document.getElementById('settings_btn').setAttribute('toggle','off');
//        document.getElementById('settings_div').style.display="none";
//    }
//}
//restoreSettings();
//document.getElementById('settings_div').style.display="none";

// window.onload=get_url;
window.onloadFuncs = [get_url,auto_archive_url,borrow_books,show_news];
window.onload = function(){
 for(var i in this.onloadFuncs){
  this.onloadFuncs[i]();
 }
}
document.getElementById('save_now').onclick = save_now;
document.getElementById('recent_capture').onclick = recent_capture;
document.getElementById('first_capture').onclick = first_capture;
document.getElementById('fb_share').onclick =social_share;
document.getElementById('twit_share').onclick =social_share;
document.getElementById('gplus_share').onclick =social_share;
document.getElementById('linkedin_share').onclick =social_share;
document.getElementById('alexa_statistics').onclick =statistics;
document.getElementById('whois_statistics').onclick =statistics;
document.getElementById('search_tweet').onclick =search_tweet;
document.getElementById('about_support_button').onclick = about_support;
document.getElementById('settings_button').onclick =settings;
document.getElementById('context-screen').onclick=show_all_screens;
document.getElementById('feedback').onclick=open_feedback_page;

document.getElementById('overview').onclick = view_all;
//document.getElementById('settings_btn').onclick=showSettings;
//document.getElementById('settings_save_btn').onclick=saveSettings;
document.getElementById('make_modal').onclick=makeModal;
document.getElementById('search_input').addEventListener('keydown',display_suggestions);
<commit_msg>Added Settings option<commit_after>global_url="";

function remove_port(url){
    if(url.substr(-4)==':80/'){
        url=url.substring(0,url.length-4);
    }
    return url;
}

function remove_wbm(url){
    var pos=url.indexOf('/http');
    if(pos!=-1){
        var new_url=url.substring(pos+1);
    }else{
        var pos=url.indexOf('/www');
        var new_url=url.substring(pos+1);
    }
    return remove_port(new_url);
}

function remove_alexa(url){
    var pos=url.indexOf('/siteinfo/');
    var new_url=url.substring(pos+10);
    return remove_port(new_url);
}

function remove_whois(url){
    var pos=url.indexOf('/whois/');
    var new_url=url.substring(pos+7);
    return remove_port(new_url);
}
/* Common method used everywhere to retrieve cleaned up URL */
function retrieve_url(){
    var search_term = document.getElementById('search_input').value;
    if(search_term == ""){
        var url=global_url;
    }else{
        var url=search_term;
    }
    return url;
}

function get_clean_url() {
    var url=retrieve_url();
    if (url.includes('web.archive.org')) {
        url=remove_wbm(url);
    } else if (url.includes('www.alexa.com')) {
        url=remove_alexa(url);
    } else if (url.includes('www.whois.com')) {
        url=remove_whois(url);
    }
    return url;
}

function save_now(){
	  chrome.runtime.sendMessage({message: "openurl",
                                wayback_url: "https://web.archive.org/save/",
                                page_url: get_clean_url(),
                                method:'save' }).then(handleResponse, handleError);
}

function recent_capture(){
	  chrome.runtime.sendMessage({message: "openurl",
                                wayback_url: "https://web.archive.org/web/2/",
                                page_url: get_clean_url(),
                                method:'recent'});
}

function first_capture(){
	  chrome.runtime.sendMessage({message: "openurl",
                                wayback_url: "https://web.archive.org/web/0/",
                                page_url: get_clean_url(),
                                method:'first'});
}

function view_all(){
	  chrome.runtime.sendMessage({message: "openurl",
                                wayback_url: "https://web.archive.org/web/*/",
                                page_url: get_clean_url(),
                                method:'viewall'});
}

function get_url(){
    chrome.tabs.query({active: true,currentWindow:true},function(tabs){
        global_url=tabs[0].url;
    });
}

function social_share(eventObj){
    var parent=eventObj.target.parentNode;
    var id=parent.getAttribute('id');
    var sharing_url="";
    var url=retrieve_url();
    var overview_url="https://web.archive.org/web/*/";
    if (url.includes('web.archive.org')){
        sharing_url=url; //If the user is already at a playback page,share that URL
    }
    else{
        sharing_url=overview_url+get_clean_url(); //When not on a playback page,share the overview version of that URL
    }
    var open_url="";
    if(!(url.includes('chrome://') || url.includes('chrome-extension://'))){ //Prevents sharing some unnecessary page
        if(id.includes('fb')){
            open_url="https://www.facebook.com/sharer/sharer.php?u="+sharing_url; //Share the wayback machine's overview of the URL
        }else if(id.includes('twit')){
            open_url="https://twitter.com/home?status="+sharing_url;
        }else if(id.includes('gplus')){
            open_url="https://plus.google.com/share?url="+sharing_url;
        }else if(id.includes('linkedin')){
            open_url="https://www.linkedin.com/shareArticle?url="+sharing_url;
        }
        window.open(open_url, 'newwindow', 'width=800, height=280,left=0');
    }
}

function statistics(eventObj) {  //Common Function for alexa and whois statistics
    var target=eventObj.target;
    var id=target.getAttribute('id');
    var url=get_clean_url();
    url = url.replace(/^https?:\/\//,'');
    var length=url.length;
    var last_index=url.indexOf('/');
    url=url.slice(0,last_index);
    if(id.includes("alexa")){
        var open_url="http://www.alexa.com/siteinfo/" + url;
        window.open(open_url, 'newwindow', 'width=1000, height=1000,left=0');
    }else if(id.includes("whois")){
        var open_url="https://www.whois.com/whois/" + url;
        window.open(open_url, 'newwindow', 'width=1000, height=1000,left=0');
    }
}

function search_tweet(eventObj){
    var url = get_clean_url();
    url = url.replace(/^https?:\/\//,'');
    if(url.slice(-1)=='/') url=url.substring(0,url.length-1);
    var open_url="https://twitter.com/search?q="+url;
    window.open(open_url, 'newwindow', 'width=1000, height=1000,left=0');
}

function display_list(key_word){
    $sbox = document.getElementById('suggestion-box');
    $sbox.style.display='none';
    $sbox.innerHTML="";
    var xhr = new XMLHttpRequest();
    xhr.open('GET', "https://web.archive.org/__wb/search/host?q="+key_word, true);
    xhr.onload=function(){
        $sbox.style.display='none';
        $sbox.innerHTML="";
        var data=JSON.parse(xhr.response);
        var n=data.hosts.length;
        if(n>0 && document.getElementById('search_input').value!=''){
            $sbox.style.display='block';
            for(var i=0;i<n;i++){
                var a=document.createElement('a');
                a.onclick=function(event){
                    document.getElementById('search_input').value=event.target.innerHTML;
                    $sbox.style.display='none';
                    $sbox.innerHTML="";
                };
                a.setAttribute('role','button');
                a.innerHTML=data.hosts[i].display_name;
                var li=document.createElement('li');
                li.appendChild(a);
                $sbox.appendChild(li);
            }
        }
    };
    xhr.send(null);
}

function display_suggestions(e){
    document.getElementById('suggestion-box').style.display='none';
    document.getElementById('suggestion-box').innerHTML="";
    if(e.keyCode==13){
        e.preventDefault();
    }else {
        //setTimeout is used to get the text in the text field after key has been pressed
        window.setTimeout(function(){
            var len=document.getElementById('search_input').value.length;
            if((len)>=3){
                display_list(document.getElementById('search_input').value);
            }else{
                document.getElementById('suggestion-box').style.display='none';
                document.getElementById('suggestion-box').innerHTML="";
            }
        },0.1);
    }
}
function open_feedback_page(){
    var feedback_url="https://chrome.google.com/webstore/detail/wayback-machine/fpnmgdkabkmnadcjpehmlllkndpkmiak/reviews?hl=en";
    chrome.tabs.create({ url: feedback_url });
}

function about_support(){
    window.open('about.html', 'newwindow', 'width=1200, height=900,left=0').focus();
}

function makeModal(){
    var url = get_clean_url();
    console.log("Making RT for "+url);
    chrome.runtime.sendMessage({message: "makemodal",rturl:url});
}

function settings(){
    window.open('settings.html','newwindow', 'width=590, height=740,left=0');
}

function auto_archive_url(){
    var tab_url="";
    chrome.tabs.query({active: true,currentWindow:true},function(tabs){
        tab_url=tabs[0].url;
        tabId=tabs[0].id;
        console.log(tab_url);
        chrome.storage.sync.get(['auto_archive'],function(event){
            if(event.auto_archive==true){
                if(!((tab_url.includes("https://web.archive.org/web/")) || (tab_url.includes("chrome://newtab")))){
                    check_url(tab_url,function(){
                        var wayback_url = "https://web.archive.org/save/";
                        chrome.browserAction.getBadgeText({tabId:tabId}, function (result){
                            if((result=="S")){
                                tab_url = wayback_url+tab_url;
                                console.log(tab_url);
                                wm_save_URL(tab_url, function(){
                                    var tabId=tabs[0].id;
                                    console.log(tabId);
                                    chrome.runtime.sendMessage({message:"changeBadge",tabId:tabId});
                                });
                            }
                        });
                    });
                }
            }
        });
    });
}

function wm_save_URL(url, callback) {
    var http=new XMLHttpRequest();
    var new_url=url;
    http.open("GET",new_url,true);
    http.send(null);
    http.onreadystatechange = function() {
        if (this.readyState==4 && this.status==200) {
            console.log("Archived");
        }
    }
    callback();
}

function check_url(url,callback){
    var xhr=new XMLHttpRequest();
    var new_url="http://archive.org/wayback/available?url="+url;
    xhr.open("GET",new_url,true);
    xhr.send(null);
    xhr.onload = function() {
        var response = JSON.parse(xhr.response);
        console.log(response);
        if(response.archived_snapshots.closest){
            console.log("available");
            chrome.tabs.query({active: true,currentWindow:true},function(tabs){
                var tab_id=tabs[0].id;
                chrome.browserAction.getBadgeText({tabId:tab_id}, function (result){
                    if(result=="S"){
                        chrome.runtime.sendMessage({message:"changeBadge",tabId:tab_id});
                    }
                });
            });
        }else{
            console.log("not available");
            callback();
        }
    }
}

function show_all_screens(){
    var url=get_clean_url();
    chrome.runtime.sendMessage({message:"showall",url:url});
}

function borrow_books(){
    chrome.tabs.query({active: true,currentWindow:true},function(tabs){
        url=tabs[0].url;
        tabId=tabs[0].id;
        chrome.browserAction.getBadgeText({tabId:tabId}, function (result){
            if(result=="B"){
                if(url.includes("www.amazon") && url.includes('/dp/')){
                    var xhr=new XMLHttpRequest();
                    var new_url="https://wwwb-api.archive.org/services/context/book?url="+url;
                    console.log(new_url);
                    xhr.open("GET",new_url,true);
                    xhr.send(null);
                    xhr.onload=function(){
                        var response = JSON.parse(xhr.response);
                        if(response.success==true && response.error==undefined){
                          var responses=response.responses;
                          for(var propName in responses) {
                            if(responses.hasOwnProperty(propName)) {
                              var propValue = responses[propName];
                            }
                          }
                          var identifier=propValue.identifier;
                        }
                        if(identifier!=undefined||null){
                        document.getElementById('borrow_books_tr').style.display="block";
                        }
                        document.getElementById('borrow_books_tr').onclick=function(){
                            chrome.tabs.create({url:"https://archive.org/details/"+identifier});
                        }
                    }
                }
            }
        });

    });
}

function show_news(){
    chrome.tabs.query({active: true,currentWindow:true},function(tabs){
        url=tabs[0].url;
        tabId=tabs[0].id;
        chrome.storage.sync.get(['news'],function(event){
            if(event.news==true){
                if(url.includes("https://www.huffingtonpost"||"https://www.nytimes"||"https://www.forbes"||"https://www.washingtonpost")){
                    document.getElementById('news_recommend_tr').style.display="block";
                    document.getElementById('news_recommend_tr').onclick=function(){
                        chrome.tabs.create({url:chrome.runtime.getURL("recommendations.html")+"?url="+url});
                    }
                }
            }
        });
    });
}

/** Disabled code for the autosave feature **/
//function restoreSettings() {
//  chrome.storage.sync.get({
//    as:false
//  }, function(items) {
//    document.getElementById('as').checked = items.as;
//      if(items.as){
//          chrome.runtime.sendMessage({message: "start_as"}, function(response) {});
//      }
//     });
//}
//
//function saveSettings(){
//    var as = document.getElementById('as').checked;
//      chrome.storage.sync.set({
//      as: as
//  });
//}
//function showSettings(eventObj){
//    var target=eventObj.target;
//    if(target.getAttribute('toggle')=='off'){
//        document.getElementById('settings_btn').setAttribute('toggle','on');
//    document.getElementById('settings_div').style.display="block";
//    }else{
//        document.getElementById('settings_btn').setAttribute('toggle','off');
//        document.getElementById('settings_div').style.display="none";
//    }
//}
//restoreSettings();
//document.getElementById('settings_div').style.display="none";

// window.onload=get_url;
window.onloadFuncs = [get_url,auto_archive_url,borrow_books,show_news];
window.onload = function(){
 for(var i in this.onloadFuncs){
  this.onloadFuncs[i]();
 }
}
document.getElementById('save_now').onclick = save_now;
document.getElementById('recent_capture').onclick = recent_capture;
document.getElementById('first_capture').onclick = first_capture;
document.getElementById('fb_share').onclick =social_share;
document.getElementById('twit_share').onclick =social_share;
document.getElementById('gplus_share').onclick =social_share;
document.getElementById('linkedin_share').onclick =social_share;
document.getElementById('alexa_statistics').onclick =statistics;
document.getElementById('whois_statistics').onclick =statistics;
document.getElementById('search_tweet').onclick =search_tweet;
document.getElementById('about_support_button').onclick = about_support;
document.getElementById('settings_button').onclick =settings;
document.getElementById('context-screen').onclick=show_all_screens;
document.getElementById('feedback').onclick=open_feedback_page;

document.getElementById('overview').onclick = view_all;
//document.getElementById('settings_btn').onclick=showSettings;
//document.getElementById('settings_save_btn').onclick=saveSettings;
document.getElementById('make_modal').onclick=makeModal;
document.getElementById('search_input').addEventListener('keydown',display_suggestions);
<|endoftext|>


<commit_before>import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import opn from 'opn';
import webpackConfig from '../webpack.config.babel';

const host = 'localhost';
const port = 8080;
const url = `http://${host}:${port}/`;

const config = webpackConfig({dev: true});

config.entry.unshift(
  `webpack-dev-server/client?${url}`,
  'webpack/hot/only-dev-server',
);

const devServer = new WebpackDevServer(webpack(config), {
  hot: true,
  historyApiFallback: true,
  stats: {
    color: true,
  },
});

devServer.listen(port, host, (err) => {
  if (err) {
    console.error(err); // eslint-disable-line no-console

    return;
  }

  console.log(`Listening at ${url}`); // eslint-disable-line no-console
  opn(url);
});
<commit_msg>Update port number<commit_after>import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import opn from 'opn';
import webpackConfig from '../webpack.config.babel';

const host = 'localhost';
const port = 3000;
const url = `http://${host}:${port}/`;

const config = webpackConfig({dev: true});

config.entry.unshift(
  `webpack-dev-server/client?${url}`,
  'webpack/hot/only-dev-server',
);

const devServer = new WebpackDevServer(webpack(config), {
  hot: true,
  historyApiFallback: true,
  stats: {
    color: true,
  },
});

devServer.listen(port, host, (err) => {
  if (err) {
    console.error(err); // eslint-disable-line no-console

    return;
  }

  console.log(`Listening at ${url}`); // eslint-disable-line no-console
  opn(url);
});
<|endoftext|>


<commit_before>var Stream = require('stream').Stream,
  util = require('util'),
  spawn = require('child_process').spawn;

var GZipStream = function() {
  this.readable = true;
  this.writable = true;

  this._gzipper = spawn('gzip');
  this._gzipper.stdout.on('data', this.emit.bind(this, 'data'));
  this._gzipper.on('exit', this.emit.bind(this, 'end'));
};
util.inherits(GZipStream, Stream);
GZipStream.prototype.write = function(data) {
  if(this._gzipper.stdin.writable) {
    this._gzipper.stdin.write(data);
  }
};
GZipStream.prototype.end = function(data) {
  this.readable = false;
  this.writable = false;

  this._gzipper.stdin.end();
  this._gzipper = null;
};

module.exports = GZipStream;
<commit_msg>comment gzipper<commit_after>var Stream = require('stream').Stream,
  util = require('util'),
  spawn = require('child_process').spawn;

var GZipStream = function() {
  // readable stream
  this.readable = true;
  // writable stream
  this.writable = true;

  this._gzipper = spawn('gzip');
  // emit data at some point
  this._gzipper.stdout.on('data', this.emit.bind(this, 'data'));
  // emit end at some point
  this._gzipper.on('exit', this.emit.bind(this, 'end'));
};

// this is a custom stream object
util.inherits(GZipStream, Stream);

// implement write, process some data
GZipStream.prototype.write = function(data) {
  if(this._gzipper.stdin.writable) {
    this._gzipper.stdin.write(data);
  }
};

// implement end
GZipStream.prototype.end = function(data) {
  // shut down processing
  this.readable = false;
  this.writable = false;

  // clean up
  this._gzipper.stdin.end();
  this._gzipper = null;
};

module.exports = GZipStream;
<|endoftext|>