<commit_before>require(['gitbook', 'jQuery', 'lodash'], function (gitbook, $, _) {
    var allThreads = [];
    var allComments = {};
    var isLoggedin = false;

    var SECTIONS_SELECTOR = 'p';
    var LIMIT_COMMENTS = 4;

    var TPL_COMMENT = _.template(
        '<img src="<%- user.urls.avatar %>" class="comment-avatar" />' +
        '
' +
            '<a href="<%- user.urls.profile %>" target="_blank" class="comment-user"><%- user.name %>' +
            '
<%= body || title %>
' +
        '
');

    var TPL_THREAD = _.template(
        '
' +
            '
<%= title %>
' +
            '
#<%- number %> posted by <%- user.name %>
' +
        '
');

    // Move content to the left
    // Calcul the right position
    function toggleComments(state) {
        var $wrapper = gitbook.state.$book.find('.page-wrapper');
        var $inner = $wrapper.find('.page-inner');
        var $nextNavigation = gitbook.state.$book.find('.navigation.navigation-next');

        $wrapper.toggleClass('comments-open', state);
        if (!$wrapper.hasClass('comments-open')) {
            $inner.css('left', 'auto');
        } else {
            var commentsWidth = 330;
            var innerWidth = $inner.width();
            var wrapperWidth = $wrapper.width();
            var navWidth = $nextNavigation.length == 0? 0 : $nextNavigation.width();
            var marginWidth = ((wrapperWidth - innerWidth) / 2) - navWidth;

            var left = (marginWidth-commentsWidth);
            left = Math.max(left, -commentsWidth);
            left = Math.min(left, 0);

            $inner.css('left', left+'px');
        }
    }

    // Reurn root for api
    function apiUrl(path) {
        //return 'http://localhost:5000/content/book/samypesse/test-beta/gitbook/api/'+path;
        return (gitbook.state.root+'/gitbook/api/'+path).replace(/\/\/+/g, '/');
    }

    // Redirect user to login page
    function redirectToLogin() {
        location.href = apiUrl('login');
    }

    // Open an url in a new tab
    function openInNewTab(url) {
        var win = window.open(url, '_blank');
        win.focus();
    }

    // Make an api request
    function apiRequest(method, route, data, success) {
        $.ajax({
            method: method,
            dataType: 'json',
            url: apiUrl(route),
            data: data,
            success: function(result, status, xhr) {
                isLoggedin = !!xhr.getResponseHeader('X-GitBook-Auth');
                success(result);
            },
            error: function(xhr, textStatus) {
                alert('Error with comments: '+textStatus);
            }
        });
    }

    // Fetch threads from gitbook.com and update listing
    function fetchThreads() {
        apiRequest('GET', 'discussions', {
            'filename': gitbook.state.filepath,
            'state': 'open'
        }, function(result) {
            allThreads = result.list;
            updateSections();
        });
    }

    // Fetch threads from gitbook.com and update listing
    function fetchComments(id) {
        apiRequest('GET', 'discussions/'+id+'/comments', {
            'limit': LIMIT_COMMENTS
        }, function(result) {
            allComments[id] = result;
            updateComments(id);
        });
    }

    // Create a new thread on th backend
    function postThread(subject, body, section, done) {
        apiRequest('POST', 'discussions', {
            'title': subject,
            'body': body,
            'context': {
                'filename': gitbook.state.filepath,
                'chapterTitle': gitbook.state.chapterTitle,
                'section': section
            }
        }, done);
    }

    // Close a thread
    function closeThread(id) {
        allThreads = _.reject(allThreads, {
            'number': id
        });
        updateSections();

        apiRequest('POST', 'discussions/'+id, {
            state: 'closed'
        }, function() {
            fetchThreads();
        });
    }

    // Post a new comment
    function postComment(id, body, done) {
        apiRequest('POST', 'discussions/'+id+'/comments', {
            body: body
        }, function(result) {
            // Prefill data
            allComments[id] = allComments[id] || [];
            allComments[id].total = allComments[id].total + 1;
            allComments[id].list.push(result);
            updateComments(id);

            // Sync fetch all comments
            fetchComments(id);
            done(result);
        });
    }

    // Return list of threads matching a section
    function filterThreads(section) {
        var words = section.split(' ');

        return _.chain(allThreads)
            .map(function(thread) {
                var threadWords = (thread.context.section || '').split(' ');

                var commonWordsWithSection = _.filter(threadWords, function(word) {
                    return _.contains(words, word);
                });
                var commonWordsFromSection = _.filter(words, function(word) {
                    return _.contains(threadWords, word);
                });

                var matching = (
                    (commonWordsWithSection.length/threadWords.length)
                    + (commonWordsFromSection.length/words.length)
                ) / 2;

                return {
                    matching: matching,
                    thread: thread
                };
            })
            .filter(function(r) {
                return r.matching > 0.8;
            })
            .sortBy('matching')
            .pluck('thread')
            .value();
    }

    // Create form to create thread
    function createThreadCreation($commentsArea, $section) {
        // Post area
        var $title, $description;
        var $postArea = $('
', {
            'class': 'comments-post'
        });

        if (isLoggedin) {
            $title = $('<input>', {
                'type': 'text',
                'placeholder': 'Start a new discussion'
            });

            $description = $('<input>', {
                'type': 'text',
                'placeholder': 'Optional comment'
            });

            var $toolbar = createToolbar([
                {
                    text: 'Post',
                    click: function() {
                        postThread($title.val(), $description.val(), $section.text(), function(thread) {
                            // Add to the list of all threads
                            allThreads.push(thread);
                            updateSections();

                            // Update view with this thread
                            createThreadComments($commentsArea, $section, thread);
                        });
                    }
                }
            ]);

            $description.hide();
            $title.keyup(function(e) {
                if ($title.val().length > 3) {
                    $description.show();
                } else if (!$description.val()) {
                    $description.hide();
                }
            })

            $postArea.append($title);
            $postArea.append($description);
            $postArea.append($toolbar);
        } else {
            var $toolbar = createToolbar([
                {
                    text: 'Sign in to comment',
                    click: redirectToLogin
                }
            ]);
            $postArea.append($toolbar);
        }

        $commentsArea.html('');
        $commentsArea.append($postArea);

        if ($title) $title.focus();
    }

    // Create and return a thread for listing
    function createThread(thread) {
        return $('
', {
            'class': 'thread',
            'html': TPL_THREAD(thread)
        });
    }

    // Create and return a comment
    function createComment(comment, isThread) {
        return $('
', {
            'class': 'comment',
            'html': TPL_COMMENT(comment)
        });
    }

    // Create an return a toolbar
    function createToolbar(actions) {
        var $toolbar = $('
', {
            'class': 'comments-toolbar'
        });

        _.each(actions, function(action) {
            var $action = $('', {
                'href': '#',
                'text': action.text,
                'click': function(e) {
                    e.preventDefault();
                    action.click();
                }
            });

            $action.appendTo($toolbar);
        });

        return $toolbar;
    }

    // Display comment entry in post area for a thread
    function createThreadCommentForm($postArea, thread) {
        $postArea.html('');

        var $input = $('<input>', {
            'type': 'text',
            'placeholder': 'Leave a comment'
        });

        var $toolbar = createToolbar([
            {
                text: 'Post',
                click: function() {
                    postComment(thread.number, $input.val(), function() {
                        $input.val('');
                    });
                }
            }
        ]);

        $postArea.append($input);
        $postArea.append($toolbar);

        $input.focus();
    }

    // Display a thread and its comments
    function createThreadComments($commentsArea, $section, thread, threads) {
        // Go fetch comments
        fetchComments(thread.number);

        var actions = [];

        if (isLoggedin) {
            if (thread.permissions.comment) {
                actions.push({
                    text: 'Comment',
                    click: function() {
                        createThreadCommentForm($postArea, thread);
                    }
                });
            }

            if (thread.permissions.close) {
                actions.push({
                    text: 'Close',
                    click: function() {
                        toggleSection($section, threads);
                        closeThread(thread.number);
                    }
                });
            }

            actions.push({
                text: 'New Thread',
                click: function() {
                    createThreadCreation($commentsArea, $section);
                }
            });
        } else {
            actions = [
                {
                    text: 'Sign in to comment',
                    click: redirectToLogin
                }
            ];
        }

        var $postArea = $('
', {
            'class': 'comments-post'
        });
        $postArea.append(createToolbar(actions));

        var $comments = $('
', {
            'class': 'comments-list',
            'data-thcomments': thread.number
        });

        $commentsArea.html('');
        $commentsArea.append(createComment(thread));
        $commentsArea.append($comments);
        $commentsArea.append($postArea);

        updateComments(thread.number);
    }

    // Create a list of threads to select one to show
    function createThreadsList($commentsArea, $section, threads) {
        var $threads = $('
', {
            'class': 'comments-threads'
        });

        _.each(threads, function(thread) {
            var $thread = createThread(thread)
            $thread.click(function(e) {
                createThreadComments($commentsArea, $section, thread);
            });
            $threads.append($thread);
        });

        var $toolbar;

        if (isLoggedin) {
            $toolbar = createToolbar([
                {
                    text: 'New Thread',
                    click: function() {
                        createThreadCreation($commentsArea, $section);
                    }
                }
            ]);
        } else {
            $toolbar = createToolbar([
                {
                    text: 'Sign in to create a thread',
                    click: redirectToLogin
                }
            ]);
        }

        $commentsArea.html('');
        $commentsArea.append($threads);
        $commentsArea.append($toolbar);
    }

    // Close all section
    function closeAllSections() {
        gitbook.state.$book.find('.page-wrapper .comments-section').removeClass('has-comments-open');
    }

    // Toggle comments display
    function toggleSection($section, threads) {
        var isOpen = !$section.hasClass('has-comments-open');
        closeAllSections();
        $section.toggleClass('has-comments-open', isOpen);
        toggleComments(isOpen);

        if (!isOpen) return;

        $section.find('.comments-area').remove();
        var $commentsArea = $('
', {
            'class': 'comments-area'
        });
        $section.append($commentsArea);

        // Has multiples threads
        if (threads.length > 1) {
            createThreadsList($commentsArea, $section, threads);
        } else if (threads.length == 1) {
            createThreadComments($commentsArea, $section, threads[0], threads);
        } else {
            createThreadCreation($commentsArea, $section);
        }
    }

    // Initialize comments system on a paragraph (aka section)
    function bindSection($section) {
        // Find matching threads with this section
        var threads = filterThreads($section.text());
        var nComments = _.reduce(threads, function(sum, thread) {
            return sum + 1 + thread.comments;
        }, 0);

        // Create marker
        var $marker = $('
', {
            'class': 'marker',
            'text': nComments? nComments : '+'
        });
        $marker.on('click', function() {
            toggleSection($section, threads);
        });

        var $icon = $('
', {
            'class': 'comments-icon'
        });
        $icon.append($marker);

        $section.find('.comments-icon').remove();
        $section.addClass('comments-section');
        $section.toggleClass('has-comments', (nComments > 0));
        $section.append($icon);
    }

    // Update all comments sections
    function updateSections() {
        var $wrapper = gitbook.state.$book.find('.page-wrapper');
        var $sections = $wrapper.find(SECTIONS_SELECTOR);

        $sections.each(function() {
            bindSection($(this));
        });
    }

    // Update comments for a thread
    function updateComments(number) {
        var thread = _.find(allThreads, {
            'number': number
        });

        if (!allComments[number] || !thread) return;

        // Comments are displayed
        var $list = gitbook.state.$book.find('.page-wrapper div[data-thcomments="'+number+'"]');
        if ($list.length == 0) return;

        // Cleanup current list
        $list.html('');

        // Has comment left?
        var hasLeft = Math.max(0, allComments[number].total - LIMIT_COMMENTS);

        if (hasLeft > 0) {
            $list.append(createToolbar([
                {
                    text: 'View '+hasLeft+' more comments',
                    click: function() {
                        openInNewTab(thread.urls.details);
                    }
                }
            ]));
        }

        _.chain(allComments[number].list || [])
            .reverse()
            .each(function(comment) {
                $list.append(createComment(comment));
            })
            .value();
    }

    gitbook.events.bind('start', function (e, config) {

    });

    gitbook.events.bind('page.change', function () {
        allThreads = [];
        fetchThreads();
    });
});
<commit_msg>Correctly extract text from section<commit_after>require(['gitbook', 'jQuery', 'lodash'], function (gitbook, $, _) {
    var allThreads = [];
    var allComments = {};
    var isLoggedin = false;

    var SECTIONS_SELECTOR = 'p';
    var LIMIT_COMMENTS = 4;

    var TPL_COMMENT = _.template(
        '<img src="<%- user.urls.avatar %>" class="comment-avatar" />' +
        '
' +
            '<a href="<%- user.urls.profile %>" target="_blank" class="comment-user"><%- user.name %>' +
            '
<%= body || title %>
' +
        '
');

    var TPL_THREAD = _.template(
        '
' +
            '
<%= title %>
' +
            '
#<%- number %> posted by <%- user.name %>
' +
        '
');

    // Move content to the left
    // Calcul the right position
    function toggleComments(state) {
        var $wrapper = gitbook.state.$book.find('.page-wrapper');
        var $inner = $wrapper.find('.page-inner');
        var $nextNavigation = gitbook.state.$book.find('.navigation.navigation-next');

        $wrapper.toggleClass('comments-open', state);
        if (!$wrapper.hasClass('comments-open')) {
            $inner.css('left', 'auto');
        } else {
            var commentsWidth = 330;
            var innerWidth = $inner.width();
            var wrapperWidth = $wrapper.width();
            var navWidth = $nextNavigation.length == 0? 0 : $nextNavigation.width();
            var marginWidth = ((wrapperWidth - innerWidth) / 2) - navWidth;

            var left = (marginWidth-commentsWidth);
            left = Math.max(left, -commentsWidth);
            left = Math.min(left, 0);

            $inner.css('left', left+'px');
        }
    }

    // Reurn root for api
    function apiUrl(path) {
        //return 'http://localhost:5000/content/book/samypesse/test-beta/gitbook/api/'+path;
        return (gitbook.state.root+'/gitbook/api/'+path).replace(/\/\/+/g, '/');
    }

    // Redirect user to login page
    function redirectToLogin() {
        location.href = apiUrl('login');
    }

    // Open an url in a new tab
    function openInNewTab(url) {
        var win = window.open(url, '_blank');
        win.focus();
    }

    // Make an api request
    function apiRequest(method, route, data, success) {
        $.ajax({
            method: method,
            dataType: 'json',
            url: apiUrl(route),
            data: data,
            success: function(result, status, xhr) {
                isLoggedin = !!xhr.getResponseHeader('X-GitBook-Auth');
                success(result);
            },
            error: function(xhr, textStatus) {
                alert('Error with comments: '+textStatus);
            }
        });
    }

    // Fetch threads from gitbook.com and update listing
    function fetchThreads() {
        apiRequest('GET', 'discussions', {
            'filename': gitbook.state.filepath,
            'state': 'open'
        }, function(result) {
            allThreads = result.list;
            updateSections();
        });
    }

    // Fetch threads from gitbook.com and update listing
    function fetchComments(id) {
        apiRequest('GET', 'discussions/'+id+'/comments', {
            'limit': LIMIT_COMMENTS
        }, function(result) {
            allComments[id] = result;
            updateComments(id);
        });
    }

    // Create a new thread on th backend
    function postThread(subject, body, section, done) {
        apiRequest('POST', 'discussions', {
            'title': subject,
            'body': body,
            'context': {
                'filename': gitbook.state.filepath,
                'chapterTitle': gitbook.state.chapterTitle,
                'section': section
            }
        }, done);
    }

    // Close a thread
    function closeThread(id) {
        allThreads = _.reject(allThreads, {
            'number': id
        });
        updateSections();

        apiRequest('POST', 'discussions/'+id, {
            state: 'closed'
        }, function() {
            fetchThreads();
        });
    }

    // Post a new comment
    function postComment(id, body, done) {
        apiRequest('POST', 'discussions/'+id+'/comments', {
            body: body
        }, function(result) {
            // Prefill data
            allComments[id] = allComments[id] || [];
            allComments[id].total = allComments[id].total + 1;
            allComments[id].list.push(result);
            updateComments(id);

            // Sync fetch all comments
            fetchComments(id);
            done(result);
        });
    }

    // Return list of threads matching a section
    function filterThreads(section) {
        var words = section.split(' ');

        return _.chain(allThreads)
            .map(function(thread) {
                var threadWords = (thread.context.section || '').split(' ');

                var commonWordsWithSection = _.filter(threadWords, function(word) {
                    return _.contains(words, word);
                });
                var commonWordsFromSection = _.filter(words, function(word) {
                    return _.contains(threadWords, word);
                });

                var matching = (
                    (commonWordsWithSection.length/threadWords.length)
                    + (commonWordsFromSection.length/words.length)
                ) / 2;

                return {
                    matching: matching,
                    thread: thread
                };
            })
            .filter(function(r) {
                return r.matching > 0.8;
            })
            .sortBy('matching')
            .pluck('thread')
            .value();
    }

    // Return text for a section
    function sectionText($section) {
        return $section
            .clone()
            .find('.comments-area,.comments-icon')
            .remove()
            .end()
            .text();
    }

    // Create form to create thread
    function createThreadCreation($commentsArea, $section) {
        console.log(sectionText($section));
        // Post area
        var $title, $description;
        var $postArea = $('
', {
            'class': 'comments-post'
        });

        if (isLoggedin) {
            $title = $('<input>', {
                'type': 'text',
                'placeholder': 'Start a new discussion'
            });

            $description = $('<input>', {
                'type': 'text',
                'placeholder': 'Optional comment'
            });

            var $toolbar = createToolbar([
                {
                    text: 'Post',
                    click: function() {
                        postThread($title.val(), $description.val(), sectionText($section), function(thread) {
                            // Add to the list of all threads
                            allThreads.push(thread);
                            updateSections();

                            // Update view with this thread
                            createThreadComments($commentsArea, $section, thread);
                        });
                    }
                }
            ]);

            $description.hide();
            $title.keyup(function(e) {
                if ($title.val().length > 3) {
                    $description.show();
                } else if (!$description.val()) {
                    $description.hide();
                }
            })

            $postArea.append($title);
            $postArea.append($description);
            $postArea.append($toolbar);
        } else {
            var $toolbar = createToolbar([
                {
                    text: 'Sign in to comment',
                    click: redirectToLogin
                }
            ]);
            $postArea.append($toolbar);
        }

        $commentsArea.html('');
        $commentsArea.append($postArea);

        if ($title) $title.focus();
    }

    // Create and return a thread for listing
    function createThread(thread) {
        return $('
', {
            'class': 'thread',
            'html': TPL_THREAD(thread)
        });
    }

    // Create and return a comment
    function createComment(comment, isThread) {
        return $('
', {
            'class': 'comment',
            'html': TPL_COMMENT(comment)
        });
    }

    // Create an return a toolbar
    function createToolbar(actions) {
        var $toolbar = $('
', {
            'class': 'comments-toolbar'
        });

        _.each(actions, function(action) {
            var $action = $('', {
                'href': '#',
                'text': action.text,
                'click': function(e) {
                    e.preventDefault();
                    action.click();
                }
            });

            $action.appendTo($toolbar);
        });

        return $toolbar;
    }

    // Display comment entry in post area for a thread
    function createThreadCommentForm($postArea, thread) {
        $postArea.html('');

        var $input = $('<input>', {
            'type': 'text',
            'placeholder': 'Leave a comment'
        });

        var $toolbar = createToolbar([
            {
                text: 'Post',
                click: function() {
                    postComment(thread.number, $input.val(), function() {
                        $input.val('');
                    });
                }
            }
        ]);

        $postArea.append($input);
        $postArea.append($toolbar);

        $input.focus();
    }

    // Display a thread and its comments
    function createThreadComments($commentsArea, $section, thread, threads) {
        // Go fetch comments
        fetchComments(thread.number);

        var actions = [];

        if (isLoggedin) {
            if (thread.permissions.comment) {
                actions.push({
                    text: 'Comment',
                    click: function() {
                        createThreadCommentForm($postArea, thread);
                    }
                });
            }

            if (thread.permissions.close) {
                actions.push({
                    text: 'Close',
                    click: function() {
                        toggleSection($section, threads);
                        closeThread(thread.number);
                    }
                });
            }

            actions.push({
                text: 'New Thread',
                click: function() {
                    createThreadCreation($commentsArea, $section);
                }
            });
        } else {
            actions = [
                {
                    text: 'Sign in to comment',
                    click: redirectToLogin
                }
            ];
        }

        var $postArea = $('
', {
            'class': 'comments-post'
        });
        $postArea.append(createToolbar(actions));

        var $comments = $('
', {
            'class': 'comments-list',
            'data-thcomments': thread.number
        });

        $commentsArea.html('');
        $commentsArea.append(createComment(thread));
        $commentsArea.append($comments);
        $commentsArea.append($postArea);

        updateComments(thread.number);
    }

    // Create a list of threads to select one to show
    function createThreadsList($commentsArea, $section, threads) {
        var $threads = $('
', {
            'class': 'comments-threads'
        });

        _.each(threads, function(thread) {
            var $thread = createThread(thread)
            $thread.click(function(e) {
                createThreadComments($commentsArea, $section, thread);
            });
            $threads.append($thread);
        });

        var $toolbar;

        if (isLoggedin) {
            $toolbar = createToolbar([
                {
                    text: 'New Thread',
                    click: function() {
                        createThreadCreation($commentsArea, $section);
                    }
                }
            ]);
        } else {
            $toolbar = createToolbar([
                {
                    text: 'Sign in to create a thread',
                    click: redirectToLogin
                }
            ]);
        }

        $commentsArea.html('');
        $commentsArea.append($threads);
        $commentsArea.append($toolbar);
    }

    // Close all section
    function closeAllSections() {
        gitbook.state.$book.find('.page-wrapper .comments-section').removeClass('has-comments-open');
    }

    // Toggle comments display
    function toggleSection($section, threads) {
        var isOpen = !$section.hasClass('has-comments-open');
        closeAllSections();
        $section.toggleClass('has-comments-open', isOpen);
        toggleComments(isOpen);

        if (!isOpen) return;

        $section.find('.comments-area').remove();
        var $commentsArea = $('
', {
            'class': 'comments-area'
        });
        $section.append($commentsArea);

        // Has multiples threads
        if (threads.length > 1) {
            createThreadsList($commentsArea, $section, threads);
        } else if (threads.length == 1) {
            createThreadComments($commentsArea, $section, threads[0], threads);
        } else {
            createThreadCreation($commentsArea, $section);
        }
    }

    // Initialize comments system on a paragraph (aka section)
    function bindSection($section) {
        // Find matching threads with this section
        var threads = filterThreads(sectionText($section));
        var nComments = _.reduce(threads, function(sum, thread) {
            return sum + 1 + thread.comments;
        }, 0);

        // Create marker
        var $marker = $('
', {
            'class': 'marker',
            'text': nComments? nComments : '+'
        });
        $marker.on('click', function() {
            toggleSection($section, threads);
        });

        var $icon = $('
', {
            'class': 'comments-icon'
        });
        $icon.append($marker);

        $section.find('.comments-icon').remove();
        $section.addClass('comments-section');
        $section.toggleClass('has-comments', (nComments > 0));
        $section.append($icon);
    }

    // Update all comments sections
    function updateSections() {
        var $wrapper = gitbook.state.$book.find('.page-wrapper');
        var $sections = $wrapper.find(SECTIONS_SELECTOR);

        $sections.each(function() {
            bindSection($(this));
        });
    }

    // Update comments for a thread
    function updateComments(number) {
        var thread = _.find(allThreads, {
            'number': number
        });

        if (!allComments[number] || !thread) return;

        // Comments are displayed
        var $list = gitbook.state.$book.find('.page-wrapper div[data-thcomments="'+number+'"]');
        if ($list.length == 0) return;

        // Cleanup current list
        $list.html('');

        // Has comment left?
        var hasLeft = Math.max(0, allComments[number].total - LIMIT_COMMENTS);

        if (hasLeft > 0) {
            $list.append(createToolbar([
                {
                    text: 'View '+hasLeft+' more comments',
                    click: function() {
                        openInNewTab(thread.urls.details);
                    }
                }
            ]));
        }

        _.chain(allComments[number].list || [])
            .reverse()
            .each(function(comment) {
                $list.append(createComment(comment));
            })
            .value();
    }

    gitbook.events.bind('start', function (e, config) {

    });

    gitbook.events.bind('page.change', function () {
        allThreads = [];
        fetchThreads();
    });
});
<|endoftext|>


