<commit_before>//
// By Osvaldas Valutis, www.osvaldas.info
// Available for use under the MIT License
//
;(function ($, window, document, undefined) {
    'use strict';
    // COMPONENTS //
    var $activityObject = $('<div/>')
            .attr('id','imagelightbox-loading')
            .append($('<div/>')),
        $arrowLeftObject = $('<button/>',{
            type: 'button',
            class: 'imagelightbox-arrow imagelightbox-arrow-left'}),
        $arrowRightObject = $('<button/>',{
            type: 'button',
            class: 'imagelightbox-arrow imagelightbox-arrow-right'}),
        $arrows = $arrowLeftObject.add($arrowRightObject),
        $captionObject = $('<div/>', {
            id: 'imagelightbox-caption'
        }),
        $buttonObject =  $('<a/>', {
            id: 'imagelightbox-close'
        }),
        $overlayObject = $('<div/>', {
            id:'imagelightbox-overlay'
        }),
        $navObject = $('<div/>', {
            id: 'imagelightbox-nav'
        }),
        //
        $wrapper = $('<div/>', {
            id: 'imagelightbox-wrapper'
        });

    var cssTransitionSupport = function () {
            var s = document.body || document.documentElement;
            s = s.style;
            if (s.WebkitTransition === '') {
                return '-webkit-';
            }
            if (s.MozTransition === '') {
                return '-moz-';
            }
            if (s.OTransition === '') {
                return '-o-';
            }
            if (s.transition === '') {
                return '';
            }
            return false;
        },

        isCssTransitionSupport = cssTransitionSupport() !== false,

        cssTransitionTranslateX = function (element, positionX, speed) {
            var options = {}, prefix = cssTransitionSupport();
            options[prefix + 'transform'] = 'translateX(' + positionX + ')';
            options[prefix + 'transition'] = prefix + 'transform ' + speed + 's linear';
            element.css(options);
        },

        hasTouch = ( 'ontouchstart' in window ),
        hasPointers = window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
        wasTouched = function (event) {
            if (hasTouch) {
                return true;
            }

            if (!hasPointers || typeof event === 'undefined' || typeof event.pointerType === 'undefined') {
                return false;
            }

            if (typeof event.MSPOINTER_TYPE_MOUSE !== 'undefined') {
                if (event.MSPOINTER_TYPE_MOUSE !== event.pointerType) {
                    return true;
                }
            }
            else if (event.pointerType !== 'mouse') {
                return true;
            }

            return false;
        };

    $.fn.imageLightbox = function (opts) {
        var options = $.extend({
                selector:       'a[data-imagelightbox]',
                id:             'imagelightbox',
                allowedTypes:   'png|jpg|jpeg||gif', // TODO make it work again
                animationSpeed: 250,
                activity:       false,
                arrows:         false,
                button:         false,
                caption:        false,
                enableKeyboard: true,
                lockBody:       false,
                navigation:     false,
                overlay:        false,
                preloadNext:    true,
                quitOnEnd:      false,
                quitOnImgClick: false,
                quitOnDocClick: true,
                quitOnEscKey:   true,
                onStart: function () {
                    if (options.arrows) {
                        arrowsOn(this);
                    }
                    if (options.navigation) {
                        navigationOn(this, options.selector);
                    }
                    if (options.overlay) {
                        overlayOn();
                    }
                    if (options.button) {
                        closeButtonOn();
                    }
                    if (options.lockBody) {
                        lockBody(true);
                    }
                },
                onEnd: function () {
                    $wrapper.remove().find("*").remove();
                    if (options.lockBody) {
                        lockBody(false);
                    }
                },
                onLoadStart: function () {
                    if (options.activity) {
                        activityIndicatorOn();
                    }
                    if (options.caption) {
                        captionOff();
                    }
                },
                onLoadEnd: function () {
                    if (options.activity) {
                        activityIndicatorOff();
                    }
                    if (options.arrows) {
                        $arrows.css('display', 'block');
                    }
                    if (options.navigation) {
                        navigationUpdate(options.selector);
                    }
                    if (options.caption) {
                        captionOn();
                    }
                },
                previousTarget: function () {
                    return this.previousTargetDefault();
                },
                previousTargetDefault: function () {
                    var targetIndex = targets.index(target) - 1;
                    if (targetIndex < 0) {
                        if (options.quitOnEnd === true) {
                            _quitImageLightbox();
                            return false;
                        }
                        else {
                            targetIndex = targets.length - 1;
                        }
                    }
                    target = targets.eq(targetIndex);
                },
                nextTarget: function () {
                    return this.nextTargetDefault();
                },
                nextTargetDefault: function () {
                    var targetIndex = targets.index(target) + 1;
                    if (targetIndex >= targets.length) {
                        if (options.quitOnEnd === true) {
                            _quitImageLightbox();
                            return false;
                        }
                        else {
                            targetIndex = 0;
                        }
                    }
                    target = targets.eq(targetIndex);
                }
            }, opts),
            activityIndicatorOn = function () {
                $wrapper.append($activityObject);
            },
            activityIndicatorOff = function () {
                $('#imagelightbox-loading').remove();
            },
            lockBody = function (toggle) {
                if (toggle) {
                    $("body").css("overflow","hidden");
                } else {
                    $("body").css("overflow","scroll");
                }
            },
            overlayOn = function () {
                $wrapper.append($overlayObject);
            },
            closeButtonOn = function () {
                $buttonObject.appendTo($wrapper).on('click', function () {
                    _quitImageLightbox();
                    return false;
                });
            },
            captionOn = function () {
                var description = $(target).find('img').attr('alt');
                if (description && description.length > 0) {
                    $wrapper.append($captionObject.text(description));
                }
            },
            captionOff = function () {
                $captionObject.remove();
            },
            navigationOn = function (instance, selector) {
                var images = $(selector);
                if (images.length) {
                    for (var i = 0; i < images.length; i++) {
                        $navObject.append($('<a/>',{href:'#'}));
                    }
                    $wrapper.append($navObject);
                    $navObject.on('click touchend', function () {
                        return false;
                    });
                    var navItems = $navObject.find('a');
                    navItems.on('click touchend', function () {
                        var $this = $(this);
                        if (images.eq($this.index()).attr('href') !== $('#imagelightbox').attr('src')) {
                            var tmpTarget = targets.eq($this.index());
                            if (tmpTarget.length) {
                                var currentIndex = targets.index(target);
                                target = tmpTarget;
                                _loadImage($this.index() < currentIndex ? 'left' : 'right');
                            }
                        }
                        navItems.removeClass('active');
                        navItems.eq($this.index()).addClass('active');
                        return false;
                    }).on('touchend', function () {
                        return false;
                    });
                }
            },
            navigationUpdate = function (selector) {
                var items = $navObject.find('a');
                items.removeClass('active');
                items.eq($(selector).filter('[href="' + $('#imagelightbox').attr('src') + '"]').index(selector)).addClass('active');
            },
            navigationOff = function () {
                $('#imagelightbox-nav').remove();
            },
            arrowsOn = function () {
                $wrapper.append($arrows);
                $arrows.on('click touchend', function (e) {
                    e.preventDefault();
                    if ($(this).hasClass('imagelightbox-arrow-left')) {
                        _loadPreviousImage();
                    } else {
                        _loadNextImage();
                    }
                    return false;
                });
            },
            arrowsOff = function () {
                $('.imagelightbox-arrow').remove();
            },

            targets = $([]),
            target = $(),
            image = $(),
            imageWidth = 0,
            imageHeight = 0,
            swipeDiff = 0,
            inProgress = false,

            // TODO make it work again
            // isTargetValid = function (element) {
            //   var classic = $(element).prop('tagName').toLowerCase() === 'a' && ( new RegExp('.(' + options.allowedTypes + ')$', 'i') ).test($(element).attr('href'));
            //   var html5 = $(element).attr('data-lightbox') !== undefined;
            //   return classic || html5;
            // },

            _setImage = function () {
                if (!image.length) {
                    return true;
                }

                var screenWidth = $(window).width() * 0.8,
                    wHeight = (window.innerHeight) ? window.innerHeight : $(window).height(),
                    screenHeight = wHeight * 0.9,
                    tmpImage = new Image();

                tmpImage.src = image.attr('src');
                tmpImage.onload = function () {
                    imageWidth = tmpImage.width;
                    imageHeight = tmpImage.height;

                    if (imageWidth > screenWidth || imageHeight > screenHeight) {
                        var ratio = imageWidth / imageHeight > screenWidth / screenHeight ? imageWidth / screenWidth : imageHeight / screenHeight;
                        imageWidth /= ratio;
                        imageHeight /= ratio;
                    }

                    image.css({
                        'width': imageWidth + 'px',
                        'height': imageHeight + 'px',
                        'top': ( wHeight - imageHeight ) / 2 + 'px',
                        'left': ( $(window).width() - imageWidth ) / 2 + 'px'
                    });
                };
            },

            _loadImage = function (direction) {
                if (inProgress) {
                    return false;
                }

                direction = typeof direction === 'undefined' ? false : direction === 'left' ? 1 : -1;

                if (image.length) {
                    var params = {'opacity': 0};
                    if (isCssTransitionSupport) {
                        cssTransitionTranslateX(image, ( 100 * direction ) - swipeDiff + 'px', options.animationSpeed / 1000);
                    }
                    else {
                        params.left = parseInt(image.css('left')) + 100 * direction + 'px';
                    }
                    image.animate(params, options.animationSpeed, function () {
                        _removeImage();
                    });
                    swipeDiff = 0;
                }

                inProgress = true;
                if (options.onLoadStart !== false) {
                    options.onLoadStart();
                }

                setTimeout(function () {
                    var imgPath = target.attr('href');
                    // if ( imgPath === undefined ) {
                    //     imgPath = target.attr( 'data-lightbox' );
                    // }
                    image = $('<img id="' + options.id + '" />')
                        .attr('src', imgPath)
                        .on('load', function () {
                            var params = {'opacity': 1};

                            image.appendTo($wrapper);
                            _setImage();
                            image.css('opacity', 0);
                            if (isCssTransitionSupport) {
                                cssTransitionTranslateX(image, -100 * direction + 'px', 0);
                                setTimeout(function () {
                                    cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000);
                                }, 50);
                            } else {
                                var imagePosLeft = parseInt(image.css('left'));
                                params.left = imagePosLeft + 'px';
                                image.css('left', imagePosLeft - 100 * direction + 'px');
                            }

                            image.animate(params, options.animationSpeed, function () {
                                inProgress = false;
                                if (options.onLoadEnd !== false) {
                                    options.onLoadEnd();
                                }
                            });
                            if (options.preloadNext) {
                                var nextTarget = targets.eq(targets.index(target) + 1);
                                if (!nextTarget.length) {
                                    nextTarget = targets.eq(0);
                                }
                                $('<img />').attr('src', nextTarget.attr('href'));
                            }
                        })
                        .on('error', function () {
                            if (options.onLoadEnd !== false) {
                                options.onLoadEnd();
                            }
                        });

                    var swipeStart = 0,
                        swipeEnd = 0,
                        imagePosLeft = 0;

                    image.on(hasPointers ? 'pointerup MSPointerUp' : 'click', function (e) {
                        e.preventDefault();
                        if (options.quitOnImgClick) {
                            _quitImageLightbox();
                            return false;
                        }
                        if (wasTouched(e.originalEvent)) {
                            return true;
                        }
                        var posX = ( e.pageX || e.originalEvent.pageX ) - e.target.offsetLeft;
                        if (imageWidth / 2 > posX) {
                            _loadPreviousImage();
                        } else {
                            _loadNextImage();
                        }
                    })
                        .on('touchstart pointerdown MSPointerDown', function (e) {
                            if (!wasTouched(e.originalEvent) || options.quitOnImgClick) {
                                return true;
                            }
                            if (isCssTransitionSupport) {
                                imagePosLeft = parseInt(image.css('left'));
                            }
                            swipeStart = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
                        })
                        .on('touchmove pointermove MSPointerMove', function (e) {
                            if (!wasTouched(e.originalEvent) || options.quitOnImgClick) {
                                return true;
                            }
                            e.preventDefault();
                            swipeEnd = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
                            swipeDiff = swipeStart - swipeEnd;
                            if (isCssTransitionSupport) {
                                cssTransitionTranslateX(image, -swipeDiff + 'px', 0);
                            } else {
                                image.css('left', imagePosLeft - swipeDiff + 'px');
                            }
                        })
                        .on('touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel', function (e) {
                            if (!wasTouched(e.originalEvent) || options.quitOnImgClick) {
                                return true;
                            }
                            if (Math.abs(swipeDiff) > 50) {
                                if (swipeDiff < 0) {
                                    _loadPreviousImage();
                                } else {
                                    _loadNextImage();
                                }
                            } else {
                                if (isCssTransitionSupport) {
                                    cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000);
                                } else {
                                    image.animate({'left': imagePosLeft + 'px'}, options.animationSpeed / 2);
                                }
                            }
                        });

                }, options.animationSpeed + 100);
            },

            _loadPreviousImage = function () {
                if (options.previousTarget() !== false) {
                    _loadImage('left');
                }
            },

            _loadNextImage = function () {
                if (options.nextTarget() !== false) {
                    _loadImage('right');
                }
            },

            _removeImage = function () {
                if (!image.length) {
                    return false;
                }
                image.remove();
                image = $();
            },

            _openImageLightbox = function ($target) {
                if (inProgress) {
                    return false;
                }
                inProgress = false;
                if (options.onStart !== false) {
                    options.onStart();
                }
                $('body').append($wrapper);
                target = $target;
                _loadImage();
            },

            _quitImageLightbox = function () {
                if (!image.length) {
                    return false;
                }
                image.animate({'opacity': 0}, options.animationSpeed, function () {
                    _removeImage();
                    inProgress = false;
                    if (options.onEnd !== false) {
                        options.onEnd();
                    }
                });
            },

            _addTargets = function( newTargets ) {
                newTargets.each(function () {
                    targets = targets.add($(this));
                });

                newTargets.on('click', function (e) {
                    e.preventDefault();
                    _openImageLightbox($(this));
                });
            };

        this.startImageLightbox = function () {
            if (this.length > 0) {
                _openImageLightbox($(this[0]));
            }
        };

        $(window).on('resize', _setImage);

        $(document).ready(function() {
            if (options.quitOnDocClick) {
                $(document).on(hasTouch ? 'touchend' : 'click', function (e) {
                    if (image.length && !$(e.target).is(image)) {
                        e.preventDefault();
                        _quitImageLightbox();
                    }
                });
            }

            if (options.enableKeyboard) {
                $(document).on('keyup', function (e) {
                    if (!image.length) {
                        return true;
                    }
                    e.preventDefault();
                    if (e.keyCode === 27 && options.quitOnEscKey === true) {
                        _quitImageLightbox();
                    }
                    if (e.keyCode === 37) {
                        _loadPreviousImage();
                    } else if (e.keyCode === 39) {
                        _loadNextImage();
                    }
                });
            }
        });

        $(document).off('click', this.selector);

        _addTargets($(this));

        this.loadPreviousImage = function () {
            _loadPreviousImage();
        };

        this.loadNextImage = function () {
            _loadNextImage();
        };

        this.quitImageLightbox = function () {
            _quitImageLightbox();
            return this;
        };

        this.addToImageLightbox = function(elements)  {
            _addTargets(elements);
        };

        return this;
    };
})(jQuery, window, document);
<commit_msg>namespace the event listeners<commit_after>//
// By Osvaldas Valutis, www.osvaldas.info
// Available for use under the MIT License
//
;(function ($, window, document, undefined) {
    'use strict';
    // COMPONENTS //
    var $activityObject = $('<div/>')
            .attr('id','imagelightbox-loading')
            .append($('<div/>')),
        $arrowLeftObject = $('<button/>',{
            type: 'button',
            class: 'imagelightbox-arrow imagelightbox-arrow-left'}),
        $arrowRightObject = $('<button/>',{
            type: 'button',
            class: 'imagelightbox-arrow imagelightbox-arrow-right'}),
        $arrows = $arrowLeftObject.add($arrowRightObject),
        $captionObject = $('<div/>', {
            id: 'imagelightbox-caption'
        }),
        $buttonObject =  $('<a/>', {
            id: 'imagelightbox-close'
        }),
        $overlayObject = $('<div/>', {
            id:'imagelightbox-overlay'
        }),
        $navObject = $('<div/>', {
            id: 'imagelightbox-nav'
        }),
        //
        $wrapper = $('<div/>', {
            id: 'imagelightbox-wrapper'
        });

    var cssTransitionSupport = function () {
            var s = document.body || document.documentElement;
            s = s.style;
            if (s.WebkitTransition === '') {
                return '-webkit-';
            }
            if (s.MozTransition === '') {
                return '-moz-';
            }
            if (s.OTransition === '') {
                return '-o-';
            }
            if (s.transition === '') {
                return '';
            }
            return false;
        },

        isCssTransitionSupport = cssTransitionSupport() !== false,

        cssTransitionTranslateX = function (element, positionX, speed) {
            var options = {}, prefix = cssTransitionSupport();
            options[prefix + 'transform'] = 'translateX(' + positionX + ')';
            options[prefix + 'transition'] = prefix + 'transform ' + speed + 's linear';
            element.css(options);
        },

        hasTouch = ( 'ontouchstart' in window ),
        hasPointers = window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
        wasTouched = function (event) {
            if (hasTouch) {
                return true;
            }

            if (!hasPointers || typeof event === 'undefined' || typeof event.pointerType === 'undefined') {
                return false;
            }

            if (typeof event.MSPOINTER_TYPE_MOUSE !== 'undefined') {
                if (event.MSPOINTER_TYPE_MOUSE !== event.pointerType) {
                    return true;
                }
            }
            else if (event.pointerType !== 'mouse') {
                return true;
            }

            return false;
        };

    $.fn.imageLightbox = function (opts) {
        var options = $.extend({
                selector:       'a[data-imagelightbox]',
                id:             'imagelightbox',
                allowedTypes:   'png|jpg|jpeg||gif', // TODO make it work again
                animationSpeed: 250,
                activity:       false,
                arrows:         false,
                button:         false,
                caption:        false,
                enableKeyboard: true,
                lockBody:       false,
                navigation:     false,
                overlay:        false,
                preloadNext:    true,
                quitOnEnd:      false,
                quitOnImgClick: false,
                quitOnDocClick: true,
                quitOnEscKey:   true,
                onStart: function () {
                    if (options.arrows) {
                        arrowsOn(this);
                    }
                    if (options.navigation) {
                        navigationOn(this, options.selector);
                    }
                    if (options.overlay) {
                        overlayOn();
                    }
                    if (options.button) {
                        closeButtonOn();
                    }
                    if (options.lockBody) {
                        lockBody(true);
                    }
                },
                onEnd: function () {
                    $wrapper.remove().find("*").remove();
                    if (options.lockBody) {
                        lockBody(false);
                    }
                },
                onLoadStart: function () {
                    if (options.activity) {
                        activityIndicatorOn();
                    }
                    if (options.caption) {
                        captionOff();
                    }
                },
                onLoadEnd: function () {
                    if (options.activity) {
                        activityIndicatorOff();
                    }
                    if (options.arrows) {
                        $arrows.css('display', 'block');
                    }
                    if (options.navigation) {
                        navigationUpdate(options.selector);
                    }
                    if (options.caption) {
                        captionOn();
                    }
                },
                previousTarget: function () {
                    return this.previousTargetDefault();
                },
                previousTargetDefault: function () {
                    var targetIndex = targets.index(target) - 1;
                    if (targetIndex < 0) {
                        if (options.quitOnEnd === true) {
                            _quitImageLightbox();
                            return false;
                        }
                        else {
                            targetIndex = targets.length - 1;
                        }
                    }
                    target = targets.eq(targetIndex);
                },
                nextTarget: function () {
                    return this.nextTargetDefault();
                },
                nextTargetDefault: function () {
                    var targetIndex = targets.index(target) + 1;
                    if (targetIndex >= targets.length) {
                        if (options.quitOnEnd === true) {
                            _quitImageLightbox();
                            return false;
                        }
                        else {
                            targetIndex = 0;
                        }
                    }
                    target = targets.eq(targetIndex);
                }
            }, opts),
            activityIndicatorOn = function () {
                $wrapper.append($activityObject);
            },
            activityIndicatorOff = function () {
                $('#imagelightbox-loading').remove();
            },
            lockBody = function (toggle) {
                if (toggle) {
                    $("body").css("overflow","hidden");
                } else {
                    $("body").css("overflow","scroll");
                }
            },
            overlayOn = function () {
                $wrapper.append($overlayObject);
            },
            closeButtonOn = function () {
                $buttonObject.appendTo($wrapper).on('click.imagelightbox', function () {
                    _quitImageLightbox();
                    return false;
                });
            },
            captionOn = function () {
                var description = $(target).find('img').attr('alt');
                if (description && description.length > 0) {
                    $wrapper.append($captionObject.text(description));
                }
            },
            captionOff = function () {
                $captionObject.remove();
            },
            navigationOn = function (instance, selector) {
                var images = $(selector);
                if (images.length) {
                    for (var i = 0; i < images.length; i++) {
                        $navObject.append($('<a/>',{href:'#'}));
                    }
                    $wrapper.append($navObject);
                    $navObject.on('click.imagelightbox touchend.imagelightbox', function () {
                        return false;
                    });
                    var navItems = $navObject.find('a');
                    navItems.on('click.imagelightbox touchend.imagelightbox', function () {
                        var $this = $(this);
                        if (images.eq($this.index()).attr('href') !== $('#imagelightbox').attr('src')) {
                            var tmpTarget = targets.eq($this.index());
                            if (tmpTarget.length) {
                                var currentIndex = targets.index(target);
                                target = tmpTarget;
                                _loadImage($this.index() < currentIndex ? 'left' : 'right');
                            }
                        }
                        navItems.removeClass('active');
                        navItems.eq($this.index()).addClass('active');
                        return false;
                    }).on('touchend.imagelightbox', function () {
                        return false;
                    });
                }
            },
            navigationUpdate = function (selector) {
                var items = $navObject.find('a');
                items.removeClass('active');
                items.eq($(selector).filter('[href="' + $('#imagelightbox').attr('src') + '"]').index(selector)).addClass('active');
            },
            navigationOff = function () {
                $('#imagelightbox-nav').remove();
            },
            arrowsOn = function () {
                $wrapper.append($arrows);
                $arrows.on('click.imagelightbox touchend.imagelightbox', function (e) {
                    e.preventDefault();
                    if ($(this).hasClass('imagelightbox-arrow-left')) {
                        _loadPreviousImage();
                    } else {
                        _loadNextImage();
                    }
                    return false;
                });
            },
            arrowsOff = function () {
                $('.imagelightbox-arrow').remove();
            },

            targets = $([]),
            target = $(),
            image = $(),
            imageWidth = 0,
            imageHeight = 0,
            swipeDiff = 0,
            inProgress = false,

            // TODO make it work again
            // isTargetValid = function (element) {
            //   var classic = $(element).prop('tagName').toLowerCase() === 'a' && ( new RegExp('.(' + options.allowedTypes + ')$', 'i') ).test($(element).attr('href'));
            //   var html5 = $(element).attr('data-lightbox') !== undefined;
            //   return classic || html5;
            // },

            _setImage = function () {
                if (!image.length) {
                    return true;
                }

                var screenWidth = $(window).width() * 0.8,
                    wHeight = (window.innerHeight) ? window.innerHeight : $(window).height(),
                    screenHeight = wHeight * 0.9,
                    tmpImage = new Image();

                tmpImage.src = image.attr('src');
                tmpImage.onload = function () {
                    imageWidth = tmpImage.width;
                    imageHeight = tmpImage.height;

                    if (imageWidth > screenWidth || imageHeight > screenHeight) {
                        var ratio = imageWidth / imageHeight > screenWidth / screenHeight ? imageWidth / screenWidth : imageHeight / screenHeight;
                        imageWidth /= ratio;
                        imageHeight /= ratio;
                    }

                    image.css({
                        'width': imageWidth + 'px',
                        'height': imageHeight + 'px',
                        'top': ( wHeight - imageHeight ) / 2 + 'px',
                        'left': ( $(window).width() - imageWidth ) / 2 + 'px'
                    });
                };
            },

            _loadImage = function (direction) {
                if (inProgress) {
                    return false;
                }

                direction = typeof direction === 'undefined' ? false : direction === 'left' ? 1 : -1;

                if (image.length) {
                    var params = {'opacity': 0};
                    if (isCssTransitionSupport) {
                        cssTransitionTranslateX(image, ( 100 * direction ) - swipeDiff + 'px', options.animationSpeed / 1000);
                    }
                    else {
                        params.left = parseInt(image.css('left')) + 100 * direction + 'px';
                    }
                    image.animate(params, options.animationSpeed, function () {
                        _removeImage();
                    });
                    swipeDiff = 0;
                }

                inProgress = true;
                if (options.onLoadStart !== false) {
                    options.onLoadStart();
                }

                setTimeout(function () {
                    var imgPath = target.attr('href');
                    // if ( imgPath === undefined ) {
                    //     imgPath = target.attr( 'data-lightbox' );
                    // }
                    image = $('<img id="' + options.id + '" />')
                        .attr('src', imgPath)
                        .on('load.imagelightbox', function () {
                            var params = {'opacity': 1};

                            image.appendTo($wrapper);
                            _setImage();
                            image.css('opacity', 0);
                            if (isCssTransitionSupport) {
                                cssTransitionTranslateX(image, -100 * direction + 'px', 0);
                                setTimeout(function () {
                                    cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000);
                                }, 50);
                            } else {
                                var imagePosLeft = parseInt(image.css('left'));
                                params.left = imagePosLeft + 'px';
                                image.css('left', imagePosLeft - 100 * direction + 'px');
                            }

                            image.animate(params, options.animationSpeed, function () {
                                inProgress = false;
                                if (options.onLoadEnd !== false) {
                                    options.onLoadEnd();
                                }
                            });
                            if (options.preloadNext) {
                                var nextTarget = targets.eq(targets.index(target) + 1);
                                if (!nextTarget.length) {
                                    nextTarget = targets.eq(0);
                                }
                                $('<img />').attr('src', nextTarget.attr('href'));
                            }
                        })
                        .on('error.imagelightbox', function () {
                            if (options.onLoadEnd !== false) {
                                options.onLoadEnd();
                            }
                        });

                    var swipeStart = 0,
                        swipeEnd = 0,
                        imagePosLeft = 0;

                    image.on(hasPointers ? 'pointerup.imagelightbox MSPointerUp.imagelightbox' : 'click.imagelightbox', function (e) {
                        e.preventDefault();
                        if (options.quitOnImgClick) {
                            _quitImageLightbox();
                            return false;
                        }
                        if (wasTouched(e.originalEvent)) {
                            return true;
                        }
                        var posX = ( e.pageX || e.originalEvent.pageX ) - e.target.offsetLeft;
                        if (imageWidth / 2 > posX) {
                            _loadPreviousImage();
                        } else {
                            _loadNextImage();
                        }
                    })
                        .on('touchstart.imagelightbox pointerdown.imagelightbox MSPointerDown.imagelightbox', function (e) {
                            if (!wasTouched(e.originalEvent) || options.quitOnImgClick) {
                                return true;
                            }
                            if (isCssTransitionSupport) {
                                imagePosLeft = parseInt(image.css('left'));
                            }
                            swipeStart = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
                        })
                        .on('touchmove.imagelightbox pointermove.imagelightbox MSPointerMove.imagelightbox', function (e) {
                            if (!wasTouched(e.originalEvent) || options.quitOnImgClick) {
                                return true;
                            }
                            e.preventDefault();
                            swipeEnd = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
                            swipeDiff = swipeStart - swipeEnd;
                            if (isCssTransitionSupport) {
                                cssTransitionTranslateX(image, -swipeDiff + 'px', 0);
                            } else {
                                image.css('left', imagePosLeft - swipeDiff + 'px');
                            }
                        })
                        .on('touchend.imagelightbox touchcancel.imagelightbox pointerup.imagelightbox pointercancel.imagelightbox MSPointerUp.imagelightbox MSPointerCancel.imagelightbox', function (e) {
                            if (!wasTouched(e.originalEvent) || options.quitOnImgClick) {
                                return true;
                            }
                            if (Math.abs(swipeDiff) > 50) {
                                if (swipeDiff < 0) {
                                    _loadPreviousImage();
                                } else {
                                    _loadNextImage();
                                }
                            } else {
                                if (isCssTransitionSupport) {
                                    cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000);
                                } else {
                                    image.animate({'left': imagePosLeft + 'px'}, options.animationSpeed / 2);
                                }
                            }
                        });

                }, options.animationSpeed + 100);
            },

            _loadPreviousImage = function () {
                if (options.previousTarget() !== false) {
                    _loadImage('left');
                }
            },

            _loadNextImage = function () {
                if (options.nextTarget() !== false) {
                    _loadImage('right');
                }
            },

            _removeImage = function () {
                if (!image.length) {
                    return false;
                }
                image.remove();
                image = $();
            },

            _openImageLightbox = function ($target) {
                if (inProgress) {
                    return false;
                }
                inProgress = false;
                if (options.onStart !== false) {
                    options.onStart();
                }
                $('body').append($wrapper);
                target = $target;
                _loadImage();
            },

            _quitImageLightbox = function () {
                if (!image.length) {
                    return false;
                }
                image.animate({'opacity': 0}, options.animationSpeed, function () {
                    _removeImage();
                    inProgress = false;
                    if (options.onEnd !== false) {
                        options.onEnd();
                    }
                });
            },

            _addTargets = function( newTargets ) {
                newTargets.each(function () {
                    targets = targets.add($(this));
                });

                newTargets.on('click.imagelightbox', function (e) {
                    e.preventDefault();
                    _openImageLightbox($(this));
                });
            };

        this.startImageLightbox = function () {
            if (this.length > 0) {
                _openImageLightbox($(this[0]));
            }
        };

        $(window).on('resize.imagelightbox', _setImage);

        $(document).ready(function() {
            if (options.quitOnDocClick) {
                $(document).on(hasTouch ? 'touchend.imagelightbox' : 'click.imagelightbox', function (e) {
                    if (image.length && !$(e.target).is(image)) {
                        e.preventDefault();
                        _quitImageLightbox();
                    }
                });
            }

            if (options.enableKeyboard) {
                $(document).on('keyup.imagelightbox', function (e) {
                    if (!image.length) {
                        return true;
                    }
                    e.preventDefault();
                    if (e.keyCode === 27 && options.quitOnEscKey === true) {
                        _quitImageLightbox();
                    }
                    if (e.keyCode === 37) {
                        _loadPreviousImage();
                    } else if (e.keyCode === 39) {
                        _loadNextImage();
                    }
                });
            }
        });

        $(document).off('click', this.selector);

        _addTargets($(this));

        this.loadPreviousImage = function () {
            _loadPreviousImage();
        };

        this.loadNextImage = function () {
            _loadNextImage();
        };

        this.quitImageLightbox = function () {
            _quitImageLightbox();
            return this;
        };

        this.addToImageLightbox = function(elements)  {
            _addTargets(elements);
        };

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


<commit_before>class Images {
  static images = {
    benningtonSt: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/10_bennington_st.png",
    brooksSt: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/10_brooks_st.png",
    maverickStreet21: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/21_maverick_st.png",
    maverickStreet17: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/17_maverick_st.png",
    saratogaPorch: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/22_saratoga_porch.png",
    saratogaStreet: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/22_saratoga_street.png",
    chelseaStreet25: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/25_chelsea_st.png",
    chelseaStreet35: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/35_chelsea_street.png",
    lubecStreet: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/64_lubec_street.png",
    goveStreetMailbox: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/gove_street_mailboxes.png",
    goveStreet: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/gove_street.png"
    1chilcott1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/1-chilcott1.jpeg",
    3oakwood1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/3-oakwood1.jpeg",
    6beach1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/6-beach1.jpeg",
    913rugglesstreet1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/9-13-ruggles-street1.jpeg",
    17maverickst: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/17-maverick-1.jpeg",
    43rosastreet1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/43-rosa-street1.jpeg",
    61tremont1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/61-tremont1.jpeg",
    johnny1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/johnny-1.jpeg",
    johnny2: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/johnny-2.jpeg",
    rosastreet1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/rosa-street-1.jpeg",
    rosastreet2: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/rosa-street-2.jpeg",
  }

  static eagerLoad = () => {
    Object.keys(Images.images).forEach( (key) => {
      let i = new Image();
      i.src = Images.images[key];
    });
  }
}

export default Images;
<commit_msg>fix issue with missing comma and starting names with numbers #46<commit_after>class Images {
  static images = {
    benningtonSt: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/10_bennington_st.png",
    brooksSt: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/10_brooks_st.png",
    maverickStreet21: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/21_maverick_st.png",
    maverickStreet17: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/17_maverick_st.png",
    saratogaPorch: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/22_saratoga_porch.png",
    saratogaStreet: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/22_saratoga_street.png",
    chelseaStreet25: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/25_chelsea_st.png",
    chelseaStreet35: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/35_chelsea_street.png",
    lubecStreet: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/64_lubec_street.png",
    goveStreetMailbox: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/gove_street_mailboxes.png",
    goveStreet: "https://cdn.rawgit.com/AntiEvictionBoston/utility/dfab5a678abde8e1a175cb7b045090e7c62f6dec/images/gove_street.png",
    chilcott11: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/1-chilcott1.jpeg",
    oakwood31: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/3-oakwood1.jpeg",
    beach61: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/6-beach1.jpeg",
    rugglesstreet9131: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/9-13-ruggles-street1.jpeg",
    maverickst171: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/17-maverick-1.jpeg",
    rosastreet431: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/43-rosa-street1.jpeg",
    tremont611: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/61-tremont1.jpeg",
    johnny1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/johnny-1.jpeg",
    johnny2: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/johnny-2.jpeg",
    rosastreet1: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/rosa-street-1.jpeg",
    rosastreet2: "https://cdn.rawgit.com/AntiEvictionBoston/utility/7a192a21ba9eca6391e08114eae87a5083dc0061/images/rosa-street-2.jpeg"
  }

  static eagerLoad = () => {
    Object.keys(Images.images).forEach( (key) => {
      let i = new Image();
      i.src = Images.images[key];
    });
  }
}

