<commit_before>var contentGrid = {
    init : function () {
        var $contentGrid = $jQ('#main-column .content-grid').not('.guide-grid'),
        $contentItems = $contentGrid.find('.content-item'),
        $quickviewLinks = $contentItems.find('.quick-view');
        $featuredHover = $contentItems.find('.featured-corner');
        $featuredReveal = $contentItems.find('.shop-this');
        $featuredHide = $contentItems.find('.back-to-story');
        $featuredReveal.click(contentGrid.featuredReveal);
        $featuredHide.click(contentGrid.featuredHide);
        $jQ('#load-more').click(MLS.ajax.lazyLoad.more);
        $jQ('#load-remaining').click(MLS.ajax.lazyLoad.remaining);
        contentGrid.sortHeader();
        contentGrid.mobileFilter.init();
        if (!isTouch) {
            MLS.ui.gridHover($contentItems.not('.large'), {
                topBar: $contentItems.find('.color-picker'),
                actions: $contentItems.find('.content-details')
            }, 10);
            //$contentItems.hover(contentGrid.productTileEnter, contentGrid.productTileLeave);
            $quickviewLinks.not('.large').on('click', {'$contentGrid' : $contentGrid}, contentGrid.quickViewHandler);
            $featuredHover.hover(contentGrid.featuredHover, contentGrid.featuredHoverOff);
        }
    },
    sortHeader: function () {
        $jQ('li', '#sort-options').on('click', function (e) {
            e.preventDefault();
            var type = $jQ(this).attr('data-type');
            //Fire Ajax
            MLS.ajax.gridSort(type);
            $jQ('li', '#sort-options').removeClass('active');
            $jQ(this).addClass('active');
        });
    },
    mobileFilter : {
        init: function () {
            //Event handler for clicks !!!D.R.Y:-(
            $jQ('a.filter', '#mobile-sort-filter').on('click', function (e) {
                e.preventDefault();
                if ($jQ(this).hasClass('active')) {
                    $jQ(this).removeClass('active').css({height: '45px'});
                    $jQ('.dropdown-menu', '#mobile-sort-filter').slideUp(200);
                } else {
                    $jQ('.dropdown-cta', '#mobile-sort-filter').not(this).removeClass('active').css({height: '45px'});
                    $jQ(this).addClass('active').css({height: '50px'});
                    $jQ('.dropdown-menu', '#mobile-sort-filter').slideDown(200);
                    $jQ('.submenu-list', '#mobile-sort-filter').hide();
                    $jQ('.filter-options-list', '#mobile-sort-filter').show();
                }
            });
            $jQ('a.sort', '#mobile-sort-filter').on('click', function (e) {
                e.preventDefault();
                if ($jQ(this).hasClass('active')) {
                    $jQ(this).removeClass('active').css({height: '45px'});
                    $jQ('.dropdown-menu', '#mobile-sort-filter').slideUp(200);
                } else {
                    $jQ('.dropdown-cta', '#mobile-sort-filter').not(this).removeClass('active').css({height: '45px'});
                    $jQ(this).addClass('active').css({height: '50px'});
                    $jQ('.dropdown-menu', '#mobile-sort-filter').slideDown(200);
                    $jQ('.submenu-list', '#mobile-sort-filter').hide();
                    $jQ('.sort-options-list', '#mobile-sort-filter').show();
                }
            });

            $jQ('li.filter-option', '.filter-options-list').on('click', function () {
                var dimension = $jQ(this).attr('data-type');
                contentGrid.mobileFilter.filterPanel(dimension);
            });
            //Toggle states for multi select
            $jQ('.list-option', '.filter-panel .multi-select').on('click', function () {
                $jQ(this).toggleClass('selected');
            });
            //Toggle states for single select
            $jQ('.list-option', '.filter-panel .single-select').on('click', function () {
                $jQ(this).parent('ul').find('li').removeClass('selected');
                $jQ(this).toggleClass('selected');
            });

        },
        filterPanel: function (dimension) {
            var viewportHeight = Response.viewportH();
            $jQ('.filter-panels .filter-panel').hide();
            $jQ('.filter-panel.' + dimension).show();
            $jQ('.filter-panels').show(function () {
                $jQ(this).animate({height: viewportHeight});
            });
            $jQ('.filter-panels .close').one('click', function () {
                $jQ('.filter-panels').animate({height: 0}, function () {
                    $jQ(this).hide();
                });
            });
        },
        updateFilters: function () {

        }
    },
    productTileEnter : function () {
        $jQ(this).addClass('active');
    },
    productTileLeave : function () {
        $jQ(this).removeClass('active');
    },
    quickViewHandler : function (e) {
        var $quickView = $jQ('#quick-view-overlay'),
        $parentTile = $jQ(this).parent().parent(),
        $contentTile = $parentTile.hasClass('featured') ? $parentTile.next() : $parentTile,
        $cTposition = $contentTile.position(),
        $closeQv = $jQ('#close-quick-view').on('click', { qv : $quickView }, contentGrid.quickViewClose);

        if ($parentTile.hasClass('bundle')) {
            $quickView = $jQ('.quick-view-overlay.bundle');
        }

        $jQ('#quick-view-modal').fadeIn('fast');
        $quickView.css({
            'display' : 'block',
            'top' : $cTposition.top + ($parentTile.hasClass('featured') ? $parentTile.outerHeight() : 0) + 15,
            //'height' : $contentTile.outerHeight() * 2,
            'width' : (e.data.$contentGrid.outerWidth())
        });
        $jQ('html, body').animate({
            scrollTop : $cTposition.top + ($contentTile.outerHeight() / 2) + ($parentTile.hasClass('featured') ? $parentTile.outerHeight() : 0)
        }, 500, function () {
            contentGrid.initSlider();
            setTimeout(function () { // ensure scroll is fully complete before attaching these event handlers
                $jQ(window).on({
                    'resize.quickView' : contentGrid.quickViewClose,
                    'scroll.quickView' : contentGrid.quickViewClose,
                    'click.quickView' : function (e) {
                        if ($jQ(e.target).closest($quickView).length === 0) {
                            contentGrid.quickViewClose(e);
                        }
                    }
                }, { 'qv' : $quickView });
            }, 1);
        });
    },
    initSlider : function () {
        $jQ('#quick-view-slider').flexslider({
            animation: 'slide',
            controlNav: true,
            directionNav: false,
            controlsContainer: '#slider-controls',
            manualControls : '.flex-control-thumbs li',
            slideshow: false
        });

        var $sliderThumbs = $jQ('#slider-controls .flex-control-thumbs');
        $sliderThumbs.attr('style','');
        contentGrid.setThumbnailMargins($sliderThumbs, ($jQ(window).width() >= 1024 ? 'left' : 'top'));
    },
    setThumbnailMargins : function ($sT, pos) {
        var offset = pos === 'left' ? $sT.outerWidth() : $sT.outerHeight();
        $sT.css('margin-' + pos, '-' + (offset / 2) + 'px');
    },
    quickViewClose : function (e) {
        e.preventDefault();
        contentGrid.removeCloseListeners();
        var $qv = $jQ(e.data.qv);
        $qv.fadeOut('fast');
        $jQ('#quick-view-modal').fadeOut('fast');
    },
    removeCloseListeners : function () {
        $jQ(window).off('resize.quickView');
        $jQ(window).off('scroll.quickView');
        $jQ(window).off('click.quickView');
    },
    featuredHover : function () {
        var rThis = $jQ(this).parent().find('.featured-item-hover').stop(true, true).fadeIn('fast');
    },
    featuredHoverOff : function () {
        var rThis = $jQ(this).parent().find('.featured-item-hover').stop().fadeOut('fast');
    },
    featuredReveal : function (e) {
        e.preventDefault();
        var rThis = $jQ(this).parent().siblings('.featured-item');
        var rWd = rThis.width();
        var rHt = rThis.height();
        var wdIncr = (rWd) * -1;
        var htIncr = (rHt * .98) * -1;
		$jQ(rThis).css({
            'opacity' : 1,
            '-webkit-transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) ',
            '-moz-transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) ',
            '-ms-transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) ',
            '-o-transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) ',
            'transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) '

		}); // end css
    }, // end vznReveal
    featuredHide : function (e) {
        e.preventDefault();
        var hThis = $jQ(this).parents('.featured-item');
        $jQ(hThis).css({
            'opacity' : 0,
            '-webkit-transform' : ' translate3d(0 ,0 , 0) ',
            '-moz-transform' : ' translate3d(0 ,0 , 0) ',
            '-ms-transform' : ' translate3d(0 ,0 , 0) ',
            '-o-transform' : ' translate3d(0 ,0 , 0) ',
            'transform' : ' translate3d(0 ,0 , 0) '
		}); // end css
    }// end featuredHide
};

// ............. TEMP state toggle buttons in header .........

var stndrd = document.getElementById('state-standard');
var newProd = document.getElementById('state-new-products');
var featSale = document.getElementById('state-sale-featured');
var itemSale = document.getElementById('state-sale-item');

$jQ(stndrd).click(function () {

	var stndrd = document.getElementById('state-standard');
	var newProd = document.getElementById('state-new-products');
	var featSale = document.getElementById('state-sale-featured');
	var itemSale = document.getElementById('state-sale-item');

	// change font colors for nav
	$jQ(this).addClass('on');
	$jQ(newProd).removeClass('on');
	$jQ(featSale).removeClass('on');
	$jQ(itemSale).removeClass('on');

	//turn off all special cases
	$jQ('.new-product').css('display', 'none');
	$jQ('.sale-featured').css('display', 'none');
	$jQ('.sale-item').css('display', 'none');

});

$jQ(newProd).click(function () {

	var stndrd = document.getElementById('state-standard');
	var newProd = document.getElementById('state-new-products');
	var featSale = document.getElementById('state-sale-featured');
	var itemSale = document.getElementById('state-sale-item');

	// change font colors for nav
	$jQ(this).addClass('on');
	$jQ(stndrd).removeClass('on');

	// turn on new product elements
    $jQ('.new-product').css('display', 'block');

});

