<commit_before>var wowtoken = {

    timeLeftMap: {
        names: ['',
            'less than 30 mins',
            '30 mins to 2 hours',
            '2 to 12 hours',
            'over 12 hours'
        ]
    },

    NumberCommas: function(v) {
        return (''+v).split("").reverse().join("").replace(/(\d{3})(?=\d)/g, '$1,').split("").reverse().join("");
    },

    Storage: {
        Get: function (key)
        {
            if (!window.localStorage) {
                return false;
            }

            var v = window.localStorage.getItem(key);
            if (v != null) {
                return JSON.parse(v);
            }
            else {
                return false;
            }
        },
        Set: function (key, val)
        {
            if (!window.localStorage) {
                return false;
            }

            window.localStorage.setItem(key, JSON.stringify(val));
        },
        Remove: function (key, val)
        {
            if (!window.localStorage) {
                return false;
            }

            window.localStorage.removeItem(key);
        }
    },

    Main: function ()
    {
        wowtoken.LastVisitCheck();
        wowtoken.LoadHistory();
        window.setTimeout(wowtoken.UpdateCheck, 60000*5);
    },

    LastVisitCheck: function()
    {
        var moveFAQ = false;

        var lv = wowtoken.Storage.Get('lastvisit');
        if (lv) {
            lv = parseInt(lv, 10);
            moveFAQ |= (lv > Date.now() - (10 * 24 * 60 * 60 * 1000));
        }
        wowtoken.Storage.Set('lastvisit', Date.now());

        if (moveFAQ) {
            var panelFAQ = document.getElementById('faq-panel');
            var panelLinks = document.getElementById('links-panel');
            if (panelFAQ && panelLinks) {
                panelLinks.parentNode.insertBefore(panelFAQ, panelLinks);
            }
        }
    },

    LoadHistory: function ()
    {
        $.ajax({
            success: function (d)
            {
                wowtoken.ShowHistory(d);
            },
            url: '/history.json'
        });
    },

    ShowHistory: function (d)
    {
        var dest;
        for (var region in d) {

            if (d[region].length) {
                dest = document.getElementById('hc-'+region.toLowerCase());
                dest.className = 'hc';
                wowtoken.ShowChart(region, d[region], dest);
            }
        }
    },

    UpdateCheck: function ()
    {
        $.ajax({
            success: function (d)
            {
                wowtoken.ParseUpdate(d);
            },
            url: '/now.json'
        });
    },

    ParseUpdate: function (d)
    {
        for (var region in d) {
            if (!d[region].hasOwnProperty('formatted')) {
                continue;
            }
            for (var attrib in d[region].formatted) {
                $('#'+region+'-'+attrib).html(d[region].formatted[attrib]);
            }
        }
        window.setTimeout(wowtoken.UpdateCheck, 60000*5);
    },

    ShowChart: function(region, dta, dest) {
        var hcdata = { buy: [], timeleft: {}, navigator: [], zones: [] };
        var maxPrice = 0;
        var o, showLabel, direction = 0, newDirection = 0, lastLabel = -1;
        var lastTimeLeft = -1;
        var labelFormatter = function() {
            return wowtoken.NumberCommas(this.y) + 'g';
        };
        var colors = {
            'line': '#0000ff',
            'fill': 'rgba(204,204,255,0.6)',
            'text': '#000099',
            'timeleft': [
                'rgba(204,204,255,0.6)',
                'rgba(204,204,255,0.6)',
                'rgba(178,178,229,0.6)',
                'rgba(153,153,204,0.6)',
                'rgba(127,127,178,0.6)',
            ],
        }
        if (region == 'EU') {
            colors = {
                'line': '#ff0000',
                'fill': 'rgba(255,204,204,0.6)',
                'text': '#990000',
                'timeleft': [
                    'rgba(255,204,204,0.6)',
                    'rgba(255,204,204,0.6)',
                    'rgba(229,178,178,0.6)',
                    'rgba(204,153,153,0.6)',
                    'rgba(178,127,127,0.6)',
                ],
            }
        }
        for (var x = 0; x < dta.length; x++) {
            o = {
                x: dta[x][0]*1000,
                y: dta[x][1],
                //color: wowtoken.timeLeftMap.colors[dta[x][2]]
            };
            hcdata.navigator.push([dta[x][0]*1000, dta[x][1]]);
            if (lastTimeLeft != dta[x][2]) {
                if (lastTimeLeft != -1) {
                    hcdata.zones.push({
                        value: o.x,
                        fillColor: colors.timeleft[lastTimeLeft],
                    });
                }
                lastTimeLeft = dta[x][2];
            }
            showLabel = false;
            if (x + 1 < dta.length) {
                if (o.y != dta[x+1][1]) {
                    newDirection = o.y > dta[x+1][1] ? -1 : 1;
                    if (newDirection != direction) {
                        showLabel |= direction != 0;
                        direction = newDirection;
                    }
                }
            }
            showLabel &= ((lastLabel == -1) || (lastLabel + 5 < x));
            if (showLabel) {
                lastLabel = x;
                o.dataLabels = {
                    enabled: true,
                    formatter: labelFormatter,
                    x: 0,
                    y: -5,
                    color: 'black',
                    rotation: 360-45,
                    align: 'left',
                    crop: false,
                };
                if (direction == 1) {
                    o.dataLabels.y = 10;
                    o.dataLabels.rotation = 45;
                }
                o.marker = {
                    enabled: true,
                    radius: 3,
                }
            }
            hcdata.buy.push(o);
            hcdata.timeleft[dta[x][0]*1000] = dta[x][2];
            if (maxPrice < dta[x][1]) {
                maxPrice = dta[x][1];
            }
        }
        if (hcdata.zones.length) {
            hcdata.zones.push({
                color: colors.timeleft[lastTimeLeft]
            });
        }

        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        $(dest).highcharts('StockChart', {
            chart: {
                zoomType: 'x',
                backgroundColor: '#f6fff6'
            },
            rangeSelector: {
                buttons: [
                    {
                        type: 'day',
                        count: 3,
                        text: '3d'
                    },
                    {
                        type: 'week',
                        count: 1,
                        text: '1w'
                    },
                    {
                        type: 'week',
                        count: 2,
                        text: '2w'
                    },
                    {
                        type: 'month',
                        count: 1,
                        text: '1m'
                    },
                    {
                        type: 'month',
                        count: 3,
                        text: '3m'
                    },
                    {
                        type: 'all',
                        text: 'all'
                    },
                ],
                selected: 1,
                inputEnabled: false
            },
            navigator: {
                series: {
                    type: 'area',
                    name: 'Market Price',
                    color: colors.line,
                    lineColor: colors.line,
                    fillColor: colors.fill,
                    data: hcdata.navigator
                }
            },
            title: {
                text: null
            },
            subtitle: {
                text: document.ontouchstart === undefined ?
                    'Click and drag in the plot area to zoom in' :
                    'Pinch the chart to zoom in',
                style: {
                    color: 'black'
                }
            },
            xAxis: {
                type: 'datetime',
                minRange: 4 * 3600000, // four hours
                title: {
                    text: null
                },
                labels: {
                    style: {
                        color: 'black'
                    }
                },
                units: [['hour',[6,12]],['day',[1]]],
                ordinal: false,
            },
            yAxis: [
                {
                    title: {
                        enabled: false
                    },
                    labels: {
                        enabled: true,
                        formatter: function ()
                        {
                            return document.ontouchstart === undefined ?
                                '' + wowtoken.NumberCommas(this.value) + 'g' :
                                '' + Math.floor(this.value/1000) + 'k' ;
                        },
                        style: {
                            color: 'black'
                        }
                    },
                    min: 0,
                    max: maxPrice
                }
            ],
            legend: {
                enabled: false
            },
            tooltip: {
                shared: true,
                formatter: function ()
                {
                    var tr = '' + Highcharts.dateFormat('%a %b %d, %I:%M%P', this.x) + '';
                    tr += '
Price: ' + wowtoken.NumberCommas(this.points[0].y) + 'g';
                    tr += '
Sells in: ' + wowtoken.timeLeftMap.names[hcdata.timeleft[this.x]] + '';
                    return tr;
                }
            },
            plotOptions: {
                area: {
                    dataGrouping: {
                        enabled: false
                    }
                },
                series: {
                    lineWidth: 2,
                    marker: {
                        enabled: false,
                        radius: 1,
                        states: {
                            hover: {
                                enabled: true
                            }
                        }
                    },
                    animation: false,
                    turboThreshold: 0,
                }
            },
            series: [
                {
                    type: 'area',
                    name: 'Market Price',
                    color: colors.line,
                    lineColor: colors.line,
                    fillColor: colors.fill,
                    data: hcdata.buy,
                    zoneAxis: 'x',
                    zones: hcdata.zones
                }
            ]
        });
    }
}