export default Images;
<|endoftext|>


<commit_before>/*!
 * Copyright 2012 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

/**
 * This module contains the handlers for native platform events.
 * From here, the dispatcher is called to create unified pointer events.
 * Included are touch events (v1), mouse events, and MSPointerEvents.
 */
(function(scope) {
  var dispatcher = scope.dispatcher;
  var installer = scope.installer;
  var pointermap = dispatcher.pointermap;
  var touchMap = Array.prototype.map.call.bind(Array.prototype.map);
  // This should be long enough to ignore compat mouse events made by touch
  var DEDUP_TIMEOUT = 2500;
  // radius around touchend that swallows mouse events
  var DEDUP_DIST = 25;
  // distance a finger can travel before being a scroll
  var SCROLL_HYSTERESIS = 10;
  // handler block for native touch events
  var touchEvents = {
    events: [
      'touchstart',
      'touchmove',
      'touchend',
      'touchcancel'
    ],
    POINTER_TYPE: 'touch',
    firstTouch: null,
    isPrimaryTouch: function(inTouch) {
      return this.firstTouch === inTouch.identifier;
    },
    setPrimaryTouch: function(inTouch) {
      if (this.firstTouch === null) {
        this.firstTouch = inTouch.identifier;
        this.firstXY = {X: inTouch.clientX, Y: inTouch.clientY};
        this.scrolling = false;
      }
    },
    removePrimaryTouch: function(inTouch) {
      if (this.isPrimaryTouch(inTouch)) {
        this.firstTouch = null;
        this.firstXY = null;
      }
    },
    touchToPointer: function(inTouch) {
      var e = dispatcher.cloneEvent(inTouch);
      // Spec specifies that pointerId 1 is reserved for Mouse.
      // Touch identifiers can start at 0.
      // Add 2 to the touch identifier for compatibility.
      e.pointerId = inTouch.identifier + 2;
      e.target = this.findTarget(e);
      e.bubbles = true;
      e.cancelable = true;
      e.button = 0;
      e.buttons = 1;
      e.isPrimary = this.isPrimaryTouch(inTouch);
      e.pointerType = this.POINTER_TYPE;
      return e;
    },
    processTouches: function(inEvent, inFunction) {
      var tl = inEvent.changedTouches;
      var pointers = touchMap(tl, this.touchToPointer, this);
      pointers.forEach(inFunction, this);
    },
    shadow: function(inEl) {
      return inEl && (inEl.webkitShadowRoot || inEl.shadowRoot);
    },
    searchRoot: function(inRoot, x, y) {
      if (inRoot) {
        var t = inRoot.elementFromPoint(x, y);
        var st, sr, os;
        // is element a shadow host?
        sr = this.shadow(t);
        while (sr) {
          // find the the element inside the shadow root
          st = sr.elementFromPoint(x, y);
          if (!st) {
            // check for older shadows
            os = sr.querySelector('shadow');
            // check the older shadow if available
            sr = os ? os.olderShadowRoot : null;
          } else {
            // shadowed element may contain a shadow root
            var ssr = this.shadow(st);
            return this.searchRoot(ssr, x, y) || st;
          }
        }
        // light dom element is the target
        return t;
      }
    },
    findTarget: function(inEvent) {
      var x = inEvent.clientX, y = inEvent.clientY;
      return this.searchRoot(document, x, y);
    },
    // For single axis scrollers, determines whether the element should emit
    // pointer events or behave as a scroller
    shouldScroll: function(inEvent) {
      if (this.firstXY) {
        var scrollAxis = dispatcher.scrollType.get(inEvent.currentTarget);
        // this element is a touch-action: none, should never scroll
        if (scrollAxis === 'none') {
          this.firstXY = null;
          return false;
        } else {
          var t = inEvent.changedTouches[0];
          // check the intended scroll axis, and other axis
          var a = scrollAxis;
          var oa = scrollAxis === 'Y' ? 'X' : 'Y';
          var da = Math.abs(t['client' + a] - this.firstXY[a]);
          var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
          // if the delta in the scroll axis is enough, scroll instead of making
          // events
          if (da > SCROLL_HYSTERESIS) {
            this.firstXY = null;
            return true;
          // if the delta in the other axis is enough, make events and don't
          // scroll
          } else if (doa > SCROLL_HYSTERESIS) {
            this.firstXY = null;
            return false;
          }
        }
      }
    },
    touchstart: function(inEvent) {
      this.setPrimaryTouch(inEvent.changedTouches[0]);
      if (!this.scrolling) {
        this.processTouches(inEvent, this.overDown);
      }
    },
    overDown: function(inPointer) {
      var p = pointermap.set(inPointer.pointerId, {
        target: inPointer.target,
        out: inPointer,
        outTarget: inPointer.target
      });
      dispatcher.over(inPointer);
      dispatcher.down(inPointer);
    },
    touchmove: function(inEvent) {
      if (!this.scrolling) {
        var scroll = this.shouldScroll(inEvent);
        if (!scroll) {
          if (!this.firstXY) {
            inEvent.preventDefault();
          }
          this.processTouches(inEvent, this.moveOverOut);
        } else {
          this.touchcancel(inEvent);
          this.scrolling = true;
        }
      }
    },
    moveOverOut: function(inPointer) {
      var event = inPointer;
      var pointer = pointermap.get(event.pointerId);
      var outEvent = pointer.out;
      var outTarget = pointer.outTarget;
      dispatcher.move(event);
      if (outEvent && outTarget !== event.target) {
        outEvent.relatedTarget = event.target;
        event.relatedTarget = outTarget;
        // recover from retargeting by shadow
        outEvent.target = outTarget;
        dispatcher.out(outEvent);
        dispatcher.over(event);
      }
      pointer.out = event;
      pointer.outTarget = event.target;
    },
    touchend: function(inEvent) {
      this.dedupSynthMouse(inEvent);
      this.processTouches(inEvent, this.upOut);
    },
    upOut: function(inPointer) {
      if (!this.scrolling) {
        dispatcher.up(inPointer);
        dispatcher.out(inPointer);
      }
      this.cleanUpPointer(inPointer);
    },
    touchcancel: function(inEvent) {
      this.processTouches(inEvent, this.cancelOut);
    },
    cancelOut: function(inPointer) {
      dispatcher.cancel(inPointer);
      dispatcher.out(inPointer);
      this.cleanUpPointer(inPointer);
    },
    cleanUpPointer: function(inPointer) {
      pointermap.delete(inPointer.pointerId);
      this.removePrimaryTouch(inPointer);
    },
    // prevent synth mouse events from creating pointer events
    dedupSynthMouse: function(inEvent) {
      var lts = mouseEvents.lastTouches;
      var t = inEvent.changedTouches[0];
      // only the primary finger will synth mouse events
      if (this.isPrimaryTouch(t)) {
        // remember x/y of last touch
        var lt = {x: t.clientX, y: t.clientY};
        lts.push(lt);
        var fn = (function(lts, lt){
          var i = lts.indexOf(lt);
          if (i > -1) {
            lts.splice(i, 1)
          }
        }).bind(null, lts, lt);
        setTimeout(fn, DEDUP_TIMEOUT);
      }
    }
  };

  // handler block for native mouse events
  var mouseEvents = {
    // Mouse is required to have a pointerId of 1
    POINTER_ID: 1,
    POINTER_TYPE: 'mouse',
    events: [
      'mousedown',
      'mousemove',
      'mouseup',
      'mouseover',
      'mouseout'
    ],
    global: [
      'mousedown',
      'mouseup',
      'mouseover',
      'mouseout'
    ],
    lastTouches: [],
    isEventSimulatedFromTouch: function(inEvent) {
      var lts = this.lastTouches;
      var x = inEvent.clientX, y = inEvent.clientY;
      for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
        // simulated mouse events will be swallowed near a primary touchend
        var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
        if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
          return true;
        }
      }
    },
    prepareEvent: function(inEvent) {
      var e = dispatcher.cloneEvent(inEvent);
      e.pointerId = this.POINTER_ID;
      e.isPrimary = true;
      e.pointerType = this.POINTER_TYPE;
      return e;
    },
    mousedown: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        if (!pointermap.has(this.POINTER_ID)) {
          var e = this.prepareEvent(inEvent);
          var p = pointermap.set(this.POINTER_ID, inEvent);
          dispatcher.down(e);
          dispatcher.listen(this.global, document);
        }
      }
    },
    mousemove: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        var e = this.prepareEvent(inEvent);
        dispatcher.move(e);
      }
    },
    mouseup: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        var p = pointermap.get(this.POINTER_ID);
        if (p && p.button === inEvent.button) {
          var e = this.prepareEvent(inEvent);
          dispatcher.up(e);
          pointermap.delete(this.POINTER_ID);
          dispatcher.unlisten(this.global, document);
        }
      }
    },
    mouseover: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        var e = this.prepareEvent(inEvent);
        dispatcher.over(e);
      }
    },
    mouseout: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        var e = this.prepareEvent(inEvent);
        dispatcher.out(e);
      }
    }
  };

  var msEvents = {
    events: [
      'MSPointerDown',
      'MSPointerMove',
      'MSPointerUp',
      'MSPointerOut',
      'MSPointerOver',
      'MSPointerCancel'
    ],
    POINTER_TYPES: [
      'NOT USED',
      'unavailable',
      'touch',
      'pen',
      'mouse'
    ],
    prepareEvent: function(inEvent) {
      var e = dispatcher.cloneEvent(inEvent);
      e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
      return e;
    },
    MSPointerDown: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.down(e);
    },
    MSPointerMove: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.move(e);
    },
    MSPointerUp: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.up(e);
    },
    MSPointerOut: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.out(e);
    },
    MSPointerOver: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.over(e);
    },
    MSPointerCancel: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.cancel(e);
    }
  };

  // only activate if this platform does not have pointer events
  if (window.navigator.pointerEnabled === undefined) {

    if (window.navigator.msPointerEnabled) {
      var tp = window.navigator.msMaxTouchPoints;
      Object.defineProperty(window.navigator, 'maxTouchPoints', {
        value: tp,
        enumerable: true
      });
      dispatcher.registerSource('ms', msEvents);
      dispatcher.registerTarget(document);
    } else {
      dispatcher.registerSource('mouse', mouseEvents);
      if ('ontouchstart' in window) {
        dispatcher.registerSource('touch', touchEvents);
      }
      installer.enableOnSubtree(document);
      // mouse move events must be on at all times
      dispatcher.listen(['mousemove'], document);
    }

    Object.defineProperty(window.navigator, 'pointerEnabled', {value: true, enumerable: true});
  }
})(window.__PointerEventShim__);
<commit_msg>One move is enough to determine scroll or events<commit_after>/*!
 * Copyright 2012 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

/**
 * This module contains the handlers for native platform events.
 * From here, the dispatcher is called to create unified pointer events.
 * Included are touch events (v1), mouse events, and MSPointerEvents.
 */