$jQ(featSale).click(function () {

	var stndrd = document.getElementById('state-standard');
	var newProd = document.getElementById('state-new-products');
	var featSale = document.getElementById('state-sale-featured');
	var itemSale = document.getElementById('state-sale-item');

	// change font colors for nav
	$jQ(this).addClass('on');
	$jQ(stndrd).removeClass('on');

	//turn on featured sale elements & add class depending on screen width
	var pageWidth = document.body.clientWidth;
	if (pageWidth < 1281) {
		$jQ('.sale-featured.three-across').css('display', 'block').parent().addClass('sale-featured-block');
	} else if (pageWidth > 1280) {
		$jQ('.sale-featured.four-across').css('display', 'block').parent().addClass('sale-featured-block');
	}
});

$jQ(itemSale).click(function () {

	var stndrd = document.getElementById('state-standard');
	var newProd = document.getElementById('state-new-products');
	var featSale = document.getElementById('state-sale-featured');
	var itemSale = document.getElementById('state-sale-item');

	// change font colors for nav
	$jQ(this).addClass('on');
	$jQ(stndrd).removeClass('on');

	//turn on item sale elements & turn off hover
	$jQ('.sale-item').css('display', 'block');

}); // end TEMP state buttons
<commit_msg>fixing grid position<commit_after>var contentGrid = {
    init : function () {
        var $contentGrid = $jQ('#main-column .content-grid').not('.guide-grid'),
        $contentItems = $contentGrid.find('.content-item'),
        $quickviewLinks = $contentItems.find('.quick-view');
        $featuredHover = $contentItems.find('.featured-corner');
        $featuredReveal = $contentItems.find('.shop-this');
        $featuredHide = $contentItems.find('.back-to-story');
        $featuredReveal.click(contentGrid.featuredReveal);
        $featuredHide.click(contentGrid.featuredHide);
        $jQ('#load-more').click(MLS.ajax.lazyLoad.more);
        $jQ('#load-remaining').click(MLS.ajax.lazyLoad.remaining);
        contentGrid.sortHeader();
        contentGrid.mobileFilter.init();
        if (!isTouch) {
            MLS.ui.gridHover($contentItems.not('.large'), {
                topBar: $contentItems.find('.color-picker'),
                actions: $contentItems.find('.content-details')
            }, 10);
            //$contentItems.hover(contentGrid.productTileEnter, contentGrid.productTileLeave);
            $quickviewLinks.not('.large').on('click', {'$contentGrid' : $contentGrid}, contentGrid.quickViewHandler);
            $featuredHover.hover(contentGrid.featuredHover, contentGrid.featuredHoverOff);
        }
    },
    sortHeader: function () {
        $jQ('li', '#sort-options').on('click', function (e) {
            e.preventDefault();
            var type = $jQ(this).attr('data-type');
            //Fire Ajax
            MLS.ajax.gridSort(type);
            $jQ('li', '#sort-options').removeClass('active');
            $jQ(this).addClass('active');
        });
    },
    mobileFilter : {
        init: function () {
            //Event handler for clicks !!!D.R.Y:-(
            $jQ('a.filter', '#mobile-sort-filter').on('click', function (e) {
                e.preventDefault();
                if ($jQ(this).hasClass('active')) {
                    $jQ(this).removeClass('active').css({height: '45px'});
                    $jQ('.dropdown-menu', '#mobile-sort-filter').slideUp(200);
                } else {
                    $jQ('.dropdown-cta', '#mobile-sort-filter').not(this).removeClass('active').css({height: '45px'});
                    $jQ(this).addClass('active').css({height: '50px'});
                    $jQ('.dropdown-menu', '#mobile-sort-filter').slideDown(200);
                    $jQ('.submenu-list', '#mobile-sort-filter').hide();
                    $jQ('.filter-options-list', '#mobile-sort-filter').show();
                }
            });
            $jQ('a.sort', '#mobile-sort-filter').on('click', function (e) {
                e.preventDefault();
                if ($jQ(this).hasClass('active')) {
                    $jQ(this).removeClass('active').css({height: '45px'});
                    $jQ('.dropdown-menu', '#mobile-sort-filter').slideUp(200);
                } else {
                    $jQ('.dropdown-cta', '#mobile-sort-filter').not(this).removeClass('active').css({height: '45px'});
                    $jQ(this).addClass('active').css({height: '50px'});
                    $jQ('.dropdown-menu', '#mobile-sort-filter').slideDown(200);
                    $jQ('.submenu-list', '#mobile-sort-filter').hide();
                    $jQ('.sort-options-list', '#mobile-sort-filter').show();
                }
            });

            $jQ('li.filter-option', '.filter-options-list').on('click', function () {
                var dimension = $jQ(this).attr('data-type');
                contentGrid.mobileFilter.filterPanel(dimension);
            });
            //Toggle states for multi select
            $jQ('.list-option', '.filter-panel .multi-select').on('click', function () {
                $jQ(this).toggleClass('selected');
            });
            //Toggle states for single select
            $jQ('.list-option', '.filter-panel .single-select').on('click', function () {
                $jQ(this).parent('ul').find('li').removeClass('selected');
                $jQ(this).toggleClass('selected');
            });

        },
        filterPanel: function (dimension) {
            var viewportHeight = Response.viewportH();
            $jQ('.filter-panels .filter-panel').hide();
            $jQ('.filter-panel.' + dimension).show();
            $jQ('.filter-panels').show(function () {
                $jQ(this).animate({height: viewportHeight});
            });
            $jQ('.filter-panels .close').one('click', function () {
                $jQ('.filter-panels').animate({height: 0}, function () {
                    $jQ(this).hide();
                });
            });
        },
        updateFilters: function () {

        }
    },
    productTileEnter : function () {
        $jQ(this).addClass('active');
    },
    productTileLeave : function () {
        $jQ(this).removeClass('active');
    },
    quickViewHandler : function (e) {
        var $quickView = $jQ('#quick-view-overlay'),
        $parentTile = $jQ(this).parent().parent(),
        $contentTile = $parentTile.hasClass('featured') ? $parentTile.next() : $parentTile,
        $cTposition = $contentTile.position(),
        $closeQv = $jQ('#close-quick-view').on('click', { qv : $quickView }, contentGrid.quickViewClose);
        if ($parentTile.hasClass('bundle')) {
            $quickView = $jQ('.quick-view-overlay.bundle');
        }
        $jQ('#quick-view-modal').fadeIn('fast');
        $quickView.css({
            'display' : 'block',
            'top' : $cTposition.top + ($parentTile.hasClass('featured') ? $parentTile.outerHeight() : 0) + 15,
            'height' : $jQ('.content-item').not('.featured').outerHeight() * 2,
            'width' : (e.data.$contentGrid.outerWidth())
        });
        $jQ('html, body').animate({
            scrollTop : $cTposition.top + $contentTile.outerHeight() + 200
        }, 500, function () {
            contentGrid.initSlider();
            setTimeout(function () { // ensure scroll is fully complete before attaching these event handlers
                $jQ(window).on({
                    'resize.quickView' : contentGrid.quickViewClose,
                    'scroll.quickView' : contentGrid.quickViewClose,
                    'click.quickView' : function (e) {
                        if ($jQ(e.target).closest($quickView).length === 0) {
                            contentGrid.quickViewClose(e);
                        }
                    }
                }, { 'qv' : $quickView });
            }, 1);
        });
    },
    initSlider : function () {
        $jQ('#quick-view-slider').flexslider({
            animation: 'slide',
            controlNav: true,
            directionNav: false,
            controlsContainer: '#slider-controls',
            manualControls : '.flex-control-thumbs li',
            slideshow: false
        });

        var $sliderThumbs = $jQ('#slider-controls .flex-control-thumbs');
        $sliderThumbs.attr('style','');
        contentGrid.setThumbnailMargins($sliderThumbs, ($jQ(window).width() >= 1024 ? 'left' : 'top'));
    },
    setThumbnailMargins : function ($sT, pos) {
        var offset = pos === 'left' ? $sT.outerWidth() : $sT.outerHeight();
        $sT.css('margin-' + pos, '-' + (offset / 2) + 'px');
    },
    quickViewClose : function (e) {
        e.preventDefault();
        contentGrid.removeCloseListeners();
        var $qv = $jQ(e.data.qv);
        $qv.fadeOut('fast');
        $jQ('#quick-view-modal').fadeOut('fast');
    },
    removeCloseListeners : function () {
        $jQ(window).off('resize.quickView');
        $jQ(window).off('scroll.quickView');
        $jQ(window).off('click.quickView');
    },
    featuredHover : function () {
        var rThis = $jQ(this).parent().find('.featured-item-hover').stop(true, true).fadeIn('fast');
    },
    featuredHoverOff : function () {
        var rThis = $jQ(this).parent().find('.featured-item-hover').stop().fadeOut('fast');
    },
    featuredReveal : function (e) {
        e.preventDefault();
        var rThis = $jQ(this).parent().siblings('.featured-item');
        var rWd = rThis.width();
        var rHt = rThis.height();
        var wdIncr = (rWd) * -1;
        var htIncr = (rHt * .98) * -1;
		$jQ(rThis).css({
            'opacity' : 1,
            '-webkit-transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) ',
            '-moz-transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) ',
            '-ms-transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) ',
            '-o-transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) ',
            'transform' : ' translate3d(' + wdIncr + 'px,' + htIncr + 'px, 0) '

		}); // end css
    }, // end vznReveal
    featuredHide : function (e) {
        e.preventDefault();
        var hThis = $jQ(this).parents('.featured-item');
        $jQ(hThis).css({
            'opacity' : 0,
            '-webkit-transform' : ' translate3d(0 ,0 , 0) ',
            '-moz-transform' : ' translate3d(0 ,0 , 0) ',
            '-ms-transform' : ' translate3d(0 ,0 , 0) ',
            '-o-transform' : ' translate3d(0 ,0 , 0) ',
            'transform' : ' translate3d(0 ,0 , 0) '
		}); // end css
    }// end featuredHide
};

// ............. TEMP state toggle buttons in header .........