$(document).ready(wowtoken.Main);
<commit_msg>fix fillcolor<commit_after>var wowtoken = {

    timeLeftMap: {
        names: ['',
            'less than 30 mins',
            '30 mins to 2 hours',
            '2 to 12 hours',
            'over 12 hours'
        ]
    },

    NumberCommas: function(v) {
        return (''+v).split("").reverse().join("").replace(/(\d{3})(?=\d)/g, '$1,').split("").reverse().join("");
    },

    Storage: {
        Get: function (key)
        {
            if (!window.localStorage) {
                return false;
            }

            var v = window.localStorage.getItem(key);
            if (v != null) {
                return JSON.parse(v);
            }
            else {
                return false;
            }
        },
        Set: function (key, val)
        {
            if (!window.localStorage) {
                return false;
            }

            window.localStorage.setItem(key, JSON.stringify(val));
        },
        Remove: function (key, val)
        {
            if (!window.localStorage) {
                return false;
            }

            window.localStorage.removeItem(key);
        }
    },

    Main: function ()
    {
        wowtoken.LastVisitCheck();
        wowtoken.LoadHistory();
        window.setTimeout(wowtoken.UpdateCheck, 60000*5);
    },

    LastVisitCheck: function()
    {
        var moveFAQ = false;

        var lv = wowtoken.Storage.Get('lastvisit');
        if (lv) {
            lv = parseInt(lv, 10);
            moveFAQ |= (lv > Date.now() - (10 * 24 * 60 * 60 * 1000));
        }
        wowtoken.Storage.Set('lastvisit', Date.now());

        if (moveFAQ) {
            var panelFAQ = document.getElementById('faq-panel');
            var panelLinks = document.getElementById('links-panel');
            if (panelFAQ && panelLinks) {
                panelLinks.parentNode.insertBefore(panelFAQ, panelLinks);
            }
        }
    },

    LoadHistory: function ()
    {
        $.ajax({
            success: function (d)
            {
                wowtoken.ShowHistory(d);
            },
            url: '/history.json'
        });
    },

    ShowHistory: function (d)
    {
        var dest;
        for (var region in d) {

            if (d[region].length) {
                dest = document.getElementById('hc-'+region.toLowerCase());
                dest.className = 'hc';
                wowtoken.ShowChart(region, d[region], dest);
            }
        }
    },

    UpdateCheck: function ()
    {
        $.ajax({
            success: function (d)
            {
                wowtoken.ParseUpdate(d);
            },
            url: '/now.json'
        });
    },

    ParseUpdate: function (d)
    {
        for (var region in d) {
            if (!d[region].hasOwnProperty('formatted')) {
                continue;
            }
            for (var attrib in d[region].formatted) {
                $('#'+region+'-'+attrib).html(d[region].formatted[attrib]);
            }
        }
        window.setTimeout(wowtoken.UpdateCheck, 60000*5);
    },

    ShowChart: function(region, dta, dest) {
        var hcdata = { buy: [], timeleft: {}, navigator: [], zones: [] };
        var maxPrice = 0;
        var o, showLabel, direction = 0, newDirection = 0, lastLabel = -1;
        var lastTimeLeft = -1;
        var labelFormatter = function() {
            return wowtoken.NumberCommas(this.y) + 'g';
        };
        var colors = {
            'line': '#0000ff',
            'fill': 'rgba(204,204,255,0.6)',
            'text': '#000099',
            'timeleft': [
                'rgba(204,204,255,0.6)',
                'rgba(204,204,255,0.6)',
                'rgba(178,178,229,0.6)',
                'rgba(153,153,204,0.6)',
                'rgba(127,127,178,0.6)',
            ],
        }
        if (region == 'EU') {
            colors = {
                'line': '#ff0000',
                'fill': 'rgba(255,204,204,0.6)',
                'text': '#990000',
                'timeleft': [
                    'rgba(255,204,204,0.6)',
                    'rgba(255,204,204,0.6)',
                    'rgba(229,178,178,0.6)',
                    'rgba(204,153,153,0.6)',
                    'rgba(178,127,127,0.6)',
                ],
            }
        }
        for (var x = 0; x < dta.length; x++) {
            o = {
                x: dta[x][0]*1000,
                y: dta[x][1],
                //color: wowtoken.timeLeftMap.colors[dta[x][2]]
            };
            hcdata.navigator.push([dta[x][0]*1000, dta[x][1]]);
            if (lastTimeLeft != dta[x][2]) {
                if (lastTimeLeft != -1) {
                    hcdata.zones.push({
                        value: o.x,
                        fillColor: colors.timeleft[lastTimeLeft],
                    });
                }
                lastTimeLeft = dta[x][2];
            }
            showLabel = false;
            if (x + 1 < dta.length) {
                if (o.y != dta[x+1][1]) {
                    newDirection = o.y > dta[x+1][1] ? -1 : 1;
                    if (newDirection != direction) {
                        showLabel |= direction != 0;
                        direction = newDirection;
                    }
                }
            }
            showLabel &= ((lastLabel == -1) || (lastLabel + 5 < x));
            if (showLabel) {
                lastLabel = x;
                o.dataLabels = {
                    enabled: true,
                    formatter: labelFormatter,
                    x: 0,
                    y: -5,
                    color: 'black',
                    rotation: 360-45,
                    align: 'left',
                    crop: false,
                };
                if (direction == 1) {
                    o.dataLabels.y = 10;
                    o.dataLabels.rotation = 45;
                }
                o.marker = {
                    enabled: true,
                    radius: 3,
                }
            }
            hcdata.buy.push(o);
            hcdata.timeleft[dta[x][0]*1000] = dta[x][2];
            if (maxPrice < dta[x][1]) {
                maxPrice = dta[x][1];
            }
        }
        if (hcdata.zones.length) {
            hcdata.zones.push({
                fillColor: colors.timeleft[lastTimeLeft]
            });
        }

        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        $(dest).highcharts('StockChart', {
            chart: {
                zoomType: 'x',
                backgroundColor: '#f6fff6'
            },
            rangeSelector: {
                buttons: [
                    {
                        type: 'day',
                        count: 3,
                        text: '3d'
                    },
                    {
                        type: 'week',
                        count: 1,
                        text: '1w'
                    },
                    {
                        type: 'week',
                        count: 2,
                        text: '2w'
                    },
                    {
                        type: 'month',
                        count: 1,
                        text: '1m'
                    },
                    {
                        type: 'month',
                        count: 3,
                        text: '3m'
                    },
                    {
                        type: 'all',
                        text: 'all'
                    },
                ],
                selected: 1,
                inputEnabled: false
            },
            navigator: {
                series: {
                    type: 'area',
                    name: 'Market Price',
                    color: colors.line,
                    lineColor: colors.line,
                    fillColor: colors.fill,
                    data: hcdata.navigator
                }
            },
            title: {
                text: null
            },
            subtitle: {
                text: document.ontouchstart === undefined ?
                    'Click and drag in the plot area to zoom in' :
                    'Pinch the chart to zoom in',
                style: {
                    color: 'black'
                }
            },
            xAxis: {
                type: 'datetime',
                minRange: 4 * 3600000, // four hours
                title: {
                    text: null
                },
                labels: {
                    style: {
                        color: 'black'
                    }
                },
                units: [['hour',[6,12]],['day',[1]]],
                ordinal: false,
            },
            yAxis: [
                {
                    title: {
                        enabled: false
                    },
                    labels: {
                        enabled: true,
                        formatter: function ()
                        {
                            return document.ontouchstart === undefined ?
                                '' + wowtoken.NumberCommas(this.value) + 'g' :
                                '' + Math.floor(this.value/1000) + 'k' ;
                        },
                        style: {
                            color: 'black'
                        }
                    },
                    min: 0,
                    max: maxPrice
                }
            ],
            legend: {
                enabled: false
            },
            tooltip: {
                shared: true,
                formatter: function ()
                {
                    var tr = '' + Highcharts.dateFormat('%a %b %d, %I:%M%P', this.x) + '';
                    tr += '
Price: ' + wowtoken.NumberCommas(this.points[0].y) + 'g';
                    tr += '
Sells in: ' + wowtoken.timeLeftMap.names[hcdata.timeleft[this.x]] + '';
                    return tr;
                }
            },
            plotOptions: {
                area: {
                    dataGrouping: {
                        enabled: false
                    }
                },
                series: {
                    lineWidth: 2,
                    marker: {
                        enabled: false,
                        radius: 1,
                        states: {
                            hover: {
                                enabled: true
                            }
                        }
                    },
                    animation: false,
                    turboThreshold: 0,
                }
            },
            series: [
                {
                    type: 'area',
                    name: 'Market Price',
                    color: colors.line,
                    lineColor: colors.line,
                    fillColor: colors.fill,
                    data: hcdata.buy,
                    zoneAxis: 'x',
                    zones: hcdata.zones
                }
            ]
        });
    }
}

$(document).ready(wowtoken.Main);
<|endoftext|>