(function(scope) {
  var dispatcher = scope.dispatcher;
  var installer = scope.installer;
  var pointermap = dispatcher.pointermap;
  var touchMap = Array.prototype.map.call.bind(Array.prototype.map);
  // This should be long enough to ignore compat mouse events made by touch
  var DEDUP_TIMEOUT = 2500;
  // radius around touchend that swallows mouse events
  var DEDUP_DIST = 25;
  // distance a finger can travel before being a scroll
  var SCROLL_HYSTERESIS = 10;
  // handler block for native touch events
  var touchEvents = {
    events: [
      'touchstart',
      'touchmove',
      'touchend',
      'touchcancel'
    ],
    POINTER_TYPE: 'touch',
    firstTouch: null,
    isPrimaryTouch: function(inTouch) {
      return this.firstTouch === inTouch.identifier;
    },
    setPrimaryTouch: function(inTouch) {
      if (this.firstTouch === null) {
        this.firstTouch = inTouch.identifier;
        this.firstXY = {X: inTouch.clientX, Y: inTouch.clientY};
        this.scrolling = false;
      }
    },
    removePrimaryTouch: function(inTouch) {
      if (this.isPrimaryTouch(inTouch)) {
        this.firstTouch = null;
        this.firstXY = null;
      }
    },
    touchToPointer: function(inTouch) {
      var e = dispatcher.cloneEvent(inTouch);
      // Spec specifies that pointerId 1 is reserved for Mouse.
      // Touch identifiers can start at 0.
      // Add 2 to the touch identifier for compatibility.
      e.pointerId = inTouch.identifier + 2;
      e.target = this.findTarget(e);
      e.bubbles = true;
      e.cancelable = true;
      e.button = 0;
      e.buttons = 1;
      e.isPrimary = this.isPrimaryTouch(inTouch);
      e.pointerType = this.POINTER_TYPE;
      return e;
    },
    processTouches: function(inEvent, inFunction) {
      var tl = inEvent.changedTouches;
      var pointers = touchMap(tl, this.touchToPointer, this);
      pointers.forEach(inFunction, this);
    },
    shadow: function(inEl) {
      return inEl && (inEl.webkitShadowRoot || inEl.shadowRoot);
    },
    searchRoot: function(inRoot, x, y) {
      if (inRoot) {
        var t = inRoot.elementFromPoint(x, y);
        var st, sr, os;
        // is element a shadow host?
        sr = this.shadow(t);
        while (sr) {
          // find the the element inside the shadow root
          st = sr.elementFromPoint(x, y);
          if (!st) {
            // check for older shadows
            os = sr.querySelector('shadow');
            // check the older shadow if available
            sr = os ? os.olderShadowRoot : null;
          } else {
            // shadowed element may contain a shadow root
            var ssr = this.shadow(st);
            return this.searchRoot(ssr, x, y) || st;
          }
        }
        // light dom element is the target
        return t;
      }
    },
    findTarget: function(inEvent) {
      var x = inEvent.clientX, y = inEvent.clientY;
      return this.searchRoot(document, x, y);
    },
    // For single axis scrollers, determines whether the element should emit
    // pointer events or behave as a scroller
    shouldScroll: function(inEvent) {
      if (this.firstXY) {
        var scrollAxis = dispatcher.scrollType.get(inEvent.currentTarget);
        // this element is a touch-action: none, should never scroll
        if (scrollAxis === 'none') {
          this.firstXY = null;
          return false;
        } else {
          var t = inEvent.changedTouches[0];
          // check the intended scroll axis, and other axis
          var a = scrollAxis;
          var oa = scrollAxis === 'Y' ? 'X' : 'Y';
          var da = Math.abs(t['client' + a] - this.firstXY[a]);
          var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
          this.firstXY = null;
          // if delta in the scroll axis > delta other axis, scroll instead of
          // making events
          console.log(da, doa);
          return da >= doa;
        }
      }
    },
    touchstart: function(inEvent) {
      this.setPrimaryTouch(inEvent.changedTouches[0]);
      if (!this.scrolling) {
        this.processTouches(inEvent, this.overDown);
      }
    },
    overDown: function(inPointer) {
      var p = pointermap.set(inPointer.pointerId, {
        target: inPointer.target,
        out: inPointer,
        outTarget: inPointer.target
      });
      dispatcher.over(inPointer);
      dispatcher.down(inPointer);
    },
    touchmove: function(inEvent) {
      if (!this.scrolling) {
        if (this.shouldScroll(inEvent)) {
          this.scrolling = true;
          this.touchcancel(inEvent);
        } else {
          inEvent.preventDefault();
          this.processTouches(inEvent, this.moveOverOut);
        }
      }
    },
    moveOverOut: function(inPointer) {
      var event = inPointer;
      var pointer = pointermap.get(event.pointerId);
      var outEvent = pointer.out;
      var outTarget = pointer.outTarget;
      dispatcher.move(event);
      if (outEvent && outTarget !== event.target) {
        outEvent.relatedTarget = event.target;
        event.relatedTarget = outTarget;
        // recover from retargeting by shadow
        outEvent.target = outTarget;
        dispatcher.out(outEvent);
        dispatcher.over(event);
      }
      pointer.out = event;
      pointer.outTarget = event.target;
    },
    touchend: function(inEvent) {
      this.dedupSynthMouse(inEvent);
      this.processTouches(inEvent, this.upOut);
    },
    upOut: function(inPointer) {
      if (!this.scrolling) {
        dispatcher.up(inPointer);
        dispatcher.out(inPointer);
      }
      this.cleanUpPointer(inPointer);
    },
    touchcancel: function(inEvent) {
      this.processTouches(inEvent, this.cancelOut);
    },
    cancelOut: function(inPointer) {
      dispatcher.cancel(inPointer);
      dispatcher.out(inPointer);
      this.cleanUpPointer(inPointer);
    },
    cleanUpPointer: function(inPointer) {
      pointermap.delete(inPointer.pointerId);
      this.removePrimaryTouch(inPointer);
    },
    // prevent synth mouse events from creating pointer events
    dedupSynthMouse: function(inEvent) {
      var lts = mouseEvents.lastTouches;
      var t = inEvent.changedTouches[0];
      // only the primary finger will synth mouse events
      if (this.isPrimaryTouch(t)) {
        // remember x/y of last touch
        var lt = {x: t.clientX, y: t.clientY};
        lts.push(lt);
        var fn = (function(lts, lt){
          var i = lts.indexOf(lt);
          if (i > -1) {
            lts.splice(i, 1)
          }
        }).bind(null, lts, lt);
        setTimeout(fn, DEDUP_TIMEOUT);
      }
    }
  };

  // handler block for native mouse events
  var mouseEvents = {
    // Mouse is required to have a pointerId of 1
    POINTER_ID: 1,
    POINTER_TYPE: 'mouse',
    events: [
      'mousedown',
      'mousemove',
      'mouseup',
      'mouseover',
      'mouseout'
    ],
    global: [
      'mousedown',
      'mouseup',
      'mouseover',
      'mouseout'
    ],
    lastTouches: [],
    isEventSimulatedFromTouch: function(inEvent) {
      var lts = this.lastTouches;
      var x = inEvent.clientX, y = inEvent.clientY;
      for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
        // simulated mouse events will be swallowed near a primary touchend
        var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
        if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
          return true;
        }
      }
    },
    prepareEvent: function(inEvent) {
      var e = dispatcher.cloneEvent(inEvent);
      e.pointerId = this.POINTER_ID;
      e.isPrimary = true;
      e.pointerType = this.POINTER_TYPE;
      return e;
    },
    mousedown: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        if (!pointermap.has(this.POINTER_ID)) {
          var e = this.prepareEvent(inEvent);
          var p = pointermap.set(this.POINTER_ID, inEvent);
          dispatcher.down(e);
          dispatcher.listen(this.global, document);
        }
      }
    },
    mousemove: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        var e = this.prepareEvent(inEvent);
        dispatcher.move(e);
      }
    },
    mouseup: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        var p = pointermap.get(this.POINTER_ID);
        if (p && p.button === inEvent.button) {
          var e = this.prepareEvent(inEvent);
          dispatcher.up(e);
          pointermap.delete(this.POINTER_ID);
          dispatcher.unlisten(this.global, document);
        }
      }
    },
    mouseover: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        var e = this.prepareEvent(inEvent);
        dispatcher.over(e);
      }
    },
    mouseout: function(inEvent) {
      if (!this.isEventSimulatedFromTouch(inEvent)) {
        var e = this.prepareEvent(inEvent);
        dispatcher.out(e);
      }
    }
  };

  var msEvents = {
    events: [
      'MSPointerDown',
      'MSPointerMove',
      'MSPointerUp',
      'MSPointerOut',
      'MSPointerOver',
      'MSPointerCancel'
    ],
    POINTER_TYPES: [
      'NOT USED',
      'unavailable',
      'touch',
      'pen',
      'mouse'
    ],
    prepareEvent: function(inEvent) {
      var e = dispatcher.cloneEvent(inEvent);
      e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
      return e;
    },
    MSPointerDown: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.down(e);
    },
    MSPointerMove: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.move(e);
    },
    MSPointerUp: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.up(e);
    },
    MSPointerOut: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.out(e);
    },
    MSPointerOver: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.over(e);
    },
    MSPointerCancel: function(inEvent) {
      var e = this.prepareEvent(inEvent);
      dispatcher.cancel(e);
    }
  };

  // only activate if this platform does not have pointer events
  if (window.navigator.pointerEnabled === undefined) {

    if (window.navigator.msPointerEnabled) {
      var tp = window.navigator.msMaxTouchPoints;
      Object.defineProperty(window.navigator, 'maxTouchPoints', {
        value: tp,
        enumerable: true
      });
      dispatcher.registerSource('ms', msEvents);
      dispatcher.registerTarget(document);
    } else {
      dispatcher.registerSource('mouse', mouseEvents);
      if ('ontouchstart' in window) {
        dispatcher.registerSource('touch', touchEvents);
      }
      installer.enableOnSubtree(document);
      // mouse move events must be on at all times
      dispatcher.listen(['mousemove'], document);
    }

    Object.defineProperty(window.navigator, 'pointerEnabled', {value: true, enumerable: true});
  }
})(window.__PointerEventShim__);
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');

