<commit_before>var React = require('react');
var ReactDOM = require('react-dom');
//function to render text
var Card = function(props) {
  return (

          {props.text}

  );
};
//function to render multiple cards
var List = function(props) {
  for (var i = 0; i < 3; i++) {
    props.cards.push(<Card />);
  }
  return (

        {props.title}

        {props.cards}

  );
};
//function to render multiple lists of cards
var Board = function(props) {
  for (var i = 0; i < 3; i++) {
    props.cardsList.push(<List />);
  }
  return (

          {{props.title}}

          {props.cardsList}

  );
};
//render the data onto div with id app
document.addEventListener('DOMContentLoaded', function() {
    ReactDOM.render(<Board />, document.getElementById('app'));
});
<commit_msg>Changed methods to using props, changed for loops to maps in public/js/index.js<commit_after>var React = require('react');
var ReactDOM = require('react-dom');
//function to render text
var Card = function(props) {
    return (

                {props.text}

    );
};
//function to render multiple cards
var List = function(props) {
    var cards = props.card.map((elem, index) => {
        return (<Card key={elem.key} text={elem.text}/>)
    });
    return (

{props.title}

                {cards}

    );
};
//function to render multiple lists of cards
var Board = function(props) {
    var list = props.cardsList.map((elem) => {
        return (<List title={elem.title} card={elem.cards} key={elem.key}/>)
    });
    return (

{props.title}

                {list}

    );
};
var data = {
    title: 'blah',
    cardsList: [
        {
            key: 1,
            title: 'something',
            cards: [
                {
                    key: 1,
                    text: 'ummmm'
                }, {
                    key: 2,
                    text: 'food'
                }
            ]
        },
        {
            key: 2,
            title: 'hungry',
            cards: [
                {
                    key: 1,
                    text: 'special'
                }, {
                    key: 2,
                    text: 'taco'
                }
            ]
        }
    ]
};
//render the data onto div with id app
document.addEventListener('DOMContentLoaded', function() {
    ReactDOM.render(
        <Board title={data.title} cardsList={data.cardsList}/>, document.getElementById('app'));
});
<|endoftext|>


<commit_before>var suits = ['clubs', 'spades', 'diamonds', 'hearts'];

$('#simulate').click(function () {
   var boardData = {
            table: { flop: ['ah', 'td', 'jh'] },
            hands: [['ac', 'jd'], ['90%']]
        };
   submitData(boardData, function(data){
        $('#output').append($('<pre>').text(JSON.stringify(data, null, '  ')));
   });
});

$('#cardPicker').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // Button that triggered the modal
    // get the data passed in
    var playerId = button.attr('data-playerId');
    var numCards = button.attr('data-numCards');

    //update modal headers
    var $modal = $(this);
    $('#selection-title #currCard', this).text(numCards);
    $('#selection-title #numCards', this).text(numCards);

    $modal.data("playerId",playerId);

    //update the number of cards in the footer
    $.each($modal.find("#picked-cards").children(),function(index){
        if ( index >= numCards){
            $(this).hide();
        }else{
            $(this).show();
        }
    });

    <!-- TODO: implement num cards functionality -->
});

$("#saveCards").click(function() {
    console.log("Saving changes for player id: " + $("#cardPicker").data("playerId"));
});

$(window).load(function() {
    $(window).trigger('resize');

    $('#liteAccordion').liteAccordion({
        containerWidth: 700,
        containerHeight: 550
    });
});

$(window).resize(function () {
    var $player = $('.player');
    $player.css({
        'height': $player.outerWidth() + 'px'
    });

    $('.plus-content p', $player).each(function() {
        var $this = $(this);
        $this.css({
            'margin-top': (-($this.parent().parent().outerHeight(true) - $this.height()) / 2) + 'px'
        });
    });
});

/*
 * Modal suit pickers:
 */

/*
 * When you click on a suit image, it will display the cards associated with the suit and hide the old display.
 */
(function () {
    var suitDisplayed = suits[0]; // init

    suits.forEach(function (suit) {
        $('.suit-select .' + suit).click(function () {
            $('.card-select .' + suitDisplayed).hide();

            $('.card-select .' + suit).show();
            suitDisplayed = suit;
        });

        $('.card-select .' + suit).hide();
    });

    $('.suit-select .' + suitDisplayed).click();
})();

(function(){

    var cards = [
        {short:"A", long:"Ace"},
        {short:"2", long:"two"},
        {short:"3", long:"three"},
        {short:"4", long:"four"},
        {short:"5", long:"five"},
        {short:"6", long:"six"},
        {short:"7", long:"seven"},
        {short:"8", long:"eight"},
        {short:"9", long:"nine"},
        {short:"T", long:"10 ten"},
        {short:"J", long:"jack"},
        {short:"Q", long:"queen"},
        {short:"K", long:"king"}
    ];

    var suits = [
        {short:"C", long:"Clubs", selector:$(".card-select .clubs")},
        {short:"D", long:"Diamonds", selector:$(".card-select .diamonds")},
        {short:"H", long:"Hearts", selector:$(".card-select .hearts")},
        {short:"S", long:"Spades", selector:$(".card-select .spades")}
    ];

    var allCards = [];
    $.each(cards,function(index,card){
        $.each(suits,function(index,suit){
            var cardObject = {
                card: card,
                suit: suit,
                search: card.short+""+suit.short+" "+card.long+" "+suit.long,
                selector:$("#card-"+card.short+""+suit.short)
            };

            allCards.push(cardObject);
        });
    });

    console.log(allCards);

    var cardsEngine = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('search'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      local: allCards,
      limit: 13
    });

    cardsEngine.initialize();

    var $searchInput = $("#search");

    //second way of doing autocomplete display
    $searchInput.on('input',function(e){
        var search = $searchInput.val();
        if ( search ){
            $(".suit-select").hide();
            //hide all cards
            $.each(allCards,function(index,value){
                value.selector.hide();
            });

            //show only cards that need to be displayed
            cardsEngine.get(search, function(suggestions){
                console.log(suggestions);
                $.each(suggestions, function(index,card){
                    card.selector.show();
                });
            });

        }else{
            //no search input, go back to default view
            $.each(allCards,function(index,value){
                value.selector.hide();
            });

            suits[0].selector.click();
            $(".suit-select").show();
            $("."+suits[0].long.toLowerCase()).show();
        }
    })

})();

<commit_msg>modal search: removing some debug statements<commit_after>var suits = ['clubs', 'spades', 'diamonds', 'hearts'];

$('#simulate').click(function () {
   var boardData = {
            table: { flop: ['ah', 'td', 'jh'] },
            hands: [['ac', 'jd'], ['90%']]
        };
   submitData(boardData, function(data){
        $('#output').append($('<pre>').text(JSON.stringify(data, null, '  ')));
   });
});

$('#cardPicker').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // Button that triggered the modal
    // get the data passed in
    var playerId = button.attr('data-playerId');
    var numCards = button.attr('data-numCards');

    //update modal headers
    var $modal = $(this);
    $('#selection-title #currCard', this).text(numCards);
    $('#selection-title #numCards', this).text(numCards);

    $modal.data("playerId",playerId);

    //update the number of cards in the footer
    $.each($modal.find("#picked-cards").children(),function(index){
        if ( index >= numCards){
            $(this).hide();
        }else{
            $(this).show();
        }
    });

    <!-- TODO: implement num cards functionality -->
});

$("#saveCards").click(function() {
    console.log("Saving changes for player id: " + $("#cardPicker").data("playerId"));
});

$(window).load(function() {
    $(window).trigger('resize');

    $('#liteAccordion').liteAccordion({
        containerWidth: 700,
        containerHeight: 550
    });
});

$(window).resize(function () {
    var $player = $('.player');
    $player.css({
        'height': $player.outerWidth() + 'px'
    });

    $('.plus-content p', $player).each(function() {
        var $this = $(this);
        $this.css({
            'margin-top': (-($this.parent().parent().outerHeight(true) - $this.height()) / 2) + 'px'
        });
    });
});

/*
 * Modal suit pickers:
 */

/*
 * When you click on a suit image, it will display the cards associated with the suit and hide the old display.
 */
(function () {
    var suitDisplayed = suits[0]; // init

    suits.forEach(function (suit) {
        $('.suit-select .' + suit).click(function () {
            $('.card-select .' + suitDisplayed).hide();

            $('.card-select .' + suit).show();
            suitDisplayed = suit;
        });

        $('.card-select .' + suit).hide();
    });

    $('.suit-select .' + suitDisplayed).click();
})();

//modal search functionality
(function(){

    var cards = [
        {short:"A", long:"Ace"},
        {short:"2", long:"two"},
        {short:"3", long:"three"},
        {short:"4", long:"four"},
        {short:"5", long:"five"},
        {short:"6", long:"six"},
        {short:"7", long:"seven"},
        {short:"8", long:"eight"},
        {short:"9", long:"nine"},
        {short:"T", long:"10 ten"},
        {short:"J", long:"jack"},
        {short:"Q", long:"queen"},
        {short:"K", long:"king"}
    ];

    var suits = [
        {short:"C", long:"Clubs", selector:$(".card-select .clubs")},
        {short:"D", long:"Diamonds", selector:$(".card-select .diamonds")},
        {short:"H", long:"Hearts", selector:$(".card-select .hearts")},
        {short:"S", long:"Spades", selector:$(".card-select .spades")}
    ];

    var allCards = [];
    $.each(cards,function(index,card){
        $.each(suits,function(index,suit){
            var cardObject = {
                card: card,
                suit: suit,
                search: card.short+""+suit.short+" "+card.long+" "+suit.long,
                selector:$("#card-"+card.short+""+suit.short)
            };

            allCards.push(cardObject);
        });
    });

    var cardsEngine = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('search'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      local: allCards,
      limit: 13
    });

    cardsEngine.initialize();

    var $searchInput = $("#search");

    //second way of doing autocomplete display
    $searchInput.on('input',function(e){
        var search = $searchInput.val();
        if ( search ){
            $(".suit-select").hide();
            //hide all cards
            $.each(allCards,function(index,value){
                value.selector.hide();
            });

            //show only cards that need to be displayed
            cardsEngine.get(search, function(suggestions){
                $.each(suggestions, function(index,card){
                    card.selector.show();
                });
            });

        }else{
            //no search input, go back to default view
            $.each(allCards,function(index,value){
                value.selector.hide();
            });

            suits[0].selector.click();
            $(".suit-select").show();
            $("."+suits[0].long.toLowerCase()).show();
        }
    })

})();

