<commit_before>(function ( $ ) {

	$.fn.hailList = function( options ) {

		// This is the easiest way to have default options.
		var settings = $.extend({
			nextSelector: ".next",
			backSelector: ".back",
			nextFunction: function() {},
			backFunction: function() {},
			dateFormat: 'ddd, MMMM d, yyyy'
		}, options );

		// Greenify the collection based on the settings variable.
		return this.each(function () {
			var $this = $(this);
			var listID = $this.attr('data-list');
			var listCount = parseInt($this.attr('data-count'));
			var pos = 0;
			var display = $this.find('.HailArticle').length;

			$this.find(settings.nextSelector).click(next);
			$this.find(settings.backSelector).click(back);

			function next(event) {
				event.preventDefault();
				pos = (pos+1) % listCount;
				get(pos+display, settings.nextFunction);
			}

			function back(event) {
				event.preventDefault();
				pos = (pos + listCount - 1);
				console.log(pos);
				pos = (pos ) % listCount;
				console.log(pos);

				listCount

				get(pos+0, settings.backFunction);
			}

			function get(fetchNumber, func) {
				returnObj = {};

				function updateImage(HeroImage, clone) {
					if (HeroImage != null) {
						$.getJSON(
							article.HeroImage.href, '',
							function (data) {
								$.each(
									['Url150Square', 'Url500', 'Url500Square', 'Url1000', 'Url1000Square', 'Url2000', 'Urloriginal'],
									function (i, imgClass) {
										clone.find('img.' + imgClass).attr('src', data[imgClass]).show();
									}
								);
								func(returnObj);
							}
						);
					}
					else {
						clone.find('img.' + imgClass).hide();
					}
				}

				fetchNumber = fetchNumber % listCount;

				$.getJSON(
					'api/v1/HailList/' + listID + '/Articles.json',
					'limit=1&start=' + fetchNumber,
					function (data) {
						console.dir(data);
						article = data.items[0];

						var clone = $this.find('.HailArticle').first().clone();
						updateArticle(article, clone);
						updateDate(article, clone);

						returnObj = {
							hailList: $this,
							article: article,
							listID: listID,
							clone: clone,
							pos: pos
						};

						updateImage(article.HeroImage, clone);

					}
				);
			}

			function updateArticle(article, clone) {
				$.each(
					['Title', 'Author', 'Lead', 'Content', 'Location', 'Rating', 'Urloriginal'],
					function (i, textClass) {
						clone.find('.' + textClass).html(article[textClass]);
					}
				);
			}

			function updateDate(article, clone) {
				$.each(
					['Date'],
					function (i, dateClass) {
						clone.find('.' + dateClass).html($.format.date(article[dateClass], settings.dateFormat));
					}
				);
			}

		});

	};

}( jQuery ));
<commit_msg>changes to hail.js, including tag and video integration<commit_after>(function ( $ ) {

	$.fn.hailList = function( options ) {

		// This is the easiest way to have default options.
		var settings = $.extend({
			nextSelector: ".next",
			backSelector: ".back",
			nextFunction: function() {},
			backFunction: function() {},
			dateFormat: 'ddd, MMMM d, yyyy',
			reponsiveDisplay: {0: 1, 768: 2, 992: 3}
		}, options );

		// Greenify the collection based on the settings variable.
		return this.each(function () {
			var $this = $(this);
			var listID = $this.data('list');
			var objectType = $this.data('object-type');
			if (typeof objectType == 'undefined' || objectType == '') objectType = 'HailList';
			var listCount = parseInt($this.data('count'));
			var pos = 0;
			var display = $this.find('.HailArticle').length;

			$this.find(settings.nextSelector).click(next);
			$this.find(settings.backSelector).click(back);

			resize();
			$( window ).resize(resize);

			function resize() {
				currentDisplay = display;
				for (minRes in settings.reponsiveDisplay) {

					if ($('body').outerWidth(true) >= minRes) {
						currentDisplay = settings.reponsiveDisplay[minRes];
					} else {
						break;
					}
				}

				if (listCount <= currentDisplay) {
					$this.find(settings.nextSelector).hide();
					$this.find(settings.backSelector).hide();
				} else {
					$this.find(settings.nextSelector).show();
					$this.find(settings.backSelector).show();
				}
			}

			function next(event) {
				event.preventDefault();
				pos = (pos+1) % listCount;
				get(pos+display-1, settings.nextFunction);
			}

			function back(event) {
				event.preventDefault();
				pos = (pos + listCount - 1);
				pos = (pos ) % listCount;

				listCount

				get(pos+0, settings.backFunction);
			}

			function get(fetchNumber, func) {
				returnObj = {};

				function updateImage(article, clone) {
					if (article.HeroImage != null && article.HeroImage.id != 0) {
						$.getJSON(
							article.HeroImage.href, '',
							function (data) {
								$.each(
									['Url150Square', 'Url500', 'Url500Square', 'Url1000', 'Url1000Square', 'Url2000', 'Urloriginal'],
									function (i, imgClass) {
										clone.find('img.' + imgClass).attr('src', data[imgClass]).show();
									}
								);
								func(returnObj);
							}
						);
					} else if (article.HeroVideo != null && article.HeroVideo.id != 0) {
				$.getJSON(
					article.HeroVideo.href, '',
					function (data) {
						$.each(
							['Url150Square', 'Url500', 'Url500Square', 'Url1000', 'Url1000Square', 'Url2000', 'Urloriginal'],
							function (i, imgClass) {
								clone.find('img.' + imgClass).attr('src', data[imgClass]).show();
							}
						);
						func(returnObj);
					}
				);
					} else {
						$.each(
							['Url150Square', 'Url500', 'Url500Square', 'Url1000', 'Url1000Square', 'Url2000', 'Urloriginal'],
							function (i, imgClass) {
								clone.find('img.' + imgClass).hide();
							}
						);
						func(returnObj);
					}
				}

				fetchNumber = fetchNumber % listCount;

				$.getJSON(
					'api/v1/HailList/' + listID + '/Articles.json',
					'limit=1&start=' + fetchNumber,
					function (data) {
						article = data.items[0];

						var clone = $this.find('.HailArticle').first().clone();
						updateArticle(article, clone);
						updateDate(article, clone);

						returnObj = {
							hailList: $this,
							article: article,
							listID: listID,
							clone: clone,
							pos: pos
						};

						updateImage(article, clone);

					}
				);
			}

			// Updates most text based property for our new article
			function updateArticle(article, clone) {
				$.each(
					['Title', 'Author', 'Content', 'Location', 'Rating', 'Urloriginal'],
					function (i, textClass) {
						clone.find('.' + textClass).html(article[textClass]);
					}
				);

				$.each(
					['Lead', 'Editorial'],
					function (i, textClass) {
						clone.find('.' + textClass).html(trimByWord(article[textClass], 50));
					}
				);

				clone.find('a.Link').each(function (i,e) {
					var href = $(e).attr('href');
					href = href.replace(/\/\d*$/g, '/' + article['ID']);
					$(e).attr('href', href);
				});

				clone.find('a.Url').each(function (i,e) {
					var href = $(e).attr('href');
					href = article['Url'];
					$(e).attr('href', href);
				});
			}

			function updateDate(article, clone) {
				$.each(
					['Date'],
					function (i, dateClass) {
						clone.find('.' + dateClass).html(formatDate(article[dateClass]));
					}
				);
			}

			function trimByWord(sentence, numberOfWords) {
				if (sentence === undefined || sentence === null) {
					return '';
				}
				var result = sentence;
				var resultArray = result.split(" ");
				if(resultArray.length > numberOfWords){
					resultArray = resultArray.slice(0, numberOfWords);
					result = resultArray.join(" ") + " ...";
				}
				return result;
			}
			function formatDate(dateData) {
				if (dateData === undefined) {
					return '';
				} else {
					return $.format.date(dateData, settings.dateFormat);
				}
			}

		});

	};

}( jQuery ));
<|endoftext|>


<commit_before>// Right nav highlighting
var sidebarObj = (document.getElementsByClassName("sidebar")[0]) ? document.getElementsByClassName("sidebar")[0] : document.getElementsByClassName("sidebar-home")[0];

// ensure that the left nav visibly displays the current topic
var current = document.getElementsByClassName("active currentPage");
var body = document.getElementsByClassName("col-content content");
if (current[0]) {
    if (sidebarObj) {
        current[0].scrollIntoView(true);
        body[0].scrollIntoView(true);
    }
    // library hack
    if (document.location.pathname.indexOf("/samples/") > -1) {
        $(".currentPage").closest("ul").addClass("in");
    }
}

function navClicked(sourceLink) {
    var classString = document.getElementById("#item" + sourceLink).className;
    if (classString.indexOf(" in") > -1) {
        //collapse
        document.getElementById("#item" + sourceLink).className = classString.replace(" in", "");
    } else {
        //expand
        document.getElementById("#item" + sourceLink).className = classString.concat(" in");
    }
}

var outputLetNav = [];
var totalTopics = 0;

function pageIsInSection(tree) {
    function processBranch(branch) {
        for (let k = 0; k < branch.length; k++) {
            if (branch[k].section) {
                processBranch(branch[k].section);
            } else {
                if (branch[k].path === pageURL && !branch[k].nosync) {
                    found = true;
                    break;
                }
            }
        }
    }

    let found = false;
    processBranch(tree);
    return found;
}