const Couch = require('../index');
const debug = require('../util/debug')('import');
const getConfig = require('../config/config').getConfig;

exports.import = function (database, importName, file) {
    debug(`import ${file} (${database}, ${importName})`);

    const filename = path.parse(file).base;
    const contents = fs.readFileSync(file);

    let config = getConfig(database);
    if (!config.import || !config.import[importName]) {
        throw new Error(`no import config for ${database}/${importName}`);
    }
    config = config.import[importName];

    const couch = Couch.get(database);

    // Callbacks
    const getID = verifyConfig('getID', null, true);
    const getOwner = verifyConfig('getOwner', null, true);
    let parse = null;
    let json = null;
    try {
        parse = verifyConfig('parse', null, true);
    } catch (e) {
        json = verifyConfig('json', null, true);
    }

    return Promise.resolve()
        .then(getMetadata)
        .then(parseFile)
        .then(getKind)
        .then(checkDocumentExists)
        .then(updateDocument)
        .then(function () {
            debug.trace(`import ${file} success`);
            couch.log(`Import ${file} ok`, 'WARN');
        }).catch(function (e) {
            debug.error(`import ${file} failure: ${e.message}, ${e.stack}`);
            couch.log(`Import ${file} failed: ${e.message}`, 'ERROR');
            throw e;
        });

    function verifyConfig(name, defaultValue, mustBeFunction) {
        const value = config[name];
        if (value === undefined) {
            if (defaultValue) {
                return defaultValue;
            }
            throw new Error('missing configuration value: ' + name);
        }
        if (mustBeFunction && typeof value !== 'function') {
            throw new Error(`configuration value ${name} must be a function`);
        }
        return value;
    }

    function getMetadata() {
        debug.trace('get metadata');
        const id = Promise.resolve(getID(filename, contents));
        const owner = Promise.resolve(getOwner(filename, contents));
        return Promise.all([id, owner]).then(function (result) {
            debug.trace(`id: ${result[0]}, owner: ${result[1]}`);
            return {id: result[0], owner: result[1]};
        });
    }

    function getKind(info) {
        debug.trace('getKind');
        if (!config.kind) return info;
        if (! (typeof config.kind === 'function')) {
            info.kind = config.kind;
            return info;
        }
        return Promise.resolve(config.kind(filename, contents)).then(function (kind) {
            info.kind = kind;
            return info;
        });
    }

    function parseFile(info) {
        debug.trace('parse file contents');
        if (parse) {
            return Promise.resolve(parse(filename, contents)).then(function (result) {
                if (typeof result.jpath !== 'string') {
                    throw new Error('parse: jpath must be a string');
                }
                if (typeof result.data !== 'object' || result.data === null) {
                    throw new Error('parse: data must be an object');
                }
                if (typeof result.type !== 'string') {
                    throw new Error('parse: type must be a string');
                }

                debug.trace(`jpath: ${result.jpath}`);
                info.jpath = result.jpath.split('.');
                info.data = result.data;
                info.content_type = result.content_type || 'application/octet-stream';
                info.type = result.type;
                return info;
            });
        } else if (json) {
            return Promise.resolve(json(filename, contents)).then(function (result) {
                info.data = result;
                return info;
            });
        }
    }

    function checkDocumentExists(info) {
        debug.trace('checkDocumentExists');
        return couch.createEntry(info.id, info.owner, {
            createParameters: [filename, contents],
            kind: info.kind
        }).then(docInfo => {
            return {
                info,
                docInfo
            };
        });
    }

    function updateDocument(info) {
        debug.trace('updateDocument');
        if (parse) {
            info = info.info;
            return couch.addFileToJpath(info.id, info.owner, info.jpath, info.data, {
                type: info.type,
                name: filename,
                data: contents,
                content_type: info.content_type
            });
        }
        else if (json) {
            var entry = {};
            entry.$id = info.info.id;
            entry.$kind = config.kind;
            entry.$content = info.info.data;
            entry._id = info.docInfo.id;
            entry._rev = info.docInfo.rev;
            return couch.insertEntry(entry, info.info.owner, {
                merge: true
            });
        }
    }
};
<commit_msg>import: if json, parse right away<commit_after>'use strict';