<|endoftext|>


<commit_before>
(function (window) {

    $('#simulate').click(function () {
       var boardData = {
                table: { flop: ['ah', 'td', 'jh'] },
                hands: [['ac', 'jd'], ['90%']]
            };
       submitData(boardData, function(data){
            $('#output').append($('<pre>').text(JSON.stringify(data, null, '  ')));
       });
    });

    var $cardPicker = $('#cardPicker');

    $cardPicker.on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // Button that triggered the modal
        // get the data passed in
        var playerId = button.attr('data-playerId');
        var numCards = button.attr('data-numCards');

        //update modal headers
        var $modal = $(this);
        $('#selection-title #currCard', this).text(numCards);
        $('#selection-title #numCards', this).text(numCards);

        $modal.data("playerId",playerId);

        //update the number of cards in the footer
        $.each($modal.find("#picked-cards").children(),function(index){
            if ( index >= numCards){
                $(this).hide();
            }else{
                $(this).show();
            }
        });
    });

    var $modalOriginalState = null;
    $cardPicker.on('shown.bs.modal', function () {
        var $modal = $(this);

        $('.plus-content .glyphicon-plus', $modal).each(function () {
            var $this = $(this);

            $this.css({
                top: (($this.parent().parent().height() - $this.height()) / 2) + 'px',
                width: $this.height() + 'px',
            });

            $this.css({
                left: (($this.parent().parent().width() - $this.width()) / 2) + 'px',
            })

        });

        var playerId = $modal.data("playerId");
        //get saved cards
        var hand = pp2.board.player(playerId).hand();
        hand.forEach(function(card){
            modalSearch.setCard($modal.find("#card-"+card.value.short+""+card.suit.short));
        });

        $('#liteAccordion').liteAccordion({
            containerWidth: 700,
            containerHeight: 550
        });
    });

    $("#saveCards").click(function() {
        var $cardPicker = $('#cardPicker');
        var playerId = $cardPicker.data("playerId");
        var hand = [];
        $("#picked-cards > .pick-card > img", $cardPicker).each(function(index, card) {
            var suit = $(card).data("card-suit");
            var value = $(card).data("card-value");
            hand.push(pp2.Cards[suit][value]);
            $modalOriginalState.find("#"+card.id).addClass("disabled");
        });

        console.log(playerId);
        console.log("saved clicked");
        pp2.board.player(playerId).hand(hand);
        GameActions.setPlayerCards(playerId, hand);
        $cardPicker.modal("hide");
    });
    /*
     * Modal close event listener
     */
    $cardPicker.on('hidden.bs.modal', function () {
        //reset modal data to default state
        $(this).replaceWith($modalOriginalState.clone(true,true));

    });

    $(window).load(function() {
        $(window).trigger('resize');
        $modalOriginalState = $("#cardPicker").clone(true,true);

    });

    $(window).resize(function () {
        var $player = $('.player .no-cards');
        $player.css({
            'height': $player.outerWidth() + 'px'
        });

        $('.plus-content .glyphicon-plus', $player).each(function() {
            var $this = $(this);
            $this.css({
                top: (($this.parent().parent().height() - $this.height()) / 2) + 'px',
                width: $this.height() + 'px'
            });
        });

        $('.table-card-set .plus-content .glyphicon-plus').each(function () {
            var $this = $(this);

            $this.css({
                top: (($this.parent().parent().height() - $this.height()) / 2) + 'px'
                //width: $this.height() + 'px'
            });
        });
    });

    /*
     * Modal suit pickers:
     */

    /*
     * When you click on a suit image, it will display the cards associated with the suit and hide the old display.
     */

    (function () {
        var suitDisplayed = pp2.Suits.Clubs.long; // init

        $.each(pp2.Suits,function (index,suitObject) {
            var suit = suitObject.long;
            $('.suit-select .' + suit).click(function () {
                $('.card-select .' + suitDisplayed).hide();

                $('.card-select .' + suit).show();
                suitDisplayed = suit;
            });

            $('.card-select .' + suit).hide();
        });

        $('.suit-select .' + suitDisplayed).click();
    })();

    //modal search functionality
    (function(){

        var allCards = [];
        $.each(pp2.Values,function(index,card){
            $.each(pp2.Suits,function(index,suit){
                var cardObject = {
                    card: card,
                    suit: suit,
                    search: card.short+""+suit.short+" "+card.long+" "+suit.long,
                    selector:"#card-"+card.short+""+suit.short
                };

                allCards.push(cardObject);
            });
        });

        var cardsEngine = new Bloodhound({
          datumTokenizer: Bloodhound.tokenizers.obj.whitespace('search'),
          queryTokenizer: Bloodhound.tokenizers.whitespace,
          local: allCards,
          limit: 13
        });

        cardsEngine.initialize();

        //second way of doing autocomplete display
        $("#search").on('input',function(e){
            var search = $(this).val();
            if ( search ){
                $(".suit-select").hide();
                //hide all cards
                $.each(allCards,function(index,value){
                    $(value.selector).hide();
                });

                //show only cards that need to be displayed
                cardsEngine.get(search, function(suggestions){

                    $.each(suggestions, function(index,card){
                        $(card.selector).show();
                    });
                });

            }else{
                //no search input, go back to default view
                $.each(allCards,function(index,value){
                    $(value.selector).hide();
                });

                $(".suit-select").show();
                $("."+pp2.Suits.Clubs.long.toLowerCase()).show();
            }
        })

    })();

    $('.player .selected').hide();

    $('.player .circle').show();

    $('#reset').click((function () {
        var circleShowing = true;
        return function () {
            var $player = $('.player');
            if (circleShowing) {
                $('.no-cards', $player).hide();
                $('.selected', $player).show();
            } else {
                $('.no-cards', $player).show();
                $('.selected', $player).hide();
            }

            circleShowing = !circleShowing;
        };
    })());

    window.GameActions = {

        /**
         * Set a player's hand on the table to be the cards passed.
         * @param playerNo Player number
         * @param {Card} cards Cards for the player
         */
        setPlayerCards: function (playerId, cards) {
            var $player = $('#' + playerId);

            if (_.isUndefined(cards)) {
                cards = [];
            }

            if (_.isArray(cards) && cards.length == 0) {
                // empty hand
                $('.selected', $player).hide();
                $('.no-cards', $player).show();
                return;
            }

            $('.selected', $player).show();
            $('.no-cards', $player).hide();

            var imgs = $('.selected img', $player);
            var selectables = $('.selected .card-placeholder', $player);
            cards.forEach(function (card, i) {
                console.log(card);
                $(imgs[i]).attr('src', 'images/Cards/' + card.suit.long + '/' + card.value.short + card.suit.short + '.svg');
            });

            // show and hide
            cards.forEach(function (card, i) {
                $(imgs[i]).show();
                $(selectables[i]).hide();
            });

             _.range(cards.length, 2).forEach(function (i) {
                 $(imgs[i]).hide();
                 $(selectables[i]).show();
            });

            $('.selected .plus-content .glyphicon-plus', $player).each(function () {
                var $this = $(this);

                $this.css({
                    'top': (($this.parent().parent().height() - $this.height())/2) + 'px'
                });
            });
        },

        /**
         * Set the labels for a player's result.
         * @param playerNo
         * @param handLikelyHood
         * @param isBest
         * @private
         */
        __setHandResult: function (playerNo, handLikelyHood, isBest) {
            var $rspan = $('#p' + playerNo + ' .result');

            if ($rspan.length === 0) {
                return;
            }

            if (_.isNumber(handLikelyHood)) {
                $rspan.text(handLikelyHood + '%');
            }

            if (isBest) {
                $rspan.removeClass('label-primary');
                $rspan.addClass('label-success');
            } else {
                $rspan.addClass('label-primary');
                $rspan.removeClass('label-success');
            }
        },

        /**
         * Sets the board to show the result likely hoods.
         * @param {Number[]} handLikelyHoods Array of percentages (out of 100).
         */
        setHandResults: function (handLikelyHoods) {
            var bestIndex = _.chain(_.range(handLikelyHoods.length)).zip(handLikelyHoods)
                .max(function (x) { return x[1]; })
                .value()[0];

            var setHand = _.bind(function (v) {
                this.__setHandResult.apply(this, v);
            }, this);

            handLikelyHoods.map(function (likelyHood, i) {
                return [i + 1, likelyHood, i === bestIndex];
            }).forEach(setHand);

            _.range(handLikelyHoods.length, 6).map(function (i) {
                return [i + 1, undefined, false];
            }).forEach(setHand);

        }
    };

    //modal select card functonality
    var modalSearch = (function(){

        function getSelectedCard(){
            var $selectedCard = $(".pick-card.enabled");
            if ( $selectedCard.length == 0 ){
                return null;
            }
            return $selectedCard;
        }

        function selectNextActiveCard(){
            var $selectedCard = getSelectedCard();
            if($selectedCard == null ){
                return;
            }

            $selectedCard.removeClass("enabled");
            $selectedCard = $selectedCard.next();
            if ( $selectedCard.is(":visible") && $selectedCard.hasClass("button") ){
                $selectedCard.removeClass("button")
                $selectedCard.addClass("enabled");
            }
        }

        //all card pick event
        $(".card-select > img").click(function(){
            if ( $(this).hasClass("disabled")){
                return;
            }

            setCard($(this));

        });

        $(".pick-card").click(function(){
            if ( $(this).hasClass("button")){
                $(this).parent().find(".enabled").removeClass("enabled").addClass("button");

                $(this).removeClass("button").addClass("enabled");
            }
        });

        var setCard = function($cardElement){
            var $selectedCard = getSelectedCard();
            //set the card image to the bottom selected card
            if ( $selectedCard  == null ){
               return;
            }

            $selectedCard.find(".plus-content").hide();
            $selectedCard.find(".delete-card").show();
            $cardElement.clone().appendTo($selectedCard);
            $cardElement.addClass("disabled");

            //remove button class from parent
            selectNextActiveCard();
        };

        $(".delete-card").click(function(){
            $(this).hide();

            //get card and renable it
            var $card = $(this).parent().find("img");
            console.log($card.attr('id'));
            console.log($(".card-select.card-display"))
            $(".card-select.card-display").find('#'+$card.attr('id')).removeClass("disabled");
            $card.remove();

            //change the selection back into a button
            $(this).parent().find(".plus-content").show();
            $(this).parent().addClass("button");
        })

        var Globals = {};
        Globals.setCard = setCard;
        return Globals;
    })();

})(window);
<commit_msg>fixed selection order after deleting pick<commit_after>
(function (window) {

    $('#simulate').click(function () {
       var boardData = {
                table: { flop: ['ah', 'td', 'jh'] },
                hands: [['ac', 'jd'], ['90%']]
            };
       submitData(boardData, function(data){
            $('#output').append($('<pre>').text(JSON.stringify(data, null, '  ')));
       });
    });

    var $cardPicker = $('#cardPicker');

    $cardPicker.on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // Button that triggered the modal
        // get the data passed in
        var playerId = button.attr('data-playerId');
        var numCards = button.attr('data-numCards');

        //update modal headers
        var $modal = $(this);
        $('#selection-title #currCard', this).text(numCards);
        $('#selection-title #numCards', this).text(numCards);

        $modal.data("playerId",playerId);

        //update the number of cards in the footer
        $.each($modal.find("#picked-cards").children(),function(index){
            if ( index >= numCards){
                $(this).hide();
            }else{
                $(this).show();
            }
        });
    });

    var $modalOriginalState = null;
    $cardPicker.on('shown.bs.modal', function () {
        var $modal = $(this);

        $('.plus-content .glyphicon-plus', $modal).each(function () {
            var $this = $(this);

            $this.css({
                top: (($this.parent().parent().height() - $this.height()) / 2) + 'px',
                width: $this.height() + 'px',
            });

            $this.css({
                left: (($this.parent().parent().width() - $this.width()) / 2) + 'px',
            })

        });

        var playerId = $modal.data("playerId");
        //get saved cards
        var hand = pp2.board.player(playerId).hand();
        hand.forEach(function(card){
            modalSearch.setCard($modal.find("#card-"+card.value.short+""+card.suit.short));
        });

        $('#liteAccordion').liteAccordion({
            containerWidth: 700,
            containerHeight: 550
        });
    });

    $("#saveCards").click(function() {
        var $cardPicker = $('#cardPicker');
        var playerId = $cardPicker.data("playerId");
        var hand = [];
        $("#picked-cards > .pick-card > img", $cardPicker).each(function(index, card) {
            var suit = $(card).data("card-suit");
            var value = $(card).data("card-value");
            hand.push(pp2.Cards[suit][value]);
            $modalOriginalState.find("#"+card.id).addClass("disabled");
        });

        console.log(playerId);
        console.log("saved clicked");
        pp2.board.player(playerId).hand(hand);
        GameActions.setPlayerCards(playerId, hand);
        $cardPicker.modal("hide");
    });
    /*
     * Modal close event listener
     */
    $cardPicker.on('hidden.bs.modal', function () {
        //reset modal data to default state
        $(this).replaceWith($modalOriginalState.clone(true,true));

    });

    $(window).load(function() {
        $(window).trigger('resize');
        $modalOriginalState = $("#cardPicker").clone(true,true);

    });

    $(window).resize(function () {
        var $player = $('.player .no-cards');
        $player.css({
            'height': $player.outerWidth() + 'px'
        });

        $('.plus-content .glyphicon-plus', $player).each(function() {
            var $this = $(this);
            $this.css({
                top: (($this.parent().parent().height() - $this.height()) / 2) + 'px',
                width: $this.height() + 'px'
            });
        });

        $('.table-card-set .plus-content .glyphicon-plus').each(function () {
            var $this = $(this);

            $this.css({
                top: (($this.parent().parent().height() - $this.height()) / 2) + 'px'
                //width: $this.height() + 'px'
            });
        });
    });

    /*
     * Modal suit pickers:
     */

    /*
     * When you click on a suit image, it will display the cards associated with the suit and hide the old display.
     */

    (function () {
        var suitDisplayed = pp2.Suits.Clubs.long; // init

        $.each(pp2.Suits,function (index,suitObject) {
            var suit = suitObject.long;
            $('.suit-select .' + suit).click(function () {
                $('.card-select .' + suitDisplayed).hide();

                $('.card-select .' + suit).show();
                suitDisplayed = suit;
            });

            $('.card-select .' + suit).hide();
        });

        $('.suit-select .' + suitDisplayed).click();
    })();

    //modal search functionality
    (function(){

        var allCards = [];
        $.each(pp2.Values,function(index,card){
            $.each(pp2.Suits,function(index,suit){
                var cardObject = {
                    card: card,
                    suit: suit,
                    search: card.short+""+suit.short+" "+card.long+" "+suit.long,
                    selector:"#card-"+card.short+""+suit.short
                };

                allCards.push(cardObject);
            });
        });

        var cardsEngine = new Bloodhound({
          datumTokenizer: Bloodhound.tokenizers.obj.whitespace('search'),
          queryTokenizer: Bloodhound.tokenizers.whitespace,
          local: allCards,
          limit: 13
        });

        cardsEngine.initialize();

        //second way of doing autocomplete display
        $("#search").on('input',function(e){
            var search = $(this).val();
            if ( search ){
                $(".suit-select").hide();
                //hide all cards
                $.each(allCards,function(index,value){
                    $(value.selector).hide();
                });

                //show only cards that need to be displayed
                cardsEngine.get(search, function(suggestions){

                    $.each(suggestions, function(index,card){
                        $(card.selector).show();
                    });
                });

            }else{
                //no search input, go back to default view
                $.each(allCards,function(index,value){
                    $(value.selector).hide();
                });

                $(".suit-select").show();
                $("."+pp2.Suits.Clubs.long.toLowerCase()).show();
            }
        })

    })();

    $('.player .selected').hide();

    $('.player .circle').show();

    $('#reset').click((function () {
        var circleShowing = true;
        return function () {
            var $player = $('.player');
            if (circleShowing) {
                $('.no-cards', $player).hide();
                $('.selected', $player).show();
            } else {
                $('.no-cards', $player).show();
                $('.selected', $player).hide();
            }

            circleShowing = !circleShowing;
        };
    })());

    window.GameActions = {

        /**
         * Set a player's hand on the table to be the cards passed.
         * @param playerNo Player number
         * @param {Card} cards Cards for the player
         */
        setPlayerCards: function (playerId, cards) {
            var $player = $('#' + playerId);

            if (_.isUndefined(cards)) {
                cards = [];
            }

            if (_.isArray(cards) && cards.length == 0) {
                // empty hand
                $('.selected', $player).hide();
                $('.no-cards', $player).show();
                return;
            }

            $('.selected', $player).show();
            $('.no-cards', $player).hide();

            var imgs = $('.selected img', $player);
            var selectables = $('.selected .card-placeholder', $player);
            cards.forEach(function (card, i) {
                console.log(card);
                $(imgs[i]).attr('src', 'images/Cards/' + card.suit.long + '/' + card.value.short + card.suit.short + '.svg');
            });

            // show and hide
            cards.forEach(function (card, i) {
                $(imgs[i]).show();
                $(selectables[i]).hide();
            });

             _.range(cards.length, 2).forEach(function (i) {
                 $(imgs[i]).hide();
                 $(selectables[i]).show();
            });

            $('.selected .plus-content .glyphicon-plus', $player).each(function () {
                var $this = $(this);

                $this.css({
                    'top': (($this.parent().parent().height() - $this.height())/2) + 'px'
                });
            });
        },

        /**
         * Set the labels for a player's result.
         * @param playerNo
         * @param handLikelyHood
         * @param isBest
         * @private
         */
        __setHandResult: function (playerNo, handLikelyHood, isBest) {
            var $rspan = $('#p' + playerNo + ' .result');

            if ($rspan.length === 0) {
                return;
            }

            if (_.isNumber(handLikelyHood)) {
                $rspan.text(handLikelyHood + '%');
            }

            if (isBest) {
                $rspan.removeClass('label-primary');
                $rspan.addClass('label-success');
            } else {
                $rspan.addClass('label-primary');
                $rspan.removeClass('label-success');
            }
        },

        /**
         * Sets the board to show the result likely hoods.
         * @param {Number[]} handLikelyHoods Array of percentages (out of 100).
         */
        setHandResults: function (handLikelyHoods) {
            var bestIndex = _.chain(_.range(handLikelyHoods.length)).zip(handLikelyHoods)
                .max(function (x) { return x[1]; })
                .value()[0];

            var setHand = _.bind(function (v) {
                this.__setHandResult.apply(this, v);
            }, this);

            handLikelyHoods.map(function (likelyHood, i) {
                return [i + 1, likelyHood, i === bestIndex];
            }).forEach(setHand);

            _.range(handLikelyHoods.length, 6).map(function (i) {
                return [i + 1, undefined, false];
            }).forEach(setHand);

        }
    };

    //modal select card functonality
    var modalSearch = (function(){

        function getSelectedCard(){
            var $selectedCard = $(".pick-card.enabled");
            if ( $selectedCard.length == 0 ){
                return null;
            }
            return $selectedCard;
        }

        function selectNextActiveCard(){
            var $selectedCard = getSelectedCard();
            if($selectedCard == null ){
                return;
            }

            $selectedCard.removeClass("enabled");
            $selectedCard = $selectedCard.next();
            if ( $selectedCard.is(":visible") && $selectedCard.hasClass("button") ){
                $selectedCard.removeClass("button")
                $selectedCard.addClass("enabled");
            }
        }

        //all card pick event
        $(".card-select > img").click(function(){
            if ( $(this).hasClass("disabled")){
                return;
            }

            setCard($(this));

        });

        $(".pick-card").click(function(){
            if ( $(this).hasClass("button")){
                $(this).parent().find(".enabled").removeClass("enabled").addClass("button");

                $(this).removeClass("button").addClass("enabled");
            }
        });

        var setCard = function($cardElement){
            var $selectedCard = getSelectedCard();
            //set the card image to the bottom selected card
            if ( $selectedCard  == null ){
               return;
            }

            $selectedCard.find(".plus-content").hide();
            $selectedCard.find(".delete-card").show();
            $cardElement.clone().appendTo($selectedCard);
            $cardElement.addClass("disabled");

            //remove button class from parent
            selectNextActiveCard();
        };

        function recalculateActiveCard(){
            console.log("recalculating route");
            $(".pick-card.enabled").removeClass("enabled").addClass("button");
            $(".pick-card.button").first().removeClass("button").addClass("enabled");
            return false;
        }

        $(".delete-card").click(function(){
            $(this).hide();

            //get card and re-enable it
            var $card = $(this).parent().find("img");
            $(".card-select.card-display").find('#'+$card.attr('id')).removeClass("disabled");
            $card.remove();

            //change the selection back into a button
            $(this).parent().find(".plus-content").show();
            $(this).parent().addClass("button");
            return recalculateActiveCard();
        })

        var Globals = {};
        Globals.setCard = setCard;
        return Globals;
    })();

})(window);
<|endoftext|>


