<commit_before>// Global state
var $upNext = null;
var $w;
var $h;
var $slides;
var $arrows;
var $nextArrow;
var $startCardButton;
var $controlBtn;
var $thisPlayerProgress;
var $playedBar;
var $subtitleWrapper;
var $subtitles;
var $slideTitle;
var $ambientPlayer;
var $narrativePlayer;
var $share;
var $shareModal;
var $progressIndicator
var $currentProgress;
var $support;
var $supportBtn;
var $question;
var $careStory;
var $careStoryBtns;
var $email;
var $emailBtn;
var isTouch = Modernizr.touch;
var mobileSuffix;
var aspectWidth = 16;
var aspectHeight = 9;
var optimalWidth;
var optimalHeight;
var w;
var h;
var completion = 0;
var arrowTest;
var progressTest;
var conclusionTest;
var firstRightArrowClicked = false;
var presentedConclusion = false;
// var hammer;
var NO_AUDIO = (window.location.search.indexOf('noaudio') >= 0);
var visibilityProperty = null;

var resize = function() {
    $w = $(window).width();
    $h = $(window).height();

    $slides.width($w);

    optimalWidth = ($h * aspectWidth) / aspectHeight;
    optimalHeight = ($w * aspectHeight) / aspectWidth;

    w = $w;
    h = optimalHeight;

    if (optimalWidth > $w) {
        w = optimalWidth;
        h = $h;
    }

};

var setUpFullPage = function() {
    var anchors = ['_'];
    for (var i = 0; i < COPY.content.length; i++) {
        anchors.push(COPY.content[i][0]);
    }
    $.fn.fullpage({
        anchors: (!APP_CONFIG.DEPLOYMENT_TARGET) ? anchors : false,
        autoScrolling: false,
        keyboardScrolling: false,
        verticalCentered: false,
        fixedElements: '.primary-navigation, #share-modal, .share, .progress-indicator',
        resize: false,
        css3: true,
        loopHorizontal: false,
        afterRender: onPageLoad,
        afterSlideLoad: lazyLoad,
        onSlideLeave: onSlideLeave
    });
};

var onPageLoad = function() {
    setSlidesForLazyLoading(0);
    $('.section').css({
      'opacity': 1,
      'visibility': 'visible',
    });
    showNavigation();
};

// after a new slide loads
var lazyLoad = function(anchorLink, index, slideAnchor, slideIndex) {
    setSlidesForLazyLoading(slideIndex);
    showNavigation();
    AUDIO.checkForAudio(slideAnchor);
    animateProgress(slideIndex);

    if (slideIndex === 0) {
        $share.hide();
    } else {
        $share.show();
    }

    if (slideIndex === $slides.length - 1) {
        buildConclusionSlide();
    }

    // Completion tracking
    how_far = (slideIndex + 1) / ($slides.length - 1);

    if (how_far >= completion + 0.25) {
        completion = how_far - (how_far % 0.25);

        if (completion === 0.25) {
            ANALYTICS.completeTwentyFivePercent(progressTest);
        }
        else if (completion === 0.5) {
            ANALYTICS.completeFiftyPercent(progressTest);
        }
        else if (completion === 0.75) {
            ANALYTICS.completeSeventyFivePercent(progressTest);
        }
        else if (completion === 1) {
            ANALYTICS.completeOneHundredPercent(progressTest);
        }
    }
};

var setSlidesForLazyLoading = function(slideIndex) {
    /*
    * Sets up a list of slides based on your position in the deck.
    * Lazy-loads images in future slides because of reasons.
    */
    var slides = [
        $slides.eq(slideIndex),
        $slides.eq(slideIndex + 1),
        $slides.eq(slideIndex + 2),
        $slides.eq(slideIndex + 3),
        $slides.eq(slideIndex + 4)
    ];

    // Mobile suffix should be blank by default.
    mobileSuffix = '';
    /*
    if ($w < 769) {
        mobileSuffix = '-sq';
    }*/

    for (var i = 0; i < slides.length; i++) {
        loadImages(slides[i]);
    };

}

var loadImages = function($slide) {
    /*
    * Sets the background image on a div for our fancy slides.
    */
    if ($slide.data('bgimage')) {
        var image_filename = $slide.data('bgimage').split('.')[0];
        var image_extension = '.' + $slide.data('bgimage').split('.')[1];
        var image_path = 'assets/' + image_filename + mobileSuffix + image_extension;

        if ($slide.css('background-image') === 'none') {
            $slide.css('background-image', 'url(' + image_path + ')');
        }
    }

    var $images = $slide.find('img.lazy-load');
    if ($images.length > 0) {
        for (var i = 0; i < $images.length; i++) {
            var image = $images.eq(i).data('src');
            $images.eq(i).attr('src', 'assets/' + image);
        }
    }
};

var showNavigation = function() {
    /*
    * Nav doesn't exist by default.
    * This function loads it up.
    */

    if ($slides.first().hasClass('active')) {
        /*
        * Don't show arrows on titlecard
        */
        $arrows.hide();
    }

    else if ($slides.last().hasClass('active')) {
        /*
        * Last card gets no next arrow but does have the nav.
        */
        if (!$arrows.hasClass('active')) {
            showArrows();
        }

        $nextArrow.removeClass('active');
        $nextArrow.hide();
    } else if ($slides.eq(1).hasClass('active')) {
        showArrows();

        switch (arrowTest) {
            case 'bright-arrow':
                $nextArrow.addClass('titlecard-nav');
                break;
            case 'bouncy-arrow':
                $nextArrow.addClass('shake animated titlecard-nav');
                break;
            default:
                break;
        }

        $nextArrow.on('click', onFirstRightArrowClick);
    } else {
        /*
        * All of the other cards? Arrows and navs.
        */
        if ($arrows.filter('active').length != $arrows.length) {
            showArrows();
        }
        $nextArrow.removeClass('shake animated titlecard-nav');

        $nextArrow.off('click', onFirstRightArrowClick);
    }

    if (progressTest === 'progress-bar') {
        $progressIndicator.show();
    }
}

var showArrows = function() {
    /*
    * Show the arrows.
    */
    $arrows.addClass('active');
    $arrows.show();
};

var determineTest = function(possibleTests) {
    var test = possibleTests[getRandomInt(0, possibleTests.length)]
    return test
}