<commit_before>(function($){
	$(function(){
		var $form = $('#esajaxform');
		var $selected = $('#facet-selected');
		var $replace = $(window.esfaceting.replace).css('position','relative');

		var onresponse = function(data){
			$selected.find('.facet-item.removable').hide();

			$.each(data.faceting, function(type){
				var container = $("#facet-" + type + '-available');
				var me = this;

				if(me.min > 0){
					container.find('.facet-item').hide();

					if(me.min < data.found){
						$.each(this.available, function(slug){
							if(this.count > 0 && this.count < data.found){
								var li = $("#facet-" + type + '-' + slug);

								li.find('.count').text('(' + this.count + ')').show();
								li.show();
								container.show();
							}
						});

						if(window.esselected && window.esselected.showEmpty == 1){
							container.find('.facet-empty').hide();
						}
					}else{
						if(window.esselected && window.esselected.showEmpty == 1){
							container.find('.facet-empty').show();
						}else{
							container.hide();
						}
					}
				}else{
					container.hide();
				}

				$.each(this.selected, function(slug){
					var li = $("#facet-" + type + '-' + slug);

					if(!window.esselected || window.esselected.showEmpty != 1 || total < data.found){
						li.find('.count').hide();
						li.show();
					}

					$("#facet-" + type + '-' + slug + '-selected').show();
				});
			});

			if($selected.find('.facet-item:visible').length > 0){
				$selected.show();
			}

			//$replace.empty().html(data.content);
			//$(document).scrollTop($replace.offset().top);
			//overlay.remove();
		};

		var buildQuery = function(){
			var s = [];

			var terms = $selected.find('.term');
			terms.each(function(){
				s.push($(this).data('term'));
			});

			if(terms.length == 1){
				terms.each(function(){
					$(this).removeClass('removable').html($(this).text());
				});
			}

			return $form.serialize() + '&esasync=1&s=' + s.join(' ');
		}

		var overlay = null;

		var showoverlay = function(){
			overlay = $('

').css({
				'position':'absolute',
				'top': '0',
				'left': '0',
				'width': '100%',
				'height': '100%',
				'background-color': '#858585',
				'z-index': 2147483646,
				'opacity': 0.8
			}).prependTo($replace);
		};

		$form.find('input[type=checkbox]').change(function(){
			var url = $form.attr('action');

			showoverlay();

			$.getJSON(url, buildQuery(), onresponse);
		});

		$('.esclear').click(function(){
			$form[0].reset();

			showoverlay();

			$.getJSON($(this).attr('href'), buildQuery(), onresponse);

			return false;
		});

		$selected.find('.term a').click(function(){
			$(this).parent().remove();

			var s = '';

			var terms = $selected.find('.term');
			terms.each(function(){
				s += $(this).data('term');
			});

			if(terms.length == 1){
				terms.each(function(){
					$(this).removeClass('removable').html($(this).text());
				});
			}

			showoverlay();

			$.getJSON('#', buildQuery(), function(data){
				$(this).parent().remove();

				onresponse(data);
			});

			return false;
		});

		$selected.find('.facet-item a').click(function(){
			var selector = $(this).attr('href');

			$(selector).find('input').click();

			return false;
		});

		$(document).on('click', '.pagination a, .navigation a', function(){
			showoverlay();

			$.getJSON($(this).attr('href'), $form.serialize() + '&esasync=1', onresponse);

			return false;
		});
	});
})(jQuery);<commit_msg>uncomment<commit_after>(function($){
	$(function(){
		var $form = $('#esajaxform');
		var $selected = $('#facet-selected');
		var $replace = $(window.esfaceting.replace).css('position','relative');

		var onresponse = function(data){
			$selected.find('.facet-item.removable').hide();

			$.each(data.faceting, function(type){
				var container = $("#facet-" + type + '-available');
				var me = this;

				if(me.min > 0){
					container.find('.facet-item').hide();

					if(me.min < data.found){
						$.each(this.available, function(slug){
							if(this.count > 0 && this.count < data.found){
								var li = $("#facet-" + type + '-' + slug);

								li.find('.count').text('(' + this.count + ')').show();
								li.show();
								container.show();
							}
						});

						if(window.esselected && window.esselected.showEmpty == 1){
							container.find('.facet-empty').hide();
						}
					}else{
						if(window.esselected && window.esselected.showEmpty == 1){
							container.find('.facet-empty').show();
						}else{
							container.hide();
						}
					}
				}else{
					container.hide();
				}

				$.each(this.selected, function(slug){
					var li = $("#facet-" + type + '-' + slug);

					if(!window.esselected || window.esselected.showEmpty != 1 || total < data.found){
						li.find('.count').hide();
						li.show();
					}

					$("#facet-" + type + '-' + slug + '-selected').show();
				});
			});

			if($selected.find('.facet-item:visible').length > 0){
				$selected.show();
			}

			$replace.empty().html(data.content);
			$(document).scrollTop($replace.offset().top);
			overlay.remove();
		};

		var buildQuery = function(){
			var s = [];

			var terms = $selected.find('.term');
			terms.each(function(){
				s.push($(this).data('term'));
			});

			if(terms.length == 1){
				terms.each(function(){
					$(this).removeClass('removable').html($(this).text());
				});
			}

			return $form.serialize() + '&esasync=1&s=' + s.join(' ');
		}

		var overlay = null;

		var showoverlay = function(){
			overlay = $('

').css({
				'position':'absolute',
				'top': '0',
				'left': '0',
				'width': '100%',
				'height': '100%',
				'background-color': '#858585',
				'z-index': 2147483646,
				'opacity': 0.8
			}).prependTo($replace);
		};

		$form.find('input[type=checkbox]').change(function(){
			var url = $form.attr('action');

			showoverlay();

			$.getJSON(url, buildQuery(), onresponse);
		});

		$('.esclear').click(function(){
			$form[0].reset();

			showoverlay();

			$.getJSON($(this).attr('href'), buildQuery(), onresponse);

			return false;
		});

		$selected.find('.term a').click(function(){
			$(this).parent().remove();

			var s = '';

			var terms = $selected.find('.term');
			terms.each(function(){
				s += $(this).data('term');
			});

			if(terms.length == 1){
				terms.each(function(){
					$(this).removeClass('removable').html($(this).text());
				});
			}

			showoverlay();

			$.getJSON('#', buildQuery(), function(data){
				$(this).parent().remove();

				onresponse(data);
			});

			return false;
		});

		$selected.find('.facet-item a').click(function(){
			var selector = $(this).attr('href');

			$(selector).find('input').click();

			return false;
		});

		$(document).on('click', '.pagination a, .navigation a', function(){
			showoverlay();

			$.getJSON($(this).attr('href'), $form.serialize() + '&esasync=1', onresponse);

			return false;
		});
	});
})(jQuery);<|endoftext|>


<commit_before>var pkg     = require('./package.json'),
    repoUrl = 'https://github.com/jan-molak/serenity-js';

module.exports = {
    // Documentation for GitBook is stored under 'docs'
    root:        './book',
    title:       'Serenity/JS Handbook',
    description: 'A comprehensive reference manual and tutorials for Serenity/JS, a next generation automated testing library',

    author: 'Jan Molak',

    plugins: [
        'anchors',
        'advanced-emoji',
        'editlink',
        'include-codeblock',
        'ga',
        'github',
        'rss',
        'styles-less',
        'youtube'
    ],

    variables: {
        package:     pkg,
        api_version: pkg.version
    },

    styles: {
        website: './styles/website.less'
    },

    custom: {
    },

    pluginsConfig: {
        editlink: {
            base: repoUrl + '/edit/master/book',
            label: 'Edit on github',
            multilingual: false
        },

        ga: {
            token: 'UA-85788349-2'
        },

        github: {
            url: repoUrl
        },

        sharing: {
            twitter: true,
            google: true,
            facebook: true,
            weibo: false,
            instapaper: false,
            vk: false,
            all: [
                'facebook', 'google', 'twitter',
                'weibo', 'instapaper', 'vk'
            ]
        },

        rss: {
            title: 'Serenity/JS Handbook',
            description: 'A comprehensive reference manual and tutorials for Serenity/JS, a next generation automated testing library.',
            author: 'Jan Molak',
            site_url: 'http://serenity-js.org',
            feed_url: 'http://serenity-js.org/updates.rss',
            image_url: 'http://serenity-js.org/assets/images/serenity-js-eye.svg',
            managingEditor: 'jan.molak@smartcodeltd.co.uk (Jan Molak)',
            webMaster: 'jan.molak@smartcodeltd.co.uk (Jan Molak)',
            categories: [
                "book",
                "manual",
                "tutorial",
                "bdd",
                "tdd",
                "testing",
                "protractor",
                "mocha",
                "cucumber",
                "angular",
                "bdd",
                "selenium",
                "webdriverjs",
                "webdriver"
            ]
        }
    }
};<commit_msg>docs(handbook): Corrected the RSS feed urls<commit_after>var pkg     = require('./package.json'),
    repoUrl = 'https://github.com/jan-molak/serenity-js';

module.exports = {
    // Documentation for GitBook is stored under 'docs'
    root:        './book',
    title:       'Serenity/JS Handbook',
    description: 'A comprehensive reference manual and tutorials for Serenity/JS, a next generation automated testing library',

    author: 'Jan Molak',

    plugins: [
        'anchors',
        'advanced-emoji',
        'editlink',
        'include-codeblock',
        'ga',
        'github',
        'rss',
        'styles-less',
        'youtube'
    ],

    variables: {
        package:     pkg,
        api_version: pkg.version
    },

    styles: {
        website: './styles/website.less'
    },

    custom: {
    },

    pluginsConfig: {
        editlink: {
            base: repoUrl + '/edit/master/book',
            label: 'Edit on github',
            multilingual: false
        },

        ga: {
            token: 'UA-85788349-2'
        },

        github: {
            url: repoUrl
        },

        sharing: {
            twitter: true,
            google: true,
            facebook: true,
            weibo: false,
            instapaper: false,
            vk: false,
            all: [
                'facebook', 'google', 'twitter',
                'weibo', 'instapaper', 'vk'
            ]
        },

        rss: {
            title: 'Serenity/JS Handbook',
            description: 'A comprehensive reference manual and tutorials for Serenity/JS, a next generation automated testing library.',
            author: 'Jan Molak',
            site_url: 'http://serenity-js.org/',
            feed_url: 'http://serenity-js.org/updates.rss',
            image_url: 'http://serenity-js.org/assets/images/serenity-js-eye.svg',
            managingEditor: 'jan.molak@smartcodeltd.co.uk (Jan Molak)',
            webMaster: 'jan.molak@smartcodeltd.co.uk (Jan Molak)',
            categories: [
                "book",
                "manual",
                "tutorial",
                "bdd",
                "tdd",
                "testing",
                "protractor",
                "mocha",
                "cucumber",
                "angular",
                "bdd",
                "selenium",
                "webdriverjs",
                "webdriver"
            ]
        }
    }
};<|endoftext|>


<commit_before>angular.module('starter.constants', [])

  .constant('APP_INFO', {
    version: '1.0 BETA',
    feedVersion: 'V1',
    appKey : 'messengerx'
  })
  //.constant('BASE_URL', 'stalk-front-s01.cloudapp.net')
  .constant('BASE_URL', 'localhost')

  .constant('DB_CONFIG', {
    name: 'stalk.db',
    tables: [
      {
        name: 'TB_MESSAGE',
        columns: [
          {name: '_id',     type: 'integer primary key autoincrement'},
          {name: 'channel',   type: 'text'},
          {name: 'sender',  type: 'text'},
          {name: 'message',    type: 'text'},
          {name: 'type', type: 'integer'},
          {name: 'time', type: 'integer'}
        ]
      },
      {
        name: 'TB_CHANNEL',
        columns: [
          //{name: '_id',     type: 'integer primary key autoincrement'},
          {name: 'channel_id',   type: 'text'},
          {name: 'channel_name',  type: 'text'},
          {name: 'channel_users',    type: 'text'},
          {name: 'channel_image', type: 'text'},
          {name: 'unread_count', type: 'integer'},
          {name: 'latest_message', type: 'text'},
          {name: 'channel_updated', type: 'integer'},
          {name: 'owner_id', type: 'text'}
        ]
      }
    ]
});<commit_msg>:gem: change BASE_URL<commit_after>angular.module('starter.constants', [])

  .constant('APP_INFO', {
    version: '1.0 BETA',
    feedVersion: 'V1',
    appKey : 'messengerx'
  })
  .constant('BASE_URL', 'stalk-front-s01.cloudapp.net')
  //.constant('BASE_URL', 'localhost')

  .constant('DB_CONFIG', {
    name: 'stalk.db',
    tables: [
      {
        name: 'TB_MESSAGE',
        columns: [
          {name: '_id',     type: 'integer primary key autoincrement'},
          {name: 'channel',   type: 'text'},
          {name: 'sender',  type: 'text'},
          {name: 'message',    type: 'text'},
          {name: 'type', type: 'integer'},
          {name: 'time', type: 'integer'}
        ]
      },
      {
        name: 'TB_CHANNEL',
        columns: [
          //{name: '_id',     type: 'integer primary key autoincrement'},
          {name: 'channel_id',   type: 'text'},
          {name: 'channel_name',  type: 'text'},
          {name: 'channel_users',    type: 'text'},
          {name: 'channel_image', type: 'text'},
          {name: 'unread_count', type: 'integer'},
          {name: 'latest_message', type: 'text'},
          {name: 'channel_updated', type: 'integer'},
          {name: 'owner_id', type: 'text'}
        ]
      }
    ]
});<|endoftext|>