<commit_before>//= require <jquery>
//= require "vendor/polyfills"

// var jQuery = window.jQuery,
//     $ = jQuery;

if (window.console === undefined) (function () {
  window.console = {
    log: function () {
      // alert([].slice.call(arguments).join('\n'));
    }
  };
})();

// required because jQuery 1.4.4 lost ability to search my object property :( (i.e. a[host=foo.com])
jQuery.expr[':'].host = function(obj, index, meta, stack) {
  return obj.host == meta[3];
};

function throttle(fn, delay) {
  var timer = null;
  var throttled = function () {
    var context = this, args = arguments;
    throttled.cancel();
    throttled.timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };

  throttled.cancel = function () {
    clearTimeout(throttled.timer);
  };

  return throttled;
}

window['jsbin'] || (window.jsbin = {});
// dodgy?
var storedSettings = localStorage.getItem('settings');
if (storedSettings === "undefined") {
  // yes, equals the *string* "undefined", then something went wrong
  storedSettings = null;
}
window.jsbin.settings = $.extend(JSON.parse(storedSettings || '{}'), jsbin.settings);

// if the above code isn't dodgy, this for hellz bells is:
jsbin.mobile = /WebKit.*Mobile.*|Android/.test(navigator.userAgent);
jsbin.tablet = /iPad/i.test(navigator.userAgent); // sue me.
// IE detect - sadly uglify is compressing the \v1 trick to death :(
// via @padolsey & @jdalton - https://gist.github.com/527683
jsbin.ie = (function(){
  var undef,
      v = 3,
      div = document.createElement('div'),
      all = div.getElementsByTagName('i');
  while (
    div.innerHTML = '',
    all[0]
  );
  return v > 4 ? v : undef;
}());