var getRandomInt = function(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

var setCustomVars = function() {
    ANALYTICS.setCustomVar(40, 'progress-test', progressTest);
}

var buildConclusionSlide = function() {
    ANALYTICS.trackEvent('tests-run', conclusionTest);

    if (!presentedConclusion) {
        presentedConclusion = true;
        if (conclusionTest === 'no-question') {
            $support.show();
        } else {
            $question.text(COPY['post_metadata'][conclusionTest]);
            $careStory.show();
        }
    }

}

var onCareStoryBtnClick = function(e) {
    e.preventDefault();

    var $this = $(this);

    $careStory.hide();

    if ($this.hasClass('yes')) {
        ANALYTICS.trackEvent('like-story', 'yes');
        $support.show();
    } else {
        ANALYTICS.trackEvent('like-story', 'no');
        $email.show();
    }
}

var onSupportBtnClick = function(e) {
    e.preventDefault();

    var $this = $(this);
    var link = $this.attr('href');

    ANALYTICS.trackEvent('support-btn-click', conclusionTest);

    window.top.location = link
    return true;
}

var onEmailBtnClick = function() {
    ANALYTICS.trackEvent('email-btn-click');
}

var animateProgress = function(index) {
    var totalSlides = $slides.length;
    var percentage = (index + 1) / totalSlides;
    $currentProgress.css('width', percentage * 100 + '%');

    if (index === 0) {
        $progressIndicator.width(0);
    } else {
        $progressIndicator.width('100%');
    }
}

var onSlideLeave = function(anchorLink, index, slideIndex, direction) {
    /*
    * Called when leaving a slide.
    */
    ANALYTICS.exitSlide(slideIndex.toString());
}

var onFirstRightArrowClick = function() {
    if (firstRightArrowClicked === false) {
        ANALYTICS.firstRightArrowClick(arrowTest);
        firstRightArrowClicked = true;
    }
}

var onStartCardButtonClick = function() {
    ANALYTICS.trackEvent('begin');

    $.fn.fullpage.moveSlideRight();
    if (isTouch) {
        AUDIO.fakeAmbientPlayer();
        AUDIO.fakeNarrativePlayer();
    }
}

var onDocumentKeyDown = function(e) {
    if (e.which === 37 || e.which === 39) {
        ANALYTICS.useKeyboardNavigation();
        if (e.which === 37) {
            $.fn.fullpage.moveSlideLeft();
        } else if (e.which === 39) {
            $.fn.fullpage.moveSlideRight();
        }
    }
    // jquery.fullpage handles actual scrolling
    return true;
}

var onSlideClick = function(e) {
    if (isTouch) {
        if ($slides.first().hasClass('active')) {
            AUDIO.fakeAmbientPlayer();
            AUDIO.fakeNarrativePlayer();
        }
        $.fn.fullpage.moveSlideRight();
    }
    return true;
}

var fakeMobileHover = function() {
    $(this).css({
        'background-color': '#fff',
        'color': '#000',
        'opacity': .9
    });
}

var rmFakeMobileHover = function() {
    $(this).css({
        'background-color': 'rgba(0, 0, 0, 0.5)',
        'color': '#fff',
        'opacity': .5
    });
}

/*
 * Text copied to clipboard.
 */
var onClippyCopy = function(e) {
    alert('Copied to your clipboard!');

    ANALYTICS.copySummary();
}

var onControlBtnClick = function(e) {
    e.preventDefault();
    AUDIO.toggleNarrativeAudio();
    ANALYTICS.trackEvent('pause-button');

    e.stopPropagation();
}

var onVisibilityChange = function() {
    AUDIO.toggleAllAudio();
}

var getHiddenProperty = function() {
    var prefixes = ['webkit','moz','ms','o'];

    // if 'hidden' is natively supported just return it
    if ('hidden' in document) return 'hidden';

    // otherwise loop over all the known prefixes until we find one
    for (var i = 0; i < prefixes.length; i++){
        if ((prefixes[i] + 'Hidden') in document)
            return prefixes[i] + 'Hidden';
    }

    // otherwise it's not supported
    return null;
}

var isHidden = function() {
    var prop = getHiddenProperty();
    if (!prop) return false;

    return document[prop];
}

/*
 * Share modal opened.
 */
var onShareModalShown = function(e) {
    ANALYTICS.openShareDiscuss();
}

/*
 * Share modal closed.
 */
var onShareModalHidden = function(e) {
    ANALYTICS.closeShareDiscuss();
}

$(document).ready(function() {
    $w = $(window).width();
    $h = $(window).height();

    $slides = $('.slide');
    $navButton = $('.primary-navigation-btn');
    $startCardButton = $('.btn-go');
    $arrows = $('.controlArrow');
    $nextArrow = $arrows.filter('.next');
    $upNext = $('.up-next');
    $controlBtn = $('.control-btn');
    $narrativePlayer = $('#narrative-player');
    $ambientPlayer = $('#ambient-player');
    $share = $('.share');
    $shareModal = $('#share-modal')
    $progressIndicator = $('.progress-indicator');
    $currentProgress = $('.current-progress');
    $support = $('.support')
    $supportBtn = $('.support-btn');
    $careStory = $('.care-story');
    $question = $('.question');
    $careStoryBtns = $('.care-story-btn');
    $email = $('.email');
    $emailBtn = $('.email-btn');

    arrowTest = determineTest(['faded-arrow', 'bright-arrow', 'bouncy-arrow']);
    progressTest = determineTest(['progress-bar', 'no-progress-bar']);
    conclusionTest = determineTest(['no-question', 'question_a', 'question_b', 'question_c', 'question_d']);

    $shareModal.on('shown.bs.modal', onShareModalShown);
    $shareModal.on('hidden.bs.modal', onShareModalHidden);
    $startCardButton.on('click', onStartCardButtonClick);
    $slides.on('click', onSlideClick);
    $controlBtn.on('click', onControlBtnClick);
    $arrows.on('touchstart', fakeMobileHover);
    $arrows.on('touchend', rmFakeMobileHover);
    $careStoryBtns.on('click', onCareStoryBtnClick);
    $supportBtn.on('click', onSupportBtnClick);
    $emailBtn.on('click', onEmailBtnClick);
    $(document).keydown(onDocumentKeyDown);

    AUDIO.setUpNarrativePlayer();
    AUDIO.setUpAmbientPlayer();
    setUpFullPage();
    resize();
    setCustomVars();

    // Redraw slides if the window resizes
    window.addEventListener("deviceorientation", resize, true);
    $(window).resize(resize);

    // listen for page visibility changes
    visibilityProperty = getHiddenProperty();
    if (visibilityProperty) {
        var evtname = visibilityProperty.replace(/[H|h]idden/,'') + 'visibilitychange';
        document.addEventListener(evtname, onVisibilityChange);
    }
});<commit_msg>add conclusion test to email btn click<commit_after>// Global state
var $upNext = null;
var $w;
var $h;
var $slides;
var $arrows;
var $nextArrow;
var $startCardButton;
var $controlBtn;
var $thisPlayerProgress;
var $playedBar;
var $subtitleWrapper;
var $subtitles;
var $slideTitle;
var $ambientPlayer;
var $narrativePlayer;
var $share;
var $shareModal;
var $progressIndicator
var $currentProgress;
var $support;
var $supportBtn;
var $question;
var $careStory;
var $careStoryBtns;
var $email;
var $emailBtn;
var isTouch = Modernizr.touch;
var mobileSuffix;
var aspectWidth = 16;
var aspectHeight = 9;
var optimalWidth;
var optimalHeight;
var w;
var h;
var completion = 0;
var arrowTest;
var progressTest;
var conclusionTest;
var firstRightArrowClicked = false;
var presentedConclusion = false;
// var hammer;
var NO_AUDIO = (window.location.search.indexOf('noaudio') >= 0);
var visibilityProperty = null;

var resize = function() {
    $w = $(window).width();
    $h = $(window).height();

    $slides.width($w);

    optimalWidth = ($h * aspectWidth) / aspectHeight;
    optimalHeight = ($w * aspectHeight) / aspectWidth;

    w = $w;
    h = optimalHeight;

    if (optimalWidth > $w) {
        w = optimalWidth;
        h = $h;
    }

};

var setUpFullPage = function() {
    var anchors = ['_'];
    for (var i = 0; i < COPY.content.length; i++) {
        anchors.push(COPY.content[i][0]);
    }
    $.fn.fullpage({
        anchors: (!APP_CONFIG.DEPLOYMENT_TARGET) ? anchors : false,
        autoScrolling: false,
        keyboardScrolling: false,
        verticalCentered: false,
        fixedElements: '.primary-navigation, #share-modal, .share, .progress-indicator',
        resize: false,
        css3: true,
        loopHorizontal: false,
        afterRender: onPageLoad,
        afterSlideLoad: lazyLoad,
        onSlideLeave: onSlideLeave
    });
};

var onPageLoad = function() {
    setSlidesForLazyLoading(0);
    $('.section').css({
      'opacity': 1,
      'visibility': 'visible',
    });
    showNavigation();
};

// after a new slide loads
var lazyLoad = function(anchorLink, index, slideAnchor, slideIndex) {
    setSlidesForLazyLoading(slideIndex);
    showNavigation();
    AUDIO.checkForAudio(slideAnchor);
    animateProgress(slideIndex);

    if (slideIndex === 0) {
        $share.hide();
    } else {
        $share.show();
    }

    if (slideIndex === $slides.length - 1) {
        buildConclusionSlide();
    }

    // Completion tracking
    how_far = (slideIndex + 1) / ($slides.length - 1);

    if (how_far >= completion + 0.25) {
        completion = how_far - (how_far % 0.25);

        if (completion === 0.25) {
            ANALYTICS.completeTwentyFivePercent(progressTest);
        }
        else if (completion === 0.5) {
            ANALYTICS.completeFiftyPercent(progressTest);
        }
        else if (completion === 0.75) {
            ANALYTICS.completeSeventyFivePercent(progressTest);
        }
        else if (completion === 1) {
            ANALYTICS.completeOneHundredPercent(progressTest);
        }
    }
};

var setSlidesForLazyLoading = function(slideIndex) {
    /*
    * Sets up a list of slides based on your position in the deck.
    * Lazy-loads images in future slides because of reasons.
    */
    var slides = [
        $slides.eq(slideIndex),
        $slides.eq(slideIndex + 1),
        $slides.eq(slideIndex + 2),
        $slides.eq(slideIndex + 3),
        $slides.eq(slideIndex + 4)
    ];

    // Mobile suffix should be blank by default.
    mobileSuffix = '';
    /*
    if ($w < 769) {
        mobileSuffix = '-sq';
    }*/

    for (var i = 0; i < slides.length; i++) {
        loadImages(slides[i]);
    };

}

var loadImages = function($slide) {
    /*
    * Sets the background image on a div for our fancy slides.
    */
    if ($slide.data('bgimage')) {
        var image_filename = $slide.data('bgimage').split('.')[0];
        var image_extension = '.' + $slide.data('bgimage').split('.')[1];
        var image_path = 'assets/' + image_filename + mobileSuffix + image_extension;

        if ($slide.css('background-image') === 'none') {
            $slide.css('background-image', 'url(' + image_path + ')');
        }
    }

    var $images = $slide.find('img.lazy-load');
    if ($images.length > 0) {
        for (var i = 0; i < $images.length; i++) {
            var image = $images.eq(i).data('src');
            $images.eq(i).attr('src', 'assets/' + image);
        }
    }
};

var showNavigation = function() {
    /*
    * Nav doesn't exist by default.
    * This function loads it up.
    */

    if ($slides.first().hasClass('active')) {
        /*
        * Don't show arrows on titlecard
        */
        $arrows.hide();
    }

    else if ($slides.last().hasClass('active')) {
        /*
        * Last card gets no next arrow but does have the nav.
        */
        if (!$arrows.hasClass('active')) {
            showArrows();
        }

        $nextArrow.removeClass('active');
        $nextArrow.hide();
    } else if ($slides.eq(1).hasClass('active')) {
        showArrows();

        switch (arrowTest) {
            case 'bright-arrow':
                $nextArrow.addClass('titlecard-nav');
                break;
            case 'bouncy-arrow':
                $nextArrow.addClass('shake animated titlecard-nav');
                break;
            default:
                break;
        }

        $nextArrow.on('click', onFirstRightArrowClick);
    } else {
        /*
        * All of the other cards? Arrows and navs.
        */
        if ($arrows.filter('active').length != $arrows.length) {
            showArrows();
        }
        $nextArrow.removeClass('shake animated titlecard-nav');

        $nextArrow.off('click', onFirstRightArrowClick);
    }

    if (progressTest === 'progress-bar') {
        $progressIndicator.show();
    }
}

var showArrows = function() {
    /*
    * Show the arrows.
    */
    $arrows.addClass('active');
    $arrows.show();
};

var determineTest = function(possibleTests) {
    var test = possibleTests[getRandomInt(0, possibleTests.length)]
    return test
}

var getRandomInt = function(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

var setCustomVars = function() {
    ANALYTICS.setCustomVar(40, 'progress-test', progressTest);
}

var buildConclusionSlide = function() {
    ANALYTICS.trackEvent('tests-run', conclusionTest);

    if (!presentedConclusion) {
        presentedConclusion = true;
        if (conclusionTest === 'no-question') {
            $support.show();
        } else {
            $question.text(COPY['post_metadata'][conclusionTest]);
            $careStory.show();
        }
    }

}

var onCareStoryBtnClick = function(e) {
    e.preventDefault();

    var $this = $(this);

    $careStory.hide();

    if ($this.hasClass('yes')) {
        ANALYTICS.trackEvent('like-story', 'yes');
        $support.show();
    } else {
        ANALYTICS.trackEvent('like-story', 'no');
        $email.show();
    }
}

var onSupportBtnClick = function(e) {
    e.preventDefault();

    var $this = $(this);
    var link = $this.attr('href');

    ANALYTICS.trackEvent('support-btn-click', conclusionTest);

    window.top.location = link
    return true;
}

var onEmailBtnClick = function() {
    ANALYTICS.trackEvent('email-btn-click', conclusionTest);
}

var animateProgress = function(index) {
    var totalSlides = $slides.length;
    var percentage = (index + 1) / totalSlides;
    $currentProgress.css('width', percentage * 100 + '%');

    if (index === 0) {
        $progressIndicator.width(0);
    } else {
        $progressIndicator.width('100%');
    }
}

var onSlideLeave = function(anchorLink, index, slideIndex, direction) {
    /*
    * Called when leaving a slide.
    */
    ANALYTICS.exitSlide(slideIndex.toString());
}

var onFirstRightArrowClick = function() {
    if (firstRightArrowClicked === false) {
        ANALYTICS.firstRightArrowClick(arrowTest);
        firstRightArrowClicked = true;
    }
}

var onStartCardButtonClick = function() {
    ANALYTICS.trackEvent('begin');

    $.fn.fullpage.moveSlideRight();
    if (isTouch) {
        AUDIO.fakeAmbientPlayer();
        AUDIO.fakeNarrativePlayer();
    }
}

var onDocumentKeyDown = function(e) {
    if (e.which === 37 || e.which === 39) {
        ANALYTICS.useKeyboardNavigation();
        if (e.which === 37) {
            $.fn.fullpage.moveSlideLeft();
        } else if (e.which === 39) {
            $.fn.fullpage.moveSlideRight();
        }
    }
    // jquery.fullpage handles actual scrolling
    return true;
}

var onSlideClick = function(e) {
    if (isTouch) {
        if ($slides.first().hasClass('active')) {
            AUDIO.fakeAmbientPlayer();
            AUDIO.fakeNarrativePlayer();
        }
        $.fn.fullpage.moveSlideRight();
    }
    return true;
}

var fakeMobileHover = function() {
    $(this).css({
        'background-color': '#fff',
        'color': '#000',
        'opacity': .9
    });
}

var rmFakeMobileHover = function() {
    $(this).css({
        'background-color': 'rgba(0, 0, 0, 0.5)',
        'color': '#fff',
        'opacity': .5
    });
}

/*
 * Text copied to clipboard.
 */
var onClippyCopy = function(e) {
    alert('Copied to your clipboard!');

    ANALYTICS.copySummary();
}

var onControlBtnClick = function(e) {
    e.preventDefault();
    AUDIO.toggleNarrativeAudio();
    ANALYTICS.trackEvent('pause-button');

    e.stopPropagation();
}

var onVisibilityChange = function() {
    AUDIO.toggleAllAudio();
}

var getHiddenProperty = function() {
    var prefixes = ['webkit','moz','ms','o'];

    // if 'hidden' is natively supported just return it
    if ('hidden' in document) return 'hidden';

    // otherwise loop over all the known prefixes until we find one
    for (var i = 0; i < prefixes.length; i++){
        if ((prefixes[i] + 'Hidden') in document)
            return prefixes[i] + 'Hidden';
    }

    // otherwise it's not supported
    return null;
}

var isHidden = function() {
    var prop = getHiddenProperty();
    if (!prop) return false;

    return document[prop];
}

/*
 * Share modal opened.
 */
var onShareModalShown = function(e) {
    ANALYTICS.openShareDiscuss();
}

/*
 * Share modal closed.
 */
var onShareModalHidden = function(e) {
    ANALYTICS.closeShareDiscuss();
}

$(document).ready(function() {
    $w = $(window).width();
    $h = $(window).height();

    $slides = $('.slide');
    $navButton = $('.primary-navigation-btn');
    $startCardButton = $('.btn-go');
    $arrows = $('.controlArrow');
    $nextArrow = $arrows.filter('.next');
    $upNext = $('.up-next');
    $controlBtn = $('.control-btn');
    $narrativePlayer = $('#narrative-player');
    $ambientPlayer = $('#ambient-player');
    $share = $('.share');
    $shareModal = $('#share-modal')
    $progressIndicator = $('.progress-indicator');
    $currentProgress = $('.current-progress');
    $support = $('.support')
    $supportBtn = $('.support-btn');
    $careStory = $('.care-story');
    $question = $('.question');
    $careStoryBtns = $('.care-story-btn');
    $email = $('.email');
    $emailBtn = $('.email-btn');

    arrowTest = determineTest(['faded-arrow', 'bright-arrow', 'bouncy-arrow']);
    progressTest = determineTest(['progress-bar', 'no-progress-bar']);
    conclusionTest = determineTest(['no-question', 'question_a', 'question_b', 'question_c', 'question_d']);

    $shareModal.on('shown.bs.modal', onShareModalShown);
    $shareModal.on('hidden.bs.modal', onShareModalHidden);
    $startCardButton.on('click', onStartCardButtonClick);
    $slides.on('click', onSlideClick);
    $controlBtn.on('click', onControlBtnClick);
    $arrows.on('touchstart', fakeMobileHover);
    $arrows.on('touchend', rmFakeMobileHover);
    $careStoryBtns.on('click', onCareStoryBtnClick);
    $supportBtn.on('click', onSupportBtnClick);
    $emailBtn.on('click', onEmailBtnClick);
    $(document).keydown(onDocumentKeyDown);

    AUDIO.setUpNarrativePlayer();
    AUDIO.setUpAmbientPlayer();
    setUpFullPage();
    resize();
    setCustomVars();

    // Redraw slides if the window resizes
    window.addEventListener("deviceorientation", resize, true);
    $(window).resize(resize);

    // listen for page visibility changes
    visibilityProperty = getHiddenProperty();
    if (visibilityProperty) {
        var evtname = visibilityProperty.replace(/[H|h]idden/,'') + 'visibilitychange';
        document.addEventListener(evtname, onVisibilityChange);
    }
});<|endoftext|>


<commit_before>export default function(app) {
  return {
    state: {
      router: match(location.pathname)
    },
    actions: {
      router: {
        match: function(state, actions, data, emit) {
          return {
            router: emit("route", match(data))
          }
        },
        go: function(state, actions, data) {
          history.pushState({}, "", data)
          actions.router.match(data.split('?')[0])
        }
      }
    },
    events: {
      loaded: function(state, actions) {
        match()
        addEventListener("popstate", match)
        function match() {
          actions.router.match(location.pathname)
        }
      },
      render: function(state, actions, view) {
        return view[state.router.match]
      }
    }
  }

  function match(data) {
    var match
    var params = {}

    for (var route in app.view) {
      var keys = []

      if (!match && route !== "*") {
        data.replace(
          RegExp(
            "^" +
              route
                .replace(/\//g, "\\/")
                .replace(/:([\w]+)/g, function(_, key) {
                  keys.push(key)
                  return "([-\\w]+)"
                }) +
              "/?$",
            "g"
          ),
          function() {
            for (var i = 1; i < arguments.length - 2; ) {
              params[keys.shift()] = arguments[i++]
            }
            match = route
          }
        )
      }
    }

    return {
      match: match || "*",
      params: params
    }
  }
}
<commit_msg>Double quotes.<commit_after>export default function(app) {
  return {
    state: {
      router: match(location.pathname)
    },
    actions: {
      router: {
        match: function(state, actions, data, emit) {
          return {
            router: emit("route", match(data))
          }
        },
        go: function(state, actions, data) {
          history.pushState({}, "", data)
          actions.router.match(data.split("?")[0])
        }
      }
    },
    events: {
      loaded: function(state, actions) {
        match()
        addEventListener("popstate", match)
        function match() {
          actions.router.match(location.pathname)
        }
      },
      render: function(state, actions, view) {
        return view[state.router.match]
      }
    }
  }

  function match(data) {
    var match
    var params = {}

    for (var route in app.view) {
      var keys = []

      if (!match && route !== "*") {
        data.replace(
          RegExp(
            "^" +
              route
                .replace(/\//g, "\\/")
                .replace(/:([\w]+)/g, function(_, key) {
                  keys.push(key)
                  return "([-\\w]+)"
                }) +
              "/?$",
            "g"
          ),
          function() {
            for (var i = 1; i < arguments.length - 2; ) {
              params[keys.shift()] = arguments[i++]
            }
            match = route
          }
        )
      }
    }

    return {
      match: match || "*",
      params: params
    }
  }
}
<|endoftext|>


<commit_before>define([
    'require',
    '../lib/jquery',
    '../logging'
], function(require) {
    var log = require('../logging').getLogger('checklist');

    // a check-list made of checkboxes with optional
    // select-all/deselect-all functionality
    var init = function($el, opts) {
        var selectallctrl = $el.find('.functions .select-all'),
            deselectallctrl = $el.find('.functions .deselect-all');

        selectallctrl.click(function(ev) {
            ev.preventDefault();
            selectall($el);
        });
        deselectallctrl.click(function(ev) {
            ev.preventDefault();
            deselectall($el);
        });

        $el.on('change', 'input[type=checkbox]', function(ev) {
            if ($el.find('input[type=checkbox]:checked').length === 0) {
                log.debug('disabling deselect-all');
                deselectallctrl.attr({disabled: 'disabled'});
            } else {
                log.debug('enabling deselect-all');
                deselectallctrl.prop('disabled', false);
            }

            if ($el.find('input[type=checkbox]:not(:checked)').length === 0) {
                log.debug('disabling select-all');
                selectallctrl.attr({disabled: 'disabled'});
            } else {
                log.debug('enabling select-all');
                selectallctrl.prop('disabled', false);
            }
        });
    };

    var selectall = function($el) {
        var $unchecked = $el.find('input[type=checkbox]:not(:checked)');
        $unchecked.prop("checked", true);
        $unchecked.change();
    };

    var deselectall = function($el) {
        var $checked = $el.find('input[type=checkbox]:checked');
        $checked.prop("checked", false);
        $checked.change();
    };

    var pattern = {
        markup_trigger: ".check-list",
        initialised_class: "check-list",
        init: init,
        selectall: selectall,
        deselectall: deselectall
    };

    return pattern;
});
<commit_msg>checklist patterns performs less changes<commit_after>define([
    'require',
    '../lib/jquery',
    '../logging'
], function(require) {
    var log = require('../logging').getLogger('checklist');

    // a check-list made of checkboxes with optional
    // select-all/deselect-all functionality
    var init = function($el, opts) {
        var selectallctrl = $el.find('.functions .select-all'),
            deselectallctrl = $el.find('.functions .deselect-all');

        selectallctrl.click(function(ev) {
            ev.preventDefault();
            selectall($el);
        });
        deselectallctrl.click(function(ev) {
            ev.preventDefault();
            deselectall($el);
        });

        $el.on('change', 'input[type=checkbox]', function(ev) {
            if (($el.find('input[type=checkbox]:checked').length === 0) &&
                (!deselectallctrl.prop('disabled'))) {
                deselectallctrl.attr({disabled: 'disabled'});
            } else if (deselectallctrl.prop('disabled')) {
                deselectallctrl.prop('disabled', false);
            }

            if (($el.find('input[type=checkbox]:not(:checked)').length === 0) &&
                (!selectallctrl.prop('disabled'))) {
                selectallctrl.attr({disabled: 'disabled'});
            } else if (selectallctrl.prop('disabled')) {
                selectallctrl.prop('disabled', false);
            }
        });
    };

    var selectall = function($el) {
        var $unchecked = $el.find('input[type=checkbox]:not(:checked)'),
            deselectallctrl = $el.find('.functions .deselect-all'),
            selectallctrl = $el.find('.functions .select-all');
        $unchecked.prop("checked", true);
        deselectallctrl.prop('disabled', false);
        selectallctrl.attr({disabled: 'disabled'});
        $el.change();
    };

    var deselectall = function($el) {
        var $checked = $el.find('input[type=checkbox]:checked'),
            deselectallctrl = $el.find('.functions .deselect-all'),
            selectallctrl = $el.find('.functions .select-all');
        $checked.prop("checked", false);
        deselectallctrl.attr({disabled: 'disabled'});
        selectallctrl.prop('disabled', false);
        $el.change();
    };

    var pattern = {
        markup_trigger: ".check-list",
        initialised_class: "check-list",
        init: init,
        selectall: selectall,
        deselectall: deselectall
    };

    return pattern;
});
<|endoftext|>


<commit_before>// DOM elements
var $source;
var $save;
var $textColor;
var $logo;
var $crop;
var $logoColor;
var $imageLoader;
var $canvas;
var canvas;
var $qualityQuestions;

// state
var scaledImageHeight;
var fixedWidth = 1000;
var dy = 0;
var logoDimensions = {
    'npr': {
        w: 150,
        h: 52
    },
    'music': {
        w: 320,
        h: 85
    }

};
var elementPadding = 40;
var imageFilename;
var currentCrop = 'original';
var currentLogo = 'npr';
var currentLogoColor = 'white';
var currentTextColor = 'white';

// JS objects
var ctx;
var img = new Image();
var logo = new Image();

var onDocumentLoad = function(e) {
    $source = $('#source');
    $canvas = $('#imageCanvas');
    canvas = $canvas[0];
    $imageLoader = $('#imageLoader');
    ctx = canvas.getContext('2d');
    $save = $('.save-btn');
    $textColor = $('input[name="textColor"]');
    $logo = $('input[name="logo"]');
    $crop = $('input[name="crop"]');
    $logoColor = $('input[name="logoColor"]');
    $qualityQuestions = $('.quality-question');

    img.src = 'assets/test-kitten.jpg';
    img.onload = renderCanvas;
    logo.onload = renderCanvas;

    $source.on('keyup', renderCanvas);
    $imageLoader.on('change', handleImage);
    $save.on('click', onSaveClick);
    $textColor.on('change', onTextColorChange);
    $logo.on('change', onLogoChange);
    $logoColor.on('change', onLogoColorChange);
    $crop.on('change', onCropChange);
    $canvas.on('mousedown', onDrag);
    $qualityQuestions.on('change', onCheckboxChange);

    $("body").on("contextmenu", "canvas", function(e) {
        return false;
    });

    loadLogo();
    renderCanvas();
}

/*
* Draw the image, then the logo, then the text
*/
var renderCanvas = function() {
    // canvas is always the same width
    canvas.width = fixedWidth;

    // if we're cropping, use the aspect ratio for the height
    if (currentCrop !== 'original') {
        canvas.height = fixedWidth / (16/9);
    }

    // clear the canvas
    ctx.clearRect(0,0,canvas.width,canvas.height);

    // determine height of canvas and scaled image, then draw the image
    var imageAspect = img.width / img.height;
    if (currentCrop === 'original') {
        canvas.height = fixedWidth / imageAspect;
        scaledImageHeight = canvas.height;
        ctx.drawImage(
            img,
            0,
            0,
            fixedWidth,
            scaledImageHeight
        );
    } else {
        scaledImageHeight = fixedWidth / imageAspect;
        ctx.drawImage(
            img,
            0,
            0,
            img.width,
            img.height,
            0,
            dy,
            fixedWidth,
            scaledImageHeight
        );
    }

    // set alpha channel, draw the logo
    if (currentLogoColor === 'white') {
        ctx.globalAlpha = "0.8";
    } else {
        ctx.globalAlpha = "0.6";
    }
    ctx.drawImage(
        logo,
        canvas.width - (logoDimensions[currentLogo]['w'] + elementPadding),
        currentLogo === 'npr'? elementPadding : elementPadding - 15,
        logoDimensions[currentLogo]['w'],
        logoDimensions[currentLogo]['h']
    );

    // reset alpha channel so text is not translucent
    ctx.globalAlpha = "1";

    // draw the text
    ctx.textBaseline = 'bottom';
    ctx.textAlign = 'left';
    ctx.fillStyle = currentTextColor;
    ctx.font = 'normal 20pt "Gotham SSm"';

    if (currentTextColor === 'white') {
        ctx.shadowColor = 'rgba(0,0,0,0.7)';
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
        ctx.shadowBlur = 10;
    }

    ctx.fillText(
        $source.val() === '' ? 'Belal Khan/Flickr': $source.val(),
        elementPadding,
        canvas.height - elementPadding
    );
}

/*
* Handle dragging the image for crops when applicable
*/
var onDrag = function(e) {
    e.preventDefault();
    var originY = e.clientY;
    var startY = dy;

    if (currentCrop === 'original') {
        return;
    }

    function update(e) {
        if (Math.abs(e.clientY - originY) > 1) {
            dy = startY - (originY - e.clientY);

            // Prevent dragging image below upper bound
            if (dy > 0) {
                dy = 0;
                return;
            }

            // Prevent dragging image above lower bound
            if (dy < canvas.height - scaledImageHeight) {
                dy = canvas.height - scaledImageHeight;
                return;
            }

            renderCanvas();
        }
    }

    // Perform drag sequence:
    $(document).on('mousemove.drag', _.debounce(update, 5, true))
        .on('mouseup.drag', function(e) {
            $(document).off('mouseup.drag mousemove.drag');
            update(e);
        });
}

/*
* Take an image from file input and load it
*/
var handleImage = function(e) {
    var reader = new FileReader();
    reader.onload = function(e){
        imageFilename = e.target.result
        img.src = imageFilename
    }
    reader.readAsDataURL(e.target.files[0]);
}

/*
* Load the logo based on radio buttons
*/
var loadLogo = function() {
    logo.src = 'assets/logo-' + currentLogo + '-' + currentLogoColor + '.svg';
}

/*
* Download the image on save click
*/
var onSaveClick = function(e) {
    e.preventDefault();

    /// create an "off-screen" anchor tag
    var link = document.createElement('a'),
        e;

    /// the key here is to set the download attribute of the a tag
    link.download = 'download.png';

    /// convert canvas content to data-uri for link. When download
    /// attribute is set the content pointed to by link will be
    /// pushed as "download" in HTML5 capable browsers
    link.href = canvas.toDataURL();
    link.target = "_blank";

    /// create a "fake" click-event to trigger the download
    if (document.createEvent) {

        e = document.createEvent("MouseEvents");
        e.initMouseEvent("click", true, true, window,
                         0, 0, 0, 0, 0, false, false, false,
                         false, 0, null);

        link.dispatchEvent(e);

    } else if (link.fireEvent) {
        link.fireEvent("onclick");
    }
}

/*
* Handle logo radio button clicks
*/
var onLogoColorChange = function(e) {
    currentLogoColor = $(this).val();

    loadLogo();
    renderCanvas();
}

/*
* Handle text color radio button clicks
*/
var onTextColorChange = function(e) {
    currentTextColor = $(this).val();

    renderCanvas();
}

/*
* Handle logo radio button clicks
*/
var onLogoChange = function(e) {
    currentLogo = $(this).val();

    loadLogo();
    renderCanvas();
}

/*
* Handle crop radio button clicks
*/
var onCropChange = function() {
    currentCrop = $(this).val();

    if (currentCrop !== 'original') {
        $canvas.addClass('is-draggable');
    } else {
        $canvas.removeClass('is-draggable');
    }

    renderCanvas();
}

// var onCheckboxChange = function() {
//     console.log('fire');
//     var checkedCount = 0;

//     for (var i = 0; i < $qualityQuestions.length; i++) {
//         if ($qualityQuestions.eq(i).is(':checked')) {
//             checkedCount++;
//         }
//     }

//     if (checkedCount === $qualityQuestions.length) {
//         $save.removeAttr('disabled');
//         $("body").off("contextmenu", "canvas");
//     } else {
//         $save.attr('disabled', '');
//         $("body").on("contextmenu", "canvas", function(e) {
//             return false;
//         });
//     }
// }

$(onDocumentLoad);<commit_msg>temporarily disable checkbox event<commit_after>// DOM elements
var $source;
var $save;
var $textColor;
var $logo;
var $crop;
var $logoColor;
var $imageLoader;
var $canvas;
var canvas;
var $qualityQuestions;

// state
var scaledImageHeight;
var fixedWidth = 1000;
var dy = 0;
var logoDimensions = {
    'npr': {
        w: 150,
        h: 52
    },
    'music': {
        w: 320,
        h: 85
    }

};
var elementPadding = 40;
var imageFilename;
var currentCrop = 'original';
var currentLogo = 'npr';
var currentLogoColor = 'white';
var currentTextColor = 'white';

// JS objects
var ctx;
var img = new Image();
var logo = new Image();

var onDocumentLoad = function(e) {
    $source = $('#source');
    $canvas = $('#imageCanvas');
    canvas = $canvas[0];
    $imageLoader = $('#imageLoader');
    ctx = canvas.getContext('2d');
    $save = $('.save-btn');
    $textColor = $('input[name="textColor"]');
    $logo = $('input[name="logo"]');
    $crop = $('input[name="crop"]');
    $logoColor = $('input[name="logoColor"]');
    $qualityQuestions = $('.quality-question');

    img.src = 'assets/test-kitten.jpg';
    img.onload = renderCanvas;
    logo.onload = renderCanvas;

    $source.on('keyup', renderCanvas);
    $imageLoader.on('change', handleImage);
    $save.on('click', onSaveClick);
    $textColor.on('change', onTextColorChange);
    $logo.on('change', onLogoChange);
    $logoColor.on('change', onLogoColorChange);
    $crop.on('change', onCropChange);
    $canvas.on('mousedown', onDrag);
    // $qualityQuestions.on('change', onCheckboxChange);

    $("body").on("contextmenu", "canvas", function(e) {
        return false;
    });

    loadLogo();
    renderCanvas();
}

/*
* Draw the image, then the logo, then the text
*/
var renderCanvas = function() {
    // canvas is always the same width
    canvas.width = fixedWidth;

    // if we're cropping, use the aspect ratio for the height
    if (currentCrop !== 'original') {
        canvas.height = fixedWidth / (16/9);
    }

    // clear the canvas
    ctx.clearRect(0,0,canvas.width,canvas.height);

    // determine height of canvas and scaled image, then draw the image
    var imageAspect = img.width / img.height;
    if (currentCrop === 'original') {
        canvas.height = fixedWidth / imageAspect;
        scaledImageHeight = canvas.height;
        ctx.drawImage(
            img,
            0,
            0,
            fixedWidth,
            scaledImageHeight
        );
    } else {
        scaledImageHeight = fixedWidth / imageAspect;
        ctx.drawImage(
            img,
            0,
            0,
            img.width,
            img.height,
            0,
            dy,
            fixedWidth,
            scaledImageHeight
        );
    }

    // set alpha channel, draw the logo
    if (currentLogoColor === 'white') {
        ctx.globalAlpha = "0.8";
    } else {
        ctx.globalAlpha = "0.6";
    }
    ctx.drawImage(
        logo,
        canvas.width - (logoDimensions[currentLogo]['w'] + elementPadding),
        currentLogo === 'npr'? elementPadding : elementPadding - 15,
        logoDimensions[currentLogo]['w'],
        logoDimensions[currentLogo]['h']
    );

    // reset alpha channel so text is not translucent
    ctx.globalAlpha = "1";

    // draw the text
    ctx.textBaseline = 'bottom';
    ctx.textAlign = 'left';
    ctx.fillStyle = currentTextColor;
    ctx.font = 'normal 20pt "Gotham SSm"';

    if (currentTextColor === 'white') {
        ctx.shadowColor = 'rgba(0,0,0,0.7)';
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
        ctx.shadowBlur = 10;
    }

    ctx.fillText(
        $source.val() === '' ? 'Belal Khan/Flickr': $source.val(),
        elementPadding,
        canvas.height - elementPadding
    );
}

/*
* Handle dragging the image for crops when applicable
*/
var onDrag = function(e) {
    e.preventDefault();
    var originY = e.clientY;
    var startY = dy;

    if (currentCrop === 'original') {
        return;
    }

    function update(e) {
        if (Math.abs(e.clientY - originY) > 1) {
            dy = startY - (originY - e.clientY);

            // Prevent dragging image below upper bound
            if (dy > 0) {
                dy = 0;
                return;
            }

            // Prevent dragging image above lower bound
            if (dy < canvas.height - scaledImageHeight) {
                dy = canvas.height - scaledImageHeight;
                return;
            }

            renderCanvas();
        }
    }

    // Perform drag sequence:
    $(document).on('mousemove.drag', _.debounce(update, 5, true))
        .on('mouseup.drag', function(e) {
            $(document).off('mouseup.drag mousemove.drag');
            update(e);
        });
}

/*
* Take an image from file input and load it
*/
var handleImage = function(e) {
    var reader = new FileReader();
    reader.onload = function(e){
        imageFilename = e.target.result
        img.src = imageFilename
    }
    reader.readAsDataURL(e.target.files[0]);
}

/*
* Load the logo based on radio buttons
*/
var loadLogo = function() {
    logo.src = 'assets/logo-' + currentLogo + '-' + currentLogoColor + '.svg';
}

/*
* Download the image on save click
*/
var onSaveClick = function(e) {
    e.preventDefault();

    /// create an "off-screen" anchor tag
    var link = document.createElement('a'),
        e;

    /// the key here is to set the download attribute of the a tag
    link.download = 'download.png';

    /// convert canvas content to data-uri for link. When download
    /// attribute is set the content pointed to by link will be
    /// pushed as "download" in HTML5 capable browsers
    link.href = canvas.toDataURL();
    link.target = "_blank";

    /// create a "fake" click-event to trigger the download
    if (document.createEvent) {

        e = document.createEvent("MouseEvents");
        e.initMouseEvent("click", true, true, window,
                         0, 0, 0, 0, 0, false, false, false,
                         false, 0, null);

        link.dispatchEvent(e);

    } else if (link.fireEvent) {
        link.fireEvent("onclick");
    }
}

/*
* Handle logo radio button clicks
*/
var onLogoColorChange = function(e) {
    currentLogoColor = $(this).val();

    loadLogo();
    renderCanvas();
}

/*
* Handle text color radio button clicks
*/
var onTextColorChange = function(e) {
    currentTextColor = $(this).val();

    renderCanvas();
}

/*
* Handle logo radio button clicks
*/
var onLogoChange = function(e) {
    currentLogo = $(this).val();

    loadLogo();
    renderCanvas();
}

/*
* Handle crop radio button clicks
*/
var onCropChange = function() {
    currentCrop = $(this).val();

    if (currentCrop !== 'original') {
        $canvas.addClass('is-draggable');
    } else {
        $canvas.removeClass('is-draggable');
    }

    renderCanvas();
}

// var onCheckboxChange = function() {
//     console.log('fire');
//     var checkedCount = 0;

//     for (var i = 0; i < $qualityQuestions.length; i++) {
//         if ($qualityQuestions.eq(i).is(':checked')) {
//             checkedCount++;
//         }
//     }

//     if (checkedCount === $qualityQuestions.length) {
//         $save.removeAttr('disabled');
//         $("body").off("contextmenu", "canvas");
//     } else {
//         $save.attr('disabled', '');
//         $("body").on("contextmenu", "canvas", function(e) {
//             return false;
//         });
//     }
// }

$(onDocumentLoad);<|endoftext|>


<commit_before>import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';
import Index from './pages/Index';
import App from './containers/App';
import NotFoundView from './pages/NotFoundView';
import UserSettings from './pages/UserSettings';
import UserListPage from 'routes/Exec/UserListPage';
import HackerListPage from 'routes/Exec/HackerList/HackerListPage';
import CheckInPage from 'routes/Exec/Checkin/CheckInPage';
import Login from './pages/Login';
export default (
  <Route path='/' component={App}>
    <IndexRoute component={Index} />
    <Route path='404' component={NotFoundView} />
    <Route path='settings' component={UserSettings} />
    <Route path='login' component={Login} />
    <Route path='signin' component={Login} />
    <Route path='exec/users' component={UserListPage} />
    <Route path='exec/hackers' component={HackerListPage} />
    <Route path='exec/checkin' component={CheckInPage} />
    <Redirect from='*' to='404' />
  </Route>
);
<commit_msg>Update case sensitivity<commit_after>import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';
import Index from './pages/Index';
import App from './containers/App';
import NotFoundView from './pages/NotFoundView';
import UserSettings from './pages/UserSettings';
import UserListPage from 'routes/Exec/UserListPage';
import HackerListPage from 'routes/Exec/HackerList/HackerListPage';
import CheckInPage from 'routes/Exec/CheckIn/CheckInPage';
import Login from './pages/Login';
export default (
  <Route path='/' component={App}>
    <IndexRoute component={Index} />
    <Route path='404' component={NotFoundView} />
    <Route path='settings' component={UserSettings} />
    <Route path='login' component={Login} />
    <Route path='signin' component={Login} />
    <Route path='exec/users' component={UserListPage} />
    <Route path='exec/hackers' component={HackerListPage} />
    <Route path='exec/checkin' component={CheckInPage} />
    <Redirect from='*' to='404' />
  </Route>
);
<|endoftext|>


<commit_before>angular.module('WatchTimer', ['ionic', 'ngCordova'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/timer');

  $stateProvider.state('timer', {
    url: '/timer',
    templateUrl: 'templates/timer.html',
    onEnter: function(timer) {
      console.log("timer onEnter");
      timer.start_updating();
    },
    onExit: function(timer) {
      console.log("timer onExit");
      timer.stop_updating();
    },
    controller: function($scope, timer, checkins, sounds, $state) {
      $scope.timer = timer;

      $scope.toggle_timer = function() {
        timer.isRunning ? $scope.stop_timer() : $scope.start_timer();
      };

      $scope.stop_timer = function() {
        checkins.add('stop');
        timer.stop();
      };

      $scope.start_timer = function() {
        checkins.add('start');
        timer.start();
      };

      $scope.increment_timer = function() {
        checkins.add('increment');
        timer.change(60);
      };

      $scope.decrement_timer = function() {
        checkins.add('decrement');
        timer.change(-60);
      };

      timer.duration = 1.2;
      // timer.start(); // FIXME

      // Watch the current state and start looping the bong if alerting
      $scope.$watch(
        "timer.current_state",
        function(newState, oldState) {
          console.log("State change: " + oldState + " -> " + newState);

          // On all state changes we can stop the previous sounds
          sounds.stopAll();

          if (newState === 'alerting') {
            sounds.loop('alert');
          }

          if (newState === 'alarming') {
            $state.go('alarm');
          }
        }
      );

    }
  });

  $stateProvider.state('alarm', {
    url: '/alarm',
    templateUrl: 'templates/alarm.html',
    onEnter: function(timer, checkins) {
      console.log("alarm onEnter");
      timer.stop();
      checkins.start_updating();
    },
    onExit: function(checkins) {
      console.log("alarm onExit");
      checkins.stop_updating();
    },
    controller: function($scope, timer, sounds, checkins) {
      var alarm = this;

      $scope.timer = timer;
      $scope.checkins = checkins;

      $scope.seconds_since_last_checkin = checkins.seconds_since_last_checkin;

      // Trigger the alarm sound
      console.log("FIXME - re-enable alarm sound here");
      // sounds.loop('alarm');

      $scope.silence = function(clickEvent) {
        sounds.stopAll();
        $scope.alarmSilenced = true;
      }

    }
  });

  $stateProvider.state('settings', {
    url: '/settings',
    templateUrl: 'templates/settings.html'
  });

});
<commit_msg>Alarm controller does not need to know about the timer<commit_after>angular.module('WatchTimer', ['ionic', 'ngCordova'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/timer');

  $stateProvider.state('timer', {
    url: '/timer',
    templateUrl: 'templates/timer.html',
    onEnter: function(timer) {
      console.log("timer onEnter");
      timer.stop();
      timer.start_updating();
    },
    onExit: function(timer) {
      console.log("timer onExit");
      timer.stop_updating();
    },
    controller: function($scope, timer, checkins, sounds, $state) {
      $scope.timer = timer;

      $scope.toggle_timer = function() {
        timer.isRunning ? $scope.stop_timer() : $scope.start_timer();
      };

      $scope.stop_timer = function() {
        checkins.add('stop');
        timer.stop();
      };

      $scope.start_timer = function() {
        checkins.add('start');
        timer.start();
      };

      $scope.increment_timer = function() {
        checkins.add('increment');
        timer.change(60);
      };

      $scope.decrement_timer = function() {
        checkins.add('decrement');
        timer.change(-60);
      };

      timer.duration = 1.2;
      // timer.start(); // FIXME

      // Watch the current state and start looping the bong if alerting
      $scope.$watch(
        "timer.current_state",
        function(newState, oldState) {
          console.log("State change: " + oldState + " -> " + newState);

          // On all state changes we can stop the previous sounds
          sounds.stopAll();

          if (newState === 'alerting') {
            sounds.loop('alert');
          }

          if (newState === 'alarming') {
            $state.go('alarm');
          }
        }
      );

    }
  });

  $stateProvider.state('alarm', {
    url: '/alarm',
    templateUrl: 'templates/alarm.html',
    onEnter: function(timer, checkins) {
      console.log("alarm onEnter");
      checkins.start_updating();
    },
    onExit: function(checkins) {
      console.log("alarm onExit");
      checkins.stop_updating();
    },
    controller: function($scope, sounds, checkins) {
      var alarm = this;

      $scope.checkins = checkins;
      $scope.alarmSilenced = false;

      $scope.seconds_since_last_checkin = checkins.seconds_since_last_checkin;

      // Trigger the alarm sound
      console.log("FIXME - re-enable alarm sound here");
      // sounds.loop('alarm');

      $scope.silence = function(clickEvent) {
        sounds.stopAll();
        $scope.alarmSilenced = true;
      }

    }
  });

  $stateProvider.state('settings', {
    url: '/settings',
    templateUrl: 'templates/settings.html'
  });

});
<|endoftext|>


<commit_before>// This object allows the user to perform multiple calculations over multiple cores
//

// Example usage:
// ScriptName="SimulationToRun.js";
// CommonData=[InfoBlock];//All sims will have access to this information
// SimSpecificDataArray=[67, 33, 99, 55, 88];//can be an array of any type (including other classes). Uses array length to determine the number of simulations to run.
// NoCores=6;//The number of cores you want the simulation to run over
// SimulationObject=new MulticoreSim(ScriptName, CommonData, SimSpecificDataArray, NoCores); // getting it ready
// SimulationObject.Start(); // Start the simulations running

// Sample set up of SimulationToRun.js
// ----------------------------------------------------------
// importScripts("usefulscripts1.js", "usefulscripts2.js");//Scripts your function needs to use (note; only scripts in the same folder can be used)
//
// self.onmessage = function (e) {
// 		var SimNumber = e.data.SimNumber;
// 		var SimData = e.data.SimData;
// 		var CommonData = e.data.CommonData;
//
//		...//Where you do the calculations
//
//		Result.Value1=24;//Stores the results
//		Result.Value2=25;
//
//		self.postMessage({SimNumber: e.data.SimNumber, Result: Result});//All simulations should end with this line
//}

function MulticoreSim(ScriptName, CommonData, SimDataArray, NoCores){
	console.log("Creating MulticoreSim object");

	this.ScriptName=ScriptName;
	this.CommonData=CommonData;
	this.SimDataArray=SimDataArray;//an array of values or objects to be passed to the specified script
	this.NoCores=NoCores;
	this.Worker=[];//An array of workers
	this.NoSims=SimDataArray.length;

	this.CurrentlyRunning=false;
	this.Complete=false;
	this.NoSimsCurrentlyRunning=0;

	this.SimsStarted=0;
	this.SimsComplete=0;
	this.Result=[];

	this.UseSimProgressBar=false;
	this.SimProgressBarID="SimProgressBar";//To allow a progress bar to be installed into the page
	this.UseWithinSimProgressBar=false;
	this.WithinSimProgressBarID="WithinSimProgressBar";

}

MulticoreSim.prototype.Start=function() {
	console.log("Starting MulticoreSim object");

	//Check that nothing else is running
	if (this.CurrentlyRunning==true){
		console.log("Warning: worker currently running");
		return 0;
	};
	this.CurrentlyRunning=true;
	this.NoSimsCurrentlyRunning=0;

	// Set progress bar to zero
	if (this.UseSimProgressBar==true){
		document.getElementById(this.NoSimsCompleteProgressBarID).value=0;
	}

	//Create workers
	this.RampUpSims();
};

MulticoreSim.prototype.RampUpSims=function() {
	console.log("Started rampup");
	while (this.NoSimsCurrentlyRunning<this.NoCores){//there are spare cores available
		if (this.SimsStarted<this.NoSims){//if there are sims that have yet to be started
			SimID=this.SimsStarted++;//run this sim, increment by 1
			this.NoSimsCurrentlyRunning++;//indicate that another core has become used
			console.log("Started sim: "+SimID);

			this.Worker= new Worker(this.ScriptName);
			this.Worker.onmessage = function (e){MulticoreSimMessageHandler(e, this)};
			this.Worker.postMessage({ SimNumber: SimID, CommonData: this.CommonData, SimData: this.SimDataArray[SimID]});

		}
	}

	//Determine if this is the last sim to complete
	if (this.SimsComplete>=this.NoSims){
		this.Terminate();//close all the workers
	}
}

MulticoreSimMessageHandler=function(e, MulticoreSimObject) {
	// There are 3 main message types that are handled
	// Messages to the StatusText (to be put somewhere on screen to indicate what is currently occurring)
	// Messages to the ProgressBar
	// Message to return result/indicate completeness

	console.log("Mulit");
	console.log(MulticoreSimObject);

	// Messages to the StatusText
	if (typeof e.data.StatusText != 'undefined'){
		console.log(e.data.WorkerStatusText);
	}
	// Messages to the ProgressBar
	if (typeof e.data.ProgressBarValue != 'undefined'){
		if (MulticoreSimObject.UseSimProgressBar==true){
			document.getElementById(MulticoreSimObject.WithinSimProgressBarID).value=e.data.ProgressBarValue;
		}
	}
	if (typeof e.data.Result != 'undefined'){
		MulticoreSimObject.NoSimsCurrentlyRunning--;
		SimNumber=e.data.SimNumber;
		MulticoreSimObject.Result[SimNumber]=e.data.Result;//Store the results of the simulation
		MulticoreSimObject.SimsComplete++;

		MulticoreSimObject.RampUpSims();//Try to run more sims

		//Update the progress bar about completion
		if (MulticoreSimObject.UseSimProgressBar==true){
			document.getElementById(MulticoreSimObject.NoSimsCompleteProgressBarID).value=MulticoreSimObject.SimsComplete/MulticoreSimObject.NoSims;
		}
	}
};

MulticoreSim.prototype.Terminate=function() {//close down all workers
	this.Worker.terminate();
	this.CurrentlyRunning==false;
};

<commit_msg>Currying function<commit_after>// This object allows the user to perform multiple calculations over multiple cores
//

// Example usage:
// ScriptName="SimulationToRun.js";
// CommonData=[InfoBlock];//All sims will have access to this information
// SimSpecificDataArray=[67, 33, 99, 55, 88];//can be an array of any type (including other classes). Uses array length to determine the number of simulations to run.
// NoCores=6;//The number of cores you want the simulation to run over
// SimulationObject=new MulticoreSim(ScriptName, CommonData, SimSpecificDataArray, NoCores); // getting it ready
// SimulationObject.Start(); // Start the simulations running

// Sample set up of SimulationToRun.js
// ----------------------------------------------------------
// importScripts("usefulscripts1.js", "usefulscripts2.js");//Scripts your function needs to use (note; only scripts in the same folder can be used)
//
// self.onmessage = function (e) {
// 		var SimNumber = e.data.SimNumber;
// 		var SimData = e.data.SimData;
// 		var CommonData = e.data.CommonData;
//
//		...//Where you do the calculations
//
//		Result.Value1=24;//Stores the results
//		Result.Value2=25;
//
//		self.postMessage({SimNumber: e.data.SimNumber, Result: Result});//All simulations should end with this line
//}

function MulticoreSim(ScriptName, CommonData, SimDataArray, NoCores){
	console.log("Creating MulticoreSim object");

	this.ScriptName=ScriptName;
	this.CommonData=CommonData;
	this.SimDataArray=SimDataArray;//an array of values or objects to be passed to the specified script
	this.NoCores=NoCores;
	this.Worker=[];//An array of workers
	this.NoSims=SimDataArray.length;

	this.CurrentlyRunning=false;
	this.Complete=false;
	this.NoSimsCurrentlyRunning=0;

	this.SimsStarted=0;
	this.SimsComplete=0;
	this.Result=[];

	this.UseSimProgressBar=false;
	this.SimProgressBarID="SimProgressBar";//To allow a progress bar to be installed into the page
	this.UseWithinSimProgressBar=false;
	this.WithinSimProgressBarID="WithinSimProgressBar";

}

MulticoreSim.prototype.Start=function() {
	console.log("Starting MulticoreSim object");

	//Check that nothing else is running
	if (this.CurrentlyRunning==true){
		console.log("Warning: worker currently running");
		return 0;
	};
	this.CurrentlyRunning=true;
	this.NoSimsCurrentlyRunning=0;

	// Set progress bar to zero
	if (this.UseSimProgressBar==true){
		document.getElementById(this.NoSimsCompleteProgressBarID).value=0;
	}

	//Create workers
	this.RampUpSims();
};

MulticoreSim.prototype.RampUpSims=function() {
	console.log("Started rampup");
	while (this.NoSimsCurrentlyRunning<this.NoCores){//there are spare cores available
		if (this.SimsStarted<this.NoSims){//if there are sims that have yet to be started
			SimID=this.SimsStarted++;//run this sim, increment by 1
			this.NoSimsCurrentlyRunning++;//indicate that another core has become used
			console.log("Started sim: "+SimID);

			this.Worker= new Worker(this.ScriptName);
			var BoundHandler = MulticoreSimMessageHandler(this, null);
			this.Worker.onmessage = BoundHandler;
			//this.Worker.onmessage = function (e){MulticoreSimMessageHandler(e, this)};
			this.Worker.postMessage({ SimNumber: SimID, CommonData: this.CommonData, SimData: this.SimDataArray[SimID]});

		}
	}

	//Determine if this is the last sim to complete
	if (this.SimsComplete>=this.NoSims){
		this.Terminate();//close all the workers
	}
}

MulticoreSimMessageHandler=function(MulticoreSimObject, e) {
	// There are 3 main message types that are handled
	// Messages to the StatusText (to be put somewhere on screen to indicate what is currently occurring)
	// Messages to the ProgressBar
	// Message to return result/indicate completeness

	console.log("Mulit");
	console.log(MulticoreSimObject);

	// Messages to the StatusText
	if (typeof e.data.StatusText != 'undefined'){
		console.log(e.data.WorkerStatusText);
	}
	// Messages to the ProgressBar
	if (typeof e.data.ProgressBarValue != 'undefined'){
		if (MulticoreSimObject.UseSimProgressBar==true){
			document.getElementById(MulticoreSimObject.WithinSimProgressBarID).value=e.data.ProgressBarValue;
		}
	}
	if (typeof e.data.Result != 'undefined'){
		MulticoreSimObject.NoSimsCurrentlyRunning--;
		SimNumber=e.data.SimNumber;
		MulticoreSimObject.Result[SimNumber]=e.data.Result;//Store the results of the simulation
		MulticoreSimObject.SimsComplete++;

		MulticoreSimObject.RampUpSims();//Try to run more sims

		//Update the progress bar about completion
		if (MulticoreSimObject.UseSimProgressBar==true){
			document.getElementById(MulticoreSimObject.NoSimsCompleteProgressBarID).value=MulticoreSimObject.SimsComplete/MulticoreSimObject.NoSims;
		}
	}
};

MulticoreSim.prototype.Terminate=function() {//close down all workers
	this.Worker.terminate();
	this.CurrentlyRunning==false;
};

<|endoftext|>


<commit_before>import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './components/App';
import HomePage from './components/HomePage';
import GKMHomePage from './components/GKMHomePage';
import IgPage from './containers/InstagramPage'; // eslint-disable-line import/no-named-as-default
import FuelSavingsPage from './containers/FuelSavingsPage'; // eslint-disable-line import/no-named-as-default
import AboutPage from './components/AboutPage.js';
import NotFoundPage from './components/NotFoundPage.js';
import EtsyPage from "./containers/EtsyPage"; // eslint-disable-line import/no-named-as-default

export default (
    <Route path="/" component={App}>
        <IndexRoute component={HomePage}/>
        <Route path="gkm" component={GKMHomePage}/>
        <Route path="etsy" component={EtsyPage}/>
        <Route path="ig" component={IgPage}/>
        <Route path="fuel-savings" component={FuelSavingsPage}/>
        <Route path="about" component={AboutPage}/>
        <Route path="*" component={NotFoundPage}/>
    </Route>
);
<commit_msg>linter fucker<commit_after>import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './components/App';
import HomePage from './components/HomePage';
import GKMHomePage from './components/GKMHomePage';
import IgPage from './containers/InstagramPage'; // eslint-disable-line import/no-named-as-default
import FuelSavingsPage from './containers/FuelSavingsPage'; // eslint-disable-line import/no-named-as-default
import AboutPage from './components/AboutPage.js';
import NotFoundPage from './components/NotFoundPage.js';
import EtsyHomePage from "./containers/EtsyPage"; // eslint-disable-line import/no-named-as-default

export default (
    <Route path="/" component={App}>
        <IndexRoute component={HomePage}/>
        <Route path="gkm" component={GKMHomePage}/>
        <Route path="etsy" component={EtsyHomePage}/>
        <Route path="ig" component={IgPage}/>
        <Route path="fuel-savings" component={FuelSavingsPage}/>
        <Route path="about" component={AboutPage}/>
        <Route path="*" component={NotFoundPage}/>
    </Route>
);
<|endoftext|>


<commit_before>/*
 * typeahead.js
 * https://github.com/twitter/typeahead
 * Copyright 2013 Twitter, Inc. and other contributors; Licensed MIT
 */

var PersistentStorage = (function() {
  var ls = window.localStorage, methods;

  function PersistentStorage(namespace) {
    this.prefix = ['__', namespace, '__'].join('');
    this.ttlKey = '__ttl__';
    this.keyMatcher = new RegExp('^' + this.prefix);
  }

  if (window.localStorage && window.JSON) {
    methods = {

      // private methods
      // ---------------

      _prefix: function(key) {
        return this.prefix + key;
      },

      _ttlKey: function(key) {
        return this._prefix(key) + this.ttlKey;
      },

      // public methods
      // --------------

      get: function(key) {
        if (this.isExpired(key)) {
          this.remove(key);
        }

        return decode(ls.getItem(this._prefix(key)));
      },

      set: function(key, val, ttl) {
        if (utils.isNumber(ttl)) {
          ls.setItem(this._ttlKey(key), encode(now() + ttl));
        }

        else {
          ls.removeItem(this._ttlKey(key));
        }

        return ls.setItem(this._prefix(key), encode(val));
      },

      remove: function(key) {
        ls.removeItem(this._ttlKey(key));
        ls.removeItem(this._prefix(key));

        return this;
      },

      clear: function() {
        var i, key, keys = [], len = ls.length;

        for (i = 0; i < len; i++) {
          if ((key = ls.key(i)).match(this.keyMatcher)) {
            // gather keys to remove after loop exits
            keys.push(key.replace(this.keyMatcher, ''));
          }
        }

        for (i = keys.length; i--;) {
          this.remove(keys[i]);
        }

        return this;
      },

      isExpired: function(key) {
        var ttl = decode(ls.getItem(this._ttlKey(key)));

        return utils.isNumber(ttl) && now() > ttl ? true : false;
      }
    };
  }

  else {
    methods = {
      get: utils.noop,
      set: utils.noop,
      remove: utils.noop,
      clear: utils.noop,
      isExpired: utils.noop
    };
  }

  utils.mixin(PersistentStorage.prototype, methods);

  return PersistentStorage;

  function now() {
    return new Date().getTime();
  }

  function encode(val) {
    // convert undefined to null to avoid issues with JSON.parse
    return JSON.stringify(utils.isUndefined(val) ? null : val);
  }

  function decode(val) {
    return JSON.parse(val);
  }
})();
<commit_msg>Wrap localStorage check in try/catch.<commit_after>/*
 * typeahead.js
 * https://github.com/twitter/typeahead
 * Copyright 2013 Twitter, Inc. and other contributors; Licensed MIT
 */

var PersistentStorage = (function() {
  var ls, methods;

  try {
    ls = window.localStorage;
  } catch (err) {
    ls = null;
  }

  function PersistentStorage(namespace) {
    this.prefix = ['__', namespace, '__'].join('');
    this.ttlKey = '__ttl__';
    this.keyMatcher = new RegExp('^' + this.prefix);
  }

  if (ls && window.JSON) {
    methods = {

      // private methods
      // ---------------

      _prefix: function(key) {
        return this.prefix + key;
      },

      _ttlKey: function(key) {
        return this._prefix(key) + this.ttlKey;
      },

      // public methods
      // --------------

      get: function(key) {
        if (this.isExpired(key)) {
          this.remove(key);
        }

        return decode(ls.getItem(this._prefix(key)));
      },

      set: function(key, val, ttl) {
        if (utils.isNumber(ttl)) {
          ls.setItem(this._ttlKey(key), encode(now() + ttl));
        }

        else {
          ls.removeItem(this._ttlKey(key));
        }

        return ls.setItem(this._prefix(key), encode(val));
      },

      remove: function(key) {
        ls.removeItem(this._ttlKey(key));
        ls.removeItem(this._prefix(key));

        return this;
      },

      clear: function() {
        var i, key, keys = [], len = ls.length;

        for (i = 0; i < len; i++) {
          if ((key = ls.key(i)).match(this.keyMatcher)) {
            // gather keys to remove after loop exits
            keys.push(key.replace(this.keyMatcher, ''));
          }
        }

        for (i = keys.length; i--;) {
          this.remove(keys[i]);
        }

        return this;
      },

      isExpired: function(key) {
        var ttl = decode(ls.getItem(this._ttlKey(key)));

        return utils.isNumber(ttl) && now() > ttl ? true : false;
      }
    };
  }

  else {
    methods = {
      get: utils.noop,
      set: utils.noop,
      remove: utils.noop,
      clear: utils.noop,
      isExpired: utils.noop
    };
  }

  utils.mixin(PersistentStorage.prototype, methods);

  return PersistentStorage;

  function now() {
    return new Date().getTime();
  }

  function encode(val) {
    // convert undefined to null to avoid issues with JSON.parse
    return JSON.stringify(utils.isUndefined(val) ? null : val);
  }

  function decode(val) {
    return JSON.parse(val);
  }
})();
<|endoftext|>


<commit_before>import React from 'react';
import ga from 'react-ga';
import Router from 'react-routing/src/Router';
import fetch from './core/fetch';
import App from './components/App';
import BecomeDealer from './components/BecomeDealer';
import Product from './components/Product';
import Category from './components/Category';
import Contact from './components/Contact';
import CustomContent from './components/CustomContent';
import Home from './components/Home';
import SearchResults from './components/SearchResults';
import VehicleResults from './components/VehicleResults';
import WhereToBuy from './components/WhereToBuy';
import About from './components/About';
import AppGuides from './components/AppGuides';
import Terms from './components/Terms';
import Warranties from './components/Warranties';
import LatestNews from './components/LatestNews';
import LatestNewsItem from './components/LatestNewsItem';
import LandingPage from './components/LandingPage';
import NotFoundPage from './components/NotFoundPage';
import ErrorPage from './components/ErrorPage';
import Envision from './components/Envision/Envision';
import LookupActions from './actions/LookupActions';
import { apiBase, apiKey, brand } from './config';

const isBrowser = typeof window !== 'undefined';
const KEY = apiKey;
const gaOptions = { debug: true };
const MyWindowDependentLibrary = isBrowser ? ga.initialize('UA-61502306-1', gaOptions) : undefined;

const router = new Router(on => {
	on('*', async (state, next) => {
		if (!state.context) {
			state.context = {};
		}
		state.context.params = state.params;
		const slugContainer = state.params[0];
		const slug = slugContainer.replace(/\//g, '');
		let siteContentResponse = null;
		if (slug !== '') {
			siteContentResponse = await fetch(`${apiBase}/site/content/${slug}?key=${KEY}&brandID=${brand}`, {
				method: 'get',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Accept': 'application/json',
				},
			});
		}
		const [yearResponse, catResponse, contentAllReponse] = await Promise.all([
			fetch(`${apiBase}/vehicle/mongo/allCollections?key=${KEY}`, {
				method: 'post',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Accept': 'application/json',
				},
				body: '{}',
			}),
			fetch(`${apiBase}/category?brandID=${brand}&key=${KEY}`),
			fetch(`${apiBase}/site/content/all?siteID=${brand}&brandID=${brand}&key=${KEY}`),
		]);

		try {
			state.context.categories = await catResponse.json();
			const vehicleResponse = await yearResponse.json();
			if (vehicleResponse.available_years !== undefined) {
				state.context.years = vehicleResponse.available_years;
			}
			state.context.siteContents = await contentAllReponse.json();
			const siteContent = await siteContentResponse.json();
			if (siteContent.metaDescription !== undefined && siteContent.metaTitle !== undefined) {
				const seo = {
					description: siteContent.metaDescription,
					title: siteContent.metaTitle,
				};
				state.context.seo(seo);
			} else {
				const seo = {
					description: 'From grille guards and modular Jeep bumpers to side bars, bull bars and floor liners, ARIES truck and SUV accessories offer a custom fit for your vehicle.',
					title: 'Aries Automotive',
				};
				state.context.seo(seo);
			}
		} catch (e) {
			state.context.error = e;
		}
		if (MyWindowDependentLibrary !== undefined) {
			ga.initialize('UA-61502306-1', gaOptions);
		}
		ga.pageview('arieact:' + state.path);
		const component = await next();
		return component && <App context={state.context}>{component}</App>;
	});

	on('/part/:id', async (state) => {
		state.context.id = state.params.id;
		try {
			const url = `${apiBase}/part/${state.context.id}?key=${KEY}&brandID=${brand}`;
			const featuredUrl = `${apiBase}/part/featured?brandID=${brand}&key=${KEY}`;
			const [partResp, featuredResp] = await Promise.all([
				fetch(url, {
					method: 'get',
				}),
				fetch(featuredUrl, {
					method: 'get',
				}),
			]);
			state.part = await partResp.json();
			state.featured = await featuredResp.json();
		} catch (e) {
			state.context.error = e;
		}
		return <Product {...state} />;
	});

	on('/category/:id', async (state) => {
		try {
			const url = `${apiBase}/category/${state.params.id}?key=${KEY}`;
			const catResponse = await fetch(url, {
				method: 'get',
			});

			state.context.category = await catResponse.json();
		} catch (e) {
			state.context.error = e;
		}

		return <Category context={state.context} category={state.context.category} />;
	});

	on('/category/:id/:title', async (state) => {
		try {
			const url = `${apiBase}/category/${state.params.id}?key=${KEY}`;
			const catResponse = await fetch(url, {
				method: 'get',
			});

			state.context.category = await catResponse.json();
		} catch (e) {
			state.context.error = e;
		}

		return <Category context={state.context} category={state.context.category} />;
	});

	on('/category/:id/:title/:sub', async (state) => {
		try {
			const url = `${apiBase}/category/${state.params.id}?key=${KEY}`;
			const catResponse = await fetch(url, {
				method: 'get',
			});

			const partURL = `${apiBase}/category/${state.params.id}/parts?key=${KEY}`;
			const partResponse = await fetch(partURL, {
				method: 'get',
			});

			state.context.category = await catResponse.json();
			state.context.category.parts = await partResponse.json();
		} catch (e) {
			state.context.error = e;
		}

		return <Category context={state.context} category={state.context.category} />;
	});

	on('/search/:term', async (state) => {
		let searchResult = {};
		let term = '';
		try {
			const searchResponse = await fetch(`${apiBase}/search/${state.params.term}?key=${KEY}&brandID=${brand}`);

			searchResult = await searchResponse.json();
			term = state.params.term;
		} catch (e) {
			state.context.error = e;
		}

		return <SearchResults context={state.context} searchResult={searchResult} term={term} />;
	});

	on('/search', async (state) => {
		let searchResult = {};
		let term = '';
		try {
			const searchResponse = await fetch(`${apiBase}/search/${state.query.term}?key=${KEY}&brandID=${brand}`);

			searchResult = await searchResponse.json();
			term = state.query.term;
		} catch (e) {
			state.context.error = e;
		}

		return <SearchResults context={state.context} searchResult={searchResult} term={term} />;
	});

	on('/vehicle', async (state) => {
		state.context.params = state.params;
		return <VehicleResults context={state.context} />;
	});

	on('/vehicle/:year', async (state) => {
		state.context.params = state.params;
		LookupActions.set({
			year: state.params.year,
		});
		return <VehicleResults context={state.context} />;
	});

	on('/vehicle/:year/:make', async (state) => {
		state.context.params = state.params;
		LookupActions.set({
			year: state.params.year,
			make: state.params.make,
		});
		return <VehicleResults context={state.context} />;
	});

	on('/vehicle/:year/:make/:model', async (state) => {
		state.context.params = state.params;
		LookupActions.set({
			year: state.params.year,
			make: state.params.make,
			model: state.params.model,
		});
		return <VehicleResults context={state.context} />;
	});

	on('/about', async (state) => {
		return <About context={state.context} />;
	});

	on('/appguides', async (state) => {
		return <AppGuides context={state.context} />;
	});

	on('/becomedealer', async (state) => {
		return <BecomeDealer context={state.context} />;
	});

	on('/contact', async (state) => {
		return <Contact context={state.context} />;
	});

	on('/terms', async (state) => {
		return <Terms context={state.context} />;
	});

	on('/news', async (state) => {
		return <LatestNews context={state.context} />;
	});

	on('/envision', async (state) => {
		const loc = typeof window !== 'undefined' ? window.location : '';
		return <Envision context={state.context} protocol={loc.protocol}/>;
	});

	on('/news/:id', async (state) => {
		state.context.id = state.params.id;
		try {
			const url = `${apiBase}/news/${state.params.id}?brand=${brand}&key=${apiKey}`;
			const resp = await fetch(url);
			state.item = await resp.json();
		} catch (e) {
			state.context.error = e;
		}
		return <LatestNewsItem context={state.context} item={state.item} />;
	});

	on('/buy', async (state) => {
		state.context.id = state.params.id;
		return <WhereToBuy context={state.context} google={state.google} navigator={state.navigator} />;
	});

	on('/warranties', async (state) => {
		state.context.id = state.params.id;
		return <Warranties context={state.context} />;
	});

	on('/styleguard', (state, next) => {
		state.redirect = '/category/321/Interior/StyleGuard%20Floor%20Liners';
		next();
	});

	on('/page/:id', async (state) => {
		state.context.id = state.params.id;
		for (let i = 0; i < state.context.siteContents.length; i++) {
			if (state.context.siteContents[i].id.toString() === state.params.id) {
				state.context.customContent = state.context.siteContents[i];
			}
		}
		return <CustomContent context={state.context} />;
	});

	on('/lp/:id', async (state, next) => {
		state.context.id = state.params.id;
		try {
			const url = `${apiBase}/lp/${state.params.id}?brand=${brand}&key=${apiKey}`;
			const resp = await fetch(url);
			state.page = await resp.json();
		} catch (e) {
			state.context.error = e;
		}
		const comp = await next();
		return comp && <LandingPage context={state.context} page={state.page} />;
	});

	on('/', async (state) => {
		state.context.featuredProducts = [];
		state.context.testimonials = [];
		state.context.carouselImages = [
			{
				image: 'http://storage.googleapis.com/aries-website/hero-images/jeep.png',
				text: 'Never Fear the Uncertain Road',
				button_text: 'VIEW BULL BARS',
				link: '/category/332',
				order: 5,
				styles: {
					backgroundImage: 'url(http://storage.googleapis.com/aries-website/hero-images/jeep.png)',
				},
			}, {
				image: 'https://storage.googleapis.com/aries-website/hero-images/GrandCherokee.png',
				text: 'Find Out What It Means to Be a Pro',
				button_text: 'VIEW PRO SERIES',
				link: '/category/331',
				order: 2,
				styles: {
					backgroundImage: 'url(https://storage.googleapis.com/aries-website/hero-images/GrandCherokee.png)',
				},
			}, {
				image: 'https://storage.googleapis.com/aries-website/hero-images/JeepWrangler2015.png',
				text: 'Choose Your Configuration and Start Customizing',
				button_text: 'VIEW MODULAR BUMPERS',
				link: '/category/324',
				order: 3,
				styles: {
					backgroundImage: 'url(https://storage.googleapis.com/aries-website/hero-images/JeepWrangler2015.png)',
				},
			}, {
				image: 'https://storage.googleapis.com/aries-website/hero-images/Floor%20Liner%20-%20Grey%20(1).jpg',
				text: 'ARIES Unveils StyleGuard™ as New Name for Floor Liners',
				button_text: 'READ MORE',
				link: '/news/47',
				order: 1,
				styles: {
					backgroundImage: `url('https://storage.googleapis.com/aries-website/hero-images/Floor%20Liner%20-%20Grey%20(1).jpg')`,
				},
			}, {
				image: 'https://storage.googleapis.com/aries-website/hero-images/navyjeep.jpg',
				text: 'Decked Out Jeep to Be Donated to Navy SEAL Foundation',
				button_text: 'READ MORE',
				link: '/news/48',
				order: 4,
				styles: {
					backgroundImage: 'url(https://storage.googleapis.com/aries-website/hero-images/navyjeep.jpg)',
				},
			},
		];
		try {
			const featResponse = await fetch(`${apiBase}/part/featured?brandID=${brand}&key=${KEY}`);
			const testResponse = await fetch(`${apiBase}/testimonials?key=${KEY}&count=2&randomize=true&brandID=${brand}`);

			state.context.featuredProducts = await featResponse.json();
			state.context.testimonials = await testResponse.json();
		} catch (e) {
			state.context.error = e;
		}

		return <Home context={state.context} />;
	});

	on('error', (state, error) => state.statusCode === 404 ?
		<App context={state.context} error={error}><NotFoundPage /></App> :
		<App context={state.context} error={error}><ErrorPage /></App>
	);
});

export default router;
<commit_msg>excluded health check from sitecontent fetches<commit_after>import React from 'react';
import ga from 'react-ga';
import Router from 'react-routing/src/Router';
import fetch from './core/fetch';
import App from './components/App';
import BecomeDealer from './components/BecomeDealer';
import Product from './components/Product';
import Category from './components/Category';
import Contact from './components/Contact';
import CustomContent from './components/CustomContent';
import Home from './components/Home';
import SearchResults from './components/SearchResults';
import VehicleResults from './components/VehicleResults';
import WhereToBuy from './components/WhereToBuy';
import About from './components/About';
import AppGuides from './components/AppGuides';
import Terms from './components/Terms';
import Warranties from './components/Warranties';
import LatestNews from './components/LatestNews';
import LatestNewsItem from './components/LatestNewsItem';
import LandingPage from './components/LandingPage';
import NotFoundPage from './components/NotFoundPage';
import ErrorPage from './components/ErrorPage';
import Envision from './components/Envision/Envision';
import LookupActions from './actions/LookupActions';
import { apiBase, apiKey, brand } from './config';

const isBrowser = typeof window !== 'undefined';
const KEY = apiKey;
const gaOptions = { debug: true };
const MyWindowDependentLibrary = isBrowser ? ga.initialize('UA-61502306-1', gaOptions) : undefined;

const router = new Router(on => {
	on('*', async (state, next) => {
		if (!state.context) {
			state.context = {};
		}
		state.context.params = state.params;
		const slugContainer = state.params[0];
		const slug = slugContainer.replace(/\//g, '');
		let siteContentResponse = null;
		if (slug !== '' && slug !== '_ahhealth') {
			siteContentResponse = await fetch(`${apiBase}/site/content/${slug}?key=${KEY}&brandID=${brand}`, {
				method: 'get',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Accept': 'application/json',
				},
			});
		}
		const [yearResponse, catResponse, contentAllReponse] = await Promise.all([
			fetch(`${apiBase}/vehicle/mongo/allCollections?key=${KEY}`, {
				method: 'post',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Accept': 'application/json',
				},
				body: '{}',
			}),
			fetch(`${apiBase}/category?brandID=${brand}&key=${KEY}`),
			fetch(`${apiBase}/site/content/all?siteID=${brand}&brandID=${brand}&key=${KEY}`),
		]);

		try {
			state.context.categories = await catResponse.json();
			const vehicleResponse = await yearResponse.json();
			if (vehicleResponse.available_years !== undefined) {
				state.context.years = vehicleResponse.available_years;
			}
			state.context.siteContents = await contentAllReponse.json();
			const siteContent = await siteContentResponse.json();
			if (siteContent.metaDescription !== undefined && siteContent.metaTitle !== undefined) {
				const seo = {
					description: siteContent.metaDescription,
					title: siteContent.metaTitle,
				};
				state.context.seo(seo);
			} else {
				const seo = {
					description: 'From grille guards and modular Jeep bumpers to side bars, bull bars and floor liners, ARIES truck and SUV accessories offer a custom fit for your vehicle.',
					title: 'Aries Automotive',
				};
				state.context.seo(seo);
			}
		} catch (e) {
			state.context.error = e;
		}
		if (MyWindowDependentLibrary !== undefined) {
			ga.initialize('UA-61502306-1', gaOptions);
		}
		ga.pageview('arieact:' + state.path);
		const component = await next();
		return component && <App context={state.context}>{component}</App>;
	});

	on('/part/:id', async (state) => {
		state.context.id = state.params.id;
		try {
			const url = `${apiBase}/part/${state.context.id}?key=${KEY}&brandID=${brand}`;
			const featuredUrl = `${apiBase}/part/featured?brandID=${brand}&key=${KEY}`;
			const [partResp, featuredResp] = await Promise.all([
				fetch(url, {
					method: 'get',
				}),
				fetch(featuredUrl, {
					method: 'get',
				}),
			]);
			state.part = await partResp.json();
			state.featured = await featuredResp.json();
		} catch (e) {
			state.context.error = e;
		}
		return <Product {...state} />;
	});

	on('/category/:id', async (state) => {
		try {
			const url = `${apiBase}/category/${state.params.id}?key=${KEY}`;
			const catResponse = await fetch(url, {
				method: 'get',
			});

			state.context.category = await catResponse.json();
		} catch (e) {
			state.context.error = e;
		}

		return <Category context={state.context} category={state.context.category} />;
	});

	on('/category/:id/:title', async (state) => {
		try {
			const url = `${apiBase}/category/${state.params.id}?key=${KEY}`;
			const catResponse = await fetch(url, {
				method: 'get',
			});

			state.context.category = await catResponse.json();
		} catch (e) {
			state.context.error = e;
		}

		return <Category context={state.context} category={state.context.category} />;
	});

	on('/category/:id/:title/:sub', async (state) => {
		try {
			const url = `${apiBase}/category/${state.params.id}?key=${KEY}`;
			const catResponse = await fetch(url, {
				method: 'get',
			});

			const partURL = `${apiBase}/category/${state.params.id}/parts?key=${KEY}`;
			const partResponse = await fetch(partURL, {
				method: 'get',
			});

			state.context.category = await catResponse.json();
			state.context.category.parts = await partResponse.json();
		} catch (e) {
			state.context.error = e;
		}

		return <Category context={state.context} category={state.context.category} />;
	});

	on('/search/:term', async (state) => {
		let searchResult = {};
		let term = '';
		try {
			const searchResponse = await fetch(`${apiBase}/search/${state.params.term}?key=${KEY}&brandID=${brand}`);

			searchResult = await searchResponse.json();
			term = state.params.term;
		} catch (e) {
			state.context.error = e;
		}

		return <SearchResults context={state.context} searchResult={searchResult} term={term} />;
	});

	on('/search', async (state) => {
		let searchResult = {};
		let term = '';
		try {
			const searchResponse = await fetch(`${apiBase}/search/${state.query.term}?key=${KEY}&brandID=${brand}`);

			searchResult = await searchResponse.json();
			term = state.query.term;
		} catch (e) {
			state.context.error = e;
		}

		return <SearchResults context={state.context} searchResult={searchResult} term={term} />;
	});

	on('/vehicle', async (state) => {
		state.context.params = state.params;
		return <VehicleResults context={state.context} />;
	});

	on('/vehicle/:year', async (state) => {
		state.context.params = state.params;
		LookupActions.set({
			year: state.params.year,
		});
		return <VehicleResults context={state.context} />;
	});

	on('/vehicle/:year/:make', async (state) => {
		state.context.params = state.params;
		LookupActions.set({
			year: state.params.year,
			make: state.params.make,
		});
		return <VehicleResults context={state.context} />;
	});

	on('/vehicle/:year/:make/:model', async (state) => {
		state.context.params = state.params;
		LookupActions.set({
			year: state.params.year,
			make: state.params.make,
			model: state.params.model,
		});
		return <VehicleResults context={state.context} />;
	});

	on('/about', async (state) => {
		return <About context={state.context} />;
	});

	on('/appguides', async (state) => {
		return <AppGuides context={state.context} />;
	});

	on('/becomedealer', async (state) => {
		return <BecomeDealer context={state.context} />;
	});

	on('/contact', async (state) => {
		return <Contact context={state.context} />;
	});

	on('/terms', async (state) => {
		return <Terms context={state.context} />;
	});

	on('/news', async (state) => {
		return <LatestNews context={state.context} />;
	});

	on('/envision', async (state) => {
		const loc = typeof window !== 'undefined' ? window.location : '';
		return <Envision context={state.context} protocol={loc.protocol}/>;
	});

	on('/news/:id', async (state) => {
		state.context.id = state.params.id;
		try {
			const url = `${apiBase}/news/${state.params.id}?brand=${brand}&key=${apiKey}`;
			const resp = await fetch(url);
			state.item = await resp.json();
		} catch (e) {
			state.context.error = e;
		}
		return <LatestNewsItem context={state.context} item={state.item} />;
	});

	on('/buy', async (state) => {
		state.context.id = state.params.id;
		return <WhereToBuy context={state.context} google={state.google} navigator={state.navigator} />;
	});

	on('/warranties', async (state) => {
		state.context.id = state.params.id;
		return <Warranties context={state.context} />;
	});

	on('/styleguard', (state, next) => {
		state.redirect = '/category/321/Interior/StyleGuard%20Floor%20Liners';
		next();
	});

	on('/page/:id', async (state) => {
		state.context.id = state.params.id;
		for (let i = 0; i < state.context.siteContents.length; i++) {
			if (state.context.siteContents[i].id.toString() === state.params.id) {
				state.context.customContent = state.context.siteContents[i];
			}
		}
		return <CustomContent context={state.context} />;
	});

	on('/lp/:id', async (state, next) => {
		state.context.id = state.params.id;
		try {
			const url = `${apiBase}/lp/${state.params.id}?brand=${brand}&key=${apiKey}`;
			const resp = await fetch(url);
			state.page = await resp.json();
		} catch (e) {
			state.context.error = e;
		}
		const comp = await next();
		return comp && <LandingPage context={state.context} page={state.page} />;
	});

	on('/', async (state) => {
		state.context.featuredProducts = [];
		state.context.testimonials = [];
		state.context.carouselImages = [
			{
				image: 'http://storage.googleapis.com/aries-website/hero-images/jeep.png',
				text: 'Never Fear the Uncertain Road',
				button_text: 'VIEW BULL BARS',
				link: '/category/332',
				order: 5,
				styles: {
					backgroundImage: 'url(http://storage.googleapis.com/aries-website/hero-images/jeep.png)',
				},
			}, {
				image: 'https://storage.googleapis.com/aries-website/hero-images/GrandCherokee.png',
				text: 'Find Out What It Means to Be a Pro',
				button_text: 'VIEW PRO SERIES',
				link: '/category/331',
				order: 2,
				styles: {
					backgroundImage: 'url(https://storage.googleapis.com/aries-website/hero-images/GrandCherokee.png)',
				},
			}, {
				image: 'https://storage.googleapis.com/aries-website/hero-images/JeepWrangler2015.png',
				text: 'Choose Your Configuration and Start Customizing',
				button_text: 'VIEW MODULAR BUMPERS',
				link: '/category/324',
				order: 3,
				styles: {
					backgroundImage: 'url(https://storage.googleapis.com/aries-website/hero-images/JeepWrangler2015.png)',
				},
			}, {
				image: 'https://storage.googleapis.com/aries-website/hero-images/Floor%20Liner%20-%20Grey%20(1).jpg',
				text: 'ARIES Unveils StyleGuard™ as New Name for Floor Liners',
				button_text: 'READ MORE',
				link: '/news/47',
				order: 1,
				styles: {
					backgroundImage: `url('https://storage.googleapis.com/aries-website/hero-images/Floor%20Liner%20-%20Grey%20(1).jpg')`,
				},
			}, {
				image: 'https://storage.googleapis.com/aries-website/hero-images/navyjeep.jpg',
				text: 'Decked Out Jeep to Be Donated to Navy SEAL Foundation',
				button_text: 'READ MORE',
				link: '/news/48',
				order: 4,
				styles: {
					backgroundImage: 'url(https://storage.googleapis.com/aries-website/hero-images/navyjeep.jpg)',
				},
			},
		];
		try {
			const featResponse = await fetch(`${apiBase}/part/featured?brandID=${brand}&key=${KEY}`);
			const testResponse = await fetch(`${apiBase}/testimonials?key=${KEY}&count=2&randomize=true&brandID=${brand}`);

			state.context.featuredProducts = await featResponse.json();
			state.context.testimonials = await testResponse.json();
		} catch (e) {
			state.context.error = e;
		}

		return <Home context={state.context} />;
	});

	on('error', (state, error) => state.statusCode === 404 ?
		<App context={state.context} error={error}><NotFoundPage /></App> :
		<App context={state.context} error={error}><ErrorPage /></App>
	);
});

export default router;
<|endoftext|>


<commit_before>define(
  'ephox/imagetools/api/BlobConversions',

  [
    'ephox/imagetools/util/Conversions'
  ],

  function (Conversions) {
    var blobToImage = function (image) {
      return Conversions.blobToImage(image);
    };

    var imageToBlob = function (blob) {
      return Conversions.imageToBlob(blob);
    };

    var blobToDataUri = function (blob) {
      return Conversions.blobToDataUri(blob);
    };

    var blobToBase64 = function (blob) {
      return Conversions.blobToBase64(blob);
    };

    return {
      // used outside
      blobToImage: blobToImage,
      // used outside
      imageToBlob: imageToBlob,
      // used outside
      blobToDataUri: blobToDataUri,
      // used outside
      blobToBase64: blobToBase64
    };
  }
);<commit_msg>Api: Expose new Conversions methods.<commit_after>define(
  'ephox/imagetools/api/BlobConversions',

  [
    'ephox/imagetools/util/Conversions'
  ],

  function (Conversions) {
    var blobToImage = function (image) {
      return Conversions.blobToImage(image);
    };

    var imageToBlob = function (blob) {
      return Conversions.imageToBlob(blob);
    };

    var blobToDataUri = function (blob) {
      return Conversions.blobToDataUri(blob);
    };

    var blobToBase64 = function (blob) {
      return Conversions.blobToBase64(blob);
    };

    var blobToImageResult = function(blob) {
      return Conversions.blobToImageResult(blob);
    };

    var dataUriToImageResult = function(uri) {
      return Conversions.dataUriToImageResult(uri);
    };

    return {
      // used outside
      blobToImage: blobToImage,
      // used outside
      imageToBlob: imageToBlob,
      // used outside
      blobToDataUri: blobToDataUri,
      // used outside
      blobToBase64: blobToBase64,
      // used outside
      blobToImageResult: blobToImageResult,
      // used outside
      dataUriToImageResult: dataUriToImageResult
    };
  }
);<|endoftext|>