var stndrd = document.getElementById('state-standard');
var newProd = document.getElementById('state-new-products');
var featSale = document.getElementById('state-sale-featured');
var itemSale = document.getElementById('state-sale-item');

$jQ(stndrd).click(function () {

	var stndrd = document.getElementById('state-standard');
	var newProd = document.getElementById('state-new-products');
	var featSale = document.getElementById('state-sale-featured');
	var itemSale = document.getElementById('state-sale-item');

	// change font colors for nav
	$jQ(this).addClass('on');
	$jQ(newProd).removeClass('on');
	$jQ(featSale).removeClass('on');
	$jQ(itemSale).removeClass('on');

	//turn off all special cases
	$jQ('.new-product').css('display', 'none');
	$jQ('.sale-featured').css('display', 'none');
	$jQ('.sale-item').css('display', 'none');

});

$jQ(newProd).click(function () {

	var stndrd = document.getElementById('state-standard');
	var newProd = document.getElementById('state-new-products');
	var featSale = document.getElementById('state-sale-featured');
	var itemSale = document.getElementById('state-sale-item');

	// change font colors for nav
	$jQ(this).addClass('on');
	$jQ(stndrd).removeClass('on');

	// turn on new product elements
    $jQ('.new-product').css('display', 'block');

});

$jQ(featSale).click(function () {

	var stndrd = document.getElementById('state-standard');
	var newProd = document.getElementById('state-new-products');
	var featSale = document.getElementById('state-sale-featured');
	var itemSale = document.getElementById('state-sale-item');

	// change font colors for nav
	$jQ(this).addClass('on');
	$jQ(stndrd).removeClass('on');

	//turn on featured sale elements & add class depending on screen width
	var pageWidth = document.body.clientWidth;
	if (pageWidth < 1281) {
		$jQ('.sale-featured.three-across').css('display', 'block').parent().addClass('sale-featured-block');
	} else if (pageWidth > 1280) {
		$jQ('.sale-featured.four-across').css('display', 'block').parent().addClass('sale-featured-block');
	}
});

$jQ(itemSale).click(function () {

	var stndrd = document.getElementById('state-standard');
	var newProd = document.getElementById('state-new-products');
	var featSale = document.getElementById('state-sale-featured');
	var itemSale = document.getElementById('state-sale-item');

	// change font colors for nav
	$jQ(this).addClass('on');
	$jQ(stndrd).removeClass('on');

	//turn on item sale elements & turn off hover
	$jQ('.sale-item').css('display', 'block');

}); // end TEMP state buttons
<|endoftext|>


<commit_before>/*! UIkit 2.24.3 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(i){"use strict";function t(t){var s=i.$(t),a="auto";if(s.is(":visible"))a=s.outerHeight();else{var e={position:s.css("position"),visibility:s.css("visibility"),display:s.css("display")};a=s.css({position:"absolute",visibility:"hidden",display:"block"}).outerHeight(),s.css(e)}return a}i.component("nav",{defaults:{toggle:">li.uk-parent > a[href='#']",lists:">li.uk-parent > ul",multiple:!1},boot:function(){i.ready(function(t){i.$("[data-uk-nav]",t).each(function(){var t=i.$(this);if(!t.data("nav")){i.nav(t,i.Utils.options(t.attr("data-uk-nav")))}})})},init:function(){var t=this;this.on("click.uikit.nav",this.options.toggle,function(s){s.preventDefault();var a=i.$(this);t.open(a.parent()[0]==t.element[0]?a:a.parent("li"))}),this.find(this.options.lists).each(function(){var s=i.$(this),a=s.parent(),e=a.hasClass("uk-active");s.wrap('

'),a.data("list-container",s.parent()[e?"removeClass":"addClass"]("uk-hidden")),a.attr("aria-expanded",a.hasClass("uk-open")),e&&t.open(a,!0)})},open:function(s,a){var e=this,n=this.element,o=i.$(s),l=o.data("list-container");this.options.multiple||n.children(".uk-open").not(s).each(function(){var t=i.$(this);t.data("list-container")&&t.data("list-container").stop().animate({height:0},function(){i.$(this).parent().removeClass("uk-open").end().addClass("uk-hidden")})}),o.toggleClass("uk-open"),o.attr("aria-expanded",o.hasClass("uk-open")),l&&(o.hasClass("uk-open")&&l.removeClass("uk-hidden"),a?(l.stop().height(o.hasClass("uk-open")?"auto":0),o.hasClass("uk-open")||l.addClass("uk-hidden"),this.trigger("display.uk.check")):l.stop().animate({height:o.hasClass("uk-open")?t(l.find("ul:first")):0},function(){o.hasClass("uk-open")?l.css("height",""):l.addClass("uk-hidden"),e.trigger("display.uk.check")}))}})}(UIkit);<commit_msg>UIkit 2.26.2<commit_after>/*! UIkit 2.26.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(i){"use strict";function t(t){var s=i.$(t),a="auto";if(s.is(":visible"))a=s.outerHeight();else{var e={position:s.css("position"),visibility:s.css("visibility"),display:s.css("display")};a=s.css({position:"absolute",visibility:"hidden",display:"block"}).outerHeight(),s.css(e)}return a}i.component("nav",{defaults:{toggle:">li.uk-parent > a[href='#']",lists:">li.uk-parent > ul",multiple:!1},boot:function(){i.ready(function(t){i.$("[data-uk-nav]",t).each(function(){var t=i.$(this);if(!t.data("nav")){i.nav(t,i.Utils.options(t.attr("data-uk-nav")))}})})},init:function(){var t=this;this.on("click.uk.nav",this.options.toggle,function(s){s.preventDefault();var a=i.$(this);t.open(a.parent()[0]==t.element[0]?a:a.parent("li"))}),this.find(this.options.lists).each(function(){var s=i.$(this),a=s.parent(),e=a.hasClass("uk-active");s.wrap('

'),a.data("list-container",s.parent()[e?"removeClass":"addClass"]("uk-hidden")),a.attr("aria-expanded",a.hasClass("uk-open")),e&&t.open(a,!0)})},open:function(s,a){var e=this,n=this.element,o=i.$(s),l=o.data("list-container");this.options.multiple||n.children(".uk-open").not(s).each(function(){var t=i.$(this);t.data("list-container")&&t.data("list-container").stop().animate({height:0},function(){i.$(this).parent().removeClass("uk-open").end().addClass("uk-hidden")})}),o.toggleClass("uk-open"),o.attr("aria-expanded",o.hasClass("uk-open")),l&&(o.hasClass("uk-open")&&l.removeClass("uk-hidden"),a?(l.stop().height(o.hasClass("uk-open")?"auto":0),o.hasClass("uk-open")||l.addClass("uk-hidden"),this.trigger("display.uk.check")):l.stop().animate({height:o.hasClass("uk-open")?t(l.find("ul:first")):0},function(){o.hasClass("uk-open")?l.css("height",""):l.addClass("uk-hidden"),e.trigger("display.uk.check")}))}})}(UIkit);
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { isEqual } from 'lodash'
import hoistStatics from 'hoist-non-react-statics'
import { createCallable, wrapDisplayName } from './utils'

/**
 * @name createFirestoreConnect
 * @description Function that creates a Higher Order Component that
 * automatically listens/unListens to provided firebase paths using
 * React's Lifecycle hooks.
 * **WARNING!!** This is an advanced feature, and should only be used when
 * needing to access a firebase instance created under a different store key.
 * @param {String} [storeKey='store'] - Name of redux store which contains
 * Firebase state (state.firebase)
 * @return {Function} - HOC that accepts a watchArray and wraps a component
 * @example
Basic

 * // this.props.firebase set on App component as firebase object with helpers
 * import { createFirestoreConnect } from 'react-redux-firebase'
 * // create firebase connect that uses another redux store
 * const firestoreConnect = createFirestoreConnect('anotherStore')
 * // use the firebaseConnect to wrap a component
 * export default firestoreConnect()(SomeComponent)
 */
export const createFirestoreConnect = (storeKey = 'store') => (
  dataOrFn = []
) => WrappedComponent => {
  class FirestoreConnect extends Component {
    static wrappedComponent = WrappedComponent
    static displayName = wrapDisplayName(WrappedComponent, 'FirestoreConnect')
    static contextTypes = {
      [storeKey]: PropTypes.object.isRequired
    }

    prevData = null
    store = this.context[storeKey]

    componentWillMount() {
      const { firebase, firestore } = this.store
      if (firebase.firestore && firestore) {
        // Allow function to be passed
        const inputAsFunc = createCallable(dataOrFn)
        this.prevData = inputAsFunc(this.props, this.store)

        firestore.setListeners(this.prevData)
      }
    }

    componentWillUnmount() {
      const { firebase, firestore } = this.store
      if (firebase.firestore && this.prevData) {
        firestore.unsetListeners(this.prevData)
      }
    }

    componentWillReceiveProps(np) {
      const { firebase, firestore } = this.store
      const inputAsFunc = createCallable(dataOrFn)
      const data = inputAsFunc(np, this.store)
      // Handle a data parameter having changed
      if (firebase.firestore && !isEqual(data, this.prevData)) {
        // UnWatch all current events
        firestore.unsetListeners(this.prevData)
        this.prevData = data
        // Watch new events
        firestore.setListeners(data)
      }
    }

    render() {
      const { firebase, firestore } = this.store
      return (
        <WrappedComponent
          {...this.props}
          {...this.state}
          firebase={{ ...firebase, ...firebase.helpers }}
          firestore={firestore}
        />
      )
    }
  }

  return hoistStatics(FirestoreConnect, WrappedComponent)
}