if (!storedSettings && (location.origin + location.pathname) === jsbin.root + '/') {
  // first timer - let's welcome them shall we, Dave?
  localStorage.setItem('settings', '{}');
  window.location = jsbin.root + '/welcome/edit?html,live'
    + (location.search.indexOf('api=') !== -1 ?  ',&' + location.search.substring(1) : '');
}

if (!jsbin.settings.editor) {
  // backward compat with jsbin-v2
  jsbin.settings.editor = {};
}

if (jsbin.settings.codemirror) {
  $.extend(jsbin.settings.editor, jsbin.settings.codemirror);
}

// Add a pre-filter to all ajax requests to add a CSRF header to prevent
// malicious form submissions from other domains.
jQuery.ajaxPrefilter(function (options, original, xhr) {
  var skip = {head: 1, get: 1};
  if (!skip[options.type.toLowerCase()]) {
    xhr.setRequestHeader('X-CSRF-Token', jsbin.state.token);
  }
});

jsbin.getURL = function () {
  var url = jsbin.root,
      state = jsbin.state;

  if (state.code) {
    url += '/' + state.code;

    if (state.revision) { //} && state.revision !== 1) {
      url += '/' + state.revision;
    }
  }
  return url;
};

function objectValue(path, context) {
  var props = path.split('.'),
      length = props.length,
      i = 1,
      currentProp = context || window,
      value = currentProp[path];
  try {
    if (currentProp[props[0]] !== undefined) {
      currentProp = currentProp[props[0]];
      for (; i < length; i++) {
        if (currentProp[props[i]] === undefined) {
          break;
        } else if (i === length - 1) {
          value = currentProp[props[i]];
        }
        currentProp = currentProp[props[i]];
      }
    }
  } catch (e) {
    value = undefined;
  }

  return value;
}

var $body = $('body'),
    $document = $(document),
    debug = jsbin.settings.debug === undefined ? false : jsbin.settings.debug,
    documentTitle = 'JS Bin',
    $bin = $('#bin'),
    loadGist,
    $document = $(document),
    // splitterSettings = JSON.parse(localStorage.getItem('splitterSettings') || '[ { "x" : null }, { "x" : null } ]'),
    unload = function () {
      // sessionStorage.setItem('javascript', editors.javascript.getCode());
      if (jsbin.panels.focused.editor) {
        try { // this causes errors in IE9 - so we'll use a try/catch to get through it
          sessionStorage.setItem('line', jsbin.panels.focused.editor.getCursor().line);
          sessionStorage.setItem('character', jsbin.panels.focused.editor.getCursor().ch);
        } catch (e) {
          debugger;
          sessionStorage.setItem('line', 0);
          sessionStorage.setItem('character', 0);
        }
      }

      sessionStorage.setItem('url', jsbin.getURL());
      localStorage.setItem('settings', JSON.stringify(jsbin.settings));

      // if (jsbin.panels.saveOnExit) ;
      jsbin.panels.save();
      jsbin.panels.savecontent();

      var panel = jsbin.panels.focused;
      if (panel) sessionStorage.setItem('panel', panel.id);
    };

$(window).unload(unload);

// hack for Opera because the unload event isn't firing to capture the settings, so we put it on a timer
if ($.browser.opera) {
  setInterval(unload, 500);
}

if (location.search.indexOf('api=') !== -1) {
  (function () {
    var urlParts = location.search.substring(1).split(','),
        newUrlParts = [],
        i = urlParts.length,
        apiurl = '';

    while (i--) {
      if (urlParts[i].indexOf('api=') !== -1) {
        apiurl = urlParts[i].replace(/&?api=/, '');
      } else {
        newUrlParts.push(urlParts[i]);
      }
    }

    $.getScript(jsbin.root + '/js/chrome/sandbox.js', function () {
      var sandbox = new Sandbox(apiurl);
      sandbox.get('settings', function (data) {
        $.extend(jsbin.settings, data);
        unload();
        window.location = location.pathname + (newUrlParts.length ? '?' + newUrlParts.join(',') : '');
      });
    });

  }());
}

$document.one('jsbinReady', function () {
  $bin.removeAttr('style');
  $body.addClass('ready');
});

if (navigator.userAgent.indexOf(' Mac ') !== -1) (function () {
  var el = $('#keyboardHelp')[0];
  el.innerHTML = el.innerHTML.replace(/ctrl/g, 'cmd');
})();

if (false) { //window.top !== window && location.pathname.indexOf('/embed') === -1) {
  // we're framed, to switch in to embed mode
  jsbin.embed = true;
  jsbin.saveDisabled = true;
  $('#saveform').attr('target', '_blank');
  $('html').addClass('embed');
  // remove elements that we don't need
  $('#homemenu').closest('.menu').remove();
  $('#login').closest('.menu').remove();
  $('#register').closest('.menu').remove();
  $('#library').closest('.menu').remove();
  $('#sharemenu').remove();
  $('a.brand').removeClass('button-dropdown').click(function (event) {
    this.hash = '';
    event.stopImmediatePropagation();
    return true;
  }).after('Save');
}<commit_msg>damn debugger statement nukes the compression<commit_after>//= require <jquery>
//= require "vendor/polyfills"

// var jQuery = window.jQuery,
//     $ = jQuery;

if (window.console === undefined) (function () {
  window.console = {
    log: function () {
      // alert([].slice.call(arguments).join('\n'));
    }
  };
})();

// required because jQuery 1.4.4 lost ability to search my object property :( (i.e. a[host=foo.com])
jQuery.expr[':'].host = function(obj, index, meta, stack) {
  return obj.host == meta[3];
};

function throttle(fn, delay) {
  var timer = null;
  var throttled = function () {
    var context = this, args = arguments;
    throttled.cancel();
    throttled.timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };

  throttled.cancel = function () {
    clearTimeout(throttled.timer);
  };

  return throttled;
}

window['jsbin'] || (window.jsbin = {});
// dodgy?
var storedSettings = localStorage.getItem('settings');
if (storedSettings === "undefined") {
  // yes, equals the *string* "undefined", then something went wrong
  storedSettings = null;
}
window.jsbin.settings = $.extend(JSON.parse(storedSettings || '{}'), jsbin.settings);