<commit_before>var boxOpened = "";
var imgOpened = "";
var counter = 0;
var imgFound = 0;

var source = "#boxcard";
//Pictures in the boxes//
var imgSource = [
  "http://a1.mzstatic.com/us/r1000/022/Purple/76/e4/ed/mzl.upwpacxr.100x100-75.jpg",
  "http://www.playgamesarcade.com/games/images/kung-fu-panda-world-tigress-jump_2.jpg",
  "http://www.freeplaynow.com/uploads/kung-fu-panda-world-monkey-run.jpg",
  "http://images5.fanpop.com/image/photos/26500000/Kung-Fu-Panda-kung-fu-panda-26505677-100-100.png",
  "http://orig14.deviantart.net/12d7/f/2008/256/8/1/kung_fu_panda_icon_2_by_oneenekochan.jpg",
  "http://images5.fanpop.com/image/category/74/74816_1332631384_100_100.jpg",
  "http://cdn.inquisitr.com/wp-content/uploads/2016/01/kung-fu-panda-3-review-100x100.jpg",
  "http://images4.fanpop.com/image/polls/740000/740031_1307490049245_100.jpg?v=1307490274",
  "http://www.thenewpotato.com/wp-content/uploads/2015/10/the-bao-st-marks-100x100.jpg?d01037",
  "http://www.whats-your-sign.com/images/100xNxChineseSymbol4.jpg.pagespeed.ic.DU3DcnK35R.jpg"
  ]