const fs = require('fs');
const path = require('path');

const Couch = require('../index');
const debug = require('../util/debug')('import');
const getConfig = require('../config/config').getConfig;

exports.import = function (database, importName, file) {
    debug(`import ${file} (${database}, ${importName})`);

    const filename = path.parse(file).base;
    let contents = fs.readFileSync(file);

    let config = getConfig(database);
    if (!config.import || !config.import[importName]) {
        throw new Error(`no import config for ${database}/${importName}`);
    }
    config = config.import[importName];

    const couch = Couch.get(database);

    // Callbacks
    const getID = verifyConfig('getID', null, true);
    const getOwner = verifyConfig('getOwner', null, true);
    let parse = null;
    let json = null;
    try {
        parse = verifyConfig('parse', null, true);
    } catch (e) {
        json = verifyConfig('json', null, true);
    }

    if(json) contents = JSON.parse(contents);

    return Promise.resolve()
        .then(getMetadata)
        .then(parseFile)
        .then(getKind)
        .then(checkDocumentExists)
        .then(updateDocument)
        .then(function () {
            debug.trace(`import ${file} success`);
            couch.log(`Import ${file} ok`, 'WARN');
        }).catch(function (e) {
            debug.error(`import ${file} failure: ${e.message}, ${e.stack}`);
            couch.log(`Import ${file} failed: ${e.message}`, 'ERROR');
            throw e;
        });

    function verifyConfig(name, defaultValue, mustBeFunction) {
        const value = config[name];
        if (value === undefined) {
            if (defaultValue) {
                return defaultValue;
            }
            throw new Error('missing configuration value: ' + name);
        }
        if (mustBeFunction && typeof value !== 'function') {
            throw new Error(`configuration value ${name} must be a function`);
        }
        return value;
    }

    function getMetadata() {
        debug.trace('get metadata');
        const id = Promise.resolve(getID(filename, contents));
        const owner = Promise.resolve(getOwner(filename, contents));
        return Promise.all([id, owner]).then(function (result) {
            debug.trace(`id: ${result[0]}, owner: ${result[1]}`);
            return {id: result[0], owner: result[1]};
        });
    }

    function getKind(info) {
        debug.trace('getKind');
        if (!config.kind) return info;
        if (! (typeof config.kind === 'function')) {
            info.kind = config.kind;
            return info;
        }
        return Promise.resolve(config.kind(filename, contents)).then(function (kind) {
            info.kind = kind;
            return info;
        });
    }

    function parseFile(info) {
        debug.trace('parse file contents');
        if (parse) {
            return Promise.resolve(parse(filename, contents)).then(function (result) {
                if (typeof result.jpath !== 'string') {
                    throw new Error('parse: jpath must be a string');
                }
                if (typeof result.data !== 'object' || result.data === null) {
                    throw new Error('parse: data must be an object');
                }
                if (typeof result.type !== 'string') {
                    throw new Error('parse: type must be a string');
                }

                debug.trace(`jpath: ${result.jpath}`);
                info.jpath = result.jpath.split('.');
                info.data = result.data;
                info.content_type = result.content_type || 'application/octet-stream';
                info.type = result.type;
                return info;
            });
        } else if (json) {
            return Promise.resolve(json(filename, contents)).then(function (result) {
                info.data = result;
                return info;
            });
        }
    }

    function checkDocumentExists(info) {
        debug.trace('checkDocumentExists');
        return couch.createEntry(info.id, info.owner, {
            createParameters: [filename, contents],
            kind: info.kind
        }).then(docInfo => {
            return {
                info,
                docInfo
            };
        });
    }

    function updateDocument(info) {
        debug.trace('updateDocument');
        if (parse) {
            info = info.info;
            return couch.addFileToJpath(info.id, info.owner, info.jpath, info.data, {
                type: info.type,
                name: filename,
                data: contents,
                content_type: info.content_type
            });
        }
        else if (json) {
            var entry = {};
            entry.$id = info.info.id;
            entry.$kind = config.kind;
            entry.$content = info.info.data;
            entry._id = info.docInfo.id;
            entry._rev = info.docInfo.rev;
            return couch.insertEntry(entry, info.info.owner, {
                merge: true
            });
        }
    }
};
<|endoftext|>