// if the above code isn't dodgy, this for hellz bells is:
jsbin.mobile = /WebKit.*Mobile.*|Android/.test(navigator.userAgent);
jsbin.tablet = /iPad/i.test(navigator.userAgent); // sue me.
// IE detect - sadly uglify is compressing the \v1 trick to death :(
// via @padolsey & @jdalton - https://gist.github.com/527683
jsbin.ie = (function(){
  var undef,
      v = 3,
      div = document.createElement('div'),
      all = div.getElementsByTagName('i');
  while (
    div.innerHTML = '',
    all[0]
  );
  return v > 4 ? v : undef;
}());

if (!storedSettings && (location.origin + location.pathname) === jsbin.root + '/') {
  // first timer - let's welcome them shall we, Dave?
  localStorage.setItem('settings', '{}');
  window.location = jsbin.root + '/welcome/edit?html,live'
    + (location.search.indexOf('api=') !== -1 ?  ',&' + location.search.substring(1) : '');
}

if (!jsbin.settings.editor) {
  // backward compat with jsbin-v2
  jsbin.settings.editor = {};
}

if (jsbin.settings.codemirror) {
  $.extend(jsbin.settings.editor, jsbin.settings.codemirror);
}

// Add a pre-filter to all ajax requests to add a CSRF header to prevent
// malicious form submissions from other domains.
jQuery.ajaxPrefilter(function (options, original, xhr) {
  var skip = {head: 1, get: 1};
  if (!skip[options.type.toLowerCase()]) {
    xhr.setRequestHeader('X-CSRF-Token', jsbin.state.token);
  }
});

jsbin.getURL = function () {
  var url = jsbin.root,
      state = jsbin.state;

  if (state.code) {
    url += '/' + state.code;

    if (state.revision) { //} && state.revision !== 1) {
      url += '/' + state.revision;
    }
  }
  return url;
};

function objectValue(path, context) {
  var props = path.split('.'),
      length = props.length,
      i = 1,
      currentProp = context || window,
      value = currentProp[path];
  try {
    if (currentProp[props[0]] !== undefined) {
      currentProp = currentProp[props[0]];
      for (; i < length; i++) {
        if (currentProp[props[i]] === undefined) {
          break;
        } else if (i === length - 1) {
          value = currentProp[props[i]];
        }
        currentProp = currentProp[props[i]];
      }
    }
  } catch (e) {
    value = undefined;
  }

  return value;
}

var $body = $('body'),
    $document = $(document),
    debug = jsbin.settings.debug === undefined ? false : jsbin.settings.debug,
    documentTitle = 'JS Bin',
    $bin = $('#bin'),
    loadGist,
    $document = $(document),
    // splitterSettings = JSON.parse(localStorage.getItem('splitterSettings') || '[ { "x" : null }, { "x" : null } ]'),
    unload = function () {
      // sessionStorage.setItem('javascript', editors.javascript.getCode());
      if (jsbin.panels.focused.editor) {
        try { // this causes errors in IE9 - so we'll use a try/catch to get through it
          sessionStorage.setItem('line', jsbin.panels.focused.editor.getCursor().line);
          sessionStorage.setItem('character', jsbin.panels.focused.editor.getCursor().ch);
        } catch (e) {
          sessionStorage.setItem('line', 0);
          sessionStorage.setItem('character', 0);
        }
      }

      sessionStorage.setItem('url', jsbin.getURL());
      localStorage.setItem('settings', JSON.stringify(jsbin.settings));

      // if (jsbin.panels.saveOnExit) ;
      jsbin.panels.save();
      jsbin.panels.savecontent();

      var panel = jsbin.panels.focused;
      if (panel) sessionStorage.setItem('panel', panel.id);
    };

$(window).unload(unload);

// hack for Opera because the unload event isn't firing to capture the settings, so we put it on a timer
if ($.browser.opera) {
  setInterval(unload, 500);
}

if (location.search.indexOf('api=') !== -1) {
  (function () {
    var urlParts = location.search.substring(1).split(','),
        newUrlParts = [],
        i = urlParts.length,
        apiurl = '';

    while (i--) {
      if (urlParts[i].indexOf('api=') !== -1) {
        apiurl = urlParts[i].replace(/&?api=/, '');
      } else {
        newUrlParts.push(urlParts[i]);
      }
    }

    $.getScript(jsbin.root + '/js/chrome/sandbox.js', function () {
      var sandbox = new Sandbox(apiurl);
      sandbox.get('settings', function (data) {
        $.extend(jsbin.settings, data);
        unload();
        window.location = location.pathname + (newUrlParts.length ? '?' + newUrlParts.join(',') : '');
      });
    });

  }());
}

$document.one('jsbinReady', function () {
  $bin.removeAttr('style');
  $body.addClass('ready');
});

if (navigator.userAgent.indexOf(' Mac ') !== -1) (function () {
  var el = $('#keyboardHelp')[0];
  el.innerHTML = el.innerHTML.replace(/ctrl/g, 'cmd');
})();

if (false) { //window.top !== window && location.pathname.indexOf('/embed') === -1) {
  // we're framed, to switch in to embed mode
  jsbin.embed = true;
  jsbin.saveDisabled = true;
  $('#saveform').attr('target', '_blank');
  $('html').addClass('embed');
  // remove elements that we don't need
  $('#homemenu').closest('.menu').remove();
  $('#login').closest('.menu').remove();
  $('#register').closest('.menu').remove();
  $('#library').closest('.menu').remove();
  $('#sharemenu').remove();
  $('a.brand').removeClass('button-dropdown').click(function (event) {
    this.hash = '';
    event.stopImmediatePropagation();
    return true;
  }).after('Save');
}<|endoftext|>


<commit_before>/*
The MIT License (MIT)
Copyright (c) 2014 Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

"use strict";

var Base = require("../base")
  , Constants = require("../constants");

//SCRIPT START
var DefaultQueryExecutionContext = Base.defineClass(
    /**
     * Provides the basic Query Execution Context. This wraps the internal logic query execution using provided fetch functions
     * @constructor DefaultQueryExecutionContext
     * @param {DocumentClient} documentclient        - The service endpoint to use to create the client.
     * @param {SqlQuerySpec | string} query          - A SQL query.
     * @param {FeedOptions} [options]                - Represents the feed options.
     * @param {callback | callback[]} fetchFunctions - A function to retrieve each page of data. An array of functions may be used to query more than one partition.
     * @ignore
     */
    function(documentclient, query, options, fetchFunctions){
        this.documentclient = documentclient;
        this.query = query;
        this.resources = [];
        this.currentIndex = 0;
        this.currentPartitionIndex = 0;
        this.fetchFunctions = (Array.isArray(fetchFunctions)) ? fetchFunctions : [fetchFunctions];
        this.continuation = null;
        this.options = options || {};
        this.state = DefaultQueryExecutionContext.STATES.start;
    },
    {
        /**
         * Execute a provided callback on the next element in the execution context.
         * @memberof DefaultQueryExecutionContext
         * @instance
         * @param {callback} callback - Function to execute for each element. the function takes two parameters error, element.
         */
        nextItem: function (callback) {
            var that = this;
            this.current(function (err, resources, headers) {
                ++that.currentIndex;
                callback(err, resources, headers);
            });
        },

        /**
         * Retrieve the current element on the execution context.
         * @memberof DefaultQueryExecutionContext
         * @instance
         * @param {callback} callback - Function to execute for the current element. the function takes two parameters error, element.
         */
        current: function(callback) {
            var that = this;
            if (this.currentIndex < this.resources.length) {
                return callback(undefined, this.resources[this.currentIndex], undefined);
            }

            if (this._canFetchMore()) {
                this.fetchMore(function (err, resources, headers) {
                    if (err) {
                        return callback(err, undefined, headers);
                    }
                    that.resources = resources;
                    if (that.resources.length === 0) {
                        if (!that.continuation && that.currentPartitionIndex >= that.fetchFunctions.length) {
                            that.state = DefaultQueryExecutionContext.STATES.ended;
                            callback(undefined, undefined, headers);
                        } else {
                            that.current(callback);
                        }
                        return undefined;
                    }
                    callback(undefined, that.resources[that.currentIndex], headers);
                });
            } else {
                this.state = DefaultQueryExecutionContext.STATES.ended;
                callback(undefined, undefined, undefined);
            }
        },

        /**
         * Determine if there are still remaining resources to processs based on the value of the continuation token or the elements remaining on the current batch in the execution context.
         * @memberof DefaultQueryExecutionContext
         * @instance
         * @returns {Boolean} true if there is other elements to process in the DefaultQueryExecutionContext.
         */
        hasMoreResults: function () {
            return this.state === DefaultQueryExecutionContext.STATES.start || this.continuation !== undefined || this.currentIndex < this.resources.length || this.currentPartitionIndex < this.fetchFunctions.length;
        },

        /**
         * Fetches the next batch of the feed and pass them as an array to a callback
         * @memberof DefaultQueryExecutionContext
         * @instance
         * @param {callback} callback - Function execute on the feed response, takes two parameters error, resourcesList
         */
        fetchMore: function(callback){
            var that = this;
            this.options.continuation = this.continuation;
            var fetchFunction = this.fetchFunctions[this.currentPartitionIndex];
            fetchFunction(this.options, function(err, resources, responseHeaders){
                if(err) {
                    that.state = DefaultQueryExecutionContext.STATES.ended;
                    return callback(err, undefined, responseHeaders);
                }

                that.continuation = responseHeaders[Constants.HttpHeaders.Continuation];
                if (!that.continuation) {
                    ++that.currentPartitionIndex;
                }

                that.state = DefaultQueryExecutionContext.STATES.inProgress;
                that.currentIndex = 0;
                callback(undefined, resources, responseHeaders);
            });
        },

        _canFetchMore: function () {
            var res = (this.state === DefaultQueryExecutionContext.STATES.start || (this.continuation && this.state === DefaultQueryExecutionContext.STATES.inProgress) || (this.currentPartitionIndex < this.fetchFunctions.length && this.state === DefaultQueryExecutionContext.STATES.inProgress));
            return res;
        }
    }, {

        STATES:  Object.freeze({ start: "start", inProgress: "inProgress", ended: "ended" })
    }
);