function randomFunction(maxValue, minValue) {
    return Math.round(Math.random() * (maxValue - minValue) + minValue);
  }

// This shuffles the images when game is restarted//

function shuffleImages() {
  var imgAll = $(source).children();
  var imgThis = $(source + " div:first-child");
  var imgArr = new Array();

// This is the  shows the current images matched.
  for (var i = 0; i < imgAll.length; i++) {
    imgArr[i] = $("#" + imgThis.attr("id") + " img").attr("src");
    imgThis = imgThis.next();
  }

    imgThis = $(source + " div:first-child");

  for (var z = 0; z < imgAll.length; z++) {
  var randomNumber = randomFunction(0, imgArr.length - 1);

    $("#" + imgThis.attr("id") + " img").attr("src", imgArr[randomNumber]);
    imgArr.splice(randomNumber, 1);
    imgThis = imgThis.next();
  }
}

// When the cards  are matched the set is removed
function resetGame() {
    shuffleImages();
    $(source + " div img").hide();
    $(source + " div").css("visibility", "visible");
    counter = 0;
    $("#success").remove();
    $("#counter").html("" + counter);
    boxOpened = "";
    imgOpened = "";
    imgFound = 0;
    return false;
}
//This make all of the cards perform their actions //

function openCard() {
  var id = $(this).attr("id");

  if ($("#" + id + " img").is(":hidden")) {
    $(source + " div").unbind("click", openCard);

    $("#" + id + " img").slideDown('fast');

    if (imgOpened == "") {
      boxOpened = id;
      imgOpened = $("#" + id + " img").attr("src");
      setTimeout(function() {
        $(source + " div").bind("click", openCard)
      }, 300);
    } else {
      currentOpened = $("#" + id + " img").attr("src");
      if (imgOpened != currentOpened) {
        setTimeout(function() {
          $("#" + id + " img").slideUp('fast');
          $("#" + boxOpened + " img").slideUp('fast');
          boxOpened = "";
          imgOpened = "";
        }, 400);
      } else {
        $("#" + id + " img").parent().css("visibility", "hidden");
        $("#" + boxOpened + " img").parent().css("visibility", "hidden");
        imgFound++;
        boxOpened = "";
        imgOpened = "";
      }
      setTimeout(function() {
        $(source + " div").bind("click", openCard)
      }, 400);
    }

    // This counts the number of clicks it takes you to finish the game//
    //  and lets you know via text the results.                        //
    counter++;
    $("#counter").html("" + counter);

    //This shows all matched images at the end of game//
    if (imgFound == imgSource.length) {
      $("#counter").prepend('你找的图片');
    }
  }
}