<commit_before>////////////////////////////////////////////////
//SUBMIT ROAD RAGE
////////////////////////////////////////////////
function submitRage(){
	$(document).ready(function(){

		$("#raterage").click(function(e) {

		  e.preventDefault();
		  var name = $("#name").val();
		  var score = $("input[type='radio'][name='score']:checked").val();
		  var city = $("#city").val();
		  var dataString = 'score='+score+'&city='+city+'&ref=mobile';
		  $.ajax({
			type:'POST',
			crossDomain: true,
			data:dataString,
			url:'http://www.monkeymeter.com/submit-app.php',
			success:function(data) {
			alert(data);
			  $( "#recent" ).trigger( "click" );
			}
		  });
		return false;

		});
	});
}

////////////////////////////////////////////////
//SHOW PAGE CONTENT/MENU
////////////////////////////////////////////////
function showPageContent(){
		$("#recentragers").css("display", "none");
		$("#forecastpage").css("display", "none");
		$("#newspage").css("display", "none");
		$("#topragerspage").css("display", "none");
		$("#recentusragerspage").css("display", "none");
		$(document).ready(function(){

				$("#rate").click(function(){
				$(".pages").css("display", "none");
				$("#rateyourroadrage").css("display", "inline-block");
			});

				$("#recent").click(function(){
				$(".pages").css("display", "none");
				$("#recentragers").css("display", "inline-block");
			});

				$("#forecast").click(function(){
				$(".pages").css("display", "none");
				$("#forecastpage").css("display", "inline-block");
			});

				$("#topragers").click(function(){
				$(".pages").css("display", "none");
				$("#topragerspage").css("display", "inline-block");
			});

				$("#news").click(function(){
				$(".pages").css("display", "none");
				$("#newspage").css("display", "inline-block");
			});

				$("#recentusragers").click(function(){
				$(".pages").css("display", "none");
				$("#recentusragerspage").css("display", "inline-block");
			});
		});
}

////////////////////////////////////////////////
//SHOW RECENT RAGERS FOR LOCATION
//AND GET TOTAL POINTS FOR CITY FORECAST
////////////////////////////////////////////////

var cityScore = 0;
var recentcityScore = 0;