//SCRIPT END

if (typeof exports !== "undefined") {
    module.exports = DefaultQueryExecutionContext;
}
<commit_msg>Fixes issue #107<commit_after>/*
The MIT License (MIT)
Copyright (c) 2014 Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

"use strict";

var Base = require("../base")
  , Constants = require("../constants");

//SCRIPT START
var DefaultQueryExecutionContext = Base.defineClass(
    /**
     * Provides the basic Query Execution Context. This wraps the internal logic query execution using provided fetch functions
     * @constructor DefaultQueryExecutionContext
     * @param {DocumentClient} documentclient        - The service endpoint to use to create the client.
     * @param {SqlQuerySpec | string} query          - A SQL query.
     * @param {FeedOptions} [options]                - Represents the feed options.
     * @param {callback | callback[]} fetchFunctions - A function to retrieve each page of data. An array of functions may be used to query more than one partition.
     * @ignore
     */
    function(documentclient, query, options, fetchFunctions){
        this.documentclient = documentclient;
        this.query = query;
        this.resources = [];
        this.currentIndex = 0;
        this.currentPartitionIndex = 0;
        this.fetchFunctions = (Array.isArray(fetchFunctions)) ? fetchFunctions : [fetchFunctions];
        this.continuation = options ? options.continuation : null;
        this.options = options || {};
        this.state = DefaultQueryExecutionContext.STATES.start;
    },
    {
        /**
         * Execute a provided callback on the next element in the execution context.
         * @memberof DefaultQueryExecutionContext
         * @instance
         * @param {callback} callback - Function to execute for each element. the function takes two parameters error, element.
         */
        nextItem: function (callback) {
            var that = this;
            this.current(function (err, resources, headers) {
                ++that.currentIndex;
                callback(err, resources, headers);
            });
        },

        /**
         * Retrieve the current element on the execution context.
         * @memberof DefaultQueryExecutionContext
         * @instance
         * @param {callback} callback - Function to execute for the current element. the function takes two parameters error, element.
         */
        current: function(callback) {
            var that = this;
            if (this.currentIndex < this.resources.length) {
                return callback(undefined, this.resources[this.currentIndex], undefined);
            }

            if (this._canFetchMore()) {
                this.fetchMore(function (err, resources, headers) {
                    if (err) {
                        return callback(err, undefined, headers);
                    }
                    that.resources = resources;
                    if (that.resources.length === 0) {
                        if (!that.continuation && that.currentPartitionIndex >= that.fetchFunctions.length) {
                            that.state = DefaultQueryExecutionContext.STATES.ended;
                            callback(undefined, undefined, headers);
                        } else {
                            that.current(callback);
                        }
                        return undefined;
                    }
                    callback(undefined, that.resources[that.currentIndex], headers);
                });
            } else {
                this.state = DefaultQueryExecutionContext.STATES.ended;
                callback(undefined, undefined, undefined);
            }
        },

        /**
         * Determine if there are still remaining resources to processs based on the value of the continuation token or the elements remaining on the current batch in the execution context.
         * @memberof DefaultQueryExecutionContext
         * @instance
         * @returns {Boolean} true if there is other elements to process in the DefaultQueryExecutionContext.
         */
        hasMoreResults: function () {
            return this.state === DefaultQueryExecutionContext.STATES.start || this.continuation !== undefined || this.currentIndex < this.resources.length || this.currentPartitionIndex < this.fetchFunctions.length;
        },

        /**
         * Fetches the next batch of the feed and pass them as an array to a callback
         * @memberof DefaultQueryExecutionContext
         * @instance
         * @param {callback} callback - Function execute on the feed response, takes two parameters error, resourcesList
         */
        fetchMore: function(callback){
            var that = this;
            this.options.continuation = this.continuation;
            var fetchFunction = this.fetchFunctions[this.currentPartitionIndex];
            fetchFunction(this.options, function(err, resources, responseHeaders){
                if(err) {
                    that.state = DefaultQueryExecutionContext.STATES.ended;
                    return callback(err, undefined, responseHeaders);
                }

                that.continuation = responseHeaders[Constants.HttpHeaders.Continuation];
                if (!that.continuation) {
                    ++that.currentPartitionIndex;
                }

                that.state = DefaultQueryExecutionContext.STATES.inProgress;
                that.currentIndex = 0;
                callback(undefined, resources, responseHeaders);
            });
        },

        _canFetchMore: function () {
            var res = (this.state === DefaultQueryExecutionContext.STATES.start || (this.continuation && this.state === DefaultQueryExecutionContext.STATES.inProgress) || (this.currentPartitionIndex < this.fetchFunctions.length && this.state === DefaultQueryExecutionContext.STATES.inProgress));
            return res;
        }
    }, {

        STATES:  Object.freeze({ start: "start", inProgress: "inProgress", ended: "ended" })
    }
);

//SCRIPT END

if (typeof exports !== "undefined") {
    module.exports = DefaultQueryExecutionContext;
}
<|endoftext|>


<commit_before>/* Function to print job to panel in view. */
function printJob(title, description, hours, salary, startDate, state, city, percentageMatch){
    var display = document.getElementById("jobs");

    var panel = document.createElement("div");
    panel.className = "panel panel-default";

    var heading = document.createElement("div");
    heading.className = "panel-heading";
    heading.innerHTML += title + " • ";

    var match = document.createElement("strong");
    match.innerHTML = percentageMatch + "%";

    var body = document.createElement("div");
    body.className = "panel-body";

    var p1 = document.createElement("p");
    p1.innerHTML = description;

    var hr1 = document.createElement("hr");

    var p2 = document.createElement("p");
    p2.innerHTML = hours;

    var p3 = document.createElement("p");
    p3.innerHTML = salary;

    var p4 = document.createElement("p");
    p4.innerHTML = startDate;

    var p5 = document.createElement("p");
    p5.innerHTML = state;

    var p6 = document.createElement("p");
    p6.innerHTML = city;

    var hr2 = document.createElement("hr");

    var p7 = document.createElement("p");

    var apply = document.createElement("button");
    apply.className = "btn btn-primary";
    apply.innerHTML = "Apply";

    panel.appendChild(heading);
    panel.appendChild(body);
    heading.append(match);
    body.append(p1);
    body.append(hr1);
    body.append(p2);
    body.append(p3);
    body.append(p4);
    body.append(p5);
    body.append(p6);
    body.append(hr2);
    body.append(p7);
    p7.append(apply);
    display.appendChild(panel);

    document.getElementById("loading").style.display = "none";
    document.getElementById("nomatches").style.display = "none";
}

/* Function to perform matchmaking. */
function match(){
    var stateFilter = document.getElementById("state").value;

    $.getJSON( "api/jobs/" + stateFilter, function(data){
        if(data.length > 0){
            for(i = 0; i < data.length; i++){
                printJob(data[i].title, data[i].description, data[i].hours, data[i].salary, data[i].startdate, data[i].state, data[i].city, 100);
            }
        }
        else{
            document.getElementById("loading").style.display = "none";
            document.getElementById("nomatches").style.display = "block";
        }
    });
}

/* Initialisation function to test for JavaScript, display loading animation, and call match function. */
function init(){
    document.getElementById("noscript").style.display = "none";
    document.getElementById("loading").style.display = "block";

    document.getElementById("jobs").innerHTML = "";

    match();
}

document.addEventListener('DOMContentLoaded', init);
document.getElementById("state").addEventListener('change', init);
<commit_msg>Add id to printJob<commit_after>/* Function to print job to panel in view. */
function printJob(id, title, description, hours, salary, startDate, state, city, percentageMatch){
    var display = document.getElementById("jobs");

    var panel = document.createElement("div");
    panel.className = "panel panel-default";

    var heading = document.createElement("div");
    heading.className = "panel-heading";
    heading.innerHTML += title + " • ";

    var match = document.createElement("strong");
    match.innerHTML = percentageMatch + "%";

    var body = document.createElement("div");
    body.className = "panel-body";

    var p1 = document.createElement("p");
    p1.innerHTML = description;

    var hr1 = document.createElement("hr");

    var p2 = document.createElement("p");
    p2.innerHTML = hours;

    var p3 = document.createElement("p");
    p3.innerHTML = salary;

    var p4 = document.createElement("p");
    p4.innerHTML = startDate;

    var p5 = document.createElement("p");
    p5.innerHTML = state;

    var p6 = document.createElement("p");
    p6.innerHTML = city;

    var hr2 = document.createElement("hr");

    var p7 = document.createElement("p");

    var apply = document.createElement("a");
    apply.className = "btn btn-primary";
    apply.href = "/job/" + id;
    apply.innerHTML = "View";

    panel.appendChild(heading);
    panel.appendChild(body);
    heading.append(match);
    body.append(p1);
    body.append(hr1);
    body.append(p2);
    body.append(p3);
    body.append(p4);
    body.append(p5);
    body.append(p6);
    body.append(hr2);
    body.append(p7);
    p7.append(apply);
    display.appendChild(panel);

    document.getElementById("loading").style.display = "none";
    document.getElementById("nomatches").style.display = "none";
}

/* Function to perform matchmaking. */
function match(){
    var stateFilter = document.getElementById("state").value;

    $.getJSON( "api/jobs/" + stateFilter, function(data){
        if(data.length > 0){
            for(i = 0; i < data.length; i++){
                printJob(data[i].id, data[i].title, data[i].description, data[i].hours, data[i].salary, data[i].startdate, data[i].state, data[i].city, 100);
            }
        }
        else{
            document.getElementById("loading").style.display = "none";
            document.getElementById("nomatches").style.display = "block";
        }
    });
}