$(function() {
  for (var y = 1; y < 3 ; y++) {
    $.each(imgSource, function(i, val) {
      $(source).append("
");
    });
  }
  $(source + " div").click(openCard);
  shuffleImages();

});

<commit_msg>Update main.js<commit_after>var boxOpened = "";
var imgOpened = "";
var counter = 0;
var imgFound = 0;

var source = "#boxcard";

var imgSource = [
  "http://a1.mzstatic.com/us/r1000/022/Purple/76/e4/ed/mzl.upwpacxr.100x100-75.jpg",
  "http://www.playgamesarcade.com/games/images/kung-fu-panda-world-tigress-jump_2.jpg",
  "http://www.freeplaynow.com/uploads/kung-fu-panda-world-monkey-run.jpg",
  "http://images5.fanpop.com/image/photos/26500000/Kung-Fu-Panda-kung-fu-panda-26505677-100-100.png",
  "http://orig14.deviantart.net/12d7/f/2008/256/8/1/kung_fu_panda_icon_2_by_oneenekochan.jpg",
  "http://images5.fanpop.com/image/category/74/74816_1332631384_100_100.jpg",
  "http://cdn.inquisitr.com/wp-content/uploads/2016/01/kung-fu-panda-3-review-100x100.jpg",
  "http://images4.fanpop.com/image/polls/740000/740031_1307490049245_100.jpg?v=1307490274",
  "http://www.thenewpotato.com/wp-content/uploads/2015/10/the-bao-st-marks-100x100.jpg?d01037",
  "http://www.whats-your-sign.com/images/100xNxChineseSymbol4.jpg.pagespeed.ic.DU3DcnK35R.jpg"
  ]

function randomFunction(maxValue, minValue) {
    return Math.round(Math.random() * (maxValue - minValue) + minValue);
  }

//  shuffles the images when game is restarted//

function shuffleImages() {
  var imgAll = $(source).children();
  var imgThis = $(source + " div:first-child");
  var imgArr = new Array();

//  shows the current images matched.
  for (var i = 0; i < imgAll.length; i++) {
    imgArr[i] = $("#" + imgThis.attr("id") + " img").attr("src");
    imgThis = imgThis.next();
  }

    imgThis = $(source + " div:first-child");

  for (var z = 0; z < imgAll.length; z++) {
  var randomNumber = randomFunction(0, imgArr.length - 1);

    $("#" + imgThis.attr("id") + " img").attr("src", imgArr[randomNumber]);
    imgArr.splice(randomNumber, 1);
    imgThis = imgThis.next();
  }
}

// When the cards  are matched the set is removed
function resetGame() {
    shuffleImages();
    $(source + " div img").hide();
    $(source + " div").css("visibility", "visible");
    counter = 0;
    $("#success").remove();
    $("#counter").html("" + counter);
    boxOpened = "";
    imgOpened = "";
    imgFound = 0;
    return false;
}
//This make all of the cards perform their actions //

function openCard() {
  var id = $(this).attr("id");

  if ($("#" + id + " img").is(":hidden")) {
    $(source + " div").unbind("click", openCard);

    $("#" + id + " img").slideDown('fast');

    if (imgOpened == "") {
      boxOpened = id;
      imgOpened = $("#" + id + " img").attr("src");
      setTimeout(function() {
        $(source + " div").bind("click", openCard)
      }, 300);
    } else {
      currentOpened = $("#" + id + " img").attr("src");
      if (imgOpened != currentOpened) {
        setTimeout(function() {
          $("#" + id + " img").slideUp('fast');
          $("#" + boxOpened + " img").slideUp('fast');
          boxOpened = "";
          imgOpened = "";
        }, 400);
      } else {
        $("#" + id + " img").parent().css("visibility", "hidden");
        $("#" + boxOpened + " img").parent().css("visibility", "hidden");
        imgFound++;
        boxOpened = "";
        imgOpened = "";
      }
      setTimeout(function() {
        $(source + " div").bind("click", openCard)
      }, 400);
    }

    // This counts the number of clicks it takes you to finish the game//
    //  and lets you know via text the results.                        //
    counter++;
    $("#counter").html("" + counter);

    //This shows all matched images at the end of game//
    if (imgFound == imgSource.length) {
      $("#counter").prepend('你找的图片');
    }
  }
}

$(function() {
  for (var y = 1; y < 3 ; y++) {
    $.each(imgSource, function(i, val) {
      $(source).append("
");
    });
  }
  $(source + " div").click(openCard);
  shuffleImages();

});

<|endoftext|>


<commit_before>'use strict';

var app = angular.module('licker', ['ngRoute'])
    .config(function ($routeProvider) {
      $routeProvider
          .when('/', {
            templateUrl: 'views/table.html',
            controller: 'MainCtrl'
          })
          .otherwise('/');
    });

app.controller('mainCtrl', ['$scope', '$q', 'githubApiConnector', function ($scope, $q, githubApiConnector) {
  $scope.githubHandle = '';
  $scope.errorMessage = '';
  $scope.repositories = [];
  $scope.fetched_repositories = [];

  $scope.fetchRepos = function (apiPage, repositories) {
    var defaultResultLength = 30;
    var page = apiPage || 1;
    var repositories = repositories || [];

    githubApiConnector.fetchReposForUser($scope.githubHandle, page).
        success(function (data) {
          if (data.length > 0) {
            repositories = repositories.concat(data);
          }
          if (data.length == defaultResultLength) {
            $scope.fetchRepos(++page, repositories);
          } else{
            $scope.updateFetchedRepositories(repositories);
          }
        }).
        error(function (data, status) {
          if (status == 403) {
            $scope.errorMessage = 'Not able to get complete information: Github just allows you to make up to 60 requests per hour.';
          }
        });
  };

  $scope.checkLicenses = function () {
    $scope.fetched_repositories = [];
    $scope.repositories = [];
    $scope.fetchRepos();
  };

  $scope.updateFetchedRepositories = function (repositories) {
    $scope.fetched_repositories = repositories;
  };

  $scope.updateRepositories = function (repositories) {
    $scope.repositories = repositories;
  };

  $scope.$watch('fetched_repositories', function () {
    var repositories = [];
    angular.forEach($scope.fetched_repositories, function (repository) {
      githubApiConnector.getLicenseForRepo(repository).
          success(function (data) {
            repositories.push(data);
          }).
          error(function () {
            alert('error.')
          });
    });
    $scope.updateRepositories(repositories);
  });
}]);

app.factory('githubApiConnector', ['$http', function ($http) {
  var api = 'https://api.github.com';
  var page_parameter = '?page=';

  return {
    fetchReposForUser: function (githubHandle, page) {
      var user_repo_endpoint = api + '/users/' + githubHandle + '/repos' + page_parameter + page;
      var request = {
        method: 'GET',
        url: user_repo_endpoint
      };
      return $http(request);
    },
    getLicenseForRepo: function (repo) {
      var license_endpoint = api + '/repos/' + repo['full_name']
      var request = {
        method: 'GET',
        url: license_endpoint,
        headers: {
          'Accept': 'application/vnd.github.drax-preview+json'
        }
      };
      return $http(request);
    }
  };
}]);<commit_msg>rename parameter.<commit_after>'use strict';

var app = angular.module('licker', ['ngRoute'])
    .config(function ($routeProvider) {
      $routeProvider
          .when('/', {
            templateUrl: 'views/table.html',
            controller: 'MainCtrl'
          })
          .otherwise('/');
    });

app.controller('mainCtrl', ['$scope', '$q', 'githubApiConnector', function ($scope, $q, githubApiConnector) {
  $scope.githubHandle = '';
  $scope.errorMessage = '';
  $scope.repositories = [];
  $scope.fetched_repositories = [];

  $scope.fetchRepos = function (apiPage, fetchedRepositories) {
    var defaultResultLength = 30;
    var page = apiPage || 1;
    var repositories = fetchedRepositories || [];

    githubApiConnector.fetchReposForUser($scope.githubHandle, page).
        success(function (data) {
          if (data.length > 0) {
            repositories = repositories.concat(data);
          }
          if (data.length == defaultResultLength) {
            $scope.fetchRepos(++page, repositories);
          } else{
            $scope.updateFetchedRepositories(repositories);
          }
        }).
        error(function (data, status) {
          if (status == 403) {
            $scope.errorMessage = 'Not able to get complete information: Github just allows you to make up to 60 requests per hour.';
          }
        });
  };

  $scope.checkLicenses = function () {
    $scope.fetched_repositories = [];
    $scope.repositories = [];
    $scope.fetchRepos();
  };

  $scope.updateFetchedRepositories = function (repositories) {
    $scope.fetched_repositories = repositories;
  };

  $scope.updateRepositories = function (repositories) {
    $scope.repositories = repositories;
  };

  $scope.$watch('fetched_repositories', function () {
    var repositories = [];
    angular.forEach($scope.fetched_repositories, function (repository) {
      githubApiConnector.getLicenseForRepo(repository).
          success(function (data) {
            repositories.push(data);
          }).
          error(function () {
            alert('error.')
          });
    });
    $scope.updateRepositories(repositories);
  });
}]);

app.factory('githubApiConnector', ['$http', function ($http) {
  var api = 'https://api.github.com';
  var page_parameter = '?page=';

  return {
    fetchReposForUser: function (githubHandle, page) {
      var user_repo_endpoint = api + '/users/' + githubHandle + '/repos' + page_parameter + page;
      var request = {
        method: 'GET',
        url: user_repo_endpoint
      };
      return $http(request);
    },
    getLicenseForRepo: function (repo) {
      var license_endpoint = api + '/repos/' + repo['full_name']
      var request = {
        method: 'GET',
        url: license_endpoint,
        headers: {
          'Accept': 'application/vnd.github.drax-preview+json'
        }
      };
      return $http(request);
    }
  };
}]);<|endoftext|>


<commit_before>// Dean Attali / Beautiful Jekyll 2016

var main = {

  bigImgEl : null,
  numImgs : null,

  init : function() {
    // Shorten the navbar after scrolling a little bit down
    $(window).scroll(function() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar").addClass("top-nav-short");
        } else {
            $(".navbar").removeClass("top-nav-short");
        }
    });

    // On mobile, hide the avatar when expanding the navbar menu
    $('#main-navbar').on('show.bs.collapse', function () {
      $(".navbar").addClass("top-nav-expanded");
    });
    $('#main-navbar').on('hidden.bs.collapse', function () {
      $(".navbar").removeClass("top-nav-expanded");
    });

    // On mobile, when clicking on a multi-level navbar menu, show the child links
    $('#main-navbar').on("click", ".navlinks-parent", function(e) {
      var target = e.target;
      $.each($(".navlinks-parent"), function(key, value) {
        if (value == target) {
          $(value).parent().toggleClass("show-children");
        } else {
          $(value).parent().removeClass("show-children");
        }
      });
    });

    // Ensure nested navbar menus are not longer than the menu header
    var menus = $(".navlinks-container");
    if (menus.length > 0) {
      var navbar = $("#main-navbar ul");
      var fakeMenuHtml = "

";
      navbar.append(fakeMenuHtml);
      var fakeMenu = $(".fake-menu");

      $.each(menus, function(i) {
        var parent = $(menus[i]).find(".navlinks-parent");
        var children = $(menus[i]).find(".navlinks-children a");
        var words = [];
        $.each(children, function(idx, el) { words = words.concat($(el).text().trim().split(/\s+/)); });
        var maxwidth = 0;
        $.each(words, function(id, word) {
          fakeMenu.html("" + word + "");
          var width =  fakeMenu.width();
          if (width > maxwidth) {
            maxwidth = width;
          }
        });
        $(menus[i]).css('min-width', maxwidth + 'px')
      });

      fakeMenu.remove();
    }

    // show the big header image
    main.initImgs();
  },

  initImgs : function() {
    // If the page was large images to randomly select from, choose an image
    if ($("#header-big-imgs").length > 0) {
      main.bigImgEl = $("#header-big-imgs");
      main.numImgs = main.bigImgEl.attr("data-num-img");

          // 2fc73a3a967e97599c9763d05e564189
	  // set an initial image
	  var imgInfo = main.getImgInfo();
	  var src = imgInfo.src;
	  var desc = imgInfo.desc;
  	  main.setImg(src, desc);

	  // For better UX, prefetch the next image so that it will already be loaded when we want to show it
  	  var getNextImg = function() {
	    var imgInfo = main.getImgInfo();
	    var src = imgInfo.src;
	    var desc = imgInfo.desc;

		var prefetchImg = new Image();
  		prefetchImg.src = src;
		// if I want to do something once the image is ready: `prefetchImg.onload = function(){}`

  		setTimeout(function(){
                  var img = $("

").addClass("big-img-transition").css("background-image", 'url(' + src + ')');
  		  $(".intro-header.big-img").prepend(img);
  		  setTimeout(function(){ img.css("opacity", "1"); }, 50);

		  // after the animation of fading in the new image is done, prefetch the next one
  		  //img.one("transitioned webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
		  setTimeout(function() {
		    main.setImg(src, desc);
			img.remove();
  			getNextImg();
		  }, 1000);
  		  //});
  		}, 6000);
  	  };

	  // If there are multiple images, cycle through them
	  if (main.numImgs > 1) {
  	    getNextImg();
	  }
    }
  },

  getImgInfo : function() {
  	var randNum = Math.floor((Math.random() * main.numImgs) + 1);
    var src = main.bigImgEl.attr("data-img-src-" + randNum);
	var desc = main.bigImgEl.attr("data-img-desc-" + randNum);

	return {
	  src : src,
	  desc : desc
	}
  },

  setImg : function(src, desc) {
	$(".intro-header.big-img").css("background-image", 'url(' + src + ')');
	if (typeof desc !== typeof undefined && desc !== false) {
	  $(".img-desc").text(desc).show();
	} else {
	  $(".img-desc").hide();
	}
  }
};

// 2fc73a3a967e97599c9763d05e564189

document.addEventListener('DOMContentLoaded', main.init);
<commit_msg>append timeline script<commit_after>// Dean Attali / Beautiful Jekyll 2016

var main = {

  bigImgEl : null,
  numImgs : null,

  init : function() {
    // Shorten the navbar after scrolling a little bit down
    $(window).scroll(function() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar").addClass("top-nav-short");
        } else {
            $(".navbar").removeClass("top-nav-short");
        }
    });

    // On mobile, hide the avatar when expanding the navbar menu
    $('#main-navbar').on('show.bs.collapse', function () {
      $(".navbar").addClass("top-nav-expanded");
    });
    $('#main-navbar').on('hidden.bs.collapse', function () {
      $(".navbar").removeClass("top-nav-expanded");
    });

    // On mobile, when clicking on a multi-level navbar menu, show the child links
    $('#main-navbar').on("click", ".navlinks-parent", function(e) {
      var target = e.target;
      $.each($(".navlinks-parent"), function(key, value) {
        if (value == target) {
          $(value).parent().toggleClass("show-children");
        } else {
          $(value).parent().removeClass("show-children");
        }
      });
    });

    // Ensure nested navbar menus are not longer than the menu header
    var menus = $(".navlinks-container");
    if (menus.length > 0) {
      var navbar = $("#main-navbar ul");
      var fakeMenuHtml = "

";
      navbar.append(fakeMenuHtml);
      var fakeMenu = $(".fake-menu");

      $.each(menus, function(i) {
        var parent = $(menus[i]).find(".navlinks-parent");
        var children = $(menus[i]).find(".navlinks-children a");
        var words = [];
        $.each(children, function(idx, el) { words = words.concat($(el).text().trim().split(/\s+/)); });
        var maxwidth = 0;
        $.each(words, function(id, word) {
          fakeMenu.html("" + word + "");
          var width =  fakeMenu.width();
          if (width > maxwidth) {
            maxwidth = width;
          }
        });
        $(menus[i]).css('min-width', maxwidth + 'px')
      });

      fakeMenu.remove();
    }

    // show the big header image
    main.initImgs();
  },

  initImgs : function() {
    // If the page was large images to randomly select from, choose an image
    if ($("#header-big-imgs").length > 0) {
      main.bigImgEl = $("#header-big-imgs");
      main.numImgs = main.bigImgEl.attr("data-num-img");

          // 2fc73a3a967e97599c9763d05e564189
	  // set an initial image
	  var imgInfo = main.getImgInfo();
	  var src = imgInfo.src;
	  var desc = imgInfo.desc;
  	  main.setImg(src, desc);

	  // For better UX, prefetch the next image so that it will already be loaded when we want to show it
  	  var getNextImg = function() {
	    var imgInfo = main.getImgInfo();
	    var src = imgInfo.src;
	    var desc = imgInfo.desc;

		var prefetchImg = new Image();
  		prefetchImg.src = src;
		// if I want to do something once the image is ready: `prefetchImg.onload = function(){}`

  		setTimeout(function(){
                  var img = $("

").addClass("big-img-transition").css("background-image", 'url(' + src + ')');
  		  $(".intro-header.big-img").prepend(img);
  		  setTimeout(function(){ img.css("opacity", "1"); }, 50);

		  // after the animation of fading in the new image is done, prefetch the next one
  		  //img.one("transitioned webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
		  setTimeout(function() {
		    main.setImg(src, desc);
			img.remove();
  			getNextImg();
		  }, 1000);
  		  //});
  		}, 6000);
  	  };

	  // If there are multiple images, cycle through them
	  if (main.numImgs > 1) {
  	    getNextImg();
	  }
    }
  },

  getImgInfo : function() {
  	var randNum = Math.floor((Math.random() * main.numImgs) + 1);
    var src = main.bigImgEl.attr("data-img-src-" + randNum);
	var desc = main.bigImgEl.attr("data-img-desc-" + randNum);

	return {
	  src : src,
	  desc : desc
	}
  },

  setImg : function(src, desc) {
	$(".intro-header.big-img").css("background-image", 'url(' + src + ')');
	if (typeof desc !== typeof undefined && desc !== false) {
	  $(".img-desc").text(desc).show();
	} else {
	  $(".img-desc").hide();
	}
  }
};