/**
 * @name firestoreConnect
 * @extends React.Component
 * @description Higher Order Component that automatically listens/unListens
 * to provided Cloud Firestore paths using React's Lifecycle hooks. Make sure you
 * have required/imported Cloud Firestore, including it's reducer, before
 * attempting to use. **Note** Populate is not yet supported.
 * @param {Array} queriesConfig - Array of objects or strings for paths to sync
 * from Firebase. Can also be a function that returns the array. The function
 * is passed the current props and the firebase object.
 * @return {Function} - that accepts a component to wrap and returns the wrapped component
 * @example
Basic

 * // this.props.firebase set on App component as firebase object with helpers
 * import { firestoreConnect } from 'react-redux-firebase'
 * export default firestoreConnect()(SomeComponent)
 * @example
Basic

 * import { connect } from 'react-redux'
 * import { firestoreConnect } from 'react-redux-firebase'
 *
 * // pass todos list from redux as this.props.todosList
 * export default compose(
 *   firestoreConnect(['todos']), // sync todos collection from Firestore into redux
 *   connect((state) => ({
 *     todosList: state.firestore.data.todos,
 *     profile: state.firestore.profile, // pass profile data as this.props.profile
 *     auth: state.firestore.auth // pass auth data as this.props.auth
 *   })
 * )(SomeComponent)
 */
export default createFirestoreConnect()
<commit_msg>Optimize unset / set listeners<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { isEqual, some, filter } from 'lodash'
import hoistStatics from 'hoist-non-react-statics'
import { createCallable, wrapDisplayName } from './utils'

/**
 * @name createFirestoreConnect
 * @description Function that creates a Higher Order Component that
 * automatically listens/unListens to provided firebase paths using
 * React's Lifecycle hooks.
 * **WARNING!!** This is an advanced feature, and should only be used when
 * needing to access a firebase instance created under a different store key.
 * @param {String} [storeKey='store'] - Name of redux store which contains
 * Firebase state (state.firebase)
 * @return {Function} - HOC that accepts a watchArray and wraps a component
 * @example
Basic

 * // this.props.firebase set on App component as firebase object with helpers
 * import { createFirestoreConnect } from 'react-redux-firebase'
 * // create firebase connect that uses another redux store
 * const firestoreConnect = createFirestoreConnect('anotherStore')
 * // use the firebaseConnect to wrap a component
 * export default firestoreConnect()(SomeComponent)
 */
export const createFirestoreConnect = (storeKey = 'store') => (
  dataOrFn = []
) => WrappedComponent => {
  class FirestoreConnect extends Component {
    static wrappedComponent = WrappedComponent
    static displayName = wrapDisplayName(WrappedComponent, 'FirestoreConnect')
    static contextTypes = {
      [storeKey]: PropTypes.object.isRequired
    }

    prevData = null
    store = this.context[storeKey]

    get firestoreIsEnabled() {
      const { firebase, firestore } = this.store
      return firebase && firebase.firestore && firestore
    }

    componentWillMount() {
      const { firestore } = this.store
      if (this.firestoreIsEnabled) {
        // Allow function to be passed
        const inputAsFunc = createCallable(dataOrFn)
        this.prevData = inputAsFunc(this.props, this.store)

        firestore.setListeners(this.prevData)
      }
    }

    componentWillUnmount() {
      const { firestore } = this.store
      if (this.firestoreIsEnabled && this.prevData) {
        firestore.unsetListeners(this.prevData)
      }
    }

    componentWillReceiveProps(np) {
      const { firestore } = this.store
      const inputAsFunc = createCallable(dataOrFn)
      const data = inputAsFunc(np, this.store)

      // Handle changes to data
      if (this.firestoreIsEnabled && !isEqual(data, this.prevData)) {
        const changes = this.getChanges(data, this.prevData)

        this.prevData = data

        // Remove listeners for inactive subscriptions
        firestore.unsetListeners(changes.removed)

        // Add listeners for new subscriptions
        firestore.setListeners(changes.added)
      }
    }

    getChanges(data = [], prevData = []) {
      const result = {}
      result.added = filter(data, d => !some(prevData, p => isEqual(d, p)))
      result.removed = filter(prevData, p => !some(data, d => isEqual(p, d)))
      return result
    }

    render() {
      const { firebase, firestore } = this.store
      return (
        <WrappedComponent
          {...this.props}
          {...this.state}
          firebase={{ ...firebase, ...firebase.helpers }}
          firestore={firestore}
        />
      )
    }
  }

  return hoistStatics(FirestoreConnect, WrappedComponent)
}

/**
 * @name firestoreConnect
 * @extends React.Component
 * @description Higher Order Component that automatically listens/unListens
 * to provided Cloud Firestore paths using React's Lifecycle hooks. Make sure you
 * have required/imported Cloud Firestore, including it's reducer, before
 * attempting to use. **Note** Populate is not yet supported.
 * @param {Array} queriesConfig - Array of objects or strings for paths to sync
 * from Firebase. Can also be a function that returns the array. The function
 * is passed the current props and the firebase object.
 * @return {Function} - that accepts a component to wrap and returns the wrapped component
 * @example
Basic

 * // this.props.firebase set on App component as firebase object with helpers
 * import { firestoreConnect } from 'react-redux-firebase'
 * export default firestoreConnect()(SomeComponent)
 * @example
Basic

 * import { connect } from 'react-redux'
 * import { firestoreConnect } from 'react-redux-firebase'
 *
 * // pass todos list from redux as this.props.todosList
 * export default compose(
 *   firestoreConnect(['todos']), // sync todos collection from Firestore into redux
 *   connect((state) => ({
 *     todosList: state.firestore.data.todos,
 *     profile: state.firestore.profile, // pass profile data as this.props.profile
 *     auth: state.firestore.auth // pass auth data as this.props.auth
 *   })
 * )(SomeComponent)
 */