/* Initialisation function to test for JavaScript, display loading animation, and call match function. */
function init(){
    document.getElementById("noscript").style.display = "none";
    document.getElementById("loading").style.display = "block";

    document.getElementById("jobs").innerHTML = "";

    match();
}

document.addEventListener('DOMContentLoaded', init);
document.getElementById("state").addEventListener('change', init);
<|endoftext|>


<commit_before>(function(window, document){
  'use strict';

  var _instance,
      config;

  var sense = {
    get: function() {
      return _instance;
    },
    init: function(options){
      return _instance || new Sense(options)
    }
  };

  /**
   * Constructor
   */
  function Sense(options){
    _instance = this;
    config = options || {debug: false};

    if (config.debug) {
      initDebuggingWindow();
    }

  }

  /**
   * Given arguments and default options, return an object containing options and the callback
   * @param args: Array of arguments
   * @param defaultOptions: Object containing default options
   * @returns {{options: *, callback: *}}
   */
  var getArgs = function (args, defaultOptions) {
    var callback;
    if (args.length === 1){
      // We only have the callback, so use default options
      callback = args[0];
      return {
        options: defaultOptions,
        callback: function(data){
          updateDebugger(data);
          callback(data);
        }
        };
    }

    if (args.length === 2){
      // We have both the callback and an arguments hash
      callback = args[1];
      return {
        options: arguments[0],
        callback: function(data){
          updateDebugger(data);
          callback(data);
        }
      }
    }
  };

  /**
   * Show a debugger with data on the
   * @param data
   */
  var initDebuggingWindow = function(){
    if (config.debug){
      var el = document.createElement('div');
      el.innerHTML = "" +
          "
" +
          "
";
      window.onload = function(){
        document.body.appendChild(el);
      }
    }
  };

  /**
   * Update the debugger div
   * @param data: JSON
   */
  var updateDebugger = function(data){
    if (config.debug){
      document.getElementById('sense-debugger')
          .innerText = JSON.stringify(data, undefined, 2);
    }
  };

  var withinThreshold = function(a, b, threshold){
    return b  a - threshold
  };

  /**
   * Orientation ([options], callback)
   * - Options:
   *    alphaThreshold (number)
   *    betaThreshold (number)
   *    gammaThreshold (number)
   *    radians (boolean)
   *
   * - Data:
   *    alpha (num)
   *    beta (num)
   *    gamma (num)
   */
  Sense.prototype.orientation = function() {
    if (window.DeviceOrientationEvent) {
      var defaults = {
            alphaThreshold: 1,
            betaThreshold: 1,
            gammaThreshold: 1,
            radians: false
          },
          args = getArgs(arguments, defaults),
          callback = args.callback,
          options = args.options;

      var prevData = {
        alpha: 0,
        beta: 0,
        gamma: 0
      };

      window.addEventListener('deviceorientation', function (eventData) {

        var data = {
          alpha: eventData.alpha,
          beta: eventData.beta,
          gamma: eventData.gamma
        };

        callback(data)

      })

    }
  };

  /*
    Tilt function!
   */
  Sense.prototype.tilt = function() {
    if (window.DeviceOrientationEvent) {
      var callback,
          options = {
            threshold: 25,
            direction: "both",
            gestureDuration: 300
          },
          args = getArgs(arguments, options),
          lastSample,
          intervalExpired = true;

      callback = args.callback;
      options = args.options;

      setInterval(function(){intervalExpired = true}, options.gestureDuration)

      window.addEventListener('deviceorientation', function(eventData){
        // Here, you take the eventData and the options that you have and
        // process the data, and then feed it to the callback
        if(intervalExpired) {
          lastSample = eventData.gamma;
          intervalExpired = false;
        }
        var delta = lastSample - eventData.gamma;

        if(delta > options.threshold) {
          lastSample = eventData.gamma;
          var data = {
            direction: "LEFT",
            magnitude: Math.round(delta)

          };
          callback(data);
        }

        if(delta < -options.threshold) {
          lastSample = eventData.gamma;
          var data = {
            direction: "RIGHT",
            magnitude: Math.round(-delta)
          };
          callback(data);
        }

      })
    }
  };

  /**
   * Flick ([options], callback)
   * - Options:
   *    interval (int)
   *    sensitivity
   *
   * - Data:
   *    direction String 'left', 'right'
   *    magnitude (float)
   */
  Sense.prototype.flick = function() {
    if (window.DeviceMotionEvent) {
      var FLICK_ACCELERATION = 15;
      var defaults = {
            interval: 150,
            sensitivity: 1
          },
          args = getArgs(arguments, defaults),
          callback = args.callback,
          options = args.options;

      var flicking = false;

      window.addEventListener('devicemotion', function (eventData) {

        var acceleration = eventData.acceleration;

        if (Math.abs(acceleration.x) > options.sensitivity * FLICK_ACCELERATION) {
          if (!flicking){
            flicking = true;
            callback({
              direction: acceleration.x > 0 ? 'left' : 'right',
              magnitude: Math.abs(acceleration.x)
            });
            setTimeout(function(){
              flicking = false;
            }, options.interval);
          }
        }
      })
    }
  };

  Sense.prototype.toss = function() {
    var intervalExpired = false;
    var z_accels = [];
    var x_accels = [];
    var y_accels = [];

    var Z_THRESHOLD = -1.5;
    var X_Y_THRESHOLD = 2;

    setInterval(function(){intervalExpired = true}, 250);

    if (window.DeviceMotionEvent) {
      var callback,
          options = {

          },
          args = getArgs(arguments, options);

      callback = args.callback;
      options = args.options;

      window.addEventListener('devicemotion', function (eventData) {
        var acceleration = eventData.acceleration;

        if (intervalExpired) {
          z_accels[z_accels.length] = Math.round(10*acceleration.z)/10;
          x_accels[x_accels.length] = Math.round(10*acceleration.x)/10;
          y_accels[y_accels.length] = Math.round(10*acceleration.y)/10;

          intervalExpired = false;
          var zMove = false;
          var xMove = true;
          var yMove = true;
          if (z_accels[z_accels.length-1] < Z_THRESHOLD || z_accels[z_accels.length-2] < Z_THRESHOLD) {
            zMove = true;
          }
          if (Math.abs(x_accels[x_accels.length-1]) > X_Y_THRESHOLD) {
            xMove = false;
          }
          if (Math.abs(y_accels[y_accels.length-1]) > X_Y_THRESHOLD) {
            yMove = false;
          }

          if (zMove && !xMove && !yMove) {
            document.getElementById("Toss").innerHTML = z_accels[z_accels.length - 1];
            document.getElementById("TossAngle").innerHTML = "TOSS";

          }
            callback({
              magnitude: z_accels[z_accels.length-1] > z_accels[z_accels.length-2] ? z_accels[z_accels.length-1] : z_accels[z_accels.length-2]
            });

        }
      });
    }
  };

  Sense.prototype.toss = function() {
    var intervalExpired = false;
    var z_accels = [];
    var x_accels = [];
    var y_accels = [];

    var Z_THRESHOLD = -1.5;
    var X_Y_THRESHOLD = 2;

    setInterval(function(){intervalExpired = true}, 250);

    if (window.DeviceMotionEvent) {
      var callback,
          options = {

          },
          args = getArgs(arguments, options);

      callback = args.callback;
      options = args.options;

      window.addEventListener('devicemotion', function (eventData) {
        var acceleration = eventData.acceleration;

        if (intervalExpired) {
          z_accels[z_accels.length] = Math.round(10*acceleration.z)/10;
          x_accels[x_accels.length] = Math.round(10*acceleration.x)/10;
          y_accels[y_accels.length] = Math.round(10*acceleration.y)/10;

          intervalExpired = false;
          var zMove = false;
          var xMove = true;
          var yMove = true;
          if (z_accels[z_accels.length-1] < Z_THRESHOLD || z_accels[z_accels.length-2] < Z_THRESHOLD) {
            zMove = true;
          }
          if (Math.abs(x_accels[x_accels.length-1]) > X_Y_THRESHOLD) {
            xMove = false;
          }
          if (Math.abs(y_accels[y_accels.length-1]) > X_Y_THRESHOLD) {
            yMove = false;
          }

          if (zMove && !xMove && !yMove) {
            document.getElementById("Toss").innerHTML = z_accels[z_accels.length - 1];
            document.getElementById("TossAngle").innerHTML = "TOSS";

          }
            callback({
              magnitude: z_accels[z_accels.length-1] > z_accels[z_accels.length-2] ? z_accels[z_accels.length-1] : z_accels[z_accels.length-2]
            });

        }
      });
    }
  };

  Sense.prototype.flip = function() {
    var gammas = [];
    if (window.DeviceOrientationEvent) {
      var callback,
          options = {
            threshold: 25,
            direction: "both",
            gestureDuration: 250
          },
          args = getArgs(arguments, options),
          lastSample,
          intervalExpired = true;

      callback = args.callback;
      options = args.options;

      setInterval(function(){intervalExpired = true}, options.gestureDuration);

      window.addEventListener('deviceorientation', function(eventData){
        // Here, you take the eventData and the options that you have and
        // process the data, and then feed it to the callback
        var final_gamma = 0
        var found = false;
        if(intervalExpired) {
          gammas[gammas.length] = eventData.gamma;
          //document.getElementById("Flip").innerHTML = eventData.gamma;
          for (var i=0; i < 5; i++) {
            if (Math.abs(gammas[gammas.length-1] - gammas[gammas.length-1-i]) > 160) {
              //document.getElementById("Floss").innerHTML = z_accels[z_accels.length - 1];
              document.getElementById("Flip").innerHTML = "FLIP";
              found = true;
              final_gamma = gammas[gammas.length - 1];
              break;
            }
          }
          intervalExpired = false;
        }

        if (found) {
          var data = {
            magnitude: Math.round(final_gamma)
          };
          callback(data);
        }
        var delta = lastSample - eventData.gamma;

        if(delta > options.threshold) {
          lastSample = eventData.gamma;
          var data = {
            direction: "LEFT",
            magnitude: Math.round(delta)

          };
          callback(data);
        }

        if(delta < -options.threshold) {
          lastSample = eventData.gamma;
          var data = {
            direction: "RIGHT",
            magnitude: Math.round(-delta)
          };
          callback(data);
        }

      })
    }
  };

  window.sense = sense;

}(window, document));
<commit_msg>final flip<commit_after>(function(window, document){
  'use strict';

  var _instance,
      config;

  var sense = {
    get: function() {
      return _instance;
    },
    init: function(options){
      return _instance || new Sense(options)
    }
  };

  /**
   * Constructor
   */
  function Sense(options){
    _instance = this;
    config = options || {debug: false};

    if (config.debug) {
      initDebuggingWindow();
    }

  }

  /**
   * Given arguments and default options, return an object containing options and the callback
   * @param args: Array of arguments
   * @param defaultOptions: Object containing default options
   * @returns {{options: *, callback: *}}
   */
  var getArgs = function (args, defaultOptions) {
    var callback;
    if (args.length === 1){
      // We only have the callback, so use default options
      callback = args[0];
      return {
        options: defaultOptions,
        callback: function(data){
          updateDebugger(data);
          callback(data);
        }
        };
    }

    if (args.length === 2){
      // We have both the callback and an arguments hash
      callback = args[1];
      return {
        options: arguments[0],
        callback: function(data){
          updateDebugger(data);
          callback(data);
        }
      }
    }
  };

  /**
   * Show a debugger with data on the
   * @param data
   */
  var initDebuggingWindow = function(){
    if (config.debug){
      var el = document.createElement('div');
      el.innerHTML = "" +
          "
" +
          "
";
      window.onload = function(){
        document.body.appendChild(el);
      }
    }
  };

  /**
   * Update the debugger div
   * @param data: JSON
   */
  var updateDebugger = function(data){
    if (config.debug){
      document.getElementById('sense-debugger')
          .innerText = JSON.stringify(data, undefined, 2);
    }
  };

  var withinThreshold = function(a, b, threshold){
    return b  a - threshold
  };

  /**
   * Orientation ([options], callback)
   * - Options:
   *    alphaThreshold (number)
   *    betaThreshold (number)
   *    gammaThreshold (number)
   *    radians (boolean)
   *
   * - Data:
   *    alpha (num)
   *    beta (num)
   *    gamma (num)
   */
  Sense.prototype.orientation = function() {
    if (window.DeviceOrientationEvent) {
      var defaults = {
            alphaThreshold: 1,
            betaThreshold: 1,
            gammaThreshold: 1,
            radians: false
          },
          args = getArgs(arguments, defaults),
          callback = args.callback,
          options = args.options;

      var prevData = {
        alpha: 0,
        beta: 0,
        gamma: 0
      };

      window.addEventListener('deviceorientation', function (eventData) {

        var data = {
          alpha: eventData.alpha,
          beta: eventData.beta,
          gamma: eventData.gamma
        };

        callback(data)

      })

    }
  };

  /*
    Tilt function!
   */
  Sense.prototype.tilt = function() {
    if (window.DeviceOrientationEvent) {
      var callback,
          options = {
            threshold: 25,
            direction: "both",
            gestureDuration: 300
          },
          args = getArgs(arguments, options),
          lastSample,
          intervalExpired = true;

      callback = args.callback;
      options = args.options;

      setInterval(function(){intervalExpired = true}, options.gestureDuration)

      window.addEventListener('deviceorientation', function(eventData){
        // Here, you take the eventData and the options that you have and
        // process the data, and then feed it to the callback
        if(intervalExpired) {
          lastSample = eventData.gamma;
          intervalExpired = false;
        }
        var delta = lastSample - eventData.gamma;

        if(delta > options.threshold) {
          lastSample = eventData.gamma;
          var data = {
            direction: "LEFT",
            magnitude: Math.round(delta)

          };
          callback(data);
        }

        if(delta < -options.threshold) {
          lastSample = eventData.gamma;
          var data = {
            direction: "RIGHT",
            magnitude: Math.round(-delta)
          };
          callback(data);
        }

      })
    }
  };

  /**
   * Flick ([options], callback)
   * - Options:
   *    interval (int)
   *    sensitivity
   *
   * - Data:
   *    direction String 'left', 'right'
   *    magnitude (float)
   */
  Sense.prototype.flick = function() {
    if (window.DeviceMotionEvent) {
      var FLICK_ACCELERATION = 15;
      var defaults = {
            interval: 150,
            sensitivity: 1
          },
          args = getArgs(arguments, defaults),
          callback = args.callback,
          options = args.options;

      var flicking = false;

      window.addEventListener('devicemotion', function (eventData) {

        var acceleration = eventData.acceleration;

        if (Math.abs(acceleration.x) > options.sensitivity * FLICK_ACCELERATION) {
          if (!flicking){
            flicking = true;
            callback({
              direction: acceleration.x > 0 ? 'left' : 'right',
              magnitude: Math.abs(acceleration.x)
            });
            setTimeout(function(){
              flicking = false;
            }, options.interval);
          }
        }
      })
    }
  };

  Sense.prototype.toss = function() {
    var intervalExpired = false;
    var z_accels = [];
    var x_accels = [];
    var y_accels = [];

    var Z_THRESHOLD = -1.5;
    var X_Y_THRESHOLD = 2;

    setInterval(function(){intervalExpired = true}, 250);

    if (window.DeviceMotionEvent) {
      var callback,
          options = {

          },
          args = getArgs(arguments, options);

      callback = args.callback;
      options = args.options;

      window.addEventListener('devicemotion', function (eventData) {
        var acceleration = eventData.acceleration;

        if (intervalExpired) {
          z_accels[z_accels.length] = Math.round(10*acceleration.z)/10;
          x_accels[x_accels.length] = Math.round(10*acceleration.x)/10;
          y_accels[y_accels.length] = Math.round(10*acceleration.y)/10;

          intervalExpired = false;
          var zMove = false;
          var xMove = true;
          var yMove = true;
          if (z_accels[z_accels.length-1] < Z_THRESHOLD || z_accels[z_accels.length-2] < Z_THRESHOLD) {
            zMove = true;
          }
          if (Math.abs(x_accels[x_accels.length-1]) > X_Y_THRESHOLD) {
            xMove = false;
          }
          if (Math.abs(y_accels[y_accels.length-1]) > X_Y_THRESHOLD) {
            yMove = false;
          }

          if (zMove && !xMove && !yMove) {
            document.getElementById("Toss").innerHTML = z_accels[z_accels.length - 1];
            document.getElementById("TossAngle").innerHTML = "TOSS";

          }
            callback({
              magnitude: z_accels[z_accels.length-1] > z_accels[z_accels.length-2] ? z_accels[z_accels.length-1] : z_accels[z_accels.length-2]
            });

        }
      });
    }
  };

  Sense.prototype.toss = function() {
    var intervalExpired = false;
    var z_accels = [];
    var x_accels = [];
    var y_accels = [];

    var Z_THRESHOLD = -1.5;
    var X_Y_THRESHOLD = 2;

    setInterval(function(){intervalExpired = true}, 250);

    if (window.DeviceMotionEvent) {
      var callback,
          options = {

          },
          args = getArgs(arguments, options);

      callback = args.callback;
      options = args.options;

      window.addEventListener('devicemotion', function (eventData) {
        var acceleration = eventData.acceleration;

        if (intervalExpired) {
          z_accels[z_accels.length] = Math.round(10*acceleration.z)/10;
          x_accels[x_accels.length] = Math.round(10*acceleration.x)/10;
          y_accels[y_accels.length] = Math.round(10*acceleration.y)/10;

          intervalExpired = false;
          var zMove = false;
          var xMove = true;
          var yMove = true;
          if (z_accels[z_accels.length-1] < Z_THRESHOLD || z_accels[z_accels.length-2] < Z_THRESHOLD) {
            zMove = true;
          }
          if (Math.abs(x_accels[x_accels.length-1]) > X_Y_THRESHOLD) {
            xMove = false;
          }
          if (Math.abs(y_accels[y_accels.length-1]) > X_Y_THRESHOLD) {
            yMove = false;
          }

          if (zMove && !xMove && !yMove) {
            document.getElementById("Toss").innerHTML = z_accels[z_accels.length - 1];
            document.getElementById("TossAngle").innerHTML = "TOSS";

          }
            callback({
              magnitude: z_accels[z_accels.length-1] > z_accels[z_accels.length-2] ? z_accels[z_accels.length-1] : z_accels[z_accels.length-2]
            });

        }
      });
    }
  };

  Sense.prototype.flip = function() {
    var gammas = [];
    if (window.DeviceOrientationEvent) {
      var callback,
          options = {
            gestureDuration: 250
          },
          args = getArgs(arguments, options),
          lastSample,
          intervalExpired = true;

      callback = args.callback;
      options = args.options;

      setInterval(function(){intervalExpired = true}, options.gestureDuration);

      window.addEventListener('deviceorientation', function(eventData){
        var final_gamma = 0
        var found = false;
        if(intervalExpired) {
          gammas[gammas.length] = eventData.gamma;
          for (var i=0; i < 5; i++) {
            if (Math.abs(gammas[gammas.length-1] - gammas[gammas.length-1-i]) > 160) {
              document.getElementById("Flip").innerHTML = "FLIP";
              found = true;
              final_gamma = gammas[gammas.length - 1];
              break;
            }
          }
          intervalExpired = false;
        }

        if (found) {
          var data = {
            magnitude: Math.round(final_gamma)
          };
          callback(data);
        }

      })
    }
  };

  window.sense = sense;

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