// 2fc73a3a967e97599c9763d05e564189

document.addEventListener('DOMContentLoaded', main.init);

jQuery(document).ready(function($) {
  var timelineBlocks = $('.cd-timeline-block'), offset=0.8;
  hideBlocks(timelineBlocks, offset);
  $(window).on('scroll', function() {
    (!window.requestAnimationFrame)
      ? setTimeout(function(){ showBlocks(timelineBlocks, offset); }, 100)
      : window.requestAnimationFrame(function(){ showBlocks(timelineBlocks, offset);});
  });

  function hideBlocks(blocks, offset) {
    blocks.each(function() {
      ( $(this).offset().top > $(window).scrollTop()+$(window).height()*offset ) && $(this).find('.cd-timeline-img, .cd-timeline-content').addClass('is-hidden');
    });
  }

  function showBlocks(blocks, offset) {
    blocks.each(function() {
      ( $(this).offset().top <= $(window).scrollTop() + $(window).height()*offset && $(this).find('.cd-timeline-img').hasClass('is-hidden') ) && $(this).find('.cd-timeline-img, .cd-timeline-content').removeClass('is-hidden').addClass('bounce-in');
    });
  }
});
<|endoftext|>


<commit_before>"use strict";

var firstBackgroundUpdate = true;
var countdownStarted = false;
var countdownTimeoutId = -1;

var QUIZ_AVAILABLE_SECONDS = 10;
var quizStartTime = QUIZ_AVAILABLE_SECONDS;

var numAnswersCorrect = 0;
var numAnswersGiven = 0;

function resetState() {
  numAnswersGiven = numAnswersCorrect = 0;
  countdownTimeoutId = -1;
  countdownStarted = false;
}

$(function() {
  $('#repeat-box').click(function() {
    // reset vars

    $(this).hide();
  });
});

function updateTime() {
  quizStartTime--;

  if (quizStartTime < 0) {
    // reset vars
    clearInterval(countdownTimeoutId);
    countdownTimeoutId = -1;
    quizStartTime = QUIZ_AVAILABLE_SECONDS;

    timeIsOver();

    return;
  }

  // update timer
  var progressPercent = (QUIZ_AVAILABLE_SECONDS - quizStartTime) / QUIZ_AVAILABLE_SECONDS * 100;
  $('#time-left').html(quizStartTime);
  $('#time-left-indicator').animate({'width': progressPercent + '%'}, 300);
}

$('#start-quiz').click(function() {
  resetState();
  showStartLayout();

});

function showStartLayout() {
  // hide timing tags
  $('#questionbox').show();
  $('#time-box').show();

  // show evaluation tags
  $('#start-quiz').hide();
  $('#results').hide();
  $('#sharebuttons').hide();
}

function showEvaluationLayout() {
  // hide timing tags
  $('#questionbox').hide();
  $('#time-box').hide();

  // show evaluation tags
  $('#start-quiz').show();
  $('#results').show();
  $('#sharebuttons').show();

  $('#time-left').text(QUIZ_AVAILABLE_SECONDS);
  $('#time-left-indicator').css({'width': '0%'});
}

// make sure always at least one checkbox is checked
$('#div-operations :checkbox').change(function(e){
  if (!$(this).is(':checked')) {
    if ($("#div-operations :checkbox:checked").length === 0) {
      $(this).prop('checked', true);
    }
  }
});

// timeIsOver();
function timeIsOver() {
  showEvaluationLayout();
  var score = calculateScore();
  setEvaluation(score, getRank(score));

  updateTwitterButton();
  // facebook does update itself

  // function definitions follow //

  function updateTwitterButton() {
    var twitterButtons = $('.twitter-share-button');
    if (twitterButtons.size() !== 0) {
      $('.twitter-share-button').remove();
      // Generate new markup
      var $tweetBtn = $('')
          .addClass('twitter-share-button')
          .attr('href', 'http://twitter.com/share')
          .attr('data-url', 'http://mental-math-trainer.com')
          .attr('data-text', 'Check out my math score: ' + score + '! In just 10 seconds <3. mental-math-trainer.com');
      $('.sharebutton').first().append($tweetBtn);
      twttr.widgets.load();
    }
  }

  function calculateScore() {
    var sliderMax = parseInt($('#math-range-slider').val());
    var numOperatorsEnabled =  $('#div-operations :checkbox').size();
    return Math.ceil(numAnswersCorrect * (sliderMax / 10 + numOperatorsEnabled));
  }

  function getRank(score) {
    // TODO we should add a real ranking one day

    var ONE_BARELY_REACHES_THIS_SCORE = 200;
    return Math.floor(100 * Math.min(Math.E * score / (ONE_BARELY_REACHES_THIS_SCORE * Math.PI), .99));
  }

  function setEvaluation(score, rank) {
    var description = 'You scored ' + score + '' +
                      'You are better than ' + rank + ' %';
    $('#results .description').html(description);
  }
}

// set up listeners
$(function() {
  var $question = $('#question');
  var $answer = $('#question-answer');
  var currentQuestion;
  var factory = new QuestionFactory();

  setFirstQuestion();
  function setFirstQuestion() {
    currentQuestion = factory.nextQuestion();
    $question.text(currentQuestion.getDisplay());
    $answer.val('');
  }

  function evaluateAnswer() {
    if (countdownTimeoutId === -1) {
      countdownTimeoutId = setInterval(updateTime, 1000);
    }

    numAnswersGiven++;

    if (currentQuestion !== undefined && currentQuestion.getAnswer() == $answer.val()) {
      numAnswersCorrect++;
    }

    currentQuestion = factory.nextQuestion();
    $question.text(currentQuestion.getDisplay());
    $answer.val('');
  }

  function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }

  function submitInputPressed(e) {
    if(e === undefined || e.which == 13) {
      if ($answer.val().trim() !== '' && isNumber($answer.val())) {
        evaluateAnswer();
      }
      $answer.val('');
    }
  }

  // register answer submit listeners
  $answer.keypress(function(e) {
    submitInputPressed(e);
  });

  $('#submit-answer').click(function() {
    submitInputPressed();
    $answer.focus();
  });
});<commit_msg>Removed double link in twitter share<commit_after>"use strict";

var firstBackgroundUpdate = true;
var countdownStarted = false;
var countdownTimeoutId = -1;

var QUIZ_AVAILABLE_SECONDS = 10;
var quizStartTime = QUIZ_AVAILABLE_SECONDS;

var numAnswersCorrect = 0;
var numAnswersGiven = 0;

function resetState() {
  numAnswersGiven = numAnswersCorrect = 0;
  countdownTimeoutId = -1;
  countdownStarted = false;
}

$(function() {
  $('#repeat-box').click(function() {
    // reset vars

    $(this).hide();
  });
});

function updateTime() {
  quizStartTime--;

  if (quizStartTime < 0) {
    // reset vars
    clearInterval(countdownTimeoutId);
    countdownTimeoutId = -1;
    quizStartTime = QUIZ_AVAILABLE_SECONDS;

    timeIsOver();

    return;
  }

  // update timer
  var progressPercent = (QUIZ_AVAILABLE_SECONDS - quizStartTime) / QUIZ_AVAILABLE_SECONDS * 100;
  $('#time-left').html(quizStartTime);
  $('#time-left-indicator').animate({'width': progressPercent + '%'}, 300);
}

$('#start-quiz').click(function() {
  resetState();
  showStartLayout();

});

function showStartLayout() {
  // hide timing tags
  $('#questionbox').show();
  $('#time-box').show();

  // show evaluation tags
  $('#start-quiz').hide();
  $('#results').hide();
  $('#sharebuttons').hide();
}

function showEvaluationLayout() {
  // hide timing tags
  $('#questionbox').hide();
  $('#time-box').hide();

  // show evaluation tags
  $('#start-quiz').show();
  $('#results').show();
  $('#sharebuttons').show();

  $('#time-left').text(QUIZ_AVAILABLE_SECONDS);
  $('#time-left-indicator').css({'width': '0%'});
}

// make sure always at least one checkbox is checked
$('#div-operations :checkbox').change(function(e){
  if (!$(this).is(':checked')) {
    if ($("#div-operations :checkbox:checked").length === 0) {
      $(this).prop('checked', true);
    }
  }
});

// timeIsOver();
function timeIsOver() {
  showEvaluationLayout();
  var score = calculateScore();
  setEvaluation(score, getRank(score));

  updateTwitterButton();
  // facebook does update itself

  // function definitions follow //

  function updateTwitterButton() {
    var twitterButtons = $('.twitter-share-button');
    if (twitterButtons.size() !== 0) {
      $('#sharebuttons .twitter-share-button').remove();
      // Generate new markup
      var $tweetBtn = $('')
          .addClass('twitter-share-button')
          .attr('href', 'http://twitter.com/share')
          .attr('data-url', 'http://mental-math-trainer.com')
          .attr('data-text', 'Check out my math score: ' + score + '! In just 10 seconds <3');
      $('.sharebutton').first().append($tweetBtn);
      twttr.widgets.load();
    }
  }

  function calculateScore() {
    var sliderMax = parseInt($('#math-range-slider').val());
    var numOperatorsEnabled =  $('#div-operations :checkbox').size();
    return Math.ceil(numAnswersCorrect * (sliderMax / 10 + numOperatorsEnabled));
  }

  function getRank(score) {
    // TODO we should add a real ranking one day

    var ONE_BARELY_REACHES_THIS_SCORE = 200;
    return Math.floor(100 * Math.min(Math.E * score / (ONE_BARELY_REACHES_THIS_SCORE * Math.PI), .99));
  }

  function setEvaluation(score, rank) {
    var description = 'You scored ' + score + '' +
                      'You are better than ' + rank + ' %';
    $('#results .description').html(description);
  }
}