export default createFirestoreConnect()
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.dao',
  name: 'EasyDAO',
  extends: 'foam.dao.ProxyDAO',
  implements: [ 'foam.mlang.Expressions' ],

  documentation: function() {/*
    Facade for easily creating decorated DAOs.

    Most DAOs are most easily created and configured with EasyDAO.
    Simply require foam.dao.EasyDAO and create() with the flags
    to indicate what behavior you're looking for. Under the hood, EasyDAO
    will create one or more DAO instances to service your requirements and then
  */},

  requires: [
    'foam.box.Context',
    'foam.box.HTTPBox',
    'foam.box.SessionClientBox',
    'foam.box.SocketBox',
    'foam.box.WebSocketBox',
    'foam.box.TimeoutBox',
    'foam.box.RetryBox',
    'foam.dao.CachingDAO',
    'foam.dao.CompoundDAODecorator',
    'foam.dao.ContextualizingDAO',
    'foam.dao.DecoratedDAO',
    'foam.dao.DeDupDAO',
    'foam.dao.GUIDDAO',
    'foam.dao.IDBDAO',
    'foam.dao.JDAO',
    'foam.dao.LoggingDAO',
    'foam.dao.MDAO',
    'foam.dao.PromisedDAO',
    'foam.dao.RequestResponseClientDAO',
    'foam.dao.SequenceNumberDAO',
    'foam.dao.SyncDAO',
    'foam.dao.TimingDAO'
  ],

  imports: [ 'document' ],

  constants: {
    // Aliases for daoType
    ALIASES: {
      ARRAY:  'foam.dao.ArrayDAO',
      CLIENT: 'foam.dao.RequestResponseClientDAO',
      IDB:    'foam.dao.IDBDAO',
      LOCAL:  'foam.dao.LocalStorageDAO',
      MDAO:   'foam.dao.MDAO'
    }
  },

  properties: [
    {
      /** The developer-friendly name for this EasyDAO. */
      name: 'name',
      factory: function() { return this.of.id; }
    },
    {
      /** This is set automatically when you create an EasyDAO.
        @private */
      name: 'delegate'
    },
    {
      /** Have EasyDAO use a sequence number to index items. Note that
        .seqNo and .guid features are mutually
        exclusive. */
      class: 'Boolean',
      name: 'seqNo',
      value: false
    },
    {
      /** Have EasyDAO generate guids to index items. Note that .seqNo and .guid features are mutually exclusive. */
      class: 'Boolean',
      name: 'guid',
      label: 'GUID',
      value: false
    },
    {
      /** The property on your items to use to store the sequence number or guid. This is required for .seqNo or .guid mode. */
      name: 'seqProperty',
      class: 'Property'
    },
    {
      /** Enable local in-memory caching of the DAO. */
      class: 'Boolean',
      name: 'cache',
      value: false
    },
    {
      /** Enable value de-duplication to save memory when caching. */
      class: 'Boolean',
      name: 'dedup',
      value: false,
    },
    {
      /** Keep a history of all state changes to the DAO. */
      class: 'FObjectProperty',
      of: 'foam.dao.Journal',
      name: 'journal'
    },
    {
      /** Enable logging on the DAO. */
      class: 'Boolean',
      name: 'logging',
      value: false,
    },
    {
      /** Enable time tracking for concurrent DAO operations. */
      class: 'Boolean',
      name: 'timing',
      value: false
    },
    {
      /** Contextualize objects on .find, re-creating them with this EasyDAO's
        exports, as if they were children of this EasyDAO. */
      class: 'Boolean',
      name: 'contextualize',
      value: false
    },
//     {
//       class: 'Boolean',
//       name: 'cloning',
//       value: false,
//       //documentation: "True to clone results on select"
//     },
    {
      /**

Selects the basic functionality this EasyDAO should provide.
        You can specify an instance of a DAO model definition such as
        MDAO, or a constant indicating your requirements.

Choices are:

IDB: Use IndexDB for storage.

LOCAL: Use local storage.

MDAO: Use non-persistent in-memory storage.

      */
      name: 'daoType',
      value: 'foam.dao.IDBDAO'
    },
    {
      /** Automatically generate indexes as necessary, if using an MDAO or cache. */
      class: 'Boolean',
      name: 'autoIndex',
      value: false
    },
//     {
//       /** Creates an internal MigrationDAO and applies the given array of MigrationRule. */
//       class: 'FObjectArray',
//       name: 'migrationRules',
//       of: 'foam.core.dao.MigrationRule',
//     },
    {
      /** Turn on to activate synchronization with a server. Specify serverUri
        and syncProperty as well. */
      class: 'Boolean',
      name: 'syncWithServer',
      value: false
    },
    {
      /** Turn on to enable remote listener support. Only useful with daoType = CLIENT. */
      class: 'Boolean',
      name: 'remoteListenerSupport',
      value: false
    },
    {
      /** Setting to true activates polling, periodically checking in with
        the server. If sockets are used, polling is optional as the server
        can push changes to this client. */
      class: 'Boolean',
      name: 'syncPolling',
      value: true
    },
    {
      /** Set to true if you are running this on a server, and clients will
        synchronize with this DAO. */
      class: 'Boolean',
      name: 'isServer',
      value: false
    },
    {
      /** The property to synchronize on. This is typically an integer value
        indicating the version last seen on the remote. */
      name: 'syncProperty'
    },
    {
      /** Destination address for server. */
      name: 'serverBox',
      factory: function() {
        // TODO: This should come from the server via a lookup from a NamedBox.
        return /*this.SessionClientBox.create({ delegate:*/ this.RetryBox.create({ delegate:
          this.TimeoutBox.create({ delegate:
          this.remoteListenerSupport ?
              this.WebSocketBox.create({ uri: this.serviceName }) :
              this.HTTPBox.create({ url: this.serviceName })
        })})/*})*/;
      }
    },
    {
      /** Simpler alternative than providing serverBox. */
      name: 'serviceName'
    },
    {
      class: 'FObjectArray',
      of: 'foam.dao.DAODecorator',
      name: 'decorators'
    },
    'testData'
  ],

  methods: [
    function init() {
      /**

On initialization, the EasyDAO creates an appropriate chain of
        internal EasyDAO instances based on the EasyDAO
        property settings.

This process is transparent to the developer, and you can use your
        EasyDAO like any other DAO.

      */
      this.SUPER.apply(this, arguments);

      var daoType = typeof this.daoType === 'string' ?
        this.ALIASES[this.daoType] || this.daoType :
        this.daoType;

      var params = { of: this.of };

      if ( daoType == 'foam.dao.RequestResponseClientDAO' ) {
        foam.assert(this.hasOwnProperty('serverBox') || this.serviceName, 'EasyDAO "client" type requires a serveBox or serviceName');

        // The RequestResonseClientDAO generates listener events locally
        // but with remoteListenerSupport, this isn't needed, so switch
        // to the regular ClientDAO instead.
        if ( this.remoteListenerSupport ) {
          daoType = 'foam.dao.ClientDAO';
        }

        params.delegate = this.serverBox;
      }

      var daoModel = typeof daoType === 'string' ?
        this.lookup(daoType) || global[daoType] :
        daoType;

      if ( ! daoModel ) {
        this.warn(
          "EasyDAO: Unknown DAO Type.  Add '" + daoType + "' to requires: list."
        );
      }

      if ( this.name && daoModel.getAxiomByName('name') ) params.name = this.name;
      if ( daoModel.getAxiomByName('autoIndex') ) params.autoIndex = this.autoIndex;
      //if ( this.seqNo || this.guid ) params.property = this.seqProperty;

      var dao = daoModel.create(params, this.__subContext__);

      // Not used by decorators.
      delete params['name'];

      if ( this.MDAO.isInstance(dao) ) {
        this.mdao = dao;
        if ( this.dedup ) dao = this.DeDupDAO.create({delegate: dao});
      } else {
//         if ( this.migrationRules && this.migrationRules.length ) {
//           dao = this.MigrationDAO.create({
//             delegate: dao,
//             rules: this.migrationRules,
//             name: this.model.id + "_" + daoModel.id + "_" + this.name
//           });
//         }
        if ( this.cache ) {
          this.mdao = this.MDAO.create({of: params.of});
          dao = this.CachingDAO.create({
            cache: this.dedup ?
              this.mdao :
              this.DeDupDAO.create({delegate: this.mdao}),
            src: dao,
            of: this.model});
        }
      }

      if ( this.journal ) {
        dao = this.JDAO.create({
          delegate: dao,
          journal: this.journal
        });
      }

      if ( this.seqNo && this.guid ) throw "EasyDAO 'seqNo' and 'guid' features are mutually exclusive.";

      if ( this.seqNo ) {
        var args = {__proto__: params, delegate: dao, of: this.of};
        if ( this.seqProperty ) args.property = this.seqProperty;
        dao = this.SequenceNumberDAO.create(args);
      }

      if ( this.guid ) {
        var args = {__proto__: params, delegate: dao, of: this.of};
        if ( this.seqProperty ) args.property = this.seqProperty;
        dao = this.GUIDDAO.create(args);
      }

      var cls = this.of;

      if ( this.syncWithServer && this.isServer ) throw "isServer and syncWithServer are mutually exclusive.";

      if ( this.syncWithServer || this.isServer ) {
        if ( ! this.syncProperty ) {
          this.syncProperty = cls.SYNC_PROPERTY;
          if ( ! this.syncProperty ) {
            throw "EasyDAO sync with class " + cls.id + " invalid. Sync requires a sync property be set, or be of a class including a property 'sync_property'.";
          }
        }
      }

      if ( this.syncWithServer ) {
        foam.assert(this.serverBox, 'syncWithServer requires serverBox');

        dao = this.SyncDAO.create({
          remoteDAO: this.RequestResponseClientDAO.create({
              name: this.name,
              delegate: this.serverBox
          }, boxContext),
          syncProperty: this.syncProperty,
          delegate: dao,
          pollingFrequency: 1000
        });
        dao.syncRecordDAO = foam.dao.EasyDAO.create({
          of: dao.SyncRecord,
          cache: true,
          daoType: this.daoType,
          name: this.name + '_SyncRecords'
        });
      }

//       if ( this.isServer ) {
//         dao = this.VersionNoDAO.create({
//           delegate: dao,
//           property: this.syncProperty,
//           version: 2
//         });
//       }

      if ( this.contextualize ) {
        dao = this.ContextualizingDAO.create({delegate: dao});
      }

      if ( this.decorators.length ) {
        var decorated = this.DecoratedDAO.create({
          decorator: this.CompoundDAODecorator.create({
            decorators: this.decorators
          }),
          delegate: dao
        });
        dao = decorated;
      }

      if ( this.timing  ) {
        dao = this.TimingDAO.create({ name: this.name + 'DAO', delegate: dao });
      }

      if ( this.logging ) {
        dao = this.LoggingDAO.create({ delegate: dao });
      }

      var self = this;

      if ( decorated ) decorated.dao = dao;

      if ( this.testData ) {
        var delegate = dao;

        dao = this.PromisedDAO.create({
          promise: new Promise(function(resolve, reject) {
            delegate.select(self.COUNT()).then(function(c) {
              // Only load testData if DAO is empty
              if ( c.value ) {
                resolve(delegate);
                return;
              }

              self.log("Loading test data");
              Promise.all(foam.json.parse(self.testData, self.of, self).map(
                function(o) { return delegate.put(o); }
              )).then(function() {
                self.log("Loaded", self.testData.length, "records.");
                resolve(delegate);
              }, reject);
            });
          })
        });
      }

      this.delegate = dao;
    },

    /** Only relevant if cache is true or if daoType
       was set to MDAO, but harmless otherwise. Generates an index
       for a query over all specified properties together.
       @param var_args specify any number of Properties to be indexed.
    */
    function addPropertyIndex() {
      this.mdao && this.mdao.addPropertyIndex.apply(this.mdao, arguments);
      return this;
    },

    /** Only relevant if cache is true or if daoType
      was set to MDAO, but harmless otherwise. Adds an existing index
      to the MDAO.
      @param index The index to add.
    */
    function addIndex(index) {
      this.mdao && this.mdao.addIndex.apply(this.mdao, arguments);
      return this;
    }
  ]
});
<commit_msg>Add SessionClientBox in EasyDAO.<commit_after>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.dao',
  name: 'EasyDAO',
  extends: 'foam.dao.ProxyDAO',
  implements: [ 'foam.mlang.Expressions' ],

  documentation: function() {/*
    Facade for easily creating decorated DAOs.

    Most DAOs are most easily created and configured with EasyDAO.
    Simply require foam.dao.EasyDAO and create() with the flags
    to indicate what behavior you're looking for. Under the hood, EasyDAO
    will create one or more DAO instances to service your requirements and then
  */},

  requires: [
    'foam.box.Context',
    'foam.box.HTTPBox',
    'foam.box.SessionClientBox',
    'foam.box.SocketBox',
    'foam.box.WebSocketBox',
    'foam.box.TimeoutBox',
    'foam.box.RetryBox',
    'foam.dao.CachingDAO',
    'foam.dao.CompoundDAODecorator',
    'foam.dao.ContextualizingDAO',
    'foam.dao.DecoratedDAO',
    'foam.dao.DeDupDAO',
    'foam.dao.GUIDDAO',
    'foam.dao.IDBDAO',
    'foam.dao.JDAO',
    'foam.dao.LoggingDAO',
    'foam.dao.MDAO',
    'foam.dao.PromisedDAO',
    'foam.dao.RequestResponseClientDAO',
    'foam.dao.SequenceNumberDAO',
    'foam.dao.SyncDAO',
    'foam.dao.TimingDAO'
  ],

  imports: [ 'document' ],

  constants: {
    // Aliases for daoType
    ALIASES: {
      ARRAY:  'foam.dao.ArrayDAO',
      CLIENT: 'foam.dao.RequestResponseClientDAO',
      IDB:    'foam.dao.IDBDAO',
      LOCAL:  'foam.dao.LocalStorageDAO',
      MDAO:   'foam.dao.MDAO'
    }
  },

  properties: [
    {
      /** The developer-friendly name for this EasyDAO. */
      name: 'name',
      factory: function() { return this.of.id; }
    },
    {
      /** This is set automatically when you create an EasyDAO.
        @private */
      name: 'delegate'
    },
    {
      /** Have EasyDAO use a sequence number to index items. Note that
        .seqNo and .guid features are mutually
        exclusive. */
      class: 'Boolean',
      name: 'seqNo',
      value: false
    },
    {
      /** Have EasyDAO generate guids to index items. Note that .seqNo and .guid features are mutually exclusive. */
      class: 'Boolean',
      name: 'guid',
      label: 'GUID',
      value: false
    },
    {
      /** The property on your items to use to store the sequence number or guid. This is required for .seqNo or .guid mode. */
      name: 'seqProperty',
      class: 'Property'
    },
    {
      /** Enable local in-memory caching of the DAO. */
      class: 'Boolean',
      name: 'cache',
      value: false
    },
    {
      /** Enable value de-duplication to save memory when caching. */
      class: 'Boolean',
      name: 'dedup',
      value: false,
    },
    {
      /** Keep a history of all state changes to the DAO. */
      class: 'FObjectProperty',
      of: 'foam.dao.Journal',
      name: 'journal'
    },
    {
      /** Enable logging on the DAO. */
      class: 'Boolean',
      name: 'logging',
      value: false,
    },
    {
      /** Enable time tracking for concurrent DAO operations. */
      class: 'Boolean',
      name: 'timing',
      value: false
    },
    {
      /** Contextualize objects on .find, re-creating them with this EasyDAO's
        exports, as if they were children of this EasyDAO. */
      class: 'Boolean',
      name: 'contextualize',
      value: false
    },
//     {
//       class: 'Boolean',
//       name: 'cloning',
//       value: false,
//       //documentation: "True to clone results on select"
//     },
    {
      /**

Selects the basic functionality this EasyDAO should provide.
        You can specify an instance of a DAO model definition such as
        MDAO, or a constant indicating your requirements.

Choices are:

IDB: Use IndexDB for storage.

LOCAL: Use local storage.

MDAO: Use non-persistent in-memory storage.

      */
      name: 'daoType',
      value: 'foam.dao.IDBDAO'
    },
    {
      /** Automatically generate indexes as necessary, if using an MDAO or cache. */
      class: 'Boolean',
      name: 'autoIndex',
      value: false
    },
//     {
//       /** Creates an internal MigrationDAO and applies the given array of MigrationRule. */
//       class: 'FObjectArray',
//       name: 'migrationRules',
//       of: 'foam.core.dao.MigrationRule',
//     },
    {
      /** Turn on to activate synchronization with a server. Specify serverUri
        and syncProperty as well. */
      class: 'Boolean',
      name: 'syncWithServer',
      value: false
    },
    {
      /** Turn on to enable remote listener support. Only useful with daoType = CLIENT. */
      class: 'Boolean',
      name: 'remoteListenerSupport',
      value: false
    },
    {
      /** Setting to true activates polling, periodically checking in with
        the server. If sockets are used, polling is optional as the server
        can push changes to this client. */
      class: 'Boolean',
      name: 'syncPolling',
      value: true
    },
    {
      /** Set to true if you are running this on a server, and clients will
        synchronize with this DAO. */
      class: 'Boolean',
      name: 'isServer',
      value: false
    },
    {
      /** The property to synchronize on. This is typically an integer value
        indicating the version last seen on the remote. */
      name: 'syncProperty'
    },
    {
      /** Destination address for server. */
      name: 'serverBox',
      factory: function() {
        // TODO: This should come from the server via a lookup from a NamedBox.
        return this.SessionClientBox.create({ delegate: this.RetryBox.create({ delegate:
          this.TimeoutBox.create({ delegate:
          this.remoteListenerSupport ?
              this.WebSocketBox.create({ uri: this.serviceName }) :
              this.HTTPBox.create({ url: this.serviceName })
        })})});
      }
    },
    {
      /** Simpler alternative than providing serverBox. */
      name: 'serviceName'
    },
    {
      class: 'FObjectArray',
      of: 'foam.dao.DAODecorator',
      name: 'decorators'
    },
    'testData'
  ],

  methods: [
    function init() {
      /**

On initialization, the EasyDAO creates an appropriate chain of
        internal EasyDAO instances based on the EasyDAO
        property settings.

This process is transparent to the developer, and you can use your
        EasyDAO like any other DAO.

      */
      this.SUPER.apply(this, arguments);

      var daoType = typeof this.daoType === 'string' ?
        this.ALIASES[this.daoType] || this.daoType :
        this.daoType;

      var params = { of: this.of };

      if ( daoType == 'foam.dao.RequestResponseClientDAO' ) {
        foam.assert(this.hasOwnProperty('serverBox') || this.serviceName, 'EasyDAO "client" type requires a serveBox or serviceName');

        // The RequestResonseClientDAO generates listener events locally
        // but with remoteListenerSupport, this isn't needed, so switch
        // to the regular ClientDAO instead.
        if ( this.remoteListenerSupport ) {
          daoType = 'foam.dao.ClientDAO';
        }

        params.delegate = this.serverBox;
      }

      var daoModel = typeof daoType === 'string' ?
        this.lookup(daoType) || global[daoType] :
        daoType;

      if ( ! daoModel ) {
        this.warn(
          "EasyDAO: Unknown DAO Type.  Add '" + daoType + "' to requires: list."
        );
      }

      if ( this.name && daoModel.getAxiomByName('name') ) params.name = this.name;
      if ( daoModel.getAxiomByName('autoIndex') ) params.autoIndex = this.autoIndex;
      //if ( this.seqNo || this.guid ) params.property = this.seqProperty;

      var dao = daoModel.create(params, this.__subContext__);

      // Not used by decorators.
      delete params['name'];

      if ( this.MDAO.isInstance(dao) ) {
        this.mdao = dao;
        if ( this.dedup ) dao = this.DeDupDAO.create({delegate: dao});
      } else {
//         if ( this.migrationRules && this.migrationRules.length ) {
//           dao = this.MigrationDAO.create({
//             delegate: dao,
//             rules: this.migrationRules,
//             name: this.model.id + "_" + daoModel.id + "_" + this.name
//           });
//         }
        if ( this.cache ) {
          this.mdao = this.MDAO.create({of: params.of});
          dao = this.CachingDAO.create({
            cache: this.dedup ?
              this.mdao :
              this.DeDupDAO.create({delegate: this.mdao}),
            src: dao,
            of: this.model});
        }
      }

      if ( this.journal ) {
        dao = this.JDAO.create({
          delegate: dao,
          journal: this.journal
        });
      }

      if ( this.seqNo && this.guid ) throw "EasyDAO 'seqNo' and 'guid' features are mutually exclusive.";

      if ( this.seqNo ) {
        var args = {__proto__: params, delegate: dao, of: this.of};
        if ( this.seqProperty ) args.property = this.seqProperty;
        dao = this.SequenceNumberDAO.create(args);
      }

      if ( this.guid ) {
        var args = {__proto__: params, delegate: dao, of: this.of};
        if ( this.seqProperty ) args.property = this.seqProperty;
        dao = this.GUIDDAO.create(args);
      }

      var cls = this.of;

      if ( this.syncWithServer && this.isServer ) throw "isServer and syncWithServer are mutually exclusive.";

      if ( this.syncWithServer || this.isServer ) {
        if ( ! this.syncProperty ) {
          this.syncProperty = cls.SYNC_PROPERTY;
          if ( ! this.syncProperty ) {
            throw "EasyDAO sync with class " + cls.id + " invalid. Sync requires a sync property be set, or be of a class including a property 'sync_property'.";
          }
        }
      }

      if ( this.syncWithServer ) {
        foam.assert(this.serverBox, 'syncWithServer requires serverBox');

        dao = this.SyncDAO.create({
          remoteDAO: this.RequestResponseClientDAO.create({
              name: this.name,
              delegate: this.serverBox
          }, boxContext),
          syncProperty: this.syncProperty,
          delegate: dao,
          pollingFrequency: 1000
        });
        dao.syncRecordDAO = foam.dao.EasyDAO.create({
          of: dao.SyncRecord,
          cache: true,
          daoType: this.daoType,
          name: this.name + '_SyncRecords'
        });
      }

//       if ( this.isServer ) {
//         dao = this.VersionNoDAO.create({
//           delegate: dao,
//           property: this.syncProperty,
//           version: 2
//         });
//       }

      if ( this.contextualize ) {
        dao = this.ContextualizingDAO.create({delegate: dao});
      }

      if ( this.decorators.length ) {
        var decorated = this.DecoratedDAO.create({
          decorator: this.CompoundDAODecorator.create({
            decorators: this.decorators
          }),
          delegate: dao
        });
        dao = decorated;
      }

      if ( this.timing  ) {
        dao = this.TimingDAO.create({ name: this.name + 'DAO', delegate: dao });
      }

      if ( this.logging ) {
        dao = this.LoggingDAO.create({ delegate: dao });
      }

      var self = this;

      if ( decorated ) decorated.dao = dao;

      if ( this.testData ) {
        var delegate = dao;

        dao = this.PromisedDAO.create({
          promise: new Promise(function(resolve, reject) {
            delegate.select(self.COUNT()).then(function(c) {
              // Only load testData if DAO is empty
              if ( c.value ) {
                resolve(delegate);
                return;
              }

              self.log("Loading test data");
              Promise.all(foam.json.parse(self.testData, self.of, self).map(
                function(o) { return delegate.put(o); }
              )).then(function() {
                self.log("Loaded", self.testData.length, "records.");
                resolve(delegate);
              }, reject);
            });
          })
        });
      }

      this.delegate = dao;
    },

    /** Only relevant if cache is true or if daoType
       was set to MDAO, but harmless otherwise. Generates an index
       for a query over all specified properties together.
       @param var_args specify any number of Properties to be indexed.
    */
    function addPropertyIndex() {
      this.mdao && this.mdao.addPropertyIndex.apply(this.mdao, arguments);
      return this;
    },

    /** Only relevant if cache is true or if daoType
      was set to MDAO, but harmless otherwise. Adds an existing index
      to the MDAO.
      @param index The index to add.
    */
    function addIndex(index) {
      this.mdao && this.mdao.addIndex.apply(this.mdao, arguments);
      return this;
    }
  ]
});
<|endoftext|>