<commit_before>Game = Game || {};

Game.setupPlayerComponent = function(){
    Crafty.c("Guardian", {
      x:1100,
      y:0,
      h:100,
      w:100,
      init: function() {
        this.bind("guardian:open", this.handleComplete);
        this.open = false;
      },
      handleComplete: function() {
        this.open = true;
      }
    });

    // Player component - for handling moving player on screen
    Crafty.c("Snowden", {
        dx: 0, // setting initial vertical speed - note variables are set differently here

        init: function() {
            var that = this;
            var score = Crafty.e("Score");
            this.bind("EnterFrame",this.handlebase); // bind the EnterFrame event to the "handlebase" function below
            this.bind("KeyDown",this.handlekey); // bind the EnterFrame event to the "handlebase" function below

            this.addComponent("PlayerPic"); // add the player picture to this entity
            this.addComponent("Collision");
            this.addComponent("Fourway");
            this.fourway(4,0);

            //setup die collisions
            _.each(Game.evilComponents, function(componentName){
                that.onHit(componentName, function(collidingComponent){
                    that.heartBar.pop().destroy();

                    if(that.heartBar.length<=0){
                        Crafty.trigger("game:over");
                        Crafty.e("2D, Canvas, Skull").attr({x:that.x+8,y:that.y+5,z:that.z-3});
                        that.destroy();
                    }
                    that.x = 100;
                    that.y = 50;
                });
            });

            //setup obstacle collisions
            _.each(Game.obstacles, function(componentName){
                that.onHit(componentName, function(collidingComponent){
                    if (!this.colliding) {
                        var player = this ,
                            origin = {
                                x: player.x - player._movement.x * 1.1 ,
                                y: player.y - player._movement.y * 1.1
                            };
                        this.colliding = true;
                        setTimeout(function () {
                            player.x = origin.x;
                            player.y = origin.y;
                            player.colliding = false;
                        }, 10);
                    }
                });
            });

            that.onHit("Guardian", function(obj) {
              office = obj[0].obj;
              if(office.open){
                Crafty.trigger('game:won');
              }
            });

            that.onHit("Document", function(doc){
              if(that.documentCount < 5){
                that.documentCount++;
                doc[0].obj.destroy();
              }

              if(that.documentCount == 5){
                Crafty.trigger('guardian:open');
              }
            });

            that.onHit("CoffeeCup", function(collidingComponent){
              if(that.heartBar.length<3){
                that.heartBar.push(Crafty.e("2D, Canvas, Heart"));
                collidingComponent[0].obj.destroy();
              }
            });

            this.onHit("Coin", function(data){
                bitcoin = data[0].obj;
                bitcoin.destroy();
                score.update(20);
            });

            this.heartBar = [Crafty.e("2D, Canvas, Heart"),
                Crafty.e("2D, Canvas, Heart"),
                Crafty.e("2D, Canvas, Heart")
            ];
            this.heartBarOffset = {x: -8, y:-8};

        },
        handlebase: function() { // runs every frame
            var that = this;
            Crafty.viewport.scroll('_x', -(this.x + (this.w / 2) - (Crafty.viewport.width / 2) ));
            Crafty.viewport.scroll('_y', -(this.y + (this.h / 2) - (Crafty.viewport.height / 2) ));

            _.each(this.heartBar,function(element,index){
                element.x = that.x + index * 8 + that.heartBarOffset.x + that._movement.x;
                element.y = that.y + that.heartBarOffset.y + that._movement.y;
                element.z = that.z + 1;
            });
        },
        handlekey: function(keyevent) { // handles key events
            if(keyevent.keyCode === Crafty.keys.SPACE) { // they hit space
                Crafty.e("2D, Canvas, Shot").attr({x:this.x+34, y:500, z:1}); // create a shot at our current position
            }
        },
    });

};