// set up listeners
$(function() {
  var $question = $('#question');
  var $answer = $('#question-answer');
  var currentQuestion;
  var factory = new QuestionFactory();

  setFirstQuestion();
  function setFirstQuestion() {
    currentQuestion = factory.nextQuestion();
    $question.text(currentQuestion.getDisplay());
    $answer.val('');
  }

  function evaluateAnswer() {
    if (countdownTimeoutId === -1) {
      countdownTimeoutId = setInterval(updateTime, 1000);
    }

    numAnswersGiven++;

    if (currentQuestion !== undefined && currentQuestion.getAnswer() == $answer.val()) {
      numAnswersCorrect++;
    }

    currentQuestion = factory.nextQuestion();
    $question.text(currentQuestion.getDisplay());
    $answer.val('');
  }

  function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }

  function submitInputPressed(e) {
    if(e === undefined || e.which == 13) {
      if ($answer.val().trim() !== '' && isNumber($answer.val())) {
        evaluateAnswer();
      }
      $answer.val('');
    }
  }

  // register answer submit listeners
  $answer.keypress(function(e) {
    submitInputPressed(e);
  });

  $('#submit-answer').click(function() {
    submitInputPressed();
    $answer.focus();
  });
});<|endoftext|>


<commit_before>function postComment() {
  // Firebase
  var ref = new Firebase("https://tauduluan.firebaseio.com"),
      comments = ref.child("comments");

  // Get input value
  var nama = $('#nama').val(),
      komentar = $('#komentar').val(),
      input = $('.input').val();

  // Time
  var date = new Date(),
  right_now = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();

  if (input === '') {
    swal({
      title: "Input is not filled",
      text: "Input is not filled",
      type: "error"
    })
    return false;
  } else if (komentar.length < 10) {
    swal({
      title: "Komentar kurang panjang",
      text: "Komentar kamu kurang panjang",
      type: "error"
    })
    return false;
  } else {
    // Log input value
    console.log('Nama: ' + nama);
    console.log('Komentar: ' + komentar);
    console.log('Waktu: ' + right_now);

    // Post data to firebase
    comments.push().set({
      nama: nama,
      komentar: komentar,
      waktu: right_now
    });

    // Friendly message
    swal({
      title: "Terima kasih atas komentar kamu",
      text: "Terima kasih atas komentar kamu",
      type: "success"
    })

    location.reload()
    return true;
  }
}

function readPost(title) {
  window.location.href = '/post/' + title;
}

function viewArtis(username) {
  window.location.href = 'artis/' + username + '/'
}
<commit_msg>Remove shitty apended /<commit_after>function postComment() {
  // Firebase
  var ref = new Firebase("https://tauduluan.firebaseio.com"),
      comments = ref.child("comments");

  // Get input value
  var nama = $('#nama').val(),
      komentar = $('#komentar').val(),
      input = $('.input').val();

  // Time
  var date = new Date(),
  right_now = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();

  if (input === '') {
    swal({
      title: "Input is not filled",
      text: "Input is not filled",
      type: "error"
    })
    return false;
  } else if (komentar.length < 10) {
    swal({
      title: "Komentar kurang panjang",
      text: "Komentar kamu kurang panjang",
      type: "error"
    })
    return false;
  } else {
    // Log input value
    console.log('Nama: ' + nama);
    console.log('Komentar: ' + komentar);
    console.log('Waktu: ' + right_now);

    // Post data to firebase
    comments.push().set({
      nama: nama,
      komentar: komentar,
      waktu: right_now
    });

    // Friendly message
    swal({
      title: "Terima kasih atas komentar kamu",
      text: "Terima kasih atas komentar kamu",
      type: "success"
    })

    location.reload()
    return true;
  }
}

function readPost(title) {
  window.location.href = 'post/' + title;
}

function viewArtis(username) {
  window.location.href = 'artis/' + username + '/'
}
<|endoftext|>


<commit_before>$(function(){
        var zoom = new ZoomView('#zoom','#zoom :first');
	var zoom2 = new ZoomView('#zoom2','#zoom2 :first');
	var zoom3 = new ZoomView('#zoom3','#zoom3 :first');
});

var zIndexBackup = 10;

function DragView(target) {
	this.target = target[0];
      	this.drag = [];
      	this.lastDrag = {};

      	this.WatchDrag = function() {
       		if(!this.drag.length) {
         		return;
        	}

        	for(var d = 0; d<this.drag.length; d++) {
         		var left = $(this.drag[d].el).offset().left;
         		var top = $(this.drag[d].el).offset().top;

			var x_offset = -(this.lastDrag.pos.x - this.drag[d].pos.x);
          		var y_offset = -(this.lastDrag.pos.y - this.drag[d].pos.y);

        		left = left + x_offset;
        		top = top + y_offset;

        		this.lastDrag = this.drag[d];

          		this.drag[d].el.style.left = left +'px';
          		this.drag[d].el.style.top = top +'px';
        	}
      	}

      	this.OnDragStart = function(event) {
        	var touches = event.originalEvent.touches || [event.originalEvent];
        	for(var t=0; t<touches.length; t++) {
          		var el = touches[t].target.parentNode;

		  	if(el.className.search('polaroid') > -1){
				el = touches[t].target.parentNode.parentNode;
		  	}
			el.style.zIndex = zIndexBackup + 1;
			zIndexBackup = zIndexBackup +1;

          		if(el && el == this.target) {
				$(el).children().toggleClass('upSky');
            			this.lastDrag = {
              				el: el,
              				pos: event.touches[t]
            			};
            			return;
          		}

		}
	}

	this.OnDrag = function(event) {
        	this.drag = [];
        	var touches = event.originalEvent.touches || [event.originalEvent];
        	for(var t=0; t<touches.length; t++) {
         	var el = touches[t].target.parentNode;

		if(el.className.search('polaroid') > -1){
			el = touches[t].target.parentNode.parentNode;
		}

          	if(el && el == this.target) {
            		this.drag.push({
              			el: el,
              			pos: event.touches[t]
            		});
        	}
	}
}

      	this.OnDragEnd = function(event) {
		this.drag = [];
        	var touches = event.originalEvent.touches || [event.originalEvent];
		 	for(var t=0; t<touches.length; t++) {
          			var el = touches[t].target.parentNode;

		  			if(el.className.search('polaroid') > -1){
				 			el = touches[t].target.parentNode.parentNode;
		  			}
					$(el).children().toggleClass('upSky');

		  	}
      	}
}

function ZoomView(container, element) {
	container = $(container).hammer({
        	prevent_default: true,
            	scale_treshold: 0,
            	drag_min_distance: 0
        });

        element = $(element);

        var displayWidth = container.width();
        var displayHeight = container.height();

        //These two constants specify the minimum and maximum zoom
        var MIN_ZOOM = 1;
        var MAX_ZOOM = 3;

        var scaleFactor = 1;
        var previousScaleFactor = 1;

        //These two variables keep track of the X and Y coordinate of the finger when it first
        //touches the screen
        var startX = 0;
        var startY = 0;

        //These two variables keep track of the amount we need to translate the canvas along the X
        //and the Y coordinate
        var translateX = 0;
        var translateY = 0;

        //These two variables keep track of the amount we translated the X and Y coordinates, the last time we
        //panned.
        var previousTranslateX = 0;
        var previousTranslateY = 0;

        //Translate Origin variables

        var tch1 = 0,
            tch2 = 0,
            tcX = 0,
            tcY = 0,
            toX = 0,
            toY = 0,
            cssOrigin = "";

        container.bind("transformstart", function(event){

            //We save the initial midpoint of the first two touches to say where our transform origin is.
            e = event

            tch1 = [e.touches[0].x, e.touches[0].y],
            tch2 = [e.touches[1].x, e.touches[1].y]

            tcX = (tch1[0]+tch2[0])/2,
            tcY = (tch1[1]+tch2[1])/2

            toX = tcX
            toY = tcY

            var left = $(element).offset().left;
            var top = $(element).offset().top;

            cssOrigin = (-(left) + toX)/scaleFactor +"px "+ (-(top) + toY)/scaleFactor +"px";
        })

        container.bind("transform", function(event) {
            scaleFactor = previousScaleFactor * event.scale;

            scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
            transform(event);
        });

        container.bind("transformend", function(event) {
            previousScaleFactor = scaleFactor;
        });

	var dragview = new DragView($(container));
	container.bind("dragstart", $.proxy(dragview.OnDragStart, dragview));
	container.bind("drag", $.proxy(dragview.OnDrag, dragview));
	container.bind("dragend", $.proxy(dragview.OnDragEnd, dragview));
	setInterval($.proxy(dragview.WatchDrag, dragview), 10);

}
<commit_msg>Added the Transform Function<commit_after>$(function(){
        var zoom = new ZoomView('#zoom','#zoom :first');
	var zoom2 = new ZoomView('#zoom2','#zoom2 :first');
	var zoom3 = new ZoomView('#zoom3','#zoom3 :first');
});

var zIndexBackup = 10;

function DragView(target) {
	this.target = target[0];
      	this.drag = [];
      	this.lastDrag = {};

      	this.WatchDrag = function() {
       		if(!this.drag.length) {
         		return;
        	}

        	for(var d = 0; d<this.drag.length; d++) {
         		var left = $(this.drag[d].el).offset().left;
         		var top = $(this.drag[d].el).offset().top;

			var x_offset = -(this.lastDrag.pos.x - this.drag[d].pos.x);
          		var y_offset = -(this.lastDrag.pos.y - this.drag[d].pos.y);

        		left = left + x_offset;
        		top = top + y_offset;

        		this.lastDrag = this.drag[d];

          		this.drag[d].el.style.left = left +'px';
          		this.drag[d].el.style.top = top +'px';
        	}
      	}

      	this.OnDragStart = function(event) {
        	var touches = event.originalEvent.touches || [event.originalEvent];
        	for(var t=0; t<touches.length; t++) {
          		var el = touches[t].target.parentNode;

		  	if(el.className.search('polaroid') > -1){
				el = touches[t].target.parentNode.parentNode;
		  	}
			el.style.zIndex = zIndexBackup + 1;
			zIndexBackup = zIndexBackup +1;

          		if(el && el == this.target) {
				$(el).children().toggleClass('upSky');
            			this.lastDrag = {
              				el: el,
              				pos: event.touches[t]
            			};
            			return;
          		}

		}
	}

	this.OnDrag = function(event) {
        	this.drag = [];
        	var touches = event.originalEvent.touches || [event.originalEvent];
        	for(var t=0; t<touches.length; t++) {
         	var el = touches[t].target.parentNode;

		if(el.className.search('polaroid') > -1){
			el = touches[t].target.parentNode.parentNode;
		}

          	if(el && el == this.target) {
            		this.drag.push({
              			el: el,
              			pos: event.touches[t]
            		});
        	}
	}
}

      	this.OnDragEnd = function(event) {
		this.drag = [];
        	var touches = event.originalEvent.touches || [event.originalEvent];
		 	for(var t=0; t<touches.length; t++) {
          			var el = touches[t].target.parentNode;

		  			if(el.className.search('polaroid') > -1){
				 			el = touches[t].target.parentNode.parentNode;
		  			}
					$(el).children().toggleClass('upSky');

		  	}
      	}
}