<commit_before>var quotes = [
'Reality is a lovely place, but I wouldn\'t want to live there.'
, 'I\'ll watch the night turn light blue, it\'s not the same without you cause it takes two to whisper quietly'
, 'Dear God, I was terribly lost when the galaxies crossed and the sun went dark. Dear God, you\'re the only North Star, I would follow this far.'
, 'You make my frown turn upside down and now my worries are gone.'
, 'Chills run down my spine as our fingers intwine and your sighs harmonize with mine unmistakably I can still feel your heart beat fast when you dance with me.'
, 'Tell me again was it love at first sight When I walked by and you caught my eye Didn\'t you know love could shine this bright? Well, smile because you\'re the deer in the headlights.'
, 'When the sky fell in When the hurricanes came for me I could finally crash again And that\'s how I became the sea.'
, 'The silence isn\'t so bad Till I look at my hands and feel sad Cause the spaces between my fingers Are right where yours fit perfectly'
, 'I forget the last time I felt brave, I just recall insecurity Cause it came down like a tidal wave, and sorrow swept over me Then I was given grace and love, I was blind but now I can see Cause I found a new hope from above, and courage swept over me'
, 'Circle me and the needle moves gracefully Back and forth, if my heart was a compass you\'d be North Risk it all cause I\'ll catch you if you fall Wherever you go, if my heart was a house you\'d be home.'
, 'I\'ll watch the night turn light blue But it\'s not the same without you Because it takes two to whisper quietly'
, 'I am the black in the book the letters on the pages that you memorize.'
, 'I wish I had covered all my tracks completely cause I\'m so afraid Is that the light at the far end of the tunnel or just the train?'
, 'Peer over the edge Can you see me? Rivulets flow from your eyes Paint runs from your mouth Like a waterfall And your lungs crystalize.'
, 'Boy I need a hug (boy I need a hug) \'Cause my heart stops without you there\'s something about you.'
, 'Where was I when the rockets came to life And carried you away into the alligator sky Even though, I\'ll never know what\'s up ahead I\'m never lettin\' go, I\'m never lettin\' go.'
, 'It makes me smile because you said it best I would clearly feel blessed if the sun rose up from the west.'
, 'Home is a boxcar and it\'s so far out of reach Hidden under umbrella beach.'
, 'If I look back when I begin to leave, will they remember me?'
, 'Where was I when the rockets came to life, and carried you away into the alligator sky?'
];