Game.createPlayerComponent = function(playerStart){

    return Crafty.e("2D, Canvas, SpriteAnimation, Snowden")
        .attr(playerStart)
        .animate('walk_up', 0, 0, 1)
        .animate('walk_up', [[0,0], [1,0], [2,0]])
        // .animate('walk_up',12, -1)
        .animate('walk_right', 0, 0, 1)
        .animate('walk_right', [[3,0], [4,0], [5,0]])
        // .animate('walk_right',12, -1)
        .animate('walk_down', 0, 0, 1)
        .animate('walk_down', [[6,0], [7,0], [8,0]])
        // .animate('walk_down',12, -1)
        .animate('walk_left', 0, 0, 1)
        .animate('walk_left', [[9,0], [10,0], [11,0]])
        // .animate('walk_left',12, -1)
        .bind("KeyDown", function(e) {
            if(e.keyCode === Crafty.keys.LEFT_ARROW || e.keyCode === Crafty.keys.A) {
                if(!this.isPlaying("walk_left"))
                    this.stop().animate("walk_left", 12, -1);
            } else if(e.keyCode === Crafty.keys.RIGHT_ARROW || e.keyCode === Crafty.keys.D) {
                if(!this.isPlaying("walk_right"))
                    this.stop().animate("walk_right", 12, -1);
            } else if(e.keyCode === Crafty.keys.UP_ARROW || e.keyCode === Crafty.keys.W) {
                if(!this.isPlaying("walk_up"))
                    this.stop().animate("walk_up", 12, -1);
            } else if(e.keyCode === Crafty.keys.DOWN_ARROW || e.keyCode === Crafty.keys.S) {
                if(!this.isPlaying("walk_down"))
                    this.stop().animate("walk_down", 12, -1);
            }
        }).bind("KeyUp", function(e) {
            this.stop();
        });

}
<commit_msg>more bad merging<commit_after>Game = Game || {};