function ZoomView(container, element) {
	container = $(container).hammer({
        	prevent_default: true,
            	scale_treshold: 0,
            	drag_min_distance: 0
        });

        element = $(element);

        var displayWidth = container.width();
        var displayHeight = container.height();

        //These two constants specify the minimum and maximum zoom
        var MIN_ZOOM = 1;
        var MAX_ZOOM = 3;

        var scaleFactor = 1;
        var previousScaleFactor = 1;

        //These two variables keep track of the X and Y coordinate of the finger when it first
        //touches the screen
        var startX = 0;
        var startY = 0;

        //These two variables keep track of the amount we need to translate the canvas along the X
        //and the Y coordinate
        var translateX = 0;
        var translateY = 0;

        //These two variables keep track of the amount we translated the X and Y coordinates, the last time we
        //panned.
        var previousTranslateX = 0;
        var previousTranslateY = 0;

        //Translate Origin variables

        var tch1 = 0,
            tch2 = 0,
            tcX = 0,
            tcY = 0,
            toX = 0,
            toY = 0,
            cssOrigin = "";

        container.bind("transformstart", function(event){

            //We save the initial midpoint of the first two touches to say where our transform origin is.
            e = event

            tch1 = [e.touches[0].x, e.touches[0].y],
            tch2 = [e.touches[1].x, e.touches[1].y]

            tcX = (tch1[0]+tch2[0])/2,
            tcY = (tch1[1]+tch2[1])/2

            toX = tcX
            toY = tcY

            var left = $(element).offset().left;
            var top = $(element).offset().top;

            cssOrigin = (-(left) + toX)/scaleFactor +"px "+ (-(top) + toY)/scaleFactor +"px";
        })

        container.bind("transform", function(event) {
            scaleFactor = previousScaleFactor * event.scale;

            scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
            transform(event);
        });

        container.bind("transformend", function(event) {
            previousScaleFactor = scaleFactor;
        });

	var dragview = new DragView($(container));
	container.bind("dragstart", $.proxy(dragview.OnDragStart, dragview));
	container.bind("drag", $.proxy(dragview.OnDrag, dragview));
	container.bind("dragend", $.proxy(dragview.OnDragEnd, dragview));
	setInterval($.proxy(dragview.WatchDrag, dragview), 10);

        function transform(e) {
            //We're going to scale the X and Y coordinates by the same amount
            var cssScale = "scaleX("+ scaleFactor +") scaleY("+ scaleFactor +") rotateZ("+ e.rotation +"deg)";

            element.css({
                webkitTransform: cssScale,
                webkitTransformOrigin: cssOrigin,

                transform: cssScale,
                transformOrigin: cssOrigin,
            });

	}

}
<|endoftext|>


<commit_before>var $nyans = $('.nyan-cats');
var $nyanOne = $('#nyan-cat-1');// currently unused variables
var $nyanTwo = $('#nyan-cat-2');// currently unused variables
var $nyanThree = $('#nyan-cat-3');// currently unused variables

var $nameOne = $('#name-one');
var $nameTwo = $('#name-two');
var $nameThree = $('#name-three');
var $nameFour = $('#name-four');
var $nameFive = $('#name-five');

var $counter = $('#counter-one');
var $counter2 = $('#counter-two');
var $counter3 = $('#counter-three');
var $counter4 = $('#counter-four');
var $counter5 = $('#counter-five');

var clickCountOne = 0;
var clickCountTwo = 0;
var clickCountThree = 0;
var clickCountFour = 0;
var clickCountFive = 0;

var cats = [$nameOne, $nameTwo, $nameThree, $nameFour, $nameFive];
var numCats = cats.length;
var names = ['Ned', 'Jaime', 'Jon', 'Arya', 'Sansa', 'Tyrion', 'Hodor', 'Petyr', 'Khal', 'Khaleesi', 'Ygritte', 'Catelyn', 'Podrick', 'Brienne'];

var catRows = $('#cat-rows');
var catDiv = '

';
var catDivId = $('#cat-div');
var catTitle = '
Nyan!
';
var catImg = '';
var catCounter = '

';
var formattedCat = catTitle;
// console.log(formattedCat);
// catRows.append(catDiv);
// catDivId.append(formattedCat);

//console.log(clickCountOne, clickCountTwo, clickCountThree);

// this function randomly names the three cats using the array of GoT character names provided
// iterates through a the number of cats and inputs the name!
var nameCats = function(){
	for (var i = 0; i < numCats; i++) {
		var catName = names[Math.floor(Math.random() * 6)];
		var cat = cats[i];
		cat.text(catName + ' Nyan');
	}
};

var clickTracker = function() {
	// Trying to work with closures here...but it's a bit of a mess! To be completed!
	// for (var i = 0; i <= numCats; i++){
	// 	(function(){
	// 		var catId = i;
	// 		$('#nyan-cat-' + catId).click(function(){
	// 			console.log(catId);
	// 			var clickCount = 'clickCount' + catId;
	// 			console.log(clickCount);
	// 			$counter.text('Current Click Count = ' + clickCount);
	// 		});
	// 	})();
	// };

	//experimentation on parseInt..
	// $nyans.click(function(){
	// 	var count = parseInt($(this).data('click')) || 0;
	// 	count++;
	// 	$(this).data('click', count);
	// 	$counter.text('Current Click Count = ' + count);
	// 	$counter2.text('Current Click Count = ' + count);
	// 	$counter3.text('Current Click Count = ' + count);
	$nyans.click(function(){
		var clickedItemId = null;
		// Practicing usage of "this" to grab the last object clicked, in this case the individual Nyan cat id
		// so we can identify and increment the appropriate clicker
		// this article helped with clarifying "this" http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
		clickedItemId = $(this).attr('id');
		//console.log(clickedItemId);
		//console.log($nyanOne);
		if (clickedItemId == "nyan-cat-1") {
			clickCountOne ++;
			$counter.text('Current Click Count = '+ clickCountOne);
		} else if (clickedItemId == "nyan-cat-2") {
			clickCountTwo ++;
			$counter2.text('Current Click Count = '+ clickCountTwo);
		} else if (clickedItemId == "nyan-cat-3"){
			clickCountThree ++;
			$counter3.text('Current Click Count = ' + clickCountThree);
		} else if (clickedItemId == "nyan-cat-4"){
			clickCountFour ++;
			$counter4.text('Current Click Count = ' + clickCountFour);
		} else if (clickedItemId == "nyan-cat-5"){
			clickCountFive ++;
			$counter5.text('Current Click Count = ' + clickCountFive);
		}
	});
};

nameCats();
clickTracker();<commit_msg>fix: added name array length variable, and updated name randomizer function<commit_after>var $nyans = $('.nyan-cats');
var $nyanOne = $('#nyan-cat-1');// currently unused variables
var $nyanTwo = $('#nyan-cat-2');// currently unused variables
var $nyanThree = $('#nyan-cat-3');// currently unused variables

var $nameOne = $('#name-one');
var $nameTwo = $('#name-two');
var $nameThree = $('#name-three');
var $nameFour = $('#name-four');
var $nameFive = $('#name-five');

var $counter = $('#counter-one');
var $counter2 = $('#counter-two');
var $counter3 = $('#counter-three');
var $counter4 = $('#counter-four');
var $counter5 = $('#counter-five');

var clickCountOne = 0;
var clickCountTwo = 0;
var clickCountThree = 0;
var clickCountFour = 0;
var clickCountFive = 0;

var cats = [$nameOne, $nameTwo, $nameThree, $nameFour, $nameFive];
var numCats = cats.length;
var names = ['Ned', 'Jaime', 'Jon', 'Arya', 'Sansa', 'Tyrion', 'Hodor', 'Petyr', 'Khal', 'Khaleesi', 'Ygritte', 'Catelyn', 'Podrick', 'Brienne'];
var nameLength = names.length;

var catRows = $('#cat-rows');
var catDiv = '

';
var catDivId = $('#cat-div');
var catTitle = '
Nyan!
';
var catImg = '';
var catCounter = '

';
var formattedCat = catTitle;
// console.log(formattedCat);
// catRows.append(catDiv);
// catDivId.append(formattedCat);

//console.log(clickCountOne, clickCountTwo, clickCountThree);

// this function randomly names the three cats using the array of GoT character names provided
// iterates through a the number of cats and inputs the name!
var nameCats = function(){
	for (var i = 0; i < numCats; i++) {
		var catName = names[Math.floor(Math.random() * nameLength)];
		var cat = cats[i];
		cat.text(catName + ' Nyan');
	}
};

var clickTracker = function() {
	// Trying to work with closures here...but it's a bit of a mess! To be completed!
	// for (var i = 0; i <= numCats; i++){
	// 	(function(){
	// 		var catId = i;
	// 		$('#nyan-cat-' + catId).click(function(){
	// 			console.log(catId);
	// 			var clickCount = 'clickCount' + catId;
	// 			console.log(clickCount);
	// 			$counter.text('Current Click Count = ' + clickCount);
	// 		});
	// 	})();
	// };

	//experimentation on parseInt..
	// $nyans.click(function(){
	// 	var count = parseInt($(this).data('click')) || 0;
	// 	count++;
	// 	$(this).data('click', count);
	// 	$counter.text('Current Click Count = ' + count);
	// 	$counter2.text('Current Click Count = ' + count);
	// 	$counter3.text('Current Click Count = ' + count);
	$nyans.click(function(){
		var clickedItemId = null;
		// Practicing usage of "this" to grab the last object clicked, in this case the individual Nyan cat id
		// so we can identify and increment the appropriate clicker
		// this article helped with clarifying "this" http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
		clickedItemId = $(this).attr('id');
		//console.log(clickedItemId);
		//console.log($nyanOne);
		if (clickedItemId == "nyan-cat-1") {
			clickCountOne ++;
			$counter.text('Current Click Count = '+ clickCountOne);
		} else if (clickedItemId == "nyan-cat-2") {
			clickCountTwo ++;
			$counter2.text('Current Click Count = '+ clickCountTwo);
		} else if (clickedItemId == "nyan-cat-3"){
			clickCountThree ++;
			$counter3.text('Current Click Count = ' + clickCountThree);
		} else if (clickedItemId == "nyan-cat-4"){
			clickCountFour ++;
			$counter4.text('Current Click Count = ' + clickCountFour);
		} else if (clickedItemId == "nyan-cat-5"){
			clickCountFive ++;
			$counter5.text('Current Click Count = ' + clickCountFive);
		}
	});
};

nameCats();
clickTracker();<|endoftext|>