$(document).ready(newQuote());

function newQuote() {
	var rand = Math.floor(Math.random() * quotes.length);
	document.getElementById('quoteContainer').innerHTML = quotes[rand];
	this.data = quotes[rand];
}

function tweetQuote() {
 //get inner text and replace inside the share
  var phrase = document.getElementById('quoteContainer').innerText;
  var tweetUrl = 'https://twitter.com/share?text=' +
    encodeURIComponent(phrase) +
    ' - QuoteGenerator By:' +
    '&via=' +
    'stevenmayo_';
  window.open(tweetUrl);
}

function tumblrPost() {
	var phrase = document.getElementById('quoteContainer').innerText;
	var tumblrURL = 'https://www.tumblr.com/widgets/share/tool?posttype=link&title=Random+%7C+Quote+%7C+Generator&caption=Basic+quote+generator.++All+quotes+from+Adam+Young+%28Owl+City%21%29%&content='
		 encodeURIComponent(phrase) + 'buttons&tags=tumblelog%2C+blog%2C+tumblog%2C+tumbler%2C+tumblr%2C+tlog%2C+microblog&canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&shareSource=tumblr_share_button&_format=html';

		alert(tumblrURL);
	window.open(tumblrURL);
}

<commit_msg>Modifies: Tumbler sharing: 1. Query string will not display locally. 2. encodeURIComponent might be the root of the issue.<commit_after>var quotes = [
'Reality is a lovely place, but I wouldn\'t want to live there.'
, 'I\'ll watch the night turn light blue, it\'s not the same without you cause it takes two to whisper quietly'
, 'Dear God, I was terribly lost when the galaxies crossed and the sun went dark. Dear God, you\'re the only North Star, I would follow this far.'
, 'You make my frown turn upside down and now my worries are gone.'
, 'Chills run down my spine as our fingers intwine and your sighs harmonize with mine unmistakably I can still feel your heart beat fast when you dance with me.'
, 'Tell me again was it love at first sight When I walked by and you caught my eye Didn\'t you know love could shine this bright? Well, smile because you\'re the deer in the headlights.'
, 'When the sky fell in When the hurricanes came for me I could finally crash again And that\'s how I became the sea.'
, 'The silence isn\'t so bad Till I look at my hands and feel sad Cause the spaces between my fingers Are right where yours fit perfectly'
, 'I forget the last time I felt brave, I just recall insecurity Cause it came down like a tidal wave, and sorrow swept over me Then I was given grace and love, I was blind but now I can see Cause I found a new hope from above, and courage swept over me'
, 'Circle me and the needle moves gracefully Back and forth, if my heart was a compass you\'d be North Risk it all cause I\'ll catch you if you fall Wherever you go, if my heart was a house you\'d be home.'
, 'I\'ll watch the night turn light blue But it\'s not the same without you Because it takes two to whisper quietly'
, 'I am the black in the book the letters on the pages that you memorize.'
, 'I wish I had covered all my tracks completely cause I\'m so afraid Is that the light at the far end of the tunnel or just the train?'
, 'Peer over the edge Can you see me? Rivulets flow from your eyes Paint runs from your mouth Like a waterfall And your lungs crystalize.'
, 'Boy I need a hug (boy I need a hug) \'Cause my heart stops without you there\'s something about you.'
, 'Where was I when the rockets came to life And carried you away into the alligator sky Even though, I\'ll never know what\'s up ahead I\'m never lettin\' go, I\'m never lettin\' go.'
, 'It makes me smile because you said it best I would clearly feel blessed if the sun rose up from the west.'
, 'Home is a boxcar and it\'s so far out of reach Hidden under umbrella beach.'
, 'If I look back when I begin to leave, will they remember me?'
, 'Where was I when the rockets came to life, and carried you away into the alligator sky?'
];

$(document).ready(newQuote());

function newQuote() {
	var rand = Math.floor(Math.random() * quotes.length);
	document.getElementById('quoteContainer').innerHTML = quotes[rand];
	this.data = quotes[rand];
}

function tweetQuote() {
 //get inner text and replace inside the share
  var phrase = document.getElementById('quoteContainer').innerText;
  var tweetUrl = 'https://twitter.com/share?text=' +
    encodeURIComponent(phrase) +
    ' - QuoteGenerator By:' +
    '&via=' +
    'stevenmayo_';
  window.open(tweetUrl);
}

function tumblrPost() {
	var phrase = document.getElementById('quoteContainer').innerText;
	var tumblrURL = 'https://www.tumblr.com/widgets/share/tool?posttype=quote&content=' + encodeURIComponent(phrase) + '&buttons&tags=tumblelog%2C+blog%2C+tumblog%2C+tumbler%2C+tumblr%2C+tlog%2C+microblog&canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&shareSource=tumblr_share_button&_format=html';

		alert(tumblrURL);
	window.open(tumblrURL);
}

<|endoftext|>


<commit_before>'use strict';

function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    for(var firework in fireworks){
        buffer.fillStyle = fireworks[firework]['color'];
        buffer.fillRect(
          fireworks[firework]['x'],
          fireworks[firework]['y'],
          fireworks[firework]['width'],
          fireworks[firework]['height']
        );
    }

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    window.requestAnimationFrame(draw);
}

function launch(firework){
    var firework = firework || {};
    firework['children'] = firework['children'] !== void 0
      ? firework['children']
      : 10;
    firework['color'] = firework['color'] || random_hex();
    firework['dx'] = firework['dx'] || Math.random() * 4 - 2;
    firework['dy'] = firework['dy'] || -4 - Math.random() * 2;
    firework['height'] = firework['height'] || 4;
    firework['timer'] = firework['timer'] || 100 + Math.floor(Math.random() * 200);
    firework['width'] = firework['width'] || 4;
    firework['x'] = firework['x'] || x;
    firework['y'] = firework['y'] || height;

    fireworks.push(firework);
}

function logic(){
    for(var firework in fireworks){
        fireworks[firework]['x'] += fireworks[firework]['dx'];
        fireworks[firework]['y'] += fireworks[firework]['dy'];

        fireworks[firework]['dy'] += .02;
        fireworks[firework]['dx'] *= .99;

        fireworks[firework]['timer'] -= 1;
        if(fireworks[firework]['timer'] <= 0){
            if(fireworks[firework]['children'] > 0){
                var loop_counter = fireworks[firework]['children'] - 1;
                do{
                    launch({
                      'children': 0,
                      'dx': Math.random() * 3 - 1.5,
                      'dy': Math.random() * 3 - 1.5,
                      'x': fireworks[firework]['x'],
                      'timer': 42 + Math.floor(Math.random() * 99),
                      'y': fireworks[firework]['y'],
                    });
                }while(loop_counter--);
            }

            fireworks.splice(
              firework,
              1
            );
        }
    }
}

function random_hex(){
    var choices = '0123456789abcdef';
    return '#'
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16));
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;
}

var buffer = document.getElementById('buffer').getContext('2d', {
  'alpha': false,
});
var canvas = document.getElementById('canvas').getContext('2d', {
  'alpha': false,
});
var fireworks = [];
var height = 0;
var width = 0;
var x = 0;
var y = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // ESC: clear.
    if(key === 27){
        fireworks.length = 0;

    }else{
        launch();
    }
};

window.onload = function(e){
    resize();
    launch();

    window.requestAnimationFrame(draw);
    window.setInterval(
      'logic()',
      30
    );
};

window.onmousedown =
  window.ontouchstart = function(e){
    launch();
};

window.onresize = resize;
<commit_msg>adjusted default fireworks dy based on height<commit_after>'use strict';

function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    for(var firework in fireworks){
        buffer.fillStyle = fireworks[firework]['color'];
        buffer.fillRect(
          fireworks[firework]['x'],
          fireworks[firework]['y'],
          fireworks[firework]['width'],
          fireworks[firework]['height']
        );
    }

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    window.requestAnimationFrame(draw);
}

function launch(firework){
    var firework = firework || {};
    firework['children'] = firework['children'] !== void 0
      ? firework['children']
      : 10;
    firework['color'] = firework['color'] || random_hex();
    firework['dx'] = firework['dx'] || Math.random() * 4 - 2;
    firework['dy'] = firework['dy'] || -(height / 200) - Math.random() * 2;
    firework['height'] = firework['height'] || 4;
    firework['timer'] = firework['timer'] || 100 + Math.floor(Math.random() * 200);
    firework['width'] = firework['width'] || 4;
    firework['x'] = firework['x'] || x;
    firework['y'] = firework['y'] || height;

    fireworks.push(firework);
}