function getScores(){
	var recentHTML = "

";
	var abc = Math.random();

	var totalPoints = 0;
	var recentPoints = 0; //first 10% of all entries, to compare with total ave, to see trend
	var tpCount = 0;

	$.ajax({
		url: "http://www.monkeymeter.com/json/scores.json?refresh=" + abc,
		//force to handle it as text
		dataType: "text",
		success: function(data) {

			//data downloaded so call parseJSON function
			//and pass downloaded data
			var json = $.parseJSON(data);

			//get recent data for the city the user is in
			var x = json.scores.length;
			var percX = x/15; //percentage of recent scores to grab
			var city = $("#city").val();

			for (var i = 0; i < x; i++){

				if (city == json.scores[i].city){
					var gw = 20*json.scores[i].score; //graph
		            var z = json.scores[i].score * 1;
					totalPoints = totalPoints + z;
					tpCount = tpCount + 1;

					if (tpCount < percX){
						recentPoints = recentPoints + z;
					}

					if (tpCount < 50){  //limiting to 25 to show on screen.
						recentHTML =  recentHTML + "
"+json.scores[i].when+"	"+json.scores[i].score+"
";
					}
				}

			}
			recentHTML = recentHTML + "

";

			recentcityScore = recentPoints/percX;
			recentcityScore = recentcityScore.toFixed(2);
			cityScore = totalPoints/tpCount;
			$('#recentscores').html(recentHTML+"

");

		}
	});

}

////////////////////////////////////////////////
//SHOW FORECAST FOR CITY
////////////////////////////////////////////////

function getForecast(){
var fcScore = [];
fcScore[0] = cityScore;
var forecastHTML = "";
var ratings = [];
var fontcolor =[];
var ratingpic= [];

//gettings days of week
var d = new Date();
var weekday = new Array(7);
weekday[0]=  ["Sun", .02];
weekday[1] = ["Mon", .03];
weekday[2] = ["Tue", .03];
weekday[3] = ["Wed", .04];
weekday[4] = ["Thu", .04];
weekday[5] = ["Fri", .05];
weekday[6] = ["Sat", .04];

var n=weekday[d.getDay()];
var dayNum = d.getDay();
if (dayNum < 3){
	var day3 = weekday[dayNum+2][0];
	var day4 = weekday[dayNum+3][0];
	var day5 = weekday[dayNum+4][0];
	fcScore[1]=fcScore[0] + weekday[dayNum+1][1];
	fcScore[2]=fcScore[0] + weekday[dayNum+2][1];
	fcScore[3]=fcScore[0] + weekday[dayNum+3][1];
	fcScore[4]=fcScore[0] + weekday[dayNum+4][1];
}

if (dayNum ==3 ){
	var day3 = weekday[5][0];
	var day4 = weekday[6][0];
	var day5 = weekday[0][0];
	fcScore[1]=fcScore[0] + weekday[4][1];
	fcScore[2]=fcScore[0] + weekday[5][1];
	fcScore[3]=fcScore[0] + weekday[6][1] ;
	fcScore[4]=fcScore[0] + weekday[0][1];

}

if (dayNum ==4 ){
	var day3 = weekday[6][0];
	var day4 = weekday[0][0];
	var day5 = weekday[1][0];
	fcScore[1]=fcScore[0] + weekday[5][1];
	fcScore[2]=fcScore[0] + weekday[6][1];
	fcScore[3]=fcScore[0] + weekday[0][1] ;
	fcScore[4]=fcScore[0] + weekday[1][1];

}
if (dayNum ==5 ){
	var day3 = weekday[0][0];
	var day4 = weekday[1][0];
	var day5 = weekday[2][0];
	fcScore[1]=fcScore[0] + weekday[6][1];
	fcScore[2]=fcScore[0] + weekday[0][1];
	fcScore[3]=fcScore[0] + weekday[1][1];
	fcScore[4]=fcScore[0] + weekday[2][1];
}
if (dayNum ==6 ){
	var day3 = weekday[1][0];
	var day4 = weekday[2][0];
	var day5 = weekday[3][0];
	fcScore[1]=fcScore[0] + weekday[0][1];
	fcScore[2]=fcScore[0] + weekday[1][1];
	fcScore[3]=fcScore[0] + weekday[2][1];
	fcScore[4]=fcScore[0] + weekday[3][1];
}

//get rating level
for (var i = 0; i < 5; i++){
	if (fcScore[i] > 0)
		{
		ratings[i]="None";
		fontcolor[i] = "blue";
		ratingpic[i]="img/monkey-ok.png";
		}
	if (fcScore[i]  > 1)
		{
		ratings[i]="Low";
		fontcolor[i] = "green";
		ratingpic[i]="img/monkey-ok.png";
		}
	if (fcScore[i]  > 2)
		{
		ratings[i]="Ave";
		fontcolor[i] = "black";
		ratingpic[i]="img/monkey-ave.png";
		}
	if (fcScore[i] > 3)
		{
		ratings[i]="High";
		fontcolor[i] = "orange";
		ratingpic[i]="img/monkey-high.png";
		}
	if (fcScore[i]  > 4)
		{
		ratings[i]="Dangerous";
		fontcolor[i] = "red";
		ratingpic[i]="img/monkey-dan.png";
		}
}

//show trend
var arrow="";
var altarrow = "";
if (cityScore <= recentcityScore){
	arrow = "up.jpg";
	altarrow = "road rage has been increasing";
	fcScore[0] = fcScore[0] + .04;
	}
else {
	arrow = "down.jpg";
	altarrow = "road rage has been decreasing";
	fcScore[0] = fcScore[0] - .03;
	}

forecastHTML = "
Current rating in your area is: " + cityScore.toFixed(2) + ", and the recent trend is that "+altarrow+".

";

forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
Today
";
		forecastHTML = forecastHTML + "

"  + ratings[0] + "
" +  fcScore[0].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
Tomorrow
";
		forecastHTML = forecastHTML + "

"  + ratings[1] + "
" +  fcScore[1].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day3 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[2] + "
" +  fcScore[2].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day4 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[3] + "
" +  fcScore[3].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day5 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[4] + "
" +  fcScore[3].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

forecastHTML = forecastHTML + "
";

$('#forecastforcity').html(forecastHTML);
}

////////////////////////////////////////////////
//SHOW RECENT RAGERS THROUGHOUT US
////////////////////////////////////////////////

function getUSratings(){
	var recentHTML = "

";
	var abc = Math.random();

	$.ajax({
		url: "http://www.monkeymeter.com/json/scores.json?refresh=" + abc,
		//force to handle it as text
		dataType: "text",
		success: function(data) {

			//data downloaded so call parseJSON function
			//and pass downloaded data
			var json = $.parseJSON(data);

			//get recent data for the city the user is in
			var x = json.scores.length;

			for (var i = 0; i < 100; i++){

					var gw = 20*json.scores[i].score; //graph
		            var z = json.scores[i].score * 1;

						recentHTML =  recentHTML + "
"+json.scores[i].city+"	"+json.scores[i].when+"	"+json.scores[i].score+"
";

			}
			recentHTML = recentHTML + "

";
			$('#recentusratings').html(recentHTML+"

");

		}
	});

}<commit_msg>Added files via upload<commit_after>////////////////////////////////////////////////
//SUBMIT ROAD RAGE
////////////////////////////////////////////////
function submitRage(){
	$(document).ready(function(){

		$("#raterage").click(function(e) {

		  e.preventDefault();
		  var name = $("#name").val();
		  var score = $("input[type='radio'][name='score']:checked").val();
		  var city = $("#city").val();
		  var dataString = 'score='+score+'&city='+city+'&ref=mobile';
		  $.ajax({
			type:'POST',
			crossDomain: true,
			data:dataString,
			url:'http://www.monkeymeter.com/submit-app.php',
			success:function(data) {
			alert(data);
			  $( "#recent" ).trigger( "click" );
			}
		  });
		return false;

		});
	});
}

////////////////////////////////////////////////
//SHOW PAGE CONTENT/MENU
////////////////////////////////////////////////
function showPageContent(){
		$("#recentragers").css("display", "none");
		$("#forecastpage").css("display", "none");
		$("#newspage").css("display", "none");
		$("#topragerspage").css("display", "none");
		$("#recentusragerspage").css("display", "none");
		$(document).ready(function(){

				$("#rate").click(function(){
				$(".pages").css("display", "none");
				$("#rateyourroadrage").css("display", "inline-block");
			});

				$("#recent").click(function(){
				$(".pages").css("display", "none");
				$("#recentragers").css("display", "inline-block");
			});

				$("#forecast").click(function(){
				$(".pages").css("display", "none");
				$("#forecastpage").css("display", "inline-block");
			});

				$("#topragers").click(function(){
				$(".pages").css("display", "none");
				$("#topragerspage").css("display", "inline-block");
			});

				$("#news").click(function(){
				$(".pages").css("display", "none");
				$("#newspage").css("display", "inline-block");
			});

				$("#recentusragers").click(function(){
				$(".pages").css("display", "none");
				$("#recentusragerspage").css("display", "inline-block");
			});
		});
}

////////////////////////////////////////////////
//SHOW RECENT RAGERS FOR LOCATION
//AND GET TOTAL POINTS FOR CITY FORECAST
////////////////////////////////////////////////

var cityScore = 0;
var recentcityScore = 0;

function getScores(){
	var recentHTML = "

";
	var abc = Math.random();

	var totalPoints = 0;
	var recentPoints = 0; //first 10% of all entries, to compare with total ave, to see trend
	var tpCount = 0;

	$.ajax({
		url: "http://www.monkeymeter.com/json/scores.json?refresh=" + abc,
		//force to handle it as text
		dataType: "text",
		success: function(data) {

			//data downloaded so call parseJSON function
			//and pass downloaded data
			var json = $.parseJSON(data);

			//get recent data for the city the user is in
			var x = json.scores.length;
			var percX = x/15; //percentage of recent scores to grab
			var city = $("#city").val();

			for (var i = 0; i < x; i++){

				if (city == json.scores[i].city){
					var gw = 20*json.scores[i].score; //graph
		            var z = json.scores[i].score * 1;
					totalPoints = totalPoints + z;
					tpCount = tpCount + 1;

					if (tpCount < percX){
						recentPoints = recentPoints + z;
					}

					if (tpCount < 50){  //limiting to 25 to show on screen.
						recentHTML =  recentHTML + "
"+json.scores[i].when+"	"+json.scores[i].score+"
";
					}
				}

			}
			recentHTML = recentHTML + "

";

			recentcityScore = recentPoints/percX;
			recentcityScore = recentcityScore.toFixed(2);
			cityScore = totalPoints/tpCount;
			$('#recentscores').html(recentHTML+"

");

		}
	});

}

////////////////////////////////////////////////
//SHOW FORECAST FOR CITY
////////////////////////////////////////////////

function getForecast(){
var fcScore = [];
fcScore[0] = cityScore;
var forecastHTML = "";
var ratings = [];
var fontcolor =[];
var ratingpic= [];

//gettings days of week
var d = new Date();
var weekday = new Array(7);
weekday[0]=  ["Sun", .02];
weekday[1] = ["Mon", .03];
weekday[2] = ["Tue", .03];
weekday[3] = ["Wed", .04];
weekday[4] = ["Thu", .04];
weekday[5] = ["Fri", .05];
weekday[6] = ["Sat", .04];

var n=weekday[d.getDay()];
var dayNum = d.getDay();
if (dayNum < 3){
	var day3 = weekday[dayNum+2][0];
	var day4 = weekday[dayNum+3][0];
	var day5 = weekday[dayNum+4][0];
	fcScore[1]=fcScore[0] + weekday[dayNum+1][1];
	fcScore[2]=fcScore[0] + weekday[dayNum+2][1];
	fcScore[3]=fcScore[0] + weekday[dayNum+3][1];
	fcScore[4]=fcScore[0] + weekday[dayNum+4][1];
}

if (dayNum ==3 ){
	var day3 = weekday[5][0];
	var day4 = weekday[6][0];
	var day5 = weekday[0][0];
	fcScore[1]=fcScore[0] + weekday[4][1];
	fcScore[2]=fcScore[0] + weekday[5][1];
	fcScore[3]=fcScore[0] + weekday[6][1] ;
	fcScore[4]=fcScore[0] + weekday[0][1];

}

if (dayNum ==4 ){
	var day3 = weekday[6][0];
	var day4 = weekday[0][0];
	var day5 = weekday[1][0];
	fcScore[1]=fcScore[0] + weekday[5][1];
	fcScore[2]=fcScore[0] + weekday[6][1];
	fcScore[3]=fcScore[0] + weekday[0][1] ;
	fcScore[4]=fcScore[0] + weekday[1][1];

}
if (dayNum ==5 ){
	var day3 = weekday[0][0];
	var day4 = weekday[1][0];
	var day5 = weekday[2][0];
	fcScore[1]=fcScore[0] + weekday[6][1];
	fcScore[2]=fcScore[0] + weekday[0][1];
	fcScore[3]=fcScore[0] + weekday[1][1];
	fcScore[4]=fcScore[0] + weekday[2][1];
}
if (dayNum ==6 ){
	var day3 = weekday[1][0];
	var day4 = weekday[2][0];
	var day5 = weekday[3][0];
	fcScore[1]=fcScore[0] + weekday[0][1];
	fcScore[2]=fcScore[0] + weekday[1][1];
	fcScore[3]=fcScore[0] + weekday[2][1];
	fcScore[4]=fcScore[0] + weekday[3][1];
}

//get rating level
for (var i = 0; i < 5; i++){
	if (fcScore[i] > 0)
		{
		ratings[i]="None";
		fontcolor[i] = "blue";
		ratingpic[i]="img/monkey-ok.png";
		}
	if (fcScore[i]  > 1)
		{
		ratings[i]="Low";
		fontcolor[i] = "green";
		ratingpic[i]="img/monkey-ok.png";
		}
	if (fcScore[i]  > 2)
		{
		ratings[i]="Ave";
		fontcolor[i] = "black";
		ratingpic[i]="img/monkey-ave.png";
		}
	if (fcScore[i] > 3)
		{
		ratings[i]="High";
		fontcolor[i] = "orange";
		ratingpic[i]="img/monkey-high.png";
		}
	if (fcScore[i]  > 4)
		{
		ratings[i]="Dangerous";
		fontcolor[i] = "red";
		ratingpic[i]="img/monkey-dan.png";
		}
}

//show trend
var arrow="";
var altarrow = "";
if (cityScore <= recentcityScore){
	arrow = "up.jpg";
	altarrow = "road rage has been increasing";
	fcScore[0] = fcScore[0] + .04;
	}
else {
	arrow = "down.jpg";
	altarrow = "road rage has been decreasing";
	fcScore[0] = fcScore[0] - .03;
	}

forecastHTML = "
Current rating in your area is: " + cityScore.toFixed(2) + ", and the recent trend is that "+altarrow+".

";

forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
Today
";
		forecastHTML = forecastHTML + "

"  + ratings[0] + "
" +  fcScore[0].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
Tomorrow
";
		forecastHTML = forecastHTML + "

"  + ratings[1] + "
" +  fcScore[1].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day3 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[2] + "
" +  fcScore[2].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day4 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[3] + "
" +  fcScore[3].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

	forecastHTML = forecastHTML + "
";
		forecastHTML = forecastHTML + "
" + day5 + "
";
		forecastHTML = forecastHTML + "

"  + ratings[4] + "
" +  fcScore[3].toFixed(2) + "
";
	forecastHTML = forecastHTML + "
";

forecastHTML = forecastHTML + "
";

$('#forecastforcity').html(forecastHTML);
}

////////////////////////////////////////////////
//SHOW RECENT RAGERS THROUGHOUT US
////////////////////////////////////////////////

function getUSratings(){
	var recentHTML = "

";
	var abc = Math.random();

	$.ajax({
		url: "http://www.monkeymeter.com/json/scores.json?refresh=" + abc,
		//force to handle it as text
		dataType: "text",
		success: function(data) {

			//data downloaded so call parseJSON function
			//and pass downloaded data
			var json = $.parseJSON(data);

			//get recent data for the city the user is in
			var x = json.scores.length;

			for (var i = 0; i < 100; i++){

					var gw = 20*json.scores[i].score; //graph
		            var z = json.scores[i].score * 1;
					//show only year
					json.scores[i].when = json.scores[i].when.slice(0,10);

						recentHTML =  recentHTML + "
"+json.scores[i].city+"	"+json.scores[i].when+"	"+json.scores[i].score+"
";

			}
			recentHTML = recentHTML + "

";
			$('#recentusratings').html(recentHTML+"

");

		}
	});

}<|endoftext|>


<commit_before>import React from 'react'
import {
  Box,
  Heading,
  Container,
  Card,
  Text,
  Flex,
  Module,
  Button,
  LargeButton,
  mediaQueries,
  cx
} from '@hackclub/design-system'
import Link from 'gatsby-link'
import Stat from 'components/Stat'
import { stats } from 'data.json'

const Grid = Box.extend`
  width: 100%;

  > div,
  > img {
    width: 100%;
    box-shadow: ${props => props.theme.boxShadows[3]};
    border-radius: ${props => props.theme.radius};
    max-width: 100%;
    margin-top: ${props => props.theme.space[2]}px;
    margin-bottom: ${props => props.theme.space[2]}px;
  }

  ${props => props.theme.mediaQueries.md} {
    column-count: 2;
    column-gap: ${props => props.theme.space[4]}px;
    max-height: 56rem;
    > div,
    > img {
      margin-top: ${props => props.theme.space[3]}px;
      margin-bottom: ${props => props.theme.space[3]}px;
    }
  }
`

const Super = Box.extend`
  background: ${props => props.theme.colors.warning} url(/diagonal.svg) top
    center repeat-x;
  background-size: auto 100%;
  position: relative;

  &:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url(/diagonal.svg) top right repeat-x;
    background-size: auto 100%;
    background-position-x: 32%;
  }

  > * {
    position: relative;
  }
`

const Modules = Box.extend`
  display: grid;
  grid-gap: ${props => props.theme.space[3]}px;
  ${props => props.theme.mediaQueries.md} {
    grid-template-columns: repeat(2, 1fr);
  }
  div {
    align-items: flex-start;
    padding: 0;
    text-align: left;
    width: 100% !important;
  }
`

const Stats = Box.extend`
  column-count: 2;
  div {
    text-align: left;
  }
`

const Image = Box.withComponent('img')

Button.link = Button.withComponent(Link)
LargeButton.link = LargeButton.withComponent(Link)

export default () => (
  <Container w={1} px={[3]} mt={[4, 5]}>
    <Container maxWidth={48} mx={0}>
      <Heading.h2 f={[4, 5]} mb={3} bold>
        Join the largest community of students building the class they wish they
        could take.
      </Heading.h2>
      <Text f={[3, 4]}>
        A Hack Club is a high school club. Every week, you and around 20 other
        students come together to build. Meetings are buzzing: people working on
        projects, learning is self-guided through workshops, leaders are
        constantly mentoring. Your members start with no experience.
      </Text>
    </Container>
    <Grid mt={3} color="white">
      <Box bg="primary" p={[3, 4]}>
        <Heading.h2 f={4} my={0} caps>
          Ready to get started?
        </Heading.h2>
        <Text f={3} my={3}>
          You, a student who knows how to code, get 1-2 others to start a Hack
          Club. You apply, we accept you, you use our resouces to start your
          club at your high school.
        </Text>
        <LargeButton.link to="/start" inverted>
          Start your Club
        </LargeButton.link>
      </Box>
      <Image src="/about_talking.jpg" />
      <Image src="/about_hacking.jpg" />
      <Box bg="info" p={[3, 4]}>
        <Heading.h2 f={4} my={0} caps>
          Start with a club in a box.
        </Heading.h2>
        <Modules my={3} w={1}>
          <Module
            icon="forum"
            heading="Online community"
            body="Talk to thousands of club leaders/members on Slack."
          />
          <Module
            icon="chrome_reader_mode"
            heading="Curriculum"
            body="Dozens of tutorials for your members to make projects."
          />
          <Module
            icon="voice_chat"
            heading="Mentorship"
            body="Talk to our team online for guidance anytime."
          />
          <Module
            icon="wallpaper"
            heading="Marketing"
            body="Get materials and ideas for spreading your club."
          />
        </Modules>
      </Box>
    </Grid>
    <Container maxWidth={48} mx={0} mt={[5, null, -5]} mb={4}>
      <Heading.h2 f={[4, 5]} mb={3} bold>
        We think people learn best when they take control of their own
        education.
      </Heading.h2>
      <Text f={[3, 4]}>
        A Hack Club is a high school club. Every week, you and around 20 other
        students come together to build. Meetings are buzzing: people working on
        projects, learning is self-guided through workshops, leaders are
        constantly mentoring. Your members start with no experience.
      </Text>
    </Container>
    <Grid pb={[5, 2]} color="white">
      <Super p={[3, 4]}>
        <Heading.h2 f={4} my={0} caps>
          Coding is a superpower.
        </Heading.h2>
        <Text f={3} my={3}>
          Learning to code is uniquely empowering: you go from a consumer to a
          creator. The goal of Hack Club is to help you become that hacker. We
          want a space at every high school where people are making interesting
          things with code, every week.
        </Text>
        <Button.link to="/philosophy" bg="warning" inverted>
          Our philosophy
        </Button.link>
      </Super>
      <Image src="/about_working.jpg" />
      <Image src="/about_group.jpg" />
      <Box bg="accent" p={[3, 4]}>
        <Heading.h2 f={4} my={0} caps>
          Be part of a movement.
        </Heading.h2>
        <Stats mt={2} mb={3}>
          <Stat f={7} value={stats.school_count} label="schools" />
          <Stat f={7} value={stats.country_count} label="countries" />
          <Stat f={7} value={stats.state_count} label="states" />
          <Stat f={7} value={stats.approximate_members} label="members" />
        </Stats>
        <Button href="/donate" bg="accent" inverted>
          Donate
        </Button>
      </Box>
    </Grid>
  </Container>
)
<commit_msg>Rewrite About with Grid<commit_after>import React from 'react'
import {
  Box,
  Heading,
  Container,
  Card,
  Text,
  Flex,
  Module,
  Button,
  LargeButton,
  mediaQueries,
  cx
} from '@hackclub/design-system'
import Link from 'gatsby-link'
import Stat from 'components/Stat'
import { stats } from 'data.json'

const Grid = Box.extend`
  display: grid;
  grid-gap: ${props => props.theme.space[3]}px;
  width: 100%;

  > div,
  > img {
    width: 100%;
    box-shadow: ${props => props.theme.boxShadows[3]};
    border-radius: ${props => props.theme.radius};
    max-width: 100%;
  }

  ${props => props.theme.mediaQueries.md} {
    grid-template-columns: repeat(2, 1fr);
    grid-gap: ${props => props.theme.space[4]}px;
  }
`

const Super = Box.extend`
  background: ${props => props.theme.colors.warning} url(/diagonal.svg) top
    center repeat-x;
  background-size: auto 100%;
  position: relative;

  &:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url(/diagonal.svg) top right repeat-x;
    background-size: auto 100%;
    background-position-x: 32%;
  }

  > * {
    position: relative;
  }
`

const Modules = Box.extend`
  display: grid;
  grid-gap: ${props => props.theme.space[3]}px;
  ${props => props.theme.mediaQueries.md} {
    grid-template-columns: repeat(2, 1fr);
  }
  div {
    align-items: flex-start;
    padding: 0;
    text-align: left;
    width: 100% !important;
  }
`

const Stats = Box.extend`
  column-count: 2;
  div {
    text-align: left;
  }
`

const Image = Box.withComponent('img')

Button.link = Button.withComponent(Link)
LargeButton.link = LargeButton.withComponent(Link)

export default () => (
  <Container w={1} px={[3]} mt={[4, 5]}>
    <Container maxWidth={48} mx={0}>
      <Heading.h2 f={[4, 5]} mb={3} bold>
        Join the largest community of students building the class they wish they
        could take.
      </Heading.h2>
      <Text f={[3, 4]}>
        A Hack Club is a high school club. Every week, you and around 20 other
        students come together to build. Meetings are buzzing: people working on
        projects, learning is self-guided through workshops, leaders are
        constantly mentoring. Your members start with no experience.
      </Text>
    </Container>
    <Grid mt={4} mb={[4, 6]} color="white">
      <Box bg="primary" p={[3, 4]}>
        <Heading.h2 f={4} my={0} caps>
          Ready to get started?
        </Heading.h2>
        <Text f={3} my={3}>
          You, a student who knows how to code, get 1-2 others to start a Hack
          Club. You apply, we accept you, you use our resouces to start your
          club at your high school.
        </Text>
        <LargeButton.link to="/start" inverted>
          Start your Club
        </LargeButton.link>
      </Box>
      <Image src="/about_talking.jpg" />
      <Image src="/about_hacking.jpg" />
      <Box bg="info" p={[3, 4]}>
        <Heading.h2 f={4} my={0} caps>
          Start with a club in a box.
        </Heading.h2>
        <Modules my={3} w={1}>
          <Module
            icon="forum"
            heading="Online community"
            body="Talk to thousands of club leaders/members on Slack."
          />
          <Module
            icon="chrome_reader_mode"
            heading="Curriculum"
            body="Dozens of tutorials for your members to make projects."
          />
          <Module
            icon="voice_chat"
            heading="Mentorship"
            body="Talk to our team online for guidance anytime."
          />
          <Module
            icon="wallpaper"
            heading="Marketing"
            body="Get materials and ideas for spreading your club."
          />
        </Modules>
      </Box>
    </Grid>
    <Container maxWidth={48} mx={0} mt={[5, null, -5]} mb={4}>
      <Heading.h2 f={[4, 5]} mb={3} bold>
        We think people learn best when they take control of their own
        education.
      </Heading.h2>
      <Text f={[3, 4]}>
        A Hack Club is a high school club. Every week, you and around 20 other
        students come together to build. Meetings are buzzing: people working on
        projects, learning is self-guided through workshops, leaders are
        constantly mentoring. Your members start with no experience.
      </Text>
    </Container>
    <Grid mt={4} mb={[4, 6]} color="white">
      <Super p={[3, 4]}>
        <Heading.h2 f={4} my={0} caps>
          Coding is a superpower.
        </Heading.h2>
        <Text f={3} my={3}>
          Learning to code is uniquely empowering: you go from a consumer to a
          creator. The goal of Hack Club is to help you become that hacker. We
          want a space for hacking at every high school, every week.
        </Text>
        <Button.link to="/philosophy" bg="warning" inverted>
          Our philosophy
        </Button.link>
      </Super>
      <Image src="/about_working.jpg" />
      <Image src="/about_group.jpg" />
      <Box bg="accent" p={[3, 4]}>
        <Heading.h2 f={4} my={0} caps>
          Be part of a movement.
        </Heading.h2>
        <Stats mt={2} mb={3}>
          <Stat f={7} value={stats.school_count} label="schools" />
          <Stat f={7} value={stats.country_count} label="countries" />
          <Stat f={7} value={stats.state_count} label="states" />
          <Stat f={7} value={stats.approximate_members} label="members" />
        </Stats>
        <Button href="/donate" bg="accent" inverted>
          Donate
        </Button>
      </Box>
    </Grid>
  </Container>
)
<|endoftext|>


<commit_before>//Define Routing for app
//Uri /AddNewOrder -> template add_order.html and Controller AddOrderController
//Uri /ShowOrders -> template show_orders.html and Controller AddOrderController
xyxxy.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
    when('/user/splash', {
        templateUrl: 'pages/user/splash.html',
        controller: 'UserSplash'
    }).
	when('/user/login', {
        templateUrl: 'pages/user/login.html',
        controller: 'UserLogin'
    }).
	when('/user/register', {
        templateUrl: 'pages/user/register.html',
        controller: 'UserRegister'
    }).
	when('/stories/index', {
        templateUrl: 'pages/stories/index.html',
        controller: 'StoriesIndex'
    }).
      otherwise({
        redirectTo: '/user/splash'
      });
}]);<commit_msg>reinstated routes<commit_after><|endoftext|>


<commit_before>var io;
var socket;
var players = [];
var host = [];
var request = require("request");
// #GowriImport the model to use its database functions
var player = require("../../models/playerModels.js");
require('dotenv').config({ path: '../../dotenv.env' });
//var currentURL = window.location.origin;

// An object that holds the global variables for the game that the host machine needs to track
// #SRM More key/value pairs get created as needed in the initialization
//#Gowri moved global var from hostmachine to game.js
var hostGlobalVar = {
    currentGreenCard: null,
    currentGreenCardIndex: 0,
    currentLeaderIndex: 0,
    dealerTracker: 0,
    greenDeck: [],
    playersArray: [],
    playerDecks: [],
    roundsNum: 2,
    roundsTracker: 1,
    submittedCards: [],
    winningCards: [],
    playersNum: 0
};

// #Amanda when a connection is created a new game instance is created
exports.initGame = function(sio, sock) {
    io = sio;
    socket = sock;
    socket.emit('connected', { message: "You are connected!" });

    //#Gowri when a user clicks start a game and there are already 5 players then room full message will display
    socket.on("can player join", function() {
        if (players.length >= 5) {
            socket.emit('player limit reached', "landing");
        } //#Gowri else display the player page
        else {
            socket.emit('display player');
        }
    })

    socket.on('set user', setUser);

    // #Gowri when start button is clicked this listener will start the game by building the deck for each players
    socket.on('start game', function() {
        hostGlobalVar.greenCardsTotal = (hostGlobalVar.playersNum * hostGlobalVar.roundsNum);
        hostGlobalVar.redCardsTotal = (((hostGlobalVar.playersNum * 4) * hostGlobalVar.roundsNum) + (((hostGlobalVar.playersNum - 1) * (hostGlobalVar.playersNum)) * hostGlobalVar.roundsNum));
        hostGlobalVar.deckArray = hostBuildDeck();

    })
}

/*============================================================================

    #SRM
    HOST FUNCTIONS
    #Moved all host functions from Host Machine to Game.js
============================================================================*/
function hostBuildDeck() {

    hostDrawGreenCards(hostGlobalVar.greenCardsTotal, 7471, 9951);
    hostDrawRedCards(hostGlobalVar.redCardsTotal, 1, 7461);

}

//function makes an AJAX call and sets global variable so our host Machine can access this array later;
function hostDrawGreenCards(cardsNum, startId, endId) {

    // #SRM AJAX call to grab an array of all the red cards that all players will need for the game
    request.post(
        "/api/cards/draw",
        // #SRM Create a shuffled array of all red card ids in our db, then splice it to match our game length, and turn it into a string
        {
            idsString: (hostGenerateIdArray(endId + 1, startId).splice(0, cardsNum).toString())
        },
        function(data) {
            //console.log("i am in host draw green")
            hostGlobalVar.greenDeck = data;

            // Prepare the first green card to be revealed
            hostGlobalVar.currentGreenCard = hostGlobalVar.greenDeck[hostGlobalVar.currentGreenCardIndex];
        });

}

function hostDrawRedCards(cardsNum, startId, endId) {
   // console.log(hostGenerateIdArray(endId + 1, startId).splice(0, cardsNum).toString());
    player.selectAllWithinIdList(hostGenerateIdArray(endId + 1, startId).splice(0, cardsNum).toString(),
        function(data) {
            for (i = 0; i < hostGlobalVar.playersArray.length; i++) {
                var cardsPerPlayer = ((hostGlobalVar.playersArray.length - 1) + 4) * hostGlobalVar.roundsNum;
                var personalDeck = [];

                for (j = 0; j < cardsPerPlayer; j++) {
                    personalDeck.push(data[hostGlobalVar.dealerTracker]);
                    hostGlobalVar.dealerTracker++;
                }

                hostGlobalVar.playerDecks.push(personalDeck);

                io.to(hostGlobalVar.playersArray[i].playerId).emit('deal cards', hostGlobalVar.playerDecks[i]);
                //alert("Player in position " + i + ": " +hostGlobalVar.playerDecks[i]);
            }
            //console.log(hostGlobalVar.playerDecks);
        });

}

// #Amanda creates a new user and assigns them to an array based on their role.
function setUser(user) {
    console.log('setting user')
    //#Gowri added conditions to check if limit is reached and send the player to no game message
    if (user.role === 'host' && host.length === 0) {
        host.push({
            userName: user.userName,
            roomId: user.roomId,
            role: user.role,
            playerId: user.playerId,
            cards: []
        })
        console.log(`added ${user.userName} to the list of hosts`);
        // #Gowri emit to initiate display of host after adding to array
        socket.emit('display host');
    } else if (user.role === "player" && players.length < 5) {
        players.push({
            userName: user.userName,
            roomId: user.roomId,
            role: user.role,
            playerId: user.playerId,
            score: 0,
            cards: []
        })
        console.log(`added ${user.userName} to the list of players ${players.length}`);
        // #Gowri emit to initiate display of player page after adding to array
        socket.emit('display pregame');
    } else {
        // #Gowri emit to display room full message if host and player limits reached the 2nd param should be the div id that should be hidden
        console.log("emit room full")
        if (user.role === "host") {
            socket.emit('player limit reached', "landing");
        } else {
            console.log("i am in player full server")
            io.to(user.playerId).emit('player limit reached', "player");
        }
    }
    if (players.length === 5) {
        //#Gowri set the players once the required number of players has joined
        hostGlobalVar.playersArray = players;
        hostGlobalVar.playersNum = hostGlobalVar.playersArray.length;
        io.to(hostGlobalVar.hostArray[0].playerId).emit('all players joined', hostGlobalVar);

    }
    // #Gowri emit the players to Host screen
    if (players.length > 0 && players.length <= 5) {
        io.to(hostGlobalVar.hostArray[0].playerId).emit('player joined', players);
    }
    //#jordan send each player their ID & hostID
    if (players.length >= 1) {
        players.forEach(player => {
            //console.log("player "+player.playerId+" emitted");
            var sendme = { hostsock: host[0].playerId, playID: player.playerId, thename: player.userName, room: player.roomId };
            io.to(player.playerId).emit('checkyoself', sendme);
        });
    }

}

//Bex: Generating array of ids
function hostSerialArray(n, initialId) {
    var arr = [];
    for (var i = initialId; i <= n - 1; i += 10) {
        arr.push(i);
    }
    return arr;
}

// Function supplied directly by Bex
function hostShuffle(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

// #SRM this assumes a databse identical to the 2017.08.26 version, if cards/ids change, the query incorporating these ids risks breaking
// #SRM This function generates a shuffled array of ids corresponding to cards in our db
function hostGenerateIdArray(endNum, startNum) {
    return hostShuffle(hostSerialArray(endNum, startNum));
}

// io.to(e.socketId).emit('test', `hi + ${e.userName}`));<commit_msg>really fixed merge conflict this time<commit_after>var io;
var socket;
var players = [];
var host = [];
var request = require("request");
// #GowriImport the model to use its database functions
var player = require("../../models/playerModels.js");
require('dotenv').config({ path: '../../dotenv.env' });
//var currentURL = window.location.origin;

// An object that holds the global variables for the game that the host machine needs to track
// #SRM More key/value pairs get created as needed in the initialization
//#Gowri moved global var from hostmachine to game.js
//#Gowri added host array and added this variable to anywhere the host gets referred
var hostGlobalVar = {
    currentGreenCard: null,
    currentGreenCardIndex: 0,
    currentLeaderIndex: 0,
    dealerTracker: 0,
    greenDeck: [],
    hostArray: [],
    playersArray: [],
    playerDecks: [],
    roundsNum: 2,
    roundsTracker: 1,
    submittedCards: [],
    winningCards: [],
    playersNum: 0
};

// #Amanda when a connection is created a new game instance is created
exports.initGame = function(sio, sock) {
    io = sio;
    socket = sock;
    socket.emit('connected', { message: "You are connected!" });

    //#Gowri when a user clicks start a game and there are already 5 players then room full message will display
    socket.on("can player join", function() {
        if (players.length >= 5) {
            socket.emit('player limit reached', "landing");
        } //#Gowri else display the player page
        else {
            socket.emit('display player');
        }
    })

    socket.on('set user', setUser);

    // #Gowri when start button is clicked this listener will start the game by building the deck for each players
    socket.on('start game', function() {
        hostGlobalVar.greenCardsTotal = (hostGlobalVar.playersNum * hostGlobalVar.roundsNum);
        hostGlobalVar.redCardsTotal = (((hostGlobalVar.playersNum * 4) * hostGlobalVar.roundsNum) + (((hostGlobalVar.playersNum - 1) * (hostGlobalVar.playersNum)) * hostGlobalVar.roundsNum));
        hostGlobalVar.deckArray = hostBuildDeck();

    })
}

/*============================================================================

    #SRM
    HOST FUNCTIONS
    #Moved all host functions from Host Machine to Game.js
============================================================================*/
function hostBuildDeck() {

    hostDrawGreenCards(hostGlobalVar.greenCardsTotal, 7471, 9951);
    hostDrawRedCards(hostGlobalVar.redCardsTotal, 1, 7461);

}

//function makes an AJAX call and sets global variable so our host Machine can access this array later;
function hostDrawGreenCards(cardsNum, startId, endId) {

    // #SRM AJAX call to grab an array of all the red cards that all players will need for the game
-        // #SRM Create a shuffled array of all red card ids in our db, then splice it to match our game length, and turn it into a string
-    player.selectAllWithinIdList(hostGenerateIdArray( endId+1, startId ).splice( 0, cardsNum ).toString(),
-    function(data){
-        console.log("i am in host draw green")
-        hostGlobalVar.greenDeck = data;
-        //console.log(hostGlobalVar.greenDeck);
-
-        // Prepare the first green card to be revealed
-        hostGlobalVar.currentGreenCard = hostGlobalVar.greenDeck[hostGlobalVar.currentGreenCardIndex];
-        //#Gowri emitting green cards to the host
-        io.to(hostGlobalVar.hostArray[0].playerId).emit('green cards', hostGlobalVar.greenDeck);
-    });

}

function hostDrawRedCards(cardsNum, startId, endId) {
   // console.log(hostGenerateIdArray(endId + 1, startId).splice(0, cardsNum).toString());
    player.selectAllWithinIdList(hostGenerateIdArray(endId + 1, startId).splice(0, cardsNum).toString(),
        function(data) {
            for (i = 0; i < hostGlobalVar.playersArray.length; i++) {
                var cardsPerPlayer = ((hostGlobalVar.playersArray.length - 1) + 4) * hostGlobalVar.roundsNum;
                var personalDeck = [];

                for (j = 0; j < cardsPerPlayer; j++) {
                    personalDeck.push(data[hostGlobalVar.dealerTracker]);
                    hostGlobalVar.dealerTracker++;
                }

                hostGlobalVar.playerDecks.push(personalDeck);

                io.to(hostGlobalVar.playersArray[i].playerId).emit('deal cards', hostGlobalVar.playerDecks[i]);
                //alert("Player in position " + i + ": " +hostGlobalVar.playerDecks[i]);
            }
            //console.log(hostGlobalVar.playerDecks);
        });

}

// #Amanda creates a new user and assigns them to an array based on their role.
function setUser(user) {
    console.log('setting user')
    //#Gowri added conditions to check if limit is reached and send the player to no game message
    if (user.role === 'host' && host.length === 0) {
        host.push({
            userName: user.userName,
            roomId: user.roomId,
            role: user.role,
            playerId: user.playerId,
            cards: []
        })
        hostGlobalVar.hostArray=host;
        console.log(`added ${user.userName} to the list of hosts`);
        // #Gowri emit to initiate display of host after adding to array
        socket.emit('display host');
    } else if (user.role === "player" && players.length < 5) {
        players.push({
            userName: user.userName,
            roomId: user.roomId,
            role: user.role,
            playerId: user.playerId,
            score: 0,
            cards: []
        })
        console.log(`added ${user.userName} to the list of players ${players.length}`);
        // #Gowri emit to initiate display of player page after adding to array
        socket.emit('display pregame');
    } else {
        // #Gowri emit to display room full message if host and player limits reached the 2nd param should be the div id that should be hidden
        console.log("emit room full")
        if (user.role === "host") {
            socket.emit('player limit reached', "landing");
        } else {
            console.log("i am in player full server")
            io.to(user.playerId).emit('player limit reached', "player");
        }
    }
    if (players.length === 5) {
        //#Gowri set the players once the required number of players has joined
        hostGlobalVar.playersArray = players;
        hostGlobalVar.playersNum = hostGlobalVar.playersArray.length;
        io.to(hostGlobalVar.hostArray[0].playerId).emit('all players joined', hostGlobalVar);

    }
    // #Gowri emit the players to Host screen
    if (players.length > 0 && players.length <= 5) {
        io.to(hostGlobalVar.hostArray[0].playerId).emit('player joined', players);
    }
    //#jordan send each player their ID & hostID
    if (players.length >= 1) {
        players.forEach(player => {
            //console.log("player "+player.playerId+" emitted");
            var sendme = { hostsock: host[0].playerId, playID: player.playerId, thename: player.userName, room: player.roomId };
            io.to(player.playerId).emit('checkyoself', sendme);
        });
    }

}

//Bex: Generating array of ids
function hostSerialArray(n, initialId) {
    var arr = [];
    for (var i = initialId; i <= n - 1; i += 10) {
        arr.push(i);
    }
    return arr;
}

// Function supplied directly by Bex
function hostShuffle(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

// #SRM this assumes a databse identical to the 2017.08.26 version, if cards/ids change, the query incorporating these ids risks breaking
// #SRM This function generates a shuffled array of ids corresponding to cards in our db
function hostGenerateIdArray(endNum, startNum) {
    return hostShuffle(hostSerialArray(endNum, startNum));
}

// io.to(e.socketId).emit('test', `hi + ${e.userName}`));<|endoftext|>


<commit_before>import React from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import {bindActionCreators} from 'redux';

import { Well, Grid, Row, Col } from 'react-bootstrap'

import LoginForm from './LoginForm'
import * as ACTIONS from '../store/actions';
import {setStorageItem} from '../store/functions';
import config from '../store/config';
import { getLoadedEntry } from '../store/initial-state'

class LoginContainer extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            inputMessage: (typeof(this.props.inputMessage) === 'undefined' || this.props.inputMessage.length === 0)
                ? 'E-mail (a valid e-mail address is required)'
                : this.props.inputMessage
        }
    }
    componentWillUnmount() {
        this.props.actions.clearForm();
        this.props.actions.clearFormExist();
    }
    handleChangeLogin = e => {
        this.props.actions.inputTyping('loggedInId', e.target.value);
    }
    handleSubmit = e => {
        e.preventDefault();
        const email = this.props.loggedInId

        this.props.actions.login(email)
        setStorageItem(sessionStorage, 'user', email)
        this.props.actions.updateStateField('currentEntry', getLoadedEntry())
        this.props.history.push('/' + config.registerText)
    }
    render() {
        const {loggedInId} = this.props;
        const handleChangeLogin = this.handleChangeLogin;
        const handleSubmit = this.handleSubmit;
        const inputMessage = this.state.inputMessage
        const propsObj = {loggedInId, handleChangeLogin, handleSubmit, inputMessage};
        return (
            <Grid fluid={true}>
                <Row>
                    <Col xs={12}>

Access Your Register

Enter your e-mail below to login or create an account.

                    </Col>
                </Row>
                <Row>
                    <Col xs={12}>

                            <Well bsSize="large">
                                <LoginForm {...propsObj} />
                            </Well>

                    </Col>
                </Row>
                <Row>
                    <Col xs={12}>

                            An account will be created if the provided e-mail does not already exist in the system.
                            This is a public 'for fun' register and should not be used to keep track of your real finances.
                            You can, however, fork this repo from GitHub and set it up on your own local box, or somewhere behind authentication.

                    </Col>
                </Row>
            </Grid>
        )
    }
}