<commit_before>(function($, _){

  var ui = {
    sudokuContainer: '#sudoku-container',
    speedText: '#speed',
    speedSelector: '#speed-selector',
    startButton: '#start-button'
  }

  var sudokuBoards = {
    board1: [[1, null, null, null, null, null, 4, null, null],
      [7, 3, 9, null, 8, null, 2, null, null],
      [6, null, 4, 3, null, null, null, null, null],
      [null, null, 2, 5, null, null, 7, null, 9],
      [null, 9, 1, 7, null, 4, 3, 6, null],
      [8, null, 3, null, null, 6, 5, null, null],
      [null, null, null, null, null, 7, 6, null, 3],
      [null, null, 7, null, 6, null, 8, 9, 2],
      [null, null, 6, null, null, null, null, null, 5]],
    board2: [[null, null, null, null, null, 8, 9, null, 2],
      [6, null, 4, 3, null, null, null, null, null],
      [null, null, null, 5, 9, null, null, null, null],
      [null, null, 5, 7, null, 3, null, null, 9],
      [7, null, null, null, 4, null, null, null, null],
      [null, null, 9, null, null, null, 3, null, 5],
      [null, 8, null, null, null, 4, null, null, null],
      [null, 4, 1, null, null, null, null, 3, null],
      [2, null, null, 1, 5, null, null, null, null]],
    board3: [[null, 9, 8, null, null, null, 4, 7, null],
      [null, null, null, null, null, null, 1, null, 5],
      [null, null, null, 7, null, null, 9, 6, null],
      [null, 6, null, null, null, null, null, 9, null],
      [null, null, null, 1, null, null, null, 2, null],
      [null, null, 3, null, 2, 4, null, null, null],
      [4, null, null, null, null, null, null, null, 8],
      [2, null, null, null, 5, 9, null, null, null],
      [null, null, null, null, 7, null, null, 1, null]]
  }

  function Sudoku(board) {

    this.__init__ = function() {
      this.board = board;
    };
    this.__init__();

    this.getSuccessors = function() {
      var empty = this._getFirstEmpty();
      var possibleVals = this._getPossibleVals(empty);

      var successors = [];
      for (var i = 0; i < possibleVals.length; i += 1) {
        var val = possibleVals[i];
        var successor = this._getSuccessor(empty, val);
        successors.push(successor);
      }
      return successors.reverse();
    }

    this._getFirstEmpty = function() {
      for (var row = 0; row < 9; row += 1){
        for (var col = 0; col < 9; col += 1) {
          if (this.board[row][col] === null)
            return {row: row, col: col};
        }
      }
      return null;
    }

    this._getRowNums = function(empty) {
      var x = empty.row;
      return this.board[x];
    }

    this._getColNums = function(empty) {
      var y = empty.col;
      return _.map(this.board, function(row){ return row[y]; });
    }

    this._getBoxNums = function(empty) {
      var rowMin = Math.floor(empty.row / 3) * 3,
          rowMax = rowMin + 3,
          colMin = Math.floor(empty.col / 3) * 3,
          colMax = colMin + 3;

      var box = [];
      for (var x = rowMin; x < rowMax; x += 1) {
        for (var y = colMin; y < colMax; y += 1) {
          box.push(this.board[x][y]);
        }
      }
      return box;
    }

    this._getPossibleVals = function(empty) {
      var values = _.range(1,10),
          row = this._getRowNums(empty),
          col = this._getColNums(empty),
          box = this._getBoxNums(empty);
      _.remove(values, function(v){
        return _.indexOf(_.union(row, col, box), v) != -1;
      });
      return values;
    }

    this._getSuccessor = function(empty, val) {
      var successor = _.cloneDeep(this);
      successor.board[empty.row][empty.col] = val;
      return successor
    }

    this.isFinalState = function() {
      return this._getFirstEmpty() === null;
    }
  }

  function DepthFirstSearchModule(startState) {

    this._exploreNode = function(){
      if (this.fringe.length){
        this.currentState = this.fringe.pop();
        this.nodesExplored += 1;
        if (this.currentState.isFinalState()){
          return "solved";
        }
        else {
          successors = this.currentState.getSuccessors();
          this.fringe = this.fringe.concat(successors);
        }
      }
      else return "failed";
    }

    this._exploreNodes = function(){
      var speed = parseInt( $('#speed-selector').val() );
      var numberOfNodes = speed * this.INTERVAL / 1000;
      for (var x = 0; x < numberOfNodes; x += 1) {

        var result = this._exploreNode();
        if (result === "solved" || result === "failed") {
          this._printState(this.currentState);
          clearInterval(this.id);
          return;
        }
      }
      this._printState(this.currentState);
    }

    this._printState = function(state) {
      var board = state.board;
      var $html = $('

').addClass('sudoku');
      for (var row = 0; row < 9; row += 1) {
        var $rowHtml = $('

').addClass('row' + row);
        for (var col = 0; col < 9; col += 1) {
          var num = board[row][col]
          var elString = num ? num : ' ';
          var $blockHtml = $('

').addClass('block')
                                           .addClass('col' + col)
                                           .html('
' + elString + '
');
          $rowHtml.append($blockHtml);
        }
        $html.append($rowHtml);
      }

      $nodesHtml = $('

').addClass('nodes-explored')
                                   .html('
Nodes Explored: ' + this.nodesExplored + '
');

      $html.append($nodesHtml);
      $(ui.sudokuContainer).html($html);

    }

    this.__init__ = function() {
      this.nodesExplored = 0;
      this.INTERVAL = 100;
    };
    this.__init__();

    this.search = function() {
      this.fringe = [startState];
      this.currentState = null;

      this.id = setInterval( this._exploreNodes.bind(this), this.INTERVAL );
    }
  }

  function initialize() {
    function updateSpeedText(){
      var speedText = $(ui.speedSelector).val();
      $(ui.speedText).text(speedText);
    };

    var startState = new Sudoku(sudokuBoards.board3);
    var DFSModule = new DepthFirstSearchModule(startState);
    DFSModule._printState(startState);

    $(ui.speedSelector).on('input', updateSpeedText );

    $(ui.startButton).on('click', DFSModule.search.bind(DFSModule) );
  }

  initialize();

})(jQuery, _);
<commit_msg>union was an expensive call so get rid of it<commit_after>(function($, _){

  var ui = {
    sudokuContainer: '#sudoku-container',
    speedText: '#speed',
    speedSelector: '#speed-selector',
    startButton: '#start-button'
  }

  var sudokuBoards = {
    board1: [[1, null, null, null, null, null, 4, null, null],
      [7, 3, 9, null, 8, null, 2, null, null],
      [6, null, 4, 3, null, null, null, null, null],
      [null, null, 2, 5, null, null, 7, null, 9],
      [null, 9, 1, 7, null, 4, 3, 6, null],
      [8, null, 3, null, null, 6, 5, null, null],
      [null, null, null, null, null, 7, 6, null, 3],
      [null, null, 7, null, 6, null, 8, 9, 2],
      [null, null, 6, null, null, null, null, null, 5]],
    board2: [[null, null, null, null, null, 8, 9, null, 2],
      [6, null, 4, 3, null, null, null, null, null],
      [null, null, null, 5, 9, null, null, null, null],
      [null, null, 5, 7, null, 3, null, null, 9],
      [7, null, null, null, 4, null, null, null, null],
      [null, null, 9, null, null, null, 3, null, 5],
      [null, 8, null, null, null, 4, null, null, null],
      [null, 4, 1, null, null, null, null, 3, null],
      [2, null, null, 1, 5, null, null, null, null]],
    board3: [[null, 9, 8, null, null, null, 4, 7, null],
      [null, null, null, null, null, null, 1, null, 5],
      [null, null, null, 7, null, null, 9, 6, null],
      [null, 6, null, null, null, null, null, 9, null],
      [null, null, null, 1, null, null, null, 2, null],
      [null, null, 3, null, 2, 4, null, null, null],
      [4, null, null, null, null, null, null, null, 8],
      [2, null, null, null, 5, 9, null, null, null],
      [null, null, null, null, 7, null, null, 1, null]]
  }

  function Sudoku(board) {

    this.__init__ = function() {
      this.board = board;
    };
    this.__init__();

    this.getSuccessors = function() {
      var empty = this._getFirstEmpty();
      var possibleVals = this._getPossibleVals(empty);

      var successors = [];
      for (var i = 0; i < possibleVals.length; i += 1) {
        var val = possibleVals[i];
        var successor = this._getSuccessor(empty, val);
        successors.push(successor);
      }
      return successors.reverse();
    }

    this._getFirstEmpty = function() {
      for (var row = 0; row < 9; row += 1){
        for (var col = 0; col < 9; col += 1) {
          if (this.board[row][col] === null)
            return {row: row, col: col};
        }
      }
      return null;
    }

    this._getRowNums = function(empty) {
      var x = empty.row;
      return this.board[x];
    }

    this._getColNums = function(empty) {
      var y = empty.col;
      return _.map(this.board, function(row){ return row[y]; });
    }

    this._getBoxNums = function(empty) {
      var rowMin = Math.floor(empty.row / 3) * 3,
          rowMax = rowMin + 3,
          colMin = Math.floor(empty.col / 3) * 3,
          colMax = colMin + 3;

      var box = [];
      for (var x = rowMin; x < rowMax; x += 1) {
        for (var y = colMin; y < colMax; y += 1) {
          box.push(this.board[x][y]);
        }
      }
      return box;
    }

    this._getPossibleVals = function(empty) {
      var values = _.range(1,10),
          row = this._getRowNums(empty),
          col = this._getColNums(empty),
          box = this._getBoxNums(empty);
      _.remove(values, function(v){
        return _.indexOf(row, v) != -1 || _.indexOf(col, v) != -1 || _.indexOf(box, v) != -1;
      });
      return values;
    }

    this._getSuccessor = function(empty, val) {
      var successor = _.cloneDeep(this);
      successor.board[empty.row][empty.col] = val;
      return successor
    }

    this.isFinalState = function() {
      return this._getFirstEmpty() === null;
    }
  }

  function DepthFirstSearchModule(startState) {

    this._exploreNode = function(){
      if (this.fringe.length){
        this.currentState = this.fringe.pop();
        this.nodesExplored += 1;
        if (this.currentState.isFinalState()){
          return "solved";
        }
        else {
          successors = this.currentState.getSuccessors();
          this.fringe = this.fringe.concat(successors);
        }
      }
      else return "failed";
    }

    this._exploreNodes = function(){
      var speed = parseInt( $('#speed-selector').val() );
      var numberOfNodes = speed * this.INTERVAL / 1000;
      for (var x = 0; x < numberOfNodes; x += 1) {

        var result = this._exploreNode();
        if (result === "solved" || result === "failed") {
          this._printState(this.currentState);
          clearInterval(this.id);
          return;
        }
      }
      this._printState(this.currentState);
    }

    this._printState = function(state) {
      var board = state.board;
      var $html = $('

').addClass('sudoku');
      for (var row = 0; row < 9; row += 1) {
        var $rowHtml = $('

').addClass('row' + row);
        for (var col = 0; col < 9; col += 1) {
          var num = board[row][col]
          var elString = num ? num : ' ';
          var $blockHtml = $('

').addClass('block')
                                           .addClass('col' + col)
                                           .html('
' + elString + '
');
          $rowHtml.append($blockHtml);
        }
        $html.append($rowHtml);
      }

      $nodesHtml = $('

').addClass('nodes-explored')
                                   .html('
Nodes Explored: ' + this.nodesExplored + '
');

      $html.append($nodesHtml);
      $(ui.sudokuContainer).html($html);

    }

    this.__init__ = function() {
      this.nodesExplored = 0;
      this.INTERVAL = 100;
    };
    this.__init__();

    this.search = function() {
      this.fringe = [startState];
      this.currentState = null;

      this.id = setInterval( this._exploreNodes.bind(this), this.INTERVAL );
    }
  }

  function initialize() {
    function updateSpeedText(){
      var speedText = $(ui.speedSelector).val();
      $(ui.speedText).text(speedText);
    };

    var startState = new Sudoku(sudokuBoards.board3);
    var DFSModule = new DepthFirstSearchModule(startState);
    DFSModule._printState(startState);

    $(ui.speedSelector).on('input', updateSpeedText );

    $(ui.startButton).on('click', DFSModule.search.bind(DFSModule) );
  }

  initialize();

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