function logic(){
    for(var firework in fireworks){
        fireworks[firework]['x'] += fireworks[firework]['dx'];
        fireworks[firework]['y'] += fireworks[firework]['dy'];

        fireworks[firework]['dy'] += .02;
        fireworks[firework]['dx'] *= .99;

        fireworks[firework]['timer'] -= 1;
        if(fireworks[firework]['timer'] <= 0){
            if(fireworks[firework]['children'] > 0){
                var loop_counter = fireworks[firework]['children'] - 1;
                do{
                    launch({
                      'children': 0,
                      'dx': Math.random() * 3 - 1.5,
                      'dy': Math.random() * 3 - 1.5,
                      'x': fireworks[firework]['x'],
                      'timer': 42 + Math.floor(Math.random() * 99),
                      'y': fireworks[firework]['y'],
                    });
                }while(loop_counter--);
            }

            fireworks.splice(
              firework,
              1
            );
        }
    }
}

function random_hex(){
    var choices = '0123456789abcdef';
    return '#'
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16))
      + choices.charAt(Math.floor(Math.random() * 16));
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;
}

var buffer = document.getElementById('buffer').getContext('2d', {
  'alpha': false,
});
var canvas = document.getElementById('canvas').getContext('2d', {
  'alpha': false,
});
var fireworks = [];
var height = 0;
var width = 0;
var x = 0;
var y = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // ESC: clear.
    if(key === 27){
        fireworks.length = 0;

    }else{
        launch();
    }
};

window.onload = function(e){
    resize();
    launch();

    window.requestAnimationFrame(draw);
    window.setInterval(
      'logic()',
      30
    );
};

window.onmousedown =
  window.ontouchstart = function(e){
    launch();
};

window.onresize = resize;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.dao',
  name: 'NullDAO',
  extends: 'foam.dao.AbstractDAO',

  documentation: 'A Null pattern (do-nothing) DAO implementation.',

  requires: [
    'foam.dao.ExternalException',
    'foam.dao.ObjectNotFoundException'
  ],

  methods: [
    function put(obj) {
      return Promise.reject(this.ExternalException.create({
        message: 'NullDAO: Cannot handle put()'
      }));
    },

    function remove(obj) {
      return Promise.resolve();
    },

    function find(id) {
      return Promise.resolve(null);
    },

    function select(sink) {
      sink.eof();
      return Promise.resolve(sink);
    },

    function removeAll() {
      return Promise.resolve();
    }
  ]
});
<commit_msg>Fix NullDAO.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.dao',
  name: 'NullDAO',
  extends: 'foam.dao.AbstractDAO',

  documentation: 'A Null pattern (do-nothing) DAO implementation.',

  requires: [
    'foam.dao.ExternalException',
    'foam.dao.ObjectNotFoundException'
  ],

  methods: [
    function put(obj) {
      return Promise.reject(this.ExternalException.create({
        message: 'NullDAO: Cannot handle put()'
      }));
    },

    function remove(obj) {
      return Promise.resolve();
    },

    function find(id) {
      return Promise.resolve(null);
    },

    function select(sink) {
      sink = sink || foam.dao.ArraySink.create();
      sink.eof();
      return Promise.resolve(sink);
    },

    function removeAll() {
      return Promise.resolve();
    }
  ]
});
<|endoftext|>


<commit_before>/* global Gallery, Thumbnails */
(function ($, Gallery, oc_requesttoken) {
	"use strict";
	/**
	 * Creates a new image object to store information about a media file
	 *
	 * @param src
	 * @param path
	 * @param fileId
	 * @param mimeType
	 * @param mTime modification time
	 * @param etag
	 * @constructor
	 */
	var GalleryImage = function (src, path, fileId, mimeType, mTime, etag) {
		this.src = src;
		this.path = path;
		this.fileId = fileId;
		this.mimeType = mimeType;
		this.mTime = mTime;
		this.etag = etag;
		this.thumbnail = null;
		this.domDef = null;
		this.domHeigth = null;
	};

	GalleryImage.prototype = {
		/**
		 * Returns the Thumbnail ID
		 *
		 * @returns {[number]}
		 */
		getThumbnailIds: function () {
			return [this.fileId];
		},

		/**
		 * Returns a reference to a loading Thumbnail.image
		 *
		 * @param {bool} square
		 *
		 * @returns {jQuery.Deferred<Thumbnail.image>}
		 */
		getThumbnail: function (square) {
			if (this.thumbnail === null) {
				this.thumbnail = Thumbnails.get(this.fileId, square);
			}
			return this.thumbnail.loadingDeferred;
		},

		/**
		 * Returns the width of a thumbnail
		 *
		 * Used to calculate the width of the row as we add more images to it
		 *
		 * @returns {number}
		 */
		getThumbnailWidth: function () {
			// img is a Thumbnail.image
			return this.getThumbnail(false).then(function (img) {
				if (img) {
					return img.originalWidth;
				}
				return 0;
			});
		},

		/**
		 * Creates the a and img element in the DOM
		 *
		 * Each image is also a link to start the full screen slideshow
		 *
		 * @param {number} targetHeight
		 *
		 * @return {a}
		 */
		getDom: function (targetHeight) {
			var image = this;
			if (this.domDef === null || this.domHeigth !== targetHeight) {
				this.domHeigth = targetHeight;
				// img is a Thumbnail.image
				this.domDef = this.getThumbnail(false).then(function (img) {
					$(img).css({
						'height': targetHeight,
						'width': targetHeight * image.thumbnail.ratio
					});
					img.alt = encodeURI(image.path);
					var url = '#' + encodeURIComponent(image.path);

					if (!image.thumbnail.valid) {
						var params = {
							c: image.etag,
							requesttoken: oc_requesttoken
						};
						url = Gallery.utility.buildGalleryUrl('files/download', '/' + image.fileId,
							params);
					}
					var a = $('<a/>').addClass('image').attr('href', url).attr('data-path',
						image.path);

					var imageLabel = $('<span/>').addClass('image-label');
					var imageTitle = $('<span/>').addClass('title').text(
						OC.basename(image.path));
					imageLabel.append(imageTitle);
					a.hover(function () {
						imageLabel.slideToggle(OC.menuSpeed);
					}, function () {
						imageLabel.slideToggle(OC.menuSpeed);
					});
					a.append(imageLabel);
					a.append(img);
					return a;
				});
			}
			return this.domDef;
		}
	};

	window.GalleryImage = GalleryImage;
})(jQuery, Gallery, oc_requesttoken);
<commit_msg>Add global oc_requesttoken to galleryimage [ci skip] (cherry picked from commit ad37372)<commit_after>/* global oc_requesttoken, Gallery, Thumbnails */
(function ($, Gallery, oc_requesttoken) {
	"use strict";
	/**
	 * Creates a new image object to store information about a media file
	 *
	 * @param src
	 * @param path
	 * @param fileId
	 * @param mimeType
	 * @param mTime modification time
	 * @param etag
	 * @constructor
	 */
	var GalleryImage = function (src, path, fileId, mimeType, mTime, etag) {
		this.src = src;
		this.path = path;
		this.fileId = fileId;
		this.mimeType = mimeType;
		this.mTime = mTime;
		this.etag = etag;
		this.thumbnail = null;
		this.domDef = null;
		this.domHeigth = null;
	};

	GalleryImage.prototype = {
		/**
		 * Returns the Thumbnail ID
		 *
		 * @returns {[number]}
		 */
		getThumbnailIds: function () {
			return [this.fileId];
		},

		/**
		 * Returns a reference to a loading Thumbnail.image
		 *
		 * @param {bool} square
		 *
		 * @returns {jQuery.Deferred<Thumbnail.image>}
		 */
		getThumbnail: function (square) {
			if (this.thumbnail === null) {
				this.thumbnail = Thumbnails.get(this.fileId, square);
			}
			return this.thumbnail.loadingDeferred;
		},

		/**
		 * Returns the width of a thumbnail
		 *
		 * Used to calculate the width of the row as we add more images to it
		 *
		 * @returns {number}
		 */
		getThumbnailWidth: function () {
			// img is a Thumbnail.image
			return this.getThumbnail(false).then(function (img) {
				if (img) {
					return img.originalWidth;
				}
				return 0;
			});
		},

		/**
		 * Creates the a and img element in the DOM
		 *
		 * Each image is also a link to start the full screen slideshow
		 *
		 * @param {number} targetHeight
		 *
		 * @return {a}
		 */
		getDom: function (targetHeight) {
			var image = this;
			if (this.domDef === null || this.domHeigth !== targetHeight) {
				this.domHeigth = targetHeight;
				// img is a Thumbnail.image
				this.domDef = this.getThumbnail(false).then(function (img) {
					$(img).css({
						'height': targetHeight,
						'width': targetHeight * image.thumbnail.ratio
					});
					img.alt = encodeURI(image.path);
					var url = '#' + encodeURIComponent(image.path);

					if (!image.thumbnail.valid) {
						var params = {
							c: image.etag,
							requesttoken: oc_requesttoken
						};
						url = Gallery.utility.buildGalleryUrl('files/download', '/' + image.fileId,
							params);
					}
					var a = $('<a/>').addClass('image').attr('href', url).attr('data-path',
						image.path);

					var imageLabel = $('<span/>').addClass('image-label');
					var imageTitle = $('<span/>').addClass('title').text(
						OC.basename(image.path));
					imageLabel.append(imageTitle);
					a.hover(function () {
						imageLabel.slideToggle(OC.menuSpeed);
					}, function () {
						imageLabel.slideToggle(OC.menuSpeed);
					});
					a.append(imageLabel);
					a.append(img);
					return a;
				});
			}
			return this.domDef;
		}
	};

	window.GalleryImage = GalleryImage;
})(jQuery, Gallery, oc_requesttoken);
<|endoftext|>