Game.setupPlayerComponent = function(){
    Crafty.c("Guardian", {
      x:1100,
      y:0,
      h:100,
      w:100,
      init: function() {
        this.bind("guardian:open", this.handleComplete);
        this.open = false;
      },
      handleComplete: function() {
        this.open = true;
      }
    });

    // Player component - for handling moving player on screen
    Crafty.c("Snowden", {
        dx: 0, // setting initial vertical speed - note variables are set differently here

        init: function() {
            var that = this;
            var score = Crafty.e("Score");
            this.bind("EnterFrame",this.handlebase); // bind the EnterFrame event to the "handlebase" function below
            this.bind("KeyDown",this.handlekey); // bind the EnterFrame event to the "handlebase" function below

            this.addComponent("PlayerPic"); // add the player picture to this entity
            this.addComponent("Collision");
            this.addComponent("Fourway");
            this.fourway(4,0);

            //setup die collisions
            _.each(Game.evilComponents, function(componentName){
                that.onHit(componentName, function(collidingComponent){
                    that.heartBar.pop().destroy();

                    if(that.heartBar.length<=0){
                        Crafty.trigger("game:over");
                        Crafty.e("2D, Canvas, Skull").attr({x:that.x+8,y:that.y+5,z:that.z-3});
                        that.destroy();
                    }
                    that.x = 100;
                    that.y = 50;
                });
            });

            //setup obstacle collisions
            _.each(Game.obstacles, function(componentName){
                that.onHit(componentName, function(collidingComponent){
                    if (!this.colliding) {
                        var player = this ,
                            origin = {
                                x: player.x - player._movement.x * 1.1 ,
                                y: player.y - player._movement.y * 1.1
                            };
                        this.colliding = true;
                        setTimeout(function () {
                            player.x = origin.x;
                            player.y = origin.y;
                            player.colliding = false;
                        }, 10);
                    }
                });
            });

            that.onHit("Guardian", function(obj) {
              office = obj[0].obj;
              if(office.open){
                Crafty.trigger('game:won');
              }
            });

            that.onHit("Document", function(doc){
              if(that.documentCount < 5){
                that.documentCount++;
                doc[0].obj.destroy();
              }

              if(that.documentCount == 5){
                Crafty.trigger('guardian:open');
              }
            });

            that.onHit("CoffeeCup", function(collidingComponent){
              if(that.heartBar.length<3){
                that.heartBar.push(Crafty.e("2D, Canvas, Heart"));
                collidingComponent[0].obj.destroy();
              }
            });

            this.onHit("Coin", function(data){
                bitcoin = data[0].obj;
                bitcoin.destroy();
                score.update(20);
            });

            this.heartBar = [Crafty.e("2D, Canvas, Heart"),
                Crafty.e("2D, Canvas, Heart"),
                Crafty.e("2D, Canvas, Heart")
            ];
            this.heartBarOffset = {x: -8, y:-8};
            this.documentCount = 0;
        },
        handlebase: function() { // runs every frame
            var that = this;
            Crafty.viewport.scroll('_x', -(this.x + (this.w / 2) - (Crafty.viewport.width / 2) ));
            Crafty.viewport.scroll('_y', -(this.y + (this.h / 2) - (Crafty.viewport.height / 2) ));

            _.each(this.heartBar,function(element,index){
                element.x = that.x + index * 8 + that.heartBarOffset.x + that._movement.x;
                element.y = that.y + that.heartBarOffset.y + that._movement.y;
                element.z = that.z + 1;
            });
        },
        handlekey: function(keyevent) { // handles key events
            if(keyevent.keyCode === Crafty.keys.SPACE) { // they hit space
                Crafty.e("2D, Canvas, Shot").attr({x:this.x+34, y:500, z:1}); // create a shot at our current position
            }
        },
    });

};

Game.createPlayerComponent = function(playerStart){

    return Crafty.e("2D, Canvas, SpriteAnimation, Snowden")
        .attr(playerStart)
        .animate('walk_up', 0, 0, 1)
        .animate('walk_up', [[0,0], [1,0], [2,0]])
        // .animate('walk_up',12, -1)
        .animate('walk_right', 0, 0, 1)
        .animate('walk_right', [[3,0], [4,0], [5,0]])
        // .animate('walk_right',12, -1)
        .animate('walk_down', 0, 0, 1)
        .animate('walk_down', [[6,0], [7,0], [8,0]])
        // .animate('walk_down',12, -1)
        .animate('walk_left', 0, 0, 1)
        .animate('walk_left', [[9,0], [10,0], [11,0]])
        // .animate('walk_left',12, -1)
        .bind("KeyDown", function(e) {
            if(e.keyCode === Crafty.keys.LEFT_ARROW || e.keyCode === Crafty.keys.A) {
                if(!this.isPlaying("walk_left"))
                    this.stop().animate("walk_left", 12, -1);
            } else if(e.keyCode === Crafty.keys.RIGHT_ARROW || e.keyCode === Crafty.keys.D) {
                if(!this.isPlaying("walk_right"))
                    this.stop().animate("walk_right", 12, -1);
            } else if(e.keyCode === Crafty.keys.UP_ARROW || e.keyCode === Crafty.keys.W) {
                if(!this.isPlaying("walk_up"))
                    this.stop().animate("walk_up", 12, -1);
            } else if(e.keyCode === Crafty.keys.DOWN_ARROW || e.keyCode === Crafty.keys.S) {
                if(!this.isPlaying("walk_down"))
                    this.stop().animate("walk_down", 12, -1);
            }
        }).bind("KeyUp", function(e) {
            this.stop();
        });

}
<|endoftext|>