function walkTree(tree) {
    for (let j = 0; j < tree.length; j++) {
        totalTopics++;
        if (tree[j].section) {
            let sectionHasPath = pageIsInSection(tree[j].section);
            outputLetNav.push('
" + tree[j].sectiontitle + '');
            outputLetNav.push('
');
            walkTree(tree[j].section);
            outputLetNav.push("

");
        } else {
            // just a regular old topic; this is a leaf, not a branch; render a link!
            outputLetNav.push('
" + tree[j].title + "
")
        }
    }
}

function renderNav(docstoc) {
    for (let i = 0; i < docstoc.horizontalnav.length; i++) {
        if (docstoc.horizontalnav[i].path === pageURL || pageIsInSection(docstoc[docstoc.horizontalnav[i].node])) {
            // This is the current section. Set the corresponding header-nav link
            // to active, and build the left-hand (vertical) navigation
            document.getElementById(docstoc.horizontalnav[i].node).closest("li").classList.add("active")
            walkTree(docstoc[docstoc.horizontalnav[i].node]);
            document.getElementById("jsTOCLeftNav").innerHTML = outputLetNav.join("");
        }
    }
    // Scroll the current menu item into view. We actually pick the item *above*
    // the current item to give some headroom above
    scrollMenuItem("#jsTOCLeftNav a.currentPage")
}

// Scroll the given menu item into view. We actually pick the item *above*
// the current item to give some headroom above
function scrollMenuItem(selector) {
    let item = document.querySelector(selector)
    if (item) {
        item = item.closest("li")
    }
    if (item) {
        item = item.previousElementSibling
    }
    if (item) {
        item.scrollIntoView(true)
        if (window.location.hash.length < 2) {
            // Scrolling the side-navigation may scroll the whole page as well
            // this is a dirty hack to scroll the main content back to the top
            // if we're not on a specific anchor
            document.querySelector("main.col-content").scrollIntoView(true)
        }
    }
}

function highlightRightNav(heading) {
    $("#my_toc a.active").removeClass("active");

    if (heading !== "title") {
        $("#my_toc a[href='#" + heading + "']").addClass("active");
    }
}

var currentHeading = "";
$(window).scroll(function () {
    var headingPositions = [];
    $("h1, h2, h3, h4, h5, h6").each(function () {
        if (this.id === "") this.id = "title";
        headingPositions[this.id] = this.getBoundingClientRect().top;
    });
    headingPositions.sort();
    // the headings have all been grabbed and sorted in order of their scroll
    // position (from the top of the page). First one is toppermost.
    for (var key in headingPositions) {
        if (!headingPositions.hasOwnProperty(key)) {
            continue;
        }
        if (headingPositions[key] > 0 && headingPositions[key] < 200) {
            if (currentHeading !== key) {
                // a new heading has scrolled to within 200px of the top of the page.
                // highlight the right-nav entry and de-highlight the others.
                highlightRightNav(key);
                currentHeading = key;
            }
            break;
        }
    }
});

// Cookie functions
function createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === " ") c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

var prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
var selectedNightTheme = readCookie("night");

if (selectedNightTheme === "true" || (selectedNightTheme === null && prefersDark)) {
    applyNight();
    $("#switch-style").prop("checked", true);
} else {
    applyDay();
    $("#switch-style").prop("checked", false);
}

/*
 *
 * toggle menu *********************************************************************
 *
 */

$("#menu-toggle").click(function (e) {
    e.preventDefault();
    $(".wrapper").toggleClass("right-open");
    $(".col-toc").toggleClass("col-toc-hidden");
});

$("#menu-toggle-left").click(function (e) {
    e.preventDefault();
    $(".col-nav").toggleClass("col-toc-hidden");
});

$(".navbar-toggle").click(function () {
    $("#sidebar-nav").each(function () {
        $(this).toggleClass("hidden-sm");
        $(this).toggleClass("hidden-xs");
    });
});

var navHeight = $(".navbar").outerHeight(true) + 80;

$(document.body).scrollspy({
    target: "#leftCol",
    offset: navHeight
});

function loadHash(hashObj) {
    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $("html, body").animate({scrollTop: $(hashObj).offset().top - 80}, 800);
}

$(document).ready(function () {
    // Add smooth scrolling to all links
    $(".toc-nav a").on("click", function (event) {
        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();

            // Store hash
            var hash = this.hash;
            loadHash(hash);

            // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
        }
    });
    if (window.location.hash) loadHash(window.location.hash);
});

$(document).ready(function () {
    // Add smooth scrolling to all links
    $(".nav-sidebar ul li a").on("click", function (event) {

        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();

            // Store hash
            var hash = this.hash;

            // Using jQuery's animate() method to add smooth page scroll
            // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
            $("html, body").animate({
                scrollTop: $(hash).offset().top - 80
            }, 800, function () {
                // Add hash (#) to URL when done scrolling (default click behavior)
                window.location.hash = hash;
            });
        }
    });
});

/*
 *
 * make dropdown show on hover *********************************************************************
 *
 */

$("ul.nav li.dropdown").hover(function () {
    $(this).find(".dropdown-menu").stop(true, true).delay(200).fadeIn(500);
}, function () {
    $(this).find(".dropdown-menu").stop(true, true).delay(200).fadeOut(500);
});

/*
 *
 * swapStyleSheet*********************************************************************
 *
 */

function applyNight() {
    $("body").addClass("night");
}

function applyDay() {
    $("body").removeClass("night");
}

$("#switch-style").change(function () {
    if ($(this).is(":checked")) {
        applyNight();
        createCookie("night", true, 999)
    } else {
        applyDay();
        createCookie("night", false, 999);
    }
});

/*
 *
 * TEMP HACK For side menu*********************************************************************
 *
 */

$(".nav-sidebar ul li a").click(function () {
    $(this).addClass("collapse").siblings().toggleClass("in");
});

if ($(".nav-sidebar ul a.active").length !== 0) {
    $(".nav-sidebar ul").click(function () {
        $(this).addClass("collapse in").siblings;
    });
}

/*
 *
 * Components *********************************************************************
 *
 */

$(function () {
    $('[data-toggle="tooltip"]').tooltip()
});

// sync tabs with the same data-group
window.onload = function () {
    $(".nav-tabs > li > a").click(function (e) {
        var group = $(this).attr("data-group");
        $('.nav-tabs > li > a[data-group="' + group + '"]').tab("show");
    });
};
<commit_msg>js/docs.js: remove temporary hack for side menu<commit_after>// Right nav highlighting
var sidebarObj = (document.getElementsByClassName("sidebar")[0]) ? document.getElementsByClassName("sidebar")[0] : document.getElementsByClassName("sidebar-home")[0];

// ensure that the left nav visibly displays the current topic
var current = document.getElementsByClassName("active currentPage");
var body = document.getElementsByClassName("col-content content");
if (current[0]) {
    if (sidebarObj) {
        current[0].scrollIntoView(true);
        body[0].scrollIntoView(true);
    }
    // library hack
    if (document.location.pathname.indexOf("/samples/") > -1) {
        $(".currentPage").closest("ul").addClass("in");
    }
}

function navClicked(sourceLink) {
    var classString = document.getElementById("#item" + sourceLink).className;
    if (classString.indexOf(" in") > -1) {
        //collapse
        document.getElementById("#item" + sourceLink).className = classString.replace(" in", "");
    } else {
        //expand
        document.getElementById("#item" + sourceLink).className = classString.concat(" in");
    }
}

var outputLetNav = [];
var totalTopics = 0;

function pageIsInSection(tree) {
    function processBranch(branch) {
        for (let k = 0; k < branch.length; k++) {
            if (branch[k].section) {
                processBranch(branch[k].section);
            } else {
                if (branch[k].path === pageURL && !branch[k].nosync) {
                    found = true;
                    break;
                }
            }
        }
    }

    let found = false;
    processBranch(tree);
    return found;
}

function walkTree(tree) {
    for (let j = 0; j < tree.length; j++) {
        totalTopics++;
        if (tree[j].section) {
            let sectionHasPath = pageIsInSection(tree[j].section);
            outputLetNav.push('
" + tree[j].sectiontitle + '');
            outputLetNav.push('
');
            walkTree(tree[j].section);
            outputLetNav.push("

");
        } else {
            // just a regular old topic; this is a leaf, not a branch; render a link!
            outputLetNav.push('
" + tree[j].title + "
")
        }
    }
}

function renderNav(docstoc) {
    for (let i = 0; i < docstoc.horizontalnav.length; i++) {
        if (docstoc.horizontalnav[i].path === pageURL || pageIsInSection(docstoc[docstoc.horizontalnav[i].node])) {
            // This is the current section. Set the corresponding header-nav link
            // to active, and build the left-hand (vertical) navigation
            document.getElementById(docstoc.horizontalnav[i].node).closest("li").classList.add("active")
            walkTree(docstoc[docstoc.horizontalnav[i].node]);
            document.getElementById("jsTOCLeftNav").innerHTML = outputLetNav.join("");
        }
    }
    // Scroll the current menu item into view. We actually pick the item *above*
    // the current item to give some headroom above
    scrollMenuItem("#jsTOCLeftNav a.currentPage")
}

// Scroll the given menu item into view. We actually pick the item *above*
// the current item to give some headroom above
function scrollMenuItem(selector) {
    let item = document.querySelector(selector)
    if (item) {
        item = item.closest("li")
    }
    if (item) {
        item = item.previousElementSibling
    }
    if (item) {
        item.scrollIntoView(true)
        if (window.location.hash.length < 2) {
            // Scrolling the side-navigation may scroll the whole page as well
            // this is a dirty hack to scroll the main content back to the top
            // if we're not on a specific anchor
            document.querySelector("main.col-content").scrollIntoView(true)
        }
    }
}

function highlightRightNav(heading) {
    $("#my_toc a.active").removeClass("active");

    if (heading !== "title") {
        $("#my_toc a[href='#" + heading + "']").addClass("active");
    }
}

var currentHeading = "";
$(window).scroll(function () {
    var headingPositions = [];
    $("h1, h2, h3, h4, h5, h6").each(function () {
        if (this.id === "") this.id = "title";
        headingPositions[this.id] = this.getBoundingClientRect().top;
    });
    headingPositions.sort();
    // the headings have all been grabbed and sorted in order of their scroll
    // position (from the top of the page). First one is toppermost.
    for (var key in headingPositions) {
        if (!headingPositions.hasOwnProperty(key)) {
            continue;
        }
        if (headingPositions[key] > 0 && headingPositions[key] < 200) {
            if (currentHeading !== key) {
                // a new heading has scrolled to within 200px of the top of the page.
                // highlight the right-nav entry and de-highlight the others.
                highlightRightNav(key);
                currentHeading = key;
            }
            break;
        }
    }
});

// Cookie functions
function createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === " ") c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

var prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
var selectedNightTheme = readCookie("night");

if (selectedNightTheme === "true" || (selectedNightTheme === null && prefersDark)) {
    applyNight();
    $("#switch-style").prop("checked", true);
} else {
    applyDay();
    $("#switch-style").prop("checked", false);
}

/*
 * toggle menu *********************************************************************
 */

$("#menu-toggle").click(function (e) {
    e.preventDefault();
    $(".wrapper").toggleClass("right-open");
    $(".col-toc").toggleClass("col-toc-hidden");
});

$("#menu-toggle-left").click(function (e) {
    e.preventDefault();
    $(".col-nav").toggleClass("col-toc-hidden");
});

$(".navbar-toggle").click(function () {
    $("#sidebar-nav").each(function () {
        $(this).toggleClass("hidden-sm");
        $(this).toggleClass("hidden-xs");
    });
});

var navHeight = $(".navbar").outerHeight(true) + 80;

$(document.body).scrollspy({
    target: "#leftCol",
    offset: navHeight
});

function loadHash(hashObj) {
    // Using jQuery's animate() method to add smooth page scroll
    // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
    $("html, body").animate({scrollTop: $(hashObj).offset().top - 80}, 800);
}

$(document).ready(function () {
    // Add smooth scrolling to all links
    $(".toc-nav a").on("click", function (event) {
        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();

            // Store hash
            var hash = this.hash;
            loadHash(hash);

            // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
        }
    });
    if (window.location.hash) loadHash(window.location.hash);
});

$(document).ready(function () {
    // Add smooth scrolling to all links
    $(".nav-sidebar ul li a").on("click", function (event) {

        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();

            // Store hash
            var hash = this.hash;

            // Using jQuery's animate() method to add smooth page scroll
            // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
            $("html, body").animate({
                scrollTop: $(hash).offset().top - 80
            }, 800, function () {
                // Add hash (#) to URL when done scrolling (default click behavior)
                window.location.hash = hash;
            });
        }
    });
});

/*
 * make dropdown show on hover *********************************************************************
 */

$("ul.nav li.dropdown").hover(function () {
    $(this).find(".dropdown-menu").stop(true, true).delay(200).fadeIn(500);
}, function () {
    $(this).find(".dropdown-menu").stop(true, true).delay(200).fadeOut(500);
});

/*
 * swapStyleSheet*********************************************************************
 */

function applyNight() {
    $("body").addClass("night");
}

function applyDay() {
    $("body").removeClass("night");
}

$("#switch-style").change(function () {
    if ($(this).is(":checked")) {
        applyNight();
        createCookie("night", true, 999)
    } else {
        applyDay();
        createCookie("night", false, 999);
    }
});

/*
 * Components *********************************************************************
 */

$(function () {
    $('[data-toggle="tooltip"]').tooltip()
});

// sync tabs with the same data-group
window.onload = function () {
    $(".nav-tabs > li > a").click(function (e) {
        var group = $(this).attr("data-group");
        $('.nav-tabs > li > a[data-group="' + group + '"]').tab("show");
    });
};
<|endoftext|>


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

import { queueReducers } from 'common/utils';
import { omit } from 'common/utils/omit';
import {
  FETCH_NESTED_STEP_START,
  FETCH_NESTED_STEP_SUCCESS,
  CLEAR_NESTED_STEP,
  CLEAR_NESTED_STEPS,
  TOGGLE_NESTED_STEP,
} from './constants';

function fetchReducer(state = {}, action) {
  switch (action.type) {
    case FETCH_NESTED_STEP_START: {
      const {
        payload: { id },
      } = action;
      return {
        ...state,
        [id]: {
          content: [],
          page: {},
          collapsed: true,
          ...state[id],
          loading: true,
        },
      };
    }
    case FETCH_NESTED_STEP_SUCCESS: {
      const {
        payload: { id, page, content },
      } = action;

      return {
        ...state,
        [id]: {
          ...state[id],
          loading: false,
          content,
          page,
        },
      };
    }
    default:
      return state;
  }
}

function mutationReducer(state, action) {
  switch (action.type) {
    case CLEAR_NESTED_STEP: {
      const {
        payload: { id },
      } = action;
      return omit(state, [id]);
    }
    case CLEAR_NESTED_STEPS:
      return {};
    case TOGGLE_NESTED_STEP: {
      const {
        payload: { id },
      } = action;
      return {
        ...state,
        [id]: {
          ...state[id],
          collapsed: !state[id].collapsed,
        },
      };
    }
    default:
      return state;
  }
}

export const nestedStepsReducer = queueReducers(fetchReducer, mutationReducer);
<commit_msg>Nested steps. Set reducer initial state<commit_after>/*
 * Copyright 2019 EPAM Systems
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { queueReducers } from 'common/utils';
import { omit } from 'common/utils/omit';
import {
  FETCH_NESTED_STEP_START,
  FETCH_NESTED_STEP_SUCCESS,
  CLEAR_NESTED_STEP,
  CLEAR_NESTED_STEPS,
  TOGGLE_NESTED_STEP,
} from './constants';

function fetchReducer(state = {}, action) {
  switch (action.type) {
    case FETCH_NESTED_STEP_START: {
      const {
        payload: { id },
      } = action;
      return {
        ...state,
        [id]: {
          content: [],
          page: {},
          collapsed: true,
          ...state[id],
          loading: true,
        },
      };
    }
    case FETCH_NESTED_STEP_SUCCESS: {
      const {
        payload: { id, page, content },
      } = action;

      return {
        ...state,
        [id]: {
          ...state[id],
          loading: false,
          content,
          page,
        },
      };
    }
    default:
      return state;
  }
}

function mutationReducer(state = {}, action) {
  switch (action.type) {
    case CLEAR_NESTED_STEP: {
      const {
        payload: { id },
      } = action;
      return omit(state, [id]);
    }
    case CLEAR_NESTED_STEPS:
      return {};
    case TOGGLE_NESTED_STEP: {
      const {
        payload: { id },
      } = action;
      return {
        ...state,
        [id]: {
          ...state[id],
          collapsed: !state[id].collapsed,
        },
      };
    }
    default:
      return state;
  }
}

export const nestedStepsReducer = queueReducers(fetchReducer, mutationReducer);
<|endoftext|>


<commit_before>(function($) {
  $(document).ready(function() {
    $(".signupForm").submit(function(event) {
      var formData = {
        'phoneNumber': $('input[name=phoneNumber]').val()
      }

      $.ajax({
        type: 'POST',
        url: 'https://autolotto-backend-production.herokuapp.com/api/v1/pres',
        data: formData,
        dataType: 'json',
        crossDomain: true,
        encode: true
      }).done(function(res) {
        window.parent.location.href = 'http://web.autolotto.com/giveaway/welcome';
      }).fail(function() {
        alert('Please enter a valid US phone number!');
      });

      event.preventDefault();
    });
  });
})(jQuery);
<commit_msg>redirect directly to leaderboard if already exists<commit_after>(function($) {
  $(document).ready(function() {
    $(".signupForm").submit(function(event) {
      var formData = {
        'phoneNumber': $('input[name=phoneNumber]').val()
      }

      $.ajax({
        type: 'POST',
        url: 'https://autolotto-backend-production.herokuapp.com/api/v1/pres',
        data: formData,
        dataType: 'json',
        crossDomain: true,
        encode: true
      }).done(function(res) {
        if (res.data.created) {
          window.parent.location.href = 'http://web.autolotto.com/giveaway/welcome';
        } else {
          window.parent.location.href = "http://autolotto.com/leaderboard/";
        }
      }).fail(function() {
        alert('Please enter a valid US phone number!');
      });

      event.preventDefault();
    });
  });
})(jQuery);
<|endoftext|>


<commit_before>var app = angular.module('HelpApp', ['ngMaterial']);
// Config
app.config(function ($mdIconProvider) {
    $mdIconProvider.defaultIconSet('/img/mdi.svg');
    console.info('Successfully initialized!');
});
app.controller('HelpController', function ($scope, $mdDialog) {
    console.info('Loaded HelpController!');
    $scope.sendFeedback = function (ev) {
        $mdDialog.show({
            controller: FeedbackController,
            templateUrl: '/templates/feedbackhelp.html',
            parent: angular.element(document.body),
            targetEvent: ev,
            clickOutsideToClose: true
        })
            .then(function (answer) {
                $scope.status = 'Your answer was: "' + answer + '".';
            }, function () {
                $scope.status = 'You cancelled the dialog.';
            });
    };
});
app.controller('SearchController', function ($scope) {
    console.info('Loaded SearchController!');
});
// Sidenav
app.controller('SideNavController', function ($scope, $mdSidenav) {
    console.info('SideNavController successfully loaded!');

    $scope.top = [
        { url: 'https://chan4077.github.io', title: 'Main', icon: 'home' },
        { url: 'https://chan4077.github.io/about', title: 'About Me', icon: 'account-box' },
        { url: 'https://chan4077.github.io/blog', title: 'Blog', icon: 'blogger' },
        { url: 'https://chan4077.github.io/media', title: 'Social Media', icon: 'google-plus' },
        { url: 'https://chan4077.github.io/angular', title: 'Angular', icon: 'angular' },
    ];
    $scope.other = [
        { url: 'https://github.com/Chan4077/chan4077.github.io', title: 'Project Page', icon: 'github-circle' },
        { url: 'https://chan4077.github.io/preferences', title: 'Preferences', icon: 'settings' },
        { url: 'https://chan4077.github.io/help', title: 'Get Help', icon: 'help-circle' },
    ];
    $scope.openLeftMenu = function () {
        $mdSidenav('left').toggle();
    };
})<commit_msg>Remove ngMaterial<commit_after>var app = angular.module('HelpApp', ['']);
// Config
app.config(function ($mdIconProvider) {
    $mdIconProvider.defaultIconSet('/img/mdi.svg');
    console.info('Successfully initialized!');
});
app.controller('HelpController', function ($scope, $mdDialog) {
    console.info('Loaded HelpController!');
    $scope.sendFeedback = function (ev) {
        $mdDialog.show({
            controller: FeedbackController,
            templateUrl: '/templates/feedbackhelp.html',
            parent: angular.element(document.body),
            targetEvent: ev,
            clickOutsideToClose: true
        })
            .then(function (answer) {
                $scope.status = 'Your answer was: "' + answer + '".';
            }, function () {
                $scope.status = 'You cancelled the dialog.';
            });
    };
});
app.controller('SearchController', function ($scope) {
    console.info('Loaded SearchController!');
});
// Sidenav
app.controller('SideNavController', function ($scope, $mdSidenav) {
    console.info('SideNavController successfully loaded!');

    $scope.top = [
        { url: 'https://chan4077.github.io', title: 'Main', icon: 'home' },
        { url: 'https://chan4077.github.io/about', title: 'About Me', icon: 'account-box' },
        { url: 'https://chan4077.github.io/blog', title: 'Blog', icon: 'blogger' },
        { url: 'https://chan4077.github.io/media', title: 'Social Media', icon: 'google-plus' },
        { url: 'https://chan4077.github.io/angular', title: 'Angular', icon: 'angular' },
    ];
    $scope.other = [
        { url: 'https://github.com/Chan4077/chan4077.github.io', title: 'Project Page', icon: 'github-circle' },
        { url: 'https://chan4077.github.io/preferences', title: 'Preferences', icon: 'settings' },
        { url: 'https://chan4077.github.io/help', title: 'Get Help', icon: 'help-circle' },
    ];
    $scope.openLeftMenu = function () {
        $mdSidenav('left').toggle();
    };
})<|endoftext|>


<commit_before>var FW = 20, // width between fitch bars
	LH = 30, // height between proof lines
	NW = 30, // width of numbering column
	OS = LH/6, // offset for text (above baseline and right of fitch bar)
	RC = 30; // space between formula and rule

function draw() {
	var SVGW = "100%",
		SVGH = LH;

	if(PROOF.length > 0) {
		var max = d3.max(PROOF, function(d) {return d.rul=="Premise" ? d.cnt : 0;}); // line number of last premise
		SVGH = PROOF.length*LH;
	}
	var proof = d3.select("#drv")
		.attr("width", SVGW)
		.attr("height", SVGH);

	var line = proof.selectAll("g")
		.data(PROOF);

	var l = line.enter()
		.append("g")
		.attr("transform",function(d,i) {return "translate(0," + i*LH + ")";});

	l.each(function(d,i) { // draw fitch lines
		var el = d3.select(this);
		var pflag = (d.rul=="Premise") && (d.cnt == max);
		if(d.rul=="Assumption" || pflag || d.rul=='Flag') { // adds fitch lines for assumption lines
			for(var i=0;i<(d.dth-1);i++) {
				el.append("path")
					.attr("d",function(d) {
						return "M"+((i*FW)+NW)+" 0, V "+LH;
					});
			}
			var x = ((d.dth-1)*FW)+NW;
			el.append("path") // adds last fitch line
				.attr("d",function(d) {
					return "M"+x+" "+(pflag ? 0 : (1.6*OS))+", V "+LH;
				});
			el.append("path") // adds horizontal assumption line
				.attr("d",function(d) {
					return "M"+x+" "+LH+", H "+(x+10);
				});
		} else { // adds fitch lines for non-assumption lines
			for(var i=0;i<=(d.dth-1);i++) {
				el.append("path")
					.attr("d", function(d) {
						return "M"+((i*FW)+NW)+" 0, V "+LH;
					});
			}
		}
	});

	l.append("text") // append line number
		.attr("x","0")
		.attr("y",""+(LH-OS))
		.text(function(d) {return d.cnt;});

	l.append("text") // append formula
		.attr("x", function(d) {return NW+(FW*(d.dth>1 ? d.dth-1 : 0))+(d.dth>0 ? OS : 0);})
		.attr("y", ""+(LH-OS))
		.attr("class","dfrm")
		.attr("id",function(d) {return "frm"+d.cnt;})
		.text(function(d) {return padBCs(richardify(d.frm));});

	l.append("text") // append rule
		.attr("class","drul")
		.text(function(d) {return d.lin.join(',')+" "+gRul(d.rul);});

	line.exit().remove();

	if(PROOF.length) {
		var w = d3.max(d3.selectAll(".dfrm")[0], function(d) {
			var e = d3.select(d);
			return parseInt(e.style("width"))+parseInt(e.attr("x"));})
		d3.selectAll('.drul')
			.attr("x",w+RC)
			.attr("y",(LH-OS));
	};

}

function draw_goals() {
	var SVG2W = "100%",
		SVG2H = 0;
	if(GOALS.length) {
		SVG2H = GOALS.length*LH;
	}

	var goals = d3.select("#gls")
 		.attr("width", SVG2W)
 		.attr("height", SVG2H);

	var goal = goals.selectAll("g")
		.data(GOALS);

	goal.select(".glfrm").text(function(d) {return padBCs(richardify(d));});

	var g = goal.enter().append("g");

	g.attr("transform",function(d,i) {return "translate(0,"+(i*LH)+")";});

	g.append("text")
		.attr("x",0)
		.attr("y",""+(LH-OS))
		.attr("class","gllbl")
		.text("Goal:");

	g.append("text")
		.attr("class","glfrm")
		.text(function(d) {return richardify(d);});

	goal.exit().remove();

	if(CONCLUSION.length) {
		var w = parseInt(d3.select("#conlbl").style("width"));
		d3.selectAll('.glfrm')
			.attr("x",w+10)
			.attr("y",(LH-OS));
	}
}

function draw_conclusion() {
	var el = d3.select("#con")
		.attr("width", "100%")
		.attr("height",LH);

	var con = el.selectAll("g")
		.data(CONCLUSION);

	con.enter()
		.append("g")
		.attr("transform","translate(0,0)")
		.attr("id","g");

	con.append("text")
		.attr("x",0)
		.attr("y",""+(LH-OS))
		.attr("id","conlbl")
		.text("Conclusion:")
		.attr("display","block");

	con.append("text")
		.attr("id","confrm")
		.text(function(d) {return padBCs(richardify(d));})
		.attr("display","block");

	con.exit().remove();

	if(CONCLUSION.length) {
		var w = parseInt(d3.select("#conlbl").style("width"));
		d3.select("#confrm")
			.attr("x",10+w)
			.attr("y",(LH-OS));
	};

}<commit_msg>revert<commit_after>var FW = 20, // width between fitch bars
	LH = 30, // height between proof lines
	NW = 30, // width of numbering column
	OS = LH/6, // offset for text (above baseline and right of fitch bar)
	RC = 30; // space between formula and rule

function draw() {
	var SVGW = "100%",
		SVGH = LH;

	if(PROOF.length > 0) {
		var max = d3.max(PROOF, function(d) {return d.rul=="Premise" ? d.cnt : 0;}); // line number of last premise
		SVGH = PROOF.length*LH;
	}
	var proof = d3.select("#drv")
		.attr("width", SVGW)
		.attr("height", SVGH);

	var line = proof.selectAll("g")
		.data(PROOF);

	var l = line.enter()
		.append("g")
		.attr("transform",function(d,i) {return "translate(0," + i*LH + ")";});

	l.each(function(d,i) { // draw fitch lines
		var el = d3.select(this);
		var pflag = (d.rul=="Premise") && (d.cnt == max);
		if(d.rul=="Assumption" || pflag || d.rul=='Flag') { // adds fitch lines for assumption lines
			for(var i=0;i<(d.dth-1);i++) {
				el.append("path")
					.attr("d",function(d) {
						return "M"+((i*FW)+NW)+" 0, V "+LH;
					});
			}
			var x = ((d.dth-1)*FW)+NW;
			el.append("path") // adds last fitch line
				.attr("d",function(d) {
					return "M"+x+" "+(pflag ? 0 : (1.6*OS))+", V "+LH;
				});
			el.append("path") // adds horizontal assumption line
				.attr("d",function(d) {
					return "M"+x+" "+LH+", H "+(x+10);
				});
		} else { // adds fitch lines for non-assumption lines
			for(var i=0;i<=(d.dth-1);i++) {
				el.append("path")
					.attr("d", function(d) {
						return "M"+((i*FW)+NW)+" 0, V "+LH;
					});
			}
		}
	});

	l.append("text") // append line number
		.attr("x","0")
		.attr("y",""+(LH-OS))
		.text(function(d) {return d.cnt;});

	l.append("text") // append formula
		.attr("x", function(d) {return NW+(FW*(d.dth>1 ? d.dth-1 : 0))+(d.dth>0 ? OS : 0);})
		.attr("y", ""+(LH-OS))
		.attr("class","dfrm")
		.attr("id",function(d) {return "frm"+d.cnt;})
		.text(function(d) {return padBCs(richardify(d.frm));});

	l.append("text") // append rule
		.attr("class","drul")
		.text(function(d) {return d.lin.join(',')+" "+gRul(d.rul);});

	line.exit().remove();

	if(PROOF.length) {
		var w = d3.max(d3.selectAll(".dfrm")[0], function(d) {
			var e = d3.select(d);
			return parseInt(e.style("width"))+parseInt(e.attr("x"));})
		d3.selectAll('.drul')
			.attr("x",w+RC)
			.attr("y",(LH-OS));
	};

}

function draw_goals() {
	var SVG2W = "100%",
		SVG2H = 0;
	if(GOALS.length) {
		SVG2H = GOALS.length*LH;
	}

	var goals = d3.select("#gls")
 		.attr("width", SVG2W)
 		.attr("height", SVG2H);

	var goal = goals.selectAll("g")
		.data(GOALS);

	goal.select(".glfrm").text(function(d) {return padBCs(richardify(d));});

	var g = goal.enter().append("g");

	g.attr("transform",function(d,i) {return "translate(0,"+(i*LH)+")";});

	g.append("text")
		.attr("x",0)
		.attr("y",""+(LH-OS))
		.attr("class","gllbl")
		.text("Goal:");

	g.append("text")
		.attr("class","glfrm")
		.text(function(d) {return richardify(d);});

	goal.exit().remove();

	if(CONCLUSION.length) {
		var w = parseInt(d3.select("#conlbl").style("width"));
		d3.selectAll('.glfrm')
			.attr("x",w+10)
			.attr("y",(LH-OS));
	}
}

function draw_conclusion() {
	var el = d3.select("#con")
		.attr("width", "100%")
		.attr("height",LH);

	var con = el.selectAll("g")
		.data(CONCLUSION);

	con.enter()
		.append("g")
		.attr("transform","translate(0,0)")
		.attr("id","g");

	con.append("text")
		.attr("x",0)
		.attr("y",""+(LH-OS))
		.attr("id","conlbl")
		.text("Conclusion:");

	con.append("text")
		.attr("id","confrm")
		.text(function(d) {return padBCs(richardify(d));});

	con.exit().remove();

	if(CONCLUSION.length) {
		var w = parseInt(d3.select("#conlbl").style("width"));
		d3.select("#confrm")
			.attr("x",10+w)
			.attr("y",(LH-OS));
	};

}<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';

import moment from 'moment';
import currency from '../../localization/currency';

import { UIDatabase } from '../../database';
import {
  CASH_TRANSACTION_KEYS,
  CASH_TRANSACTION_TYPES,
} from '../../utilities/modules/dispensary/constants';

import { ToggleBar } from '../ToggleBar';
import { ModalContainer } from './ModalContainer';
import { BottomModalContainer, BottomTextEditor, BottomCurrencyEditor } from '../bottomModals';
import { GenericChoiceList, AutocompleteSelector } from '../modalChildren';
import { PageButton } from '../PageButton';
import { PencilIcon, ChevronDownIcon } from '../icons';

import globalStyles, { WARM_GREY, SUSSOL_ORANGE, COMPONENT_HEIGHT } from '../../globalStyles';
import { buttonStrings, dispensingStrings, generalStrings } from '../../localization';

export const CashTransactionModal = ({ onConfirm }) => {
  const [name, setName] = useState(null);
  const [isCashIn, setIsCashIn] = useState(true);
  const [amount, setAmount] = useState(null);
  const [reason, setReason] = useState(null);
  const [description, setDescription] = useState(null);

  const [amountBuffer, setAmountBuffer] = useState(currency(0).format());
  const [descriptionBuffer, setDescriptionBuffer] = useState('');

  const [isNameModalOpen, setIsNameModalOpen] = useState(false);
  const [isAmountModalOpen, setIsAmountModalOpen] = useState(false);
  const [isReasonModalOpen, setIsReasonModalOpen] = useState(false);
  const [isDescriptionModalOpen, setIsDescriptionModalOpen] = useState(false);

  const names = useMemo(() => UIDatabase.objects('CashTransactionName'), []);
  const reasons = useMemo(() => UIDatabase.objects('CashTransactionReason'), []);
  const type = useMemo(
    () => (isCashIn ? CASH_TRANSACTION_TYPES.CASH_IN : CASH_TRANSACTION_TYPES.CASH_OUT),
    [isCashIn]
  );

  const isValidTransaction = useMemo(() => !!name && !!amount && (isCashIn || !!reason), [
    name,
    amount,
    reason,
    isCashIn,
  ]);

  const onCreate = useCallback(
    () => onConfirm({ name, type, amount: amount.value, reason, description }),
    [name, type, amount, reason, description]
  );

  const onChangeText = useMemo(() => text => setDescriptionBuffer(text));
  const onChangeAmount = useMemo(() => value => setAmountBuffer(value));

  const renderNameLeftText = useCallback(({ firstName, lastName, name: fullName, isPatient }) =>
    isPatient ? `${lastName}, ${firstName}` : `${fullName}`
  );

  const renderNameRightText = useCallback(({ isCustomer, isSupplier, isPatient, dateOfBirth }) => {
    if (isCustomer) {
      if (isPatient) {
        return `${dispensingStrings.patient} \n ${dispensingStrings.date_of_birth}: ${
          dateOfBirth ? moment(dateOfBirth).format('DD/MM/YYYY') : generalStrings.not_available
        }`;
      }
      return dispensingStrings.customer;
    }
    if (isSupplier) {
      return dispensingStrings.supplier;
    }
    return '';
  });

  const resetBottomModal = () => {
    setIsNameModalOpen(false);
    setIsAmountModalOpen(false);
    setIsReasonModalOpen(false);
    setIsDescriptionModalOpen(false);
  };

  const onPressName = () => {
    resetBottomModal();
    setIsNameModalOpen(true);
  };

  const onPressAmount = () => {
    resetBottomModal();
    if (amount) {
      setAmountBuffer(amount.format(false));
    }
    setIsAmountModalOpen(true);
  };

  const onPressReason = () => {
    resetBottomModal();
    setIsReasonModalOpen(true);
  };

  const onPressDescription = () => {
    resetBottomModal();
    if (description) {
      setDescriptionBuffer(description);
    }
    setIsDescriptionModalOpen(true);
  };

  const onSubmitName = nameItem => {
    setName(nameItem);
    setIsNameModalOpen(false);
  };

  const onCloseName = () => setIsNameModalOpen(false);

  const onSubmitAmount = () => {
    setAmount(currency(amountBuffer));
    setIsAmountModalOpen(false);
  };

  const onSubmitReason = ({ item: reasonItem }) => {
    setReason(reasonItem);
    setIsReasonModalOpen(false);
  };

  const onSubmitDescription = () => {
    setDescription(descriptionBuffer);
    setIsDescriptionModalOpen(false);
  };

  const nameText = useMemo(() => name?.name ?? dispensingStrings.choose_a_name, [name]);
  const amountText = useMemo(() => amount?.format(false) ?? dispensingStrings.enter_the_amount, [
    amount,
  ]);
  const reasonText = useMemo(() => reason?.title ?? dispensingStrings.choose_a_reason, [reason]);
  const descriptionText = useMemo(() => description ?? dispensingStrings.enter_a_description, [
    description,
  ]);
  const toggleTransactionType = () => setIsCashIn(!isCashIn);

  const toggles = useMemo(
    () => [
      { text: dispensingStrings.cash_in, onPress: toggleTransactionType, isOn: isCashIn },
      { text: dispensingStrings.cash_out, onPress: toggleTransactionType, isOn: !isCashIn },
    ],
    [isCashIn]
  );

  const PressReason = useCallback(
    () =>
      isCashIn ? (
        <TouchableOpacity style={localStyles.containerStyle}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{generalStrings.not_available}</Text>
          </View>
          <View style={localStyles.iconContainerStyle} />
        </TouchableOpacity>
      ) : (
        <TouchableOpacity style={localStyles.containerStyle} onPress={onPressReason}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{reasonText}</Text>
          </View>
          <View style={localStyles.iconContainerStyle}>
            <ChevronDownIcon />
          </View>
        </TouchableOpacity>
      ),
    [isCashIn, reason]
  );

  return (
    <>
      <View style={localStyles.modalContainerStyle}>
        <ToggleBar style={localStyles.toggleBarStyle} toggles={toggles} />
        <TouchableOpacity style={localStyles.containerStyle} onPress={onPressName}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{nameText}</Text>
          </View>
          <View style={localStyles.iconContainerStyle}>
            <ChevronDownIcon />
          </View>
        </TouchableOpacity>
        <TouchableOpacity style={localStyles.containerStyle} onPress={onPressAmount}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{amountText}</Text>
          </View>
          <View style={localStyles.iconContainerStyle}>
            <PencilIcon />
          </View>
        </TouchableOpacity>
        <PressReason />
        <TouchableOpacity style={localStyles.containerStyle} onPress={onPressDescription}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{descriptionText}</Text>
          </View>
          <View style={localStyles.iconContainerStyle}>
            <PencilIcon />
          </View>
        </TouchableOpacity>
        <BottomCurrencyEditor
          isOpen={isAmountModalOpen}
          buttonText={buttonStrings.confirm}
          value={amountBuffer}
          placeholder={dispensingStrings.enter_the_amount}
          onChangeText={onChangeAmount}
          onConfirm={onSubmitAmount}
        />
        <BottomModalContainer
          isOpen={isReasonModalOpen}
          modalStyle={localStyles.bottomModalContainerStyle}
        >
          <GenericChoiceList
            data={reasons}
            keyToDisplay={CASH_TRANSACTION_KEYS.REASON}
            onPress={onSubmitReason}
            highlightValue={reason?.title}
          />
        </BottomModalContainer>
        <BottomTextEditor
          isOpen={isDescriptionModalOpen}
          buttonText={buttonStrings.confirm}
          value={descriptionBuffer}
          placeholder={dispensingStrings.enter_a_description}
          onChangeText={onChangeText}
          onConfirm={onSubmitDescription}
        />
        <PageButton
          text={buttonStrings.confirm}
          onPress={onCreate}
          isDisabled={!isValidTransaction}
          disabledColor={WARM_GREY}
          style={localStyles.okButton}
          textStyle={localStyles.pageButtonTextStyle}
        />
      </View>
      <ModalContainer
        title={dispensingStrings.choose_a_name}
        isVisible={isNameModalOpen}
        onClose={onCloseName}
      >
        <AutocompleteSelector
          options={names}
          queryString="name CONTAINS[c] $0"
          sortKeyString="name"
          renderLeftText={renderNameLeftText}
          renderRightText={renderNameRightText}
          onSelect={onSubmitName}
        />
      </ModalContainer>
    </>
  );
};

CashTransactionModal.defaultProps = {};

CashTransactionModal.propTypes = {
  onConfirm: PropTypes.func.isRequired,
};

const localStyles = StyleSheet.create({
  modalContainerStyle: {
    flexDirection: 'column',
    flexGrow: 1,
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  containerStyle: {
    flexDirection: 'row',
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    minHeight: '10%',
  },
  bottomModalContainerStyle: {
    height: 120,
  },
  textContainerStyle: { width: '30%', justifyContent: 'center' },
  iconContainerStyle: { width: '5%', justifyContent: 'flex-end', alignItems: 'flex-end' },
  toggleBarStyle: { marginBottom: COMPONENT_HEIGHT },
  textStyle: { color: 'white' },
  okButton: {
    ...globalStyles.button,
    backgroundColor: SUSSOL_ORANGE,
    alignSelf: 'center',
    marginTop: 60,
  },
  pageButtonTextStyle: {
    ...globalStyles.buttonText,
    color: 'white',
    fontSize: 14,
  },
});
<commit_msg>Fix more missing cash register dependencies<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';

import moment from 'moment';
import currency from '../../localization/currency';

import { UIDatabase } from '../../database';
import {
  CASH_TRANSACTION_KEYS,
  CASH_TRANSACTION_TYPES,
} from '../../utilities/modules/dispensary/constants';

import { ToggleBar } from '../ToggleBar';
import { ModalContainer } from './ModalContainer';
import { BottomModalContainer, BottomTextEditor, BottomCurrencyEditor } from '../bottomModals';
import { GenericChoiceList, AutocompleteSelector } from '../modalChildren';
import { PageButton } from '../PageButton';
import { PencilIcon, ChevronDownIcon } from '../icons';

import globalStyles, { WARM_GREY, SUSSOL_ORANGE, COMPONENT_HEIGHT } from '../../globalStyles';
import { buttonStrings, dispensingStrings, generalStrings } from '../../localization';

export const CashTransactionModal = ({ onConfirm }) => {
  const [name, setName] = useState(null);
  const [isCashIn, setIsCashIn] = useState(true);
  const [amount, setAmount] = useState(null);
  const [reason, setReason] = useState(null);
  const [description, setDescription] = useState(null);

  const [amountBuffer, setAmountBuffer] = useState(currency(0).format());
  const [descriptionBuffer, setDescriptionBuffer] = useState('');

  const [isNameModalOpen, setIsNameModalOpen] = useState(false);
  const [isAmountModalOpen, setIsAmountModalOpen] = useState(false);
  const [isReasonModalOpen, setIsReasonModalOpen] = useState(false);
  const [isDescriptionModalOpen, setIsDescriptionModalOpen] = useState(false);

  const names = useMemo(() => UIDatabase.objects('CashTransactionName'), []);
  const reasons = useMemo(() => UIDatabase.objects('CashTransactionReason'), []);
  const type = useMemo(
    () => (isCashIn ? CASH_TRANSACTION_TYPES.CASH_IN : CASH_TRANSACTION_TYPES.CASH_OUT),
    [isCashIn]
  );

  const isValidTransaction = useMemo(() => !!name && !!amount && (isCashIn || !!reason), [
    name,
    amount,
    reason,
    isCashIn,
  ]);

  const onCreate = useCallback(
    () => onConfirm({ name, type, amount: amount.value, reason, description }),
    [name, type, amount, reason, description]
  );

  const onChangeText = useMemo(() => text => setDescriptionBuffer(text), []);
  const onChangeAmount = useMemo(() => value => setAmountBuffer(value), []);

  const renderNameLeftText = useCallback(
    ({ firstName, lastName, name: fullName, isPatient }) =>
      isPatient ? `${lastName}, ${firstName}` : `${fullName}`,
    []
  );

  const renderNameRightText = useCallback(({ isCustomer, isSupplier, isPatient, dateOfBirth }) => {
    if (isCustomer) {
      if (isPatient) {
        return `${dispensingStrings.patient} \n ${dispensingStrings.date_of_birth}: ${
          dateOfBirth ? moment(dateOfBirth).format('DD/MM/YYYY') : generalStrings.not_available
        }`;
      }
      return dispensingStrings.customer;
    }
    if (isSupplier) {
      return dispensingStrings.supplier;
    }
    return '';
  }, []);

  const resetBottomModal = () => {
    setIsNameModalOpen(false);
    setIsAmountModalOpen(false);
    setIsReasonModalOpen(false);
    setIsDescriptionModalOpen(false);
  };

  const onPressName = () => {
    resetBottomModal();
    setIsNameModalOpen(true);
  };

  const onPressAmount = () => {
    resetBottomModal();
    if (amount) {
      setAmountBuffer(amount.format(false));
    }
    setIsAmountModalOpen(true);
  };

  const onPressReason = () => {
    resetBottomModal();
    setIsReasonModalOpen(true);
  };

  const onPressDescription = () => {
    resetBottomModal();
    if (description) {
      setDescriptionBuffer(description);
    }
    setIsDescriptionModalOpen(true);
  };

  const onSubmitName = nameItem => {
    setName(nameItem);
    setIsNameModalOpen(false);
  };

  const onCloseName = () => setIsNameModalOpen(false);

  const onSubmitAmount = () => {
    setAmount(currency(amountBuffer));
    setIsAmountModalOpen(false);
  };

  const onSubmitReason = ({ item: reasonItem }) => {
    setReason(reasonItem);
    setIsReasonModalOpen(false);
  };

  const onSubmitDescription = () => {
    setDescription(descriptionBuffer);
    setIsDescriptionModalOpen(false);
  };

  const nameText = useMemo(() => name?.name ?? dispensingStrings.choose_a_name, [name]);
  const amountText = useMemo(() => amount?.format(false) ?? dispensingStrings.enter_the_amount, [
    amount,
  ]);
  const reasonText = useMemo(() => reason?.title ?? dispensingStrings.choose_a_reason, [reason]);
  const descriptionText = useMemo(() => description ?? dispensingStrings.enter_a_description, [
    description,
  ]);
  const toggleTransactionType = () => setIsCashIn(!isCashIn);

  const toggles = useMemo(
    () => [
      { text: dispensingStrings.cash_in, onPress: toggleTransactionType, isOn: isCashIn },
      { text: dispensingStrings.cash_out, onPress: toggleTransactionType, isOn: !isCashIn },
    ],
    [isCashIn]
  );

  const PressReason = useCallback(
    () =>
      isCashIn ? (
        <TouchableOpacity style={localStyles.containerStyle}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{generalStrings.not_available}</Text>
          </View>
          <View style={localStyles.iconContainerStyle} />
        </TouchableOpacity>
      ) : (
        <TouchableOpacity style={localStyles.containerStyle} onPress={onPressReason}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{reasonText}</Text>
          </View>
          <View style={localStyles.iconContainerStyle}>
            <ChevronDownIcon />
          </View>
        </TouchableOpacity>
      ),
    [isCashIn, reason]
  );

  return (
    <>
      <View style={localStyles.modalContainerStyle}>
        <ToggleBar style={localStyles.toggleBarStyle} toggles={toggles} />
        <TouchableOpacity style={localStyles.containerStyle} onPress={onPressName}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{nameText}</Text>
          </View>
          <View style={localStyles.iconContainerStyle}>
            <ChevronDownIcon />
          </View>
        </TouchableOpacity>
        <TouchableOpacity style={localStyles.containerStyle} onPress={onPressAmount}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{amountText}</Text>
          </View>
          <View style={localStyles.iconContainerStyle}>
            <PencilIcon />
          </View>
        </TouchableOpacity>
        <PressReason />
        <TouchableOpacity style={localStyles.containerStyle} onPress={onPressDescription}>
          <View style={localStyles.textContainerStyle}>
            <Text style={localStyles.textStyle}>{descriptionText}</Text>
          </View>
          <View style={localStyles.iconContainerStyle}>
            <PencilIcon />
          </View>
        </TouchableOpacity>
        <BottomCurrencyEditor
          isOpen={isAmountModalOpen}
          buttonText={buttonStrings.confirm}
          value={amountBuffer}
          placeholder={dispensingStrings.enter_the_amount}
          onChangeText={onChangeAmount}
          onConfirm={onSubmitAmount}
        />
        <BottomModalContainer
          isOpen={isReasonModalOpen}
          modalStyle={localStyles.bottomModalContainerStyle}
        >
          <GenericChoiceList
            data={reasons}
            keyToDisplay={CASH_TRANSACTION_KEYS.REASON}
            onPress={onSubmitReason}
            highlightValue={reason?.title}
          />
        </BottomModalContainer>
        <BottomTextEditor
          isOpen={isDescriptionModalOpen}
          buttonText={buttonStrings.confirm}
          value={descriptionBuffer}
          placeholder={dispensingStrings.enter_a_description}
          onChangeText={onChangeText}
          onConfirm={onSubmitDescription}
        />
        <PageButton
          text={buttonStrings.confirm}
          onPress={onCreate}
          isDisabled={!isValidTransaction}
          disabledColor={WARM_GREY}
          style={localStyles.okButton}
          textStyle={localStyles.pageButtonTextStyle}
        />
      </View>
      <ModalContainer
        title={dispensingStrings.choose_a_name}
        isVisible={isNameModalOpen}
        onClose={onCloseName}
      >
        <AutocompleteSelector
          options={names}
          queryString="name CONTAINS[c] $0"
          sortKeyString="name"
          renderLeftText={renderNameLeftText}
          renderRightText={renderNameRightText}
          onSelect={onSubmitName}
        />
      </ModalContainer>
    </>
  );
};

CashTransactionModal.defaultProps = {};

CashTransactionModal.propTypes = {
  onConfirm: PropTypes.func.isRequired,
};

const localStyles = StyleSheet.create({
  modalContainerStyle: {
    flexDirection: 'column',
    flexGrow: 1,
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  containerStyle: {
    flexDirection: 'row',
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    minHeight: '10%',
  },
  bottomModalContainerStyle: {
    height: 120,
  },
  textContainerStyle: { width: '30%', justifyContent: 'center' },
  iconContainerStyle: { width: '5%', justifyContent: 'flex-end', alignItems: 'flex-end' },
  toggleBarStyle: { marginBottom: COMPONENT_HEIGHT },
  textStyle: { color: 'white' },
  okButton: {
    ...globalStyles.button,
    backgroundColor: SUSSOL_ORANGE,
    alignSelf: 'center',
    marginTop: 60,
  },
  pageButtonTextStyle: {
    ...globalStyles.buttonText,
    color: 'white',
    fontSize: 14,
  },
});
<|endoftext|>


<commit_before>var results;
var topNumResults = 120;

function getTweets() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			results = xmlhttp.responseText;
			makeMapping(JSON.parse(results));
			makeWordCloud();
			$("#resultsTitle").html(twitterUsername + "'s last " + numTweets + " tweets:");
		}
    }

    var twitterUsername = document.getElementById('inputTwitterName').value;
    var numTweets = document.getElementById('inputNumTweets').value;
    xmlhttp.open("POST", "php/getTweets.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("inputTwitterUsername=" + twitterUsername + "&inputNumTweets=" + numTweets);
}

function makeMapping(rawJSON) {
	var sentences = [];
	for (var i = 0; i < rawJSON.length; ++i) {
		sentences[i] = rawJSON[i]["text"];
	}
	var dictionary = {};
	var common = "via,000,&amp,\\n,&lt,&gt,rt,http://t,https://t,i,me,my,myself,we,us,our,ours,ourselves,you,your,yours,yourself,yourselves,he,him,his,himself,she,her,hers,herself,it,its,itself,they,them,their,theirs,themselves,what,which,who,whom,whose,this,that,these,those,am,is,are,was,were,be,been,being,have,has,had,having,do,does,did,doing,will,would,should,can,could,ought,i'm,you're,he's,she's,it's,we're,they're,i've,you've,we've,they've,i'd,you'd,he'd,she'd,we'd,they'd,i'll,you'll,he'll,she'll,we'll,they'll,isn't,aren't,wasn't,weren't,hasn't,haven't,hadn't,doesn't,don't,didn't,won't,wouldn't,shan't,shouldn't,can't,cannot,couldn't,mustn't,let's,that's,who's,what's,here's,there's,when's,where's,why's,how's,a,an,the,and,but,if,or,because,as,until,while,of,at,by,for,with,about,against,between,into,through,during,before,after,above,below,to,from,up,upon,down,in,out,on,off,over,under,again,further,then,once,here,there,when,where,why,how,all,any,both,each,few,more,most,other,some,such,no,nor,not,only,own,same,so,than,too,very,say,says,said,shall";

        var word_count = {};
	for (var i = 0; i < sentences.length; ++i) {
		var theseWords = sentences[i].split(/[ \n\r'\-\(\)\*";\[\]|{},.!?]+/);
		for (var j = 0; j < theseWords.length; ++j) {
			var word = theseWords[j].toLowerCase();
			if (common.indexOf(word) == -1) {
				if (!dictionary[word]) {
					dictionary[word] = 0;
				}
				dictionary[word] += 1;
			}
		}
	}
  var sortedValues = [];
  for(a in dictionary) {
    tmp = {};
    tmp['text'] = a;
    tmp['size'] = dictionary[a];
    sortedValues.push(tmp);
  }
  sortedValues.sort(function(a,b) {return a['size']-b['size'];}).reverse();
	topResults = [];
	for (var i = 0; i < Math.min(topNumResults, sortedValues.length); ++i) {
		topResults[i] = sortedValues[i];
	}
	var topMin = topResults[topResults.length-1]['size'];
	var topMax = topResults[0]['size'];
	for (var i = 0; i < topResults.length; ++i) {
		var word = topResults[i];
		word['size'] = Math.floor(word['size'].map(topMin, topMax, 5, 120));
		topResults[i] = word;
	}
	topResultsForBlob = [];
	for (var i = 0; i < topResults.length; ++i) {
    var tmp = topResults[i];
    var newObj = {};
    newObj['text'] = tmp['text'];
    newObj['size'] = tmp['size'];
		topResultsForBlob[i] = newObj;
	}
}

Number.prototype.map = function (inMin, inMax, outMin, outMax) {
  return (this - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}

function saveTweet() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			console.log("successfully saved the tweet");
			console.log(xmlhttp.responseText);
		}
    }

    var twitterUsername = document.getElementById('inputTwitterName').value;
    var numTweets = document.getElementById('inputNumTweets').value;
    var json = topResultsForBlob;
    json = JSON.stringify(json);
    xmlhttp.open("POST", "php/saveTweet.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("inputTwitterUsername=" + twitterUsername + "&inputNumTweets=" + numTweets + "&json=" + json);
}

var test_pre_run = [{"text":"study","size":40},{"text":"motion","size":15},{"text":"forces","size":10},{"text":"electricity","size":15},{"text":"movement","size":10},{"text":"relation","size":5}];

var test = [{"text":"study","size":40},{"text":"motion","size":15},{"text":"forces","size":10},{"text":"electricity","size":15},{"text":"movement","size":10},{"text":"relation","size":5}];

var color = d3.scale.linear()
    .domain([0,1,2,3,4,5,6,10,15,20,100])
    .range(["#ddd", "#ccc", "#bbb", "#aaa", "#999", "#888", "#777", "#666", "#555", "#444", "#333", "#222"]);

function makeWordCloud() {
	$("#resultsWell").removeClass("hidden");

	d3.layout.cloud().size([900, 400])
	    .words(topResults)
	    .rotate(0)
	    .fontSize(function(d) { return d.size; })
	    .on("end", draw)
	    .start();
}

function draw(words) {
	$("svg").remove();
	d3.select("#chart").append("svg")
		.attr("width", 1200)
		.attr("height", 450)
		.attr("class", "wordcloud")
		.append("g")
		// without the transform, words words would get cutoff to the left and top, they would
		// appear outside of the SVG area
		.attr("transform", "translate(500,225)")
		.selectAll("text")
		.data(words)
		.enter().append("text")
		.style("font-size", function(d) { return d.size + "px"; })
		.style("fill", function(d, i) { return color(i); })
		.attr("transform", function(d) {
		    return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
		})
		.text(function(d) { return d.text; });
}
<commit_msg>whitespace issues<commit_after>var results;
var topNumResults = 120;

function getTweets() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			results = xmlhttp.responseText;
			makeMapping(JSON.parse(results));
			makeWordCloud();
			$("#resultsTitle").html(twitterUsername + "'s last " + numTweets + " tweets:");
		}
    }

    var twitterUsername = document.getElementById('inputTwitterName').value;
    var numTweets = document.getElementById('inputNumTweets').value;
    xmlhttp.open("POST", "php/getTweets.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("inputTwitterUsername=" + twitterUsername + "&inputNumTweets=" + numTweets);
}

function makeMapping(rawJSON) {
	var sentences = [];
	for (var i = 0; i < rawJSON.length; ++i) {
		sentences[i] = rawJSON[i]["text"];
	}
	var dictionary = {};
	var common = "via,000,&amp,\\n,&lt,&gt,rt,http://t,https://t,i,me,my,myself,we,us,our,ours,ourselves,you,your,yours,yourself,yourselves,he,him,his,himself,she,her,hers,herself,it,its,itself,they,them,their,theirs,themselves,what,which,who,whom,whose,this,that,these,those,am,is,are,was,were,be,been,being,have,has,had,having,do,does,did,doing,will,would,should,can,could,ought,i'm,you're,he's,she's,it's,we're,they're,i've,you've,we've,they've,i'd,you'd,he'd,she'd,we'd,they'd,i'll,you'll,he'll,she'll,we'll,they'll,isn't,aren't,wasn't,weren't,hasn't,haven't,hadn't,doesn't,don't,didn't,won't,wouldn't,shan't,shouldn't,can't,cannot,couldn't,mustn't,let's,that's,who's,what's,here's,there's,when's,where's,why's,how's,a,an,the,and,but,if,or,because,as,until,while,of,at,by,for,with,about,against,between,into,through,during,before,after,above,below,to,from,up,upon,down,in,out,on,off,over,under,again,further,then,once,here,there,when,where,why,how,all,any,both,each,few,more,most,other,some,such,no,nor,not,only,own,same,so,than,too,very,say,says,said,shall";

        var word_count = {};
	for (var i = 0; i < sentences.length; ++i) {
		var theseWords = sentences[i].split(/[ \n\r'\-\(\)\*";\[\]|{},.!?]+/);
		for (var j = 0; j < theseWords.length; ++j) {
			var word = theseWords[j].toLowerCase();
			if (common.indexOf(word) == -1) {
				if (!dictionary[word]) {
					dictionary[word] = 0;
				}
				dictionary[word] += 1;
			}
		}
	}
  	var sortedValues = [];
  	for(a in dictionary) {
    		tmp = {};
    		tmp['text'] = a;
    		tmp['size'] = dictionary[a];
    		sortedValues.push(tmp);
  	}
  	sortedValues.sort(function(a,b) {return a['size']-b['size'];}).reverse();
	topResults = [];
	for (var i = 0; i < Math.min(topNumResults, sortedValues.length); ++i) {
		topResults[i] = sortedValues[i];
	}
	var topMin = topResults[topResults.length-1]['size'];
	var topMax = topResults[0]['size'];
	for (var i = 0; i < topResults.length; ++i) {
		var word = topResults[i];
		word['size'] = Math.floor(word['size'].map(topMin, topMax, 5, 120));
		topResults[i] = word;
	}
	topResultsForBlob = [];
	for (var i = 0; i < topResults.length; ++i) {
    	var tmp = topResults[i];
    	var newObj = {};
    	newObj['text'] = tmp['text'];
    	newObj['size'] = tmp['size'];
		topResultsForBlob[i] = newObj;
	}
}

Number.prototype.map = function (inMin, inMax, outMin, outMax) {
	return (this - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}

function saveTweet() {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
        	if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			console.log("successfully saved the tweet");
			console.log(xmlhttp.responseText);
		}
	}

    	var twitterUsername = document.getElementById('inputTwitterName').value;
    	var numTweets = document.getElementById('inputNumTweets').value;
    	var json = topResultsForBlob;
    	json = JSON.stringify(json);
    	xmlhttp.open("POST", "php/saveTweet.php", true);
    	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    	xmlhttp.send("inputTwitterUsername=" + twitterUsername + "&inputNumTweets=" + numTweets + "&json=" + json);
}

var test_pre_run = [{"text":"study","size":40},{"text":"motion","size":15},{"text":"forces","size":10},{"text":"electricity","size":15},{"text":"movement","size":10},{"text":"relation","size":5}];

var test = [{"text":"study","size":40},{"text":"motion","size":15},{"text":"forces","size":10},{"text":"electricity","size":15},{"text":"movement","size":10},{"text":"relation","size":5}];

var color = d3.scale.linear()
    .domain([0,1,2,3,4,5,6,10,15,20,100])
    .range(["#ddd", "#ccc", "#bbb", "#aaa", "#999", "#888", "#777", "#666", "#555", "#444", "#333", "#222"]);

function makeWordCloud() {
	$("#resultsWell").removeClass("hidden");

	d3.layout.cloud().size([900, 400])
	    .words(topResults)
	    .rotate(0)
	    .fontSize(function(d) { return d.size; })
	    .on("end", draw)
	    .start();
}

function draw(words) {
	$("svg").remove();
	d3.select("#chart").append("svg")
		.attr("width", 1200)
		.attr("height", 450)
		.attr("class", "wordcloud")
		.append("g")
		// without the transform, words words would get cutoff to the left and top, they would
		// appear outside of the SVG area
		.attr("transform", "translate(500,225)")
		.selectAll("text")
		.data(words)
		.enter().append("text")
		.style("font-size", function(d) { return d.size + "px"; })
		.style("fill", function(d, i) { return color(i); })
		.attr("transform", function(d) {
		    return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
		})
		.text(function(d) { return d.text; });
}
<|endoftext|>


<commit_before>var Emit;
(function (Emit) {
    'use strict';

    function noop() {};

    function async(callback) {
        Promise.resolve().then(callback);
    }

    function create(source, done) {
        var toFilter = typeof Sequences !== 'undefined' ?
            Sequences.toFilter :
            function (f) { return f; };

        function pump(generator) {
            var iterator = generator();
            source(function notify(v) {
                var r = iterator.next(v);
                if (r.done && typeof done === 'function') {
                    done(notify);
                }
            }, function exception(e) {
                iterator.throw(e);
            });
            iterator.next();
        }

        function forEach(callback, report) {
            callback || (callback = noop);
            report || (report = function (e) { throw e; });
            pump(function* () {
                while (true) {
                    try {
                        callback(yield);
                    } catch (e) {
                        report(e);
                    }
                }
            });
            return this;
        }

        return {
            isEmitter: true,

            forEach: forEach,
            then: forEach,
            match: function match(filter) {
                var callback = toFilter(filter);
                var resolved = noop;
                var resolvedRethrow = noop;
                var rejected = noop;
                var rejectedRethrow = noop;
                pump(function* () {
                    while (true) {
                        try {
                            var v = yield;
                            (callback(v) ? resolved : rejected)(v);
                        } catch (e) {
                            resolvedRethrow(e);
                            rejectedRethrow(e);
                        }
                    }
                });
                return {
                    resolved: Emit.create(function (notify, rethrow) {
                        resolved = notify;
                        resolvedRethrow = rethrow;
                    }),
                    rejected: Emit.create(function (notify, rethrow) {
                        rejected = notify;
                        rejectedRethrow = rethrow;
                    })
                };
            },
            filter: function filter(filter) {
                return this.match(filter).resolved;
            },
            map: function map(callback, fixer) {
                callback || (callback = function (v) { return v; });
                fixer || (fixer = function (e) { throw e; });
                return Emit.create(function (notify, rethrow) {
                    pump(function* () {
                        try {
                            while (true) {
                                notify(callback(yield));
                            }
                        } catch (e) {
                            try {
                                notify(fixer(e));
                            } catch (ee) {
                                rethrow(ee);
                            }
                        }
                    });
                });
            },
            until: function until(filter) {
                var callback;
                if (filter.isEmitter) {
                    var finished = false;
                    filter.head().forEach(function () {
                        finished = true;
                    });
                    callback = function () {
                        return finished;
                    };
                } else {
                    callback = toFilter(filter);
                }
                return Emit.create(function (notify, rethrow) {
                    pump(function* () {
                        while (true) {
                            try {
                                var v = yield;
                                if (callback(v)) {
                                    break;
                                }
                                notify(v);
                            } catch (e) {
                                rethrow(e);
                            }
                        }
                    });
                });
            },
            head: function head(number) {
                number = typeof number === 'undefined' ? 1 : Number(number);
                return Emit.create(function (notify, rethrow) {
                    pump(function* () {
                        for (var i = 0; i < number; ++i) {
                            try {
                                notify(yield);
                            } catch (e) {
                                rethrow(e);
                            }
                        }
                    });
                });
            },
            delay: function delay(duration) {
                return Emit.create(function (notify, rethrow) {
                    pump(function* () {
                        while (true) {
                            try {
                                setTimeout(notify.bind(null, yield), duration);
                            } catch (e) {
                                rethrow(e);
                            }
                        }
                    });
                });
            }
        };
    }

    function join(args, isReady) {
        var emitters = args.length === 1 ? args[0] : Array.prototype.slice.call(args, 0);
        var done = false;

        function isDone() {
            return done;
        }

        return Emit.create(function (notify, rethrow) {
            var values = emitters.map(function () { return undefined; });
            var states = emitters.map(function () { return false; });
            function update(index, value) {
                values[index] = value;
                states[index] = true;
                if (isReady(states)) {
                    notify(values.slice(0));
                }
            }
            emitters.forEach(function (emitter, index) {
                emitter.until(isDone).forEach(update.bind(null, index), rethrow);
            });
        }, function () {
            done = true;
        });
    }

    Object.defineProperties(Emit, {
        create: {
            writable: true,
            value: create
        },
        value: {
            writable: true,
            value: function value(v) {
                return Emit.create(function (notify) {
                    async(notify.bind(null, v));
                });
            }
        },
        sequence: {
            writable: true,
            value: function sequence(s) {
                return Emit.create(function (notify, rethrow) {
                    async(function () {
                        try {
                            s.forEach(notify);
                        } catch (e) {
                            rethrow(e);
                        }
                    });
                });
            }
        },
        merge: {
            writable: true,
            value: function merge() {
                var emitters = arguments.length === 1 ? arguments[0] : Array.prototype.slice.call(arguments, 0);
                return Emit.create(function (notify, rethrow) {
                    emitters.forEach(function (emitter) {
                        Emit.sequence(emitter).forEach(notify, rethrow);
                    });
                });
            }
        },
        sync: {
            writable: true,
            value: function sync() {
                return join(arguments,
                    function isReady(states) {
                        if (states.every(function (state) { return state; })) {
                            states.forEach(function (state, index, array) { array[index] = false; });
                            return true;
                        }
                        return false;
                    }
                );
            }
        },
        combine: {
            writable: true,
            value: function combine() {
                var ready = false;
                return join(arguments,
                    function isReady(states) {
                        if (ready || states.every(function (state) { return state; })) {
                            ready = true;
                            return true;
                        }
                        return false;
                    }
                );
            }
        },
        events: {
            writable: true,
            value: function events(type, element) {
                return Emit.create(function (notify) {
                    element.addEventListener(type, notify, false);
                }, function (notify) {
                    element.removeEventListener(type, notify, false);
                });
            }
        },
        animationFrames: {
            writable: true,
            value: function animationFrames() {
                var id;
                return Emit.create(function (notify) {
                    id = window.requestAnimationFrame(function raf(timestamp) {
                        notify(timestamp);
                        id = window.requestAnimationFrame(raf);
                    });
                }, function () {
                    window.cancelAnimationFrame(id);
                });
            }
        },
        interval: {
            writable: true,
            value: function interval() {
                var args = Array.prototype.slice.call(arguments, 0);
                var id;
                return Emit.create(function (notify) {
                    id = window.setInterval.apply(window, [notify].concat(args));
                }, function () {
                    window.clearInterval(id);
                });
            }
        },
        promise: {
            writable: true,
            value: function promise(p) {
                return Emit.create(function (notify, rethrow) {
                    p.then(notify, rethrow);
                });
            }
        }
    });
}(Emit || (Emit = {})));
<commit_msg>fold prmise into value (as thenable)<commit_after>var Emit;
(function (Emit) {
    'use strict';

    function noop() {};

    function async(callback) {
        Promise.resolve().then(callback);
    }

    function create(source, done) {
        var toFilter = typeof Sequences !== 'undefined' ?
            Sequences.toFilter :
            function (f) { return f; };

        function pump(generator) {
            var iterator = generator();
            source(function notify(v) {
                var r = iterator.next(v);
                if (r.done && typeof done === 'function') {
                    done(notify);
                }
            }, function exception(e) {
                iterator.throw(e);
            });
            iterator.next();
        }

        function forEach(callback, report) {
            callback || (callback = noop);
            report || (report = function (e) { throw e; });
            pump(function* () {
                while (true) {
                    try {
                        callback(yield);
                    } catch (e) {
                        report(e);
                    }
                }
            });
            return this;
        }

        return {
            isEmitter: true,

            forEach: forEach,
            then: forEach,
            match: function match(filter) {
                var callback = toFilter(filter);
                var resolved = noop;
                var resolvedRethrow = noop;
                var rejected = noop;
                var rejectedRethrow = noop;
                pump(function* () {
                    while (true) {
                        try {
                            var v = yield;
                            (callback(v) ? resolved : rejected)(v);
                        } catch (e) {
                            resolvedRethrow(e);
                            rejectedRethrow(e);
                        }
                    }
                });
                return {
                    resolved: Emit.create(function (notify, rethrow) {
                        resolved = notify;
                        resolvedRethrow = rethrow;
                    }),
                    rejected: Emit.create(function (notify, rethrow) {
                        rejected = notify;
                        rejectedRethrow = rethrow;
                    })
                };
            },
            filter: function filter(filter) {
                return this.match(filter).resolved;
            },
            map: function map(callback, fixer) {
                callback || (callback = function (v) { return v; });
                fixer || (fixer = function (e) { throw e; });
                return Emit.create(function (notify, rethrow) {
                    pump(function* () {
                        try {
                            while (true) {
                                notify(callback(yield));
                            }
                        } catch (e) {
                            try {
                                notify(fixer(e));
                            } catch (ee) {
                                rethrow(ee);
                            }
                        }
                    });
                });
            },
            until: function until(filter) {
                var callback;
                if (filter.isEmitter) {
                    var finished = false;
                    filter.head().forEach(function () {
                        finished = true;
                    });
                    callback = function () {
                        return finished;
                    };
                } else {
                    callback = toFilter(filter);
                }
                return Emit.create(function (notify, rethrow) {
                    pump(function* () {
                        while (true) {
                            try {
                                var v = yield;
                                if (callback(v)) {
                                    break;
                                }
                                notify(v);
                            } catch (e) {
                                rethrow(e);
                            }
                        }
                    });
                });
            },
            head: function head(number) {
                number = typeof number === 'undefined' ? 1 : Number(number);
                return Emit.create(function (notify, rethrow) {
                    pump(function* () {
                        for (var i = 0; i < number; ++i) {
                            try {
                                notify(yield);
                            } catch (e) {
                                rethrow(e);
                            }
                        }
                    });
                });
            },
            delay: function delay(duration) {
                return Emit.create(function (notify, rethrow) {
                    pump(function* () {
                        while (true) {
                            try {
                                setTimeout(notify.bind(null, yield), duration);
                            } catch (e) {
                                rethrow(e);
                            }
                        }
                    });
                });
            }
        };
    }

    function join(args, isReady) {
        var emitters = args.length === 1 ? args[0] : Array.prototype.slice.call(args, 0);
        var done = false;

        function isDone() {
            return done;
        }

        return Emit.create(function (notify, rethrow) {
            var values = emitters.map(function () { return undefined; });
            var states = emitters.map(function () { return false; });
            function update(index, value) {
                values[index] = value;
                states[index] = true;
                if (isReady(states)) {
                    notify(values.slice(0));
                }
            }
            emitters.forEach(function (emitter, index) {
                emitter.until(isDone).forEach(update.bind(null, index), rethrow);
            });
        }, function () {
            done = true;
        });
    }

    Object.defineProperties(Emit, {
        create: {
            writable: true,
            value: create
        },
        value: {
            writable: true,
            value: function value(v) {
                return Emit.create(function (notify) {
                    if (v && typeof v.then === 'function') {
                        v.then(notify, rethrow);
                    } else {
                        async(notify.bind(null, v));
                    }
                });
            }
        },
        sequence: {
            writable: true,
            value: function sequence(s) {
                return Emit.create(function (notify, rethrow) {
                    async(function () {
                        try {
                            s.forEach(notify);
                        } catch (e) {
                            rethrow(e);
                        }
                    });
                });
            }
        },
        merge: {
            writable: true,
            value: function merge() {
                var emitters = arguments.length === 1 ? arguments[0] : Array.prototype.slice.call(arguments, 0);
                return Emit.create(function (notify, rethrow) {
                    emitters.forEach(function (emitter) {
                        Emit.sequence(emitter).forEach(notify, rethrow);
                    });
                });
            }
        },
        sync: {
            writable: true,
            value: function sync() {
                return join(arguments,
                    function isReady(states) {
                        if (states.every(function (state) { return state; })) {
                            states.forEach(function (state, index, array) { array[index] = false; });
                            return true;
                        }
                        return false;
                    }
                );
            }
        },
        combine: {
            writable: true,
            value: function combine() {
                var ready = false;
                return join(arguments,
                    function isReady(states) {
                        if (ready || states.every(function (state) { return state; })) {
                            ready = true;
                            return true;
                        }
                        return false;
                    }
                );
            }
        },
        events: {
            writable: true,
            value: function events(type, element) {
                return Emit.create(function (notify) {
                    element.addEventListener(type, notify, false);
                }, function (notify) {
                    element.removeEventListener(type, notify, false);
                });
            }
        },
        animationFrames: {
            writable: true,
            value: function animationFrames() {
                var id;
                return Emit.create(function (notify) {
                    id = window.requestAnimationFrame(function raf(timestamp) {
                        notify(timestamp);
                        id = window.requestAnimationFrame(raf);
                    });
                }, function () {
                    window.cancelAnimationFrame(id);
                });
            }
        },
        interval: {
            writable: true,
            value: function interval() {
                var args = Array.prototype.slice.call(arguments, 0);
                var id;
                return Emit.create(function (notify) {
                    id = window.setInterval.apply(window, [notify].concat(args));
                }, function () {
                    window.clearInterval(id);
                });
            }
        }
    });
}(Emit || (Emit = {})));
<|endoftext|>