const mapStateToProps = state => {
    return {
        loggedInId: state.loggedInId
    }
}

const mapDispatchToProps = dispatch => {
    return {
        actions: bindActionCreators(ACTIONS, dispatch)
    }
}

const Login = withRouter(connect(
    mapStateToProps,
    mapDispatchToProps
)(LoginContainer))

export default Login
<commit_msg>Fixed intermittent 404 issue.<commit_after>import React from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import {bindActionCreators} from 'redux';

import { Well, Grid, Row, Col } from 'react-bootstrap'

import LoginForm from './LoginForm'
import * as ACTIONS from '../store/actions';
import {setStorageItem} from '../store/functions';
import config from '../store/config';
import { getLoadedEntry } from '../store/initial-state'

class LoginContainer extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            inputMessage: (typeof(this.props.inputMessage) === 'undefined' || this.props.inputMessage.length === 0)
                ? 'E-mail (a valid e-mail address is required)'
                : this.props.inputMessage
        }
    }
    componentWillUnmount() {
        this.props.actions.clearForm();
        this.props.actions.clearFormExist();
    }
    handleChangeLogin = e => {
        this.props.actions.inputTyping('loggedInId', e.target.value);
    }
    handleSubmit = e => {
        e.preventDefault();
        const email = this.props.loggedInId

        this.props.actions.login(email)
        setStorageItem(sessionStorage, 'user', email)
        this.props.actions.updateStateField('currentEntry', getLoadedEntry())
        this.props.history.push('/' + config.registerText.toLowerCase())
    }
    render() {
        const {loggedInId} = this.props;
        const handleChangeLogin = this.handleChangeLogin;
        const handleSubmit = this.handleSubmit;
        const inputMessage = this.state.inputMessage
        const propsObj = {loggedInId, handleChangeLogin, handleSubmit, inputMessage};
        return (
            <Grid fluid={true}>
                <Row>
                    <Col xs={12}>

Access Your Register

Enter your e-mail below to login or create an account.

                    </Col>
                </Row>
                <Row>
                    <Col xs={12}>

                            <Well bsSize="large">
                                <LoginForm {...propsObj} />
                            </Well>

                    </Col>
                </Row>
                <Row>
                    <Col xs={12}>

                            An account will be created if the provided e-mail does not already exist in the system.
                            This is a public 'for fun' register and should not be used to keep track of your real finances.
                            You can, however, fork this repo from GitHub and set it up on your own local box, or somewhere behind authentication.

                    </Col>
                </Row>
            </Grid>
        )
    }
}

const mapStateToProps = state => {
    return {
        loggedInId: state.loggedInId
    }
}

const mapDispatchToProps = dispatch => {
    return {
        actions: bindActionCreators(ACTIONS, dispatch)
    }
}

const Login = withRouter(connect(
    mapStateToProps,
    mapDispatchToProps
)(LoginContainer))

export default Login
<|endoftext|>