<commit_before>var decoder = $('#qr-canvas'),
    pr = $('.glyphicon-print'),
    sl = $('.scanner-laser'),
    pl = $('#play'),
    si = $('#scanned-img'),
    sQ = $('#scanned-QR'),
    sv = $('#save'),
    sp = $('#stop'),
    co = $('#contrast'),
    cov = $('#contrast-value'),
    zo = $('#zoom'),
    zov = $('#zoom-value'),
    br = $('#brightness'),
    brv = $('#brightness-value'),
    tr = $('#threshold')
    trv = $('#threshold-value'),
    sh = $('#sharpness'),
    shv = $('#sharpness-value'),
    gr = $('#grayscale'),
    grv = $('#grayscale-value');
pr.parent().click(function() {
    printDiv('.img-thumbnail');
});
sl.css('opacity', .5);
pl.click(function() {
    if (typeof decoder.data().plugin_WebCodeCam == "undefined") {
        decoder.WebCodeCam({
            videoSource: {
                id: $('select#cameraId').val(),
                maxWidth: 640,
                maxHeight: 480
            },
            autoBrightnessValue: 100,
            resultFunction: function(text, imgSrc) {
                si.attr('src', imgSrc);
                sQ.text(text);
                sl.fadeOut(150, function() {
                    sl.fadeIn(150);
                });
            }
        });
        sQ.text('Scanning ...');
        sv.removeClass('disabled');
        sp.click(function(event) {
            sv.addClass('disabled');
            sQ.text('Stopped');
            decoder.data().plugin_WebCodeCam.cameraStop();
        });
    } else {
        sv.removeClass('disabled');
        sQ.text('Scanning ...');
        decoder.data().plugin_WebCodeCam.cameraPlay();
    }
});
sv.click(function() {
    if (typeof decoder.data().plugin_WebCodeCam == "undefined") return;
    var src = decoder.data().plugin_WebCodeCam.getLastImageSrc();
    si.attr('src', src);
});

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
}

function changeZoom(a) {
    var value = typeof a != 'undefined' ? parseFloat(a.toPrecision(2)) : zo.val() / 10;
    zov.text(zov.text().split(':')[0] + ': ' + value.toString());
    decoder.data().plugin_WebCodeCam.options.zoom = parseFloat(value);
    if (typeof a != 'undefined') zo.val(a * 10);
}

function changeContrast() {
    var value = co.val();
    cov.text(cov.text().split(':')[0] + ': ' + value.toString());
    decoder.data().plugin_WebCodeCam.options.contrast = parseFloat(value);
}

function changeBrightness() {
    var value = br.val();
    brv.text(brv.text().split(':')[0] + ': ' + value.toString());
    decoder.data().plugin_WebCodeCam.options.brightness = parseFloat(value);
}

function changeThreshold() {
    var value = tr.val();
    trv.text(trv.text().split(':')[0] + ': ' + value.toString());
    decoder.data().plugin_WebCodeCam.options.threshold = parseFloat(value);
}

function changeSharpness() {
    var value = sh.prop('checked');
    if (value) {
        shv.text(shv.text().split(':')[0] + ': on');
        decoder.data().plugin_WebCodeCam.options.sharpness = [0, -1, 0, -1, 5, -1, 0, -1, 0];
    } else {
        shv.text(shv.text().split(':')[0] + ': off');
        decoder.data().plugin_WebCodeCam.options.sharpness = [];
    }
}

function changeGrayscale() {
    var value = gr.prop('checked');
    if (value) {
        grv.text(grv.text().split(':')[0] + ': on');
        decoder.data().plugin_WebCodeCam.options.grayScale = true;
    } else {
        grv.text(grv.text().split(':')[0] + ': off');
        decoder.data().plugin_WebCodeCam.options.grayScale = false;
    }
}
var getZomm = setInterval(function() {
    var a;
    try {
        a = decoder.data().plugin_WebCodeCam.optimalZoom();
    } catch (e) {
        a = 0;
    }
    if (a != 0) {
        changeZoom(a);
        clearInterval(getZomm);
    }
}, 500);

function gotSources(sourceInfos) {
    for (var i = 0; i !== sourceInfos.length; ++i) {
        var sourceInfo = sourceInfos[i];
        var option = document.createElement('option');
        option.value = sourceInfo.id;
        if (sourceInfo.kind === 'video') {
            var face = sourceInfo.facing == '' ? 'unknown' : sourceInfo.facing;
            option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1) + ' (facing: ' + face + ')';
            videoSelect.appendChild(option);
        }
    }
}
if (typeof MediaStreamTrack.getSources !== 'undefined') {
    var videoSelect = document.querySelector('select#cameraId');
    $(videoSelect).change(function(event) {
        if (typeof decoder.data().plugin_WebCodeCam !== "undefined") {
            decoder.data().plugin_WebCodeCam.options.videoSource.id = $(this).val();
            decoder.data().plugin_WebCodeCam.cameraStop();
            decoder.data().plugin_WebCodeCam.init();
            decoder.data().plugin_WebCodeCam.cameraPlay();
        }
    });
    MediaStreamTrack.getSources(gotSources);
} else {
    document.querySelector('select#cameraId').remove();
}
<commit_msg>minor bug fixed.<commit_after>var decoder = $('#qr-canvas'),
    pr = $('.glyphicon-print'),
    sl = $('.scanner-laser'),
    pl = $('#play'),
    si = $('#scanned-img'),
    sQ = $('#scanned-QR'),
    sv = $('#save'),
    sp = $('#stop'),
    co = $('#contrast'),
    cov = $('#contrast-value'),
    zo = $('#zoom'),
    zov = $('#zoom-value'),
    br = $('#brightness'),
    brv = $('#brightness-value'),
    tr = $('#threshold')
    trv = $('#threshold-value'),
    sh = $('#sharpness'),
    shv = $('#sharpness-value'),
    gr = $('#grayscale'),
    grv = $('#grayscale-value');
pr.parent().click(function() {
    printDiv('.img-thumbnail');
});
sl.css('opacity', .5);
pl.click(function() {
    if (typeof decoder.data().plugin_WebCodeCam == "undefined") {
        decoder.WebCodeCam({
            videoSource: {
                id: $('select#cameraId').val(),
                maxWidth: 640,
                maxHeight: 480
            },
            autoBrightnessValue: 100,
            resultFunction: function(text, imgSrc) {
                si.attr('src', imgSrc);
                sQ.text(text);
                sl.fadeOut(150, function() {
                    sl.fadeIn(150);
                });
            }
        });
        sQ.text('Scanning ...');
        sv.removeClass('disabled');
        sp.click(function(event) {
            sv.addClass('disabled');
            sQ.text('Stopped');
            decoder.data().plugin_WebCodeCam.cameraStop();
        });
    } else {
        sv.removeClass('disabled');
        sQ.text('Scanning ...');
        decoder.data().plugin_WebCodeCam.cameraPlay();
    }
});
sv.click(function() {
    if (typeof decoder.data().plugin_WebCodeCam == "undefined") return;
    var src = decoder.data().plugin_WebCodeCam.getLastImageSrc();
    si.attr('src', src);
});

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
}

function changeZoom(a) {
	if(typeof decoder.data().plugin_WebCodeCam == "undefined") return;
    var value = typeof a != 'undefined' ? parseFloat(a.toPrecision(2)) : zo.val() / 10;
    zov.text(zov.text().split(':')[0] + ': ' + value.toString());
    decoder.data().plugin_WebCodeCam.options.zoom = parseFloat(value);
    if (typeof a != 'undefined') zo.val(a * 10);
}

function changeContrast() {
	if(typeof decoder.data().plugin_WebCodeCam == "undefined") return;
    var value = co.val();
    cov.text(cov.text().split(':')[0] + ': ' + value.toString());
    decoder.data().plugin_WebCodeCam.options.contrast = parseFloat(value);
}

function changeBrightness() {
	if(typeof decoder.data().plugin_WebCodeCam == "undefined") return;
    var value = br.val();
    brv.text(brv.text().split(':')[0] + ': ' + value.toString());
    decoder.data().plugin_WebCodeCam.options.brightness = parseFloat(value);
}

function changeThreshold() {
	if(typeof decoder.data().plugin_WebCodeCam == "undefined") return;
    var value = tr.val();
    trv.text(trv.text().split(':')[0] + ': ' + value.toString());
    decoder.data().plugin_WebCodeCam.options.threshold = parseFloat(value);
}

function changeSharpness() {
	if(typeof decoder.data().plugin_WebCodeCam == "undefined") return;
    var value = sh.prop('checked');
    if (value) {
        shv.text(shv.text().split(':')[0] + ': on');
        decoder.data().plugin_WebCodeCam.options.sharpness =  [  0, -1,  0, -1,  5, -1,   0, -1,  0 ];
    } else {
        shv.text(shv.text().split(':')[0] + ': off');
        decoder.data().plugin_WebCodeCam.options.sharpness = [];
    }
}

function changeGrayscale() {
	if(typeof decoder.data().plugin_WebCodeCam == "undefined") return;
    var value = gr.prop('checked');
    if (value) {
        grv.text(grv.text().split(':')[0] + ': on');
        decoder.data().plugin_WebCodeCam.options.grayScale = true;
    } else {
        grv.text(grv.text().split(':')[0] + ': off');
        decoder.data().plugin_WebCodeCam.options.grayScale = false;
    }
}

var getZomm = setInterval(function() {
    var a;
    try {
        a = decoder.data().plugin_WebCodeCam.optimalZoom();
    } catch (e) {
        a = 0;
    }
    if (a != 0) {
        changeZoom(a);
        clearInterval(getZomm);
    }
}, 500);

function gotSources(sourceInfos) {
    for (var i = 0; i !== sourceInfos.length; ++i) {
        var sourceInfo = sourceInfos[i];
        var option = document.createElement('option');
        option.value = sourceInfo.id;
        if (sourceInfo.kind === 'video') {
            var face = sourceInfo.facing == '' ? 'unknown' : sourceInfo.facing;
            option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1) + ' (facing: ' + face + ')';
            videoSelect.appendChild(option);
        }
    }
}
if (typeof MediaStreamTrack.getSources !== 'undefined') {
    var videoSelect = document.querySelector('select#cameraId');
    $(videoSelect).change(function(event) {
        if (typeof decoder.data().plugin_WebCodeCam !== "undefined") {
            decoder.data().plugin_WebCodeCam.options.videoSource.id = $(this).val();
            decoder.data().plugin_WebCodeCam.cameraStop();
            decoder.data().plugin_WebCodeCam.init();
            decoder.data().plugin_WebCodeCam.cameraPlay();
        }
    });
    MediaStreamTrack.getSources(gotSources);
} else {
    document.querySelector('select#cameraId').remove();
}
<|endoftext|>


<commit_before>"use strict";

var plugin = {};

plugin.getConditions = function(conditions, callback) {
	conditions = conditions.concat([
		{
			"name": "Reputation",
			"condition": "core:user.reputation"
		},
		{
			"name": "Post Count",
			"condition": "core:user.postcount"
		},
		{
			"name": "Last Logged in Time",
			"condition": "core:user.lastonline"
		}
	]);

	callback(false, conditions);
};

plugin.getConditionals = function(conditionals, callback) {
	conditionals = conditionals.concat([
		[
			{
				"name": ">",
				"conditional": "greaterthan"
			},
			{
				"name": ">=",
				"conditional": "greaterorequalthan"
			},
			{
				"name": "<",
				"conditional": "lesserthan"
			},
			{
				"name": "<=",
				"conditional": "lesserorequalthan"
			},
			{
				"name": "string:",
				"conditional": "string"
			}
		]
	]);

	callback(false, conditionals);
};

plugin.getRewards = function(rewards, callback) {
	rewards = rewards.concat([
		{
			"rid": "core:add-to-group",
			"name": "Add to Group",
			"inputs": [
				{
					"type": "select",
					"name": "groupname",
					"label": "Group Name:",
					"values": [
						{
							"name": "Group 1",
							"value": "group1"
						},
						{
							"name": "Group 2",
							"value": "group2"
						},
						{
							"name": "Group 3",
							"value": "group3"
						}
					],
				}
			]
		},
		{
			"rid": "core:alert-user",
			"name": "Send alert message",
			"inputs": [
				{
					"type": "text",
					"name": "title",
					"label": "Title:"
				},
				{
					"type": "text",
					"name": "message",
					"label": "Message:"
				}
			]
		}
	]);
};

module.exports = plugin;<commit_msg>son I heard you like arrays<commit_after>"use strict";

var plugin = {};

plugin.getConditions = function(conditions, callback) {
	conditions = conditions.concat([
		{
			"name": "Reputation",
			"condition": "core:user.reputation"
		},
		{
			"name": "Post Count",
			"condition": "core:user.postcount"
		},
		{
			"name": "Last Logged in Time",
			"condition": "core:user.lastonline"
		}
	]);

	callback(false, conditions);
};

plugin.getConditionals = function(conditionals, callback) {
	conditionals = conditionals.concat([
		{
			"name": ">",
			"conditional": "greaterthan"
		},
		{
			"name": ">=",
			"conditional": "greaterorequalthan"
		},
		{
			"name": "<",
			"conditional": "lesserthan"
		},
		{
			"name": "<=",
			"conditional": "lesserorequalthan"
		},
		{
			"name": "string:",
			"conditional": "string"
		}
	]);

	callback(false, conditionals);
};

plugin.getRewards = function(rewards, callback) {
	rewards = rewards.concat([
		{
			"rid": "core:add-to-group",
			"name": "Add to Group",
			"inputs": [
				{
					"type": "select",
					"name": "groupname",
					"label": "Group Name:",
					"values": [
						{
							"name": "Group 1",
							"value": "group1"
						},
						{
							"name": "Group 2",
							"value": "group2"
						},
						{
							"name": "Group 3",
							"value": "group3"
						}
					],
				}
			]
		},
		{
			"rid": "core:alert-user",
			"name": "Send alert message",
			"inputs": [
				{
					"type": "text",
					"name": "title",
					"label": "Title:"
				},
				{
					"type": "text",
					"name": "message",
					"label": "Message:"
				}
			]
		}
	]);

	callback(false, rewards);
};

module.exports = plugin;<|endoftext|>


<commit_before>(function() {
    var LOVE_CHANGE_TIME = 3000;
    var AUTHORS = [
        'the HackMIT Team',
        'clowns',
        'space monkeys',
        'dragons',
        'the Kimberli Zhong squad',
        'a PRNG',
        'a thousand monkeys with a thousand keyboards',
        'doge',
        'nyan cat',
        'the hivemind',
        'hackbot',
        'Kevin Kwok',
        'left-pad',
        'twitch',
        'a Mersenne twister',
        'HELP I\'M TRAPPED IN A WEBSITE FACTORY',
        'the Illuminati',
        'Beyonc\u00e9',
        'Jack Florey',
        'Oliver Smoot',
        'Ben Bitdiddle',
        'Alyssa P. Hacker',
        'John Harvard',
    ];

    // uniform int from [min, max)
    var uniform = function(min, max) {
        return min + Math.floor(Math.random() * (max - min));
    };

    var choice = function(arr) {
        return arr[uniform(0, arr.length)];
    };

    var update = function() {
        var love = document.getElementById('love');

        var symbol = String.fromCharCode(uniform(0x2700, 0x27c0));

        var author = choice(AUTHORS);

        love.innerHTML = 'Made with ' +
            symbol + ' by ' + author;
    };

    setInterval(update, LOVE_CHANGE_TIME);
}());
<commit_msg>more authors<commit_after>(function() {
    var LOVE_CHANGE_TIME = 3000;
    var AUTHORS = [
        'the HackMIT Team',
        'clowns',
        'space monkeys',
        'dragons',
        'the Kimberli Zhong squad',
        'a PRNG',
        'a thousand monkeys with a thousand keyboards',
        'doge',
        'nyan cat',
        'the hivemind',
        'hackbot',
        'Kevin Kwok',
        'left-pad',
        'twitch',
        'a Mersenne twister',
        'HELP I\'M TRAPPED IN A WEBSITE FACTORY',
        'the Illuminati',
        'Beyonc\u00e9',
        'Jack Florey',
        'Oliver Smoot',
        'Ben Bitdiddle',
        'Alyssa P. Hacker',
        'John Harvard',
        'Kim Zhong Il',
        'jizzboi'
    ];

    // uniform int from [min, max)
    var uniform = function(min, max) {
        return min + Math.floor(Math.random() * (max - min));
    };

    var choice = function(arr) {
        return arr[uniform(0, arr.length)];
    };

    var update = function() {
        var love = document.getElementById('love');

        var symbol = String.fromCharCode(uniform(0x2700, 0x27c0));

        var author = choice(AUTHORS);

        love.innerHTML = 'Made with ' +
            symbol + ' by ' + author;
    };

    setInterval(update, LOVE_CHANGE_TIME);
}());
<|endoftext|>


<commit_before>$(function() {
    // hack for older jquery calls
    $.browser = function() {};

    // fixed header position
    $('#main-header').sticky();

    // scroll smooth
    $('[role=navigation] a').click(function(evt) {
        var href = $.attr(this, 'href');
        $('html,body').animate({
            scrollTop: $(href).offset().top
        }, 500, function() {
            window.location.hash = href;
        });
        evt.preventDefault();
    });

    // Temporarly deactivated pages.
    var disabledSections = [
        //'#schedule',
        '#staff'
        //'#dresscode'
    ];
    $(disabledSections.join(',')).addClass('disabled');
    var disabledClicks = [
            '#home > nav:not([role]) li:first-child a'
    ];
    disabledSections.forEach(function(id) {
        disabledClicks.push('nav a[href="' + id + '"]');
    });
    $(disabledClicks.join(',')).addClass('disabled');
    $('.disabled').on('click', function(evt) {
        $.fallr('show', {
            content: '
In progress

We are working hard to get this very soon
'
        });
        evt.preventDefault();
    });
    // end Temp script

    // Gmaps
    loadMap();

    /* Modal windows */
    // register buttons
    $('.register').click(function(evt) {
        $.fallr('show', {
            content: $('#register').html(),
            width: 560 + 100, // 100 = padding width
            closeOverlay: true,
            buttons: {
                button1: {
                    text: 'Close'
                }
            }
        });
        evt.preventDefault();
        return false;
    });
    // support us
    $('[href="#support-content"]').click(function(evt) {
        $.fallr('show', {
            content: $('#support-content').html(),
            width: 400 + 100, // 100 = padding width
            closeOverlay: true,
            buttons: {
                button1: {
                    text: 'Close'
                }
            }
        });
        evt.preventDefault();
        return false;
    });
    // speaker details
    $('#speakers').on('click', 'a.details', function(evt) {
        $.fallr('show', {
            content: $(this).siblings('.body').html(),
            width: 400 + 100, // 100 = padding width
            closeOverlay: true,
            buttons: {
                button1: {
                    text: 'Close'
                }
            }
        });
        evt.preventDefault();
        return false;
    });

    // retrieve contents from speakers to schedule

    function loadScheduleContent() {
        var name, content;
        $('#schedule section p').each(function(e) {
            content = $('#speakers figcaption:contains("' + $(this).text() + '")').closest('li').find('.body').html();
            $(this).siblings('.body').html(content);
        });

        // schedule details
        $('.talk').on('click', 'a', function(evt) {
            $.fallr('show', {
                content: $(this).siblings('.body').html(),
                width: 400 + 100, // 100 = padding width
                closeOverlay: true,
                buttons: {
                    button1: {
                        text: 'Close'
                    }
                }
            });
            evt.preventDefault();
            return false;
        });
    }

    // speakers generator
    $.get('./data/speakers.json', function(speakers) {
        var context = {
            speakers: speakers
        },
            container = $('#speakers .container > ul > li > ul'),
            compiled = Hogan.compile(container.html()),
            render = compiled.render(context);
        container.html(render);
    });
    // schedule generator
    $.get('./data/schedule.json', function(schedules) {
        var context = {
            schedules: schedules
        },
            container = $('#schedule .container > ul'),
            compiled = Hogan.compile(container.html()),
            render = compiled.render(context);
        container.html(render);
        $('#schedule ul li ul.room1 li.day2').prependTo("#day2 .room1");
        $('#schedule ul li ul.room2 li.day2').prependTo("#day2 .room2");
        loadScheduleContent();
    });
});

function loadMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 14,
        scrollwheel: false, // scroll page
        center: new google.maps.LatLng(43.34684, 3.222342),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    }),
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(43.34684, 3.222342),
            map: map,
            icon: "./img/marker-logo.png",
            title: 'Web5 Baby!'
        });
}<commit_msg>added register tracking<commit_after>$(function() {
    // hack for older jquery calls
    $.browser = function() {};

    // fixed header position
    $('#main-header').sticky();

    // scroll smooth
    $('[role=navigation] a').click(function(evt) {
        var href = $.attr(this, 'href');
        $('html,body').animate({
            scrollTop: $(href).offset().top
        }, 500, function() {
            window.location.hash = href;
        });
        evt.preventDefault();
    });

    // Temporarly deactivated pages.
    var disabledSections = [
        //'#schedule',
        '#staff'
        //'#dresscode'
    ];
    $(disabledSections.join(',')).addClass('disabled');
    var disabledClicks = [
            '#home > nav:not([role]) li:first-child a'
    ];
    disabledSections.forEach(function(id) {
        disabledClicks.push('nav a[href="' + id + '"]');
    });
    $(disabledClicks.join(',')).addClass('disabled');
    $('.disabled').on('click', function(evt) {
        $.fallr('show', {
            content: '
In progress

We are working hard to get this very soon
'
        });
        evt.preventDefault();
    });
    // end Temp script

    // Gmaps
    loadMap();

    /* Modal windows */
    // register buttons
    $('.register').click(function(evt) {
        $.fallr('show', {
            content: $('#register').html(),
            width: 560 + 100, // 100 = padding width
            closeOverlay: true,
            buttons: {
                button1: {
                    text: 'Close'
                }
            }
        });
        evt.preventDefault();
        return false;
    });
    // support us
    $('[href="#support-content"]').click(function(evt) {
        $.fallr('show', {
            content: $('#support-content').html(),
            width: 400 + 100, // 100 = padding width
            closeOverlay: true,
            buttons: {
                button1: {
                    text: 'Close'
                }
            }
        });
        evt.preventDefault();
        return false;
    });
    // speaker details
    $('#speakers').on('click', 'a.details', function(evt) {
        $.fallr('show', {
            content: $(this).siblings('.body').html(),
            width: 400 + 100, // 100 = padding width
            closeOverlay: true,
            buttons: {
                button1: {
                    text: 'Close'
                }
            }
        });
        evt.preventDefault();
        return false;
    });

    // retrieve contents from speakers to schedule

    function loadScheduleContent() {
        var name, content;
        $('#schedule section p').each(function(e) {
            content = $('#speakers figcaption:contains("' + $(this).text() + '")').closest('li').find('.body').html();
            $(this).siblings('.body').html(content);
        });

        // schedule details
        $('.talk').on('click', 'a', function(evt) {
            $.fallr('show', {
                content: $(this).siblings('.body').html(),
                width: 400 + 100, // 100 = padding width
                closeOverlay: true,
                buttons: {
                    button1: {
                        text: 'Close'
                    }
                }
            });
            evt.preventDefault();
            return false;
        });
    }

    // speakers generator
    $.get('./data/speakers.json', function(speakers) {
        var context = {
            speakers: speakers
        },
            container = $('#speakers .container > ul > li > ul'),
            compiled = Hogan.compile(container.html()),
            render = compiled.render(context);
        container.html(render);
    });
    // schedule generator
    $.get('./data/schedule.json', function(schedules) {
        var context = {
            schedules: schedules
        },
            container = $('#schedule .container > ul'),
            compiled = Hogan.compile(container.html()),
            render = compiled.render(context);
        container.html(render);
        $('#schedule ul li ul.room1 li.day2').prependTo("#day2 .room1");
        $('#schedule ul li ul.room2 li.day2').prependTo("#day2 .room2");
        loadScheduleContent();
    });

    $('.register').on('click', function(e) {
        _gaq.push(['_trackEvent', 'registration', 'register', 'register button']);
    });
});

function loadMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 14,
        scrollwheel: false, // scroll page
        center: new google.maps.LatLng(43.34684, 3.222342),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    }),
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(43.34684, 3.222342),
            map: map,
            icon: "./img/marker-logo.png",
            title: 'Web5 Baby!'
        });
}<|endoftext|>


<commit_before>// Method chaining in jquery
$("li").css("color", "blue")
       .slideUp(1000)
       .slideDown(1000)
       .attr("title", "My Title");

// What is JSON
var employeesJSON = [{
    "firstName": "Goran",
    "lastName": "Djordjijevski",
    "gender": "Male",
    "years": 29
},
{
    "firstName": "Sara",
    "lastName": "Jovanovic",
    "gender": "Female",
    "years": 25
}];

var result = "";
result += "First Name = " + employeesJSON[0].firstName + "
";
result += "Last Name = " + employeesJSON[0].lastName + "
";
result += "Gender = " + employeesJSON[0].gender + "
";
result += "Years = " + employeesJSON[0].years + "
";

result += "First Name = " + employeesJSON[1].firstName + "
";
result += "Last Name = " + employeesJSON[1].lastName + "
";
result += "Gender = " + employeesJSON[1].gender + "
";
result += "Years = " + employeesJSON[1].years + "
"

// $("#result").html(result);

// DOM Manipulation methods
// var returnAttr = $("div").attr("title");
// console.log(returnAttr);

// $("div").each(function() {
//     console.log($(this).attr("title"));
// });

// DOM Manipulation methods with JSON object
var config = {
    "title": "New DIV Title",
    "style": "border: 1px solid red",
    "name": "MY DIV"
};

// DOM Manipulation with .wrap() method
// $("div").wrap("

");
// $("div").append("
add a new parent div container
");

// Add or remove class
$("#btn1").on("click", function() {
    $("h1").addClass("colorClass");
});

$("#btn2").on("click", function() {
    $("h1").removeClass("colorClass");
});

$("#btn3").on("click", function() {
    $("h1").addClass("colorClass italicClass");
});

$("#btn4").on("click", function() {
    $("h1").removeClass("colorClass italicClass");
});

$("#btn5").on("click", function() {
    $("h1").addClass("colorClass italicClass boldClass");
});

$("#btn6").on("click", function() {
    $("h1").removeClass("colorClass italicClass boldClass");
});

$("#btn7").on("click", function() {
    $("h1").toggleClass("colorClass italicClass boldClass");
});

$("input[type='text']").each(function() {
    $(this).focus(function() {
        $(this).toggleClass("textBoxStyle");
    });
});

// jQuery change event
// $("#ddlCity").change(function() {
//     var selectedValue = $(this).val();
//     $("#divResult").html(selectedValue);
// });

// $("input").change(function() {
//     var result = "";
//     if (result == "") {
//         result = $(this).val();
//     }
//     else {
//         result += ", " + $(this).val();
//     }

//     $("#divResult").html(result);
// });

// jQuery mouse events
$("img[src='img/help.png']").mouseover(function() {
    $("#" + getDivId(this)).fadeIn(500);
}).mouseout(function() {
    $("#" + getDivId(this)).fadeOut(500);
});

function getDivId(helpIcon) {
    var helpIconId = $(helpIcon).attr("id");
    return helpIconId.replace("img", "div");
}<commit_msg>Idemo.<commit_after>// Method chaining in jquery
$("li").css("color", "blue")
       .slideUp(1000)
       .slideDown(1000)
       .attr("title", "My Title");

// What is JSON
var employeesJSON = [{
    "firstName": "Goran",
    "lastName": "Djordjijevski",
    "gender": "Male",
    "years": 29
},
{
    "firstName": "Sara",
    "lastName": "Jovanovic",
    "gender": "Female",
    "years": 25
}];

var result = "";
result += "First Name = " + employeesJSON[0].firstName + "
";
result += "Last Name = " + employeesJSON[0].lastName + "
";
result += "Gender = " + employeesJSON[0].gender + "
";
result += "Years = " + employeesJSON[0].years + "
";

result += "First Name = " + employeesJSON[1].firstName + "
";
result += "Last Name = " + employeesJSON[1].lastName + "
";
result += "Gender = " + employeesJSON[1].gender + "
";
result += "Years = " + employeesJSON[1].years + "
"

// $("#result").html(result);

// DOM Manipulation methods
// var returnAttr = $("div").attr("title");
// console.log(returnAttr);

// $("div").each(function() {
//     console.log($(this).attr("title"));
// });

// DOM Manipulation methods with JSON object
var config = {
    "title": "New DIV Title",
    "style": "border: 1px solid red",
    "name": "MY DIV"
};

// DOM Manipulation with .wrap() method
// $("div").wrap("

");
// $("div").append("
add a new parent div container
");

// Add or remove class
$("#btn1").on("click", function() {
    $("h1").addClass("colorClass");
});

$("#btn2").on("click", function() {
    $("h1").removeClass("colorClass");
});

$("#btn3").on("click", function() {
    $("h1").addClass("colorClass italicClass");
});

$("#btn4").on("click", function() {
    $("h1").removeClass("colorClass italicClass");
});

$("#btn5").on("click", function() {
    $("h1").addClass("colorClass italicClass boldClass");
});

$("#btn6").on("click", function() {
    $("h1").removeClass("colorClass italicClass boldClass");
});

$("#btn7").on("click", function() {
    $("h1").toggleClass("colorClass italicClass boldClass");
});

$("input[type='text']").each(function() {
    $(this).focus(function() {
        $(this).toggleClass("textBoxStyle");
    });
});

// jQuery change event
// $("#ddlCity").change(function() {
//     var selectedValue = $(this).val();
//     $("#divResult").html(selectedValue);
// });

// $("input").change(function() {
//     var result = "";
//     if (result == "") {
//         result = $(this).val();
//     }
//     else {
//         result += ", " + $(this).val();
//     }

//     $("#divResult").html(result);
// });

// jQuery mouse events
$("img[src='img/help.png']").mouseover(function() {
    $("#" + getDivId(this)).fadeIn(500);
}).mouseout(function() {
    $("#" + getDivId(this)).fadeOut(500);
});

function getDivId(helpIcon) {
    var helpIconId = $(helpIcon).attr("id");
    return helpIconId.replace("img", "div");
}

// samo test komentar<|endoftext|>


<commit_before>$(document).ready(function(){

    var nav = $('.main-nav');

    // Toggle mobile nav
    $('.toggle-nav').click(function(e){
        e.preventDefault();
        nav.slideToggle();
    });

    // Reset when window switches to desktop view
    $(window).resize(function() {
        if ($(window).width() > 750) {
            nav.show();
        } else {
            nav.hide();
        }
    });
});
<commit_msg>Add JS link scrolling<commit_after>$(document).ready(function(){

    var nav = $('.main-nav');

    // Toggle mobile nav
    $('.toggle-nav').click(function(e){
        e.preventDefault();
        nav.slideToggle();
    });

    // Reset when window switches to desktop view
    $(window).resize(function() {
        if ($(window).width() > 750) {
            nav.show();
        } else {
            nav.hide();
        }
    });

    //Smooth scroll to page id (for index page)

    $('a[href^="/#"], a[href^="#"]').on('click',function (e) {

        var target = this.hash;
        var $target = $(target);
        var path = window.location.pathname;

        if (path == '/' || target == '#contact'){
            e.preventDefault();

            $('html, body').stop().animate({
                'scrollTop': $target.offset().top
            }, 900, 'swing', function () {
                window.location.hash = target;
            });
        }
    });

});
<|endoftext|>


<commit_before>$.backstretch("img/bg.svg");
var $happybday = $('.happy-bday'),
    $page      = $('.page');
    $window    = $(window);

$happybday.css({
  top: $window.height()
});

$("img.lazy").show().lazyload({
    // effect : "fadeIn"
});

$window.on('resize', function(){
  $happybday.height($window.height());
});

$window.on('load', function(){
  $page.css({
    visibility: 'visible'
  });
  $happybday.transition({
    top: 0
  }, 2000);
  setTimeout(function() {
    $happybday.addClass('floating');
  }, 2000);
});

$window.trigger('resize');

<commit_msg>Changed lazyload event to be triggered on window load<commit_after>$.backstretch("img/bg.svg");
var $happybday = $('.happy-bday'),
    $page      = $('.page'),
    $lazyImg   = $("img.lazy"),
    $window    = $(window);

$happybday.css({
  top: $window.height()
});

$lazyImg.show().lazyload({
    'effect': "fadeIn",
    'event' : "custom"
});

$window.on('resize', function(){
  $happybday.height($window.height());
});

$window.on('load', function(){
  $lazyImg.trigger("custom");
  $page.css({
    visibility: 'visible'
  });
  $happybday.transition({
    top: 0
  }, 2000);
  setTimeout(function() {
    $happybday.addClass('floating');
  }, 2000);
});

$window.trigger('resize');

<|endoftext|>


<commit_before>var TAGS_TO_FILTERS = {
  lang: 'language',
  ctry: 'country',
  cat: 'category',
  src: 'datasource'
};

var CATEGORY_ICONS = {
  biz: 'briefcase',
  economy: 'area-chart',
  health: 'heart',
  edu: 'graduation-cap',
  ecology: 'leaf',
  culture: 'paint-brush',
  security: 'shield',
  transport: 'car',
  geo: 'map',
  state: 'university',
  tourism: 'plane'
};

function isEmptyPathnameIgnoreLanguage(pathname) {
  var pathnameParts = pathname.split('/').filter(function(part) { return part !== ''; });
  return pathnameParts.length === 0 || pathnameParts.length === 1 && pathnameParts[0].length <= 2;
}

function search_parseQuery() {
  var ret = '';
  var params = MDSCommon.parseQuery(window.location.search);
  if (MDSCommon.isPresent(params.tags)) {
    var tags = params.tags.split(',');
    tags.forEach(function(tag) {
      if (tag[0] !== '@') {
        ret += '#';
      }
      ret += tag + ' ';
    });
  }
  if (MDSCommon.isPresent(params.q)) {
    ret += params.q;
  }
  return ret;
}

function search_parseSearchString(search, useFilterTags) {
  var tags = [];
  var newSearch = '';
  var filters = {};
  var parts = search.split(/\s+/);
  for (var i in parts) {
    var part = parts[i];
    if (part[0] === '#') {
      var filter2val = part.split(':');
      if (filter2val.length === 1) {
        tags.push(part.substring(1));
      } else {
        filter = useFilterTags ?filter2val[0].substring(1) : TAGS_TO_FILTERS[filter2val[0].substring(1)];
        if (filter) {
          filters[filter] = filter2val[1];
        }
      }
    } else {
      if (newSearch !== '') {
        newSearch += ' ';
      }
      newSearch += part;
    }
  }

  return {
    search: newSearch,
    filters: filters,
    tags: tags
  }
}

function search_getQueryFromSearchString(search) {
  var options = search_parseSearchString(search, true);
  var ret = '';
  for (var filter in options.filters) {
    if (ret === '') {
      ret += 'tags='
    } else {
      ret += ','
    }
    ret += filter + ':' + options.filters[filter];
  }

  options.tags.forEach(function(tag) {
    if (ret === '') {
      ret += 'tags='
    } else {
      ret += ','
    }
    ret += tag;
  });

  if (MDSCommon.isPresent(options.search)) {
    if (ret !== '') {
      ret += '&'
    }
    ret += 'q=' + options.search;
  }

  if (ret === '') {
    return '';
  }
  return '?' + ret;
}

function getHtmlFromTemplate(template, data) {
  var ret = '';
  var state = '';
  var statement;
  for (var i = 0; i < template.length; i++) {
    var c = template[i];
    switch (c) {
      case '{':
        switch (state) {
          case 'left_brace':
            state = 'statement';
            statement = '';
            break;
          case '':
            state = 'left_brace';
            break;
          default:
            throw new Error('Unexpected character');
        }
        break;
      case '}':
        switch (state) {
          case 'statement':
            state = 'right_brace';
            break;
          case 'right_brace':
            ret += data[statement];
            statement = null;
            state = '';
            break;
          case '':
            ret += c;
            break;
          default:
            throw new Error('Unexpected character');
        }
        break;
      default:
        switch (state) {
          case 'statement':
            var code = c.charCodeAt(0);
            if (c === '_' || c === '-' || c === '.' ||
                code >= 'a'.charCodeAt(0) && code <= 'z'.charCodeAt(0) ||
                code >= 'A'.charCodeAt(0) && code <= 'Z'.charCodeAt(0) ||
                code >= '0'.charCodeAt(0) && code <= '9'.charCodeAt(0)) {
              statement += c;
            } else if (c !== ' ') {
              throw new Error('Unexpected character');
            }
            break;
          case 'left_brace':
            state = '';
            ret += '{' + c;
            break;
          default:
            ret += c;
        }
        break;
    }
  }
  return ret;
}

function parseSnippetTemplate(template) {
  if (template == null) {
    throw new Error('Parameter template can not be null');
  }
  var parts = template.split('\n---\n');
  return {
    template: Handlebars.compile(parts[0]),
    scripts: Handlescripts.compile(parts[1] || '')
  };
}

function parseSingleScript(s, fields) {
  var state = 'helper_name';
  var helperName = '';
  var options = [];
  s += ' ';
  for (var i in s) {
    var c = s[i];
    switch (c) {
      case ' ':
        switch (state) {
          case 'space':
            break;
          case 'helper_name':
            state = 'space';
            break;
          case 'string':
            options[options.length-1] += c;
            break;
          case 'option':
            options[options.length-1] = fields[options[options.length-1]];
            state = 'space';
            break;
          default:
            throw new Error('Unexpected char' + c + ' in state ' + state);
            break;
        }
        break;
      case '"':
        switch (state) {
          case 'space':
            options.push('');
            state = 'string';
            break;
          case 'string':
            state = 'space';
            break;
          case 'helper_name':
          case 'option':
          default:
            throw new Error('Unexpected char' + c + ' in state ' + state);
            break;
        }
        break;
      default:
        switch (state) {
          case 'space':
            state = 'option';
            options.push(c);
            break;
          case 'string':
            options[options.length-1] += c;
            break;
          case 'helper_name':
            helperName += c;
            break;
          case 'option':
            options[options.length-1] += c;
            break;
          default:
            throw new Error('Unexpected char ' + c + ' in state ' + state);
            break;
        }
        break;
    }
  }
  return Handlescripts.helpers[helperName] ? Handlescripts.helpers[helperName](options) : '';
}

function parseScripts(scripts, fields) {
  return scripts.split('\n').filter(function(l) { return l.trim() !== ''; }).map(function(l) {
    return parseSingleScript(l, fields);
  });
}

Handlescripts = {
  helpers: {},
  registerHelper: function(name, fn) {
    Handlescripts.helpers[name] = fn;
  },
  registerSource: function(name, src) {
    if (typeof src !== 'string') {
      throw new Error('src must be string');
    }
    Handlescripts.helpers[name] = function() {
      return '<script>' +
      ' $.ajax({\n' +
      '    async: false,\n' +
      '    url: "' + src + '",\n' +
      '    dataType: "script"\n' +
      ' });' +
      '</script>';
    };

    // Handlescripts.helpers[name] = function() {
    //   return '<script>(function() {\n' +
    //     '    var req = new XMLHttpRequest();\n' +
    //     '    req.open("GET", "' + src + '", false);\n' +
    //     '    req.send();\n' +
    //     '    eval(req.responseText);\n' +
    //     '})();</script>';
    // };
  },

  compile: function(scripts) {
    return parseScripts.bind(Handlescripts, scripts);
  }
};

Handlescripts.registerSource('vk', 'https://vk.com/js/api/openapi.js?150');
Handlescripts.registerSource('ok', 'https://connect.ok.ru/connect.js');
Handlescripts.registerSource('ymaps', 'https://api-maps.yandex.ru/2.1/?lang=en_RU');

Handlescripts.registerHelper('ymapsAddr', function(options) {
  var address = encodeURIComponent(options[0] + ', ' + options[1]);
  return '<script>' +
    '$.getJSON(\'https://geocode-maps.yandex.ru/1.x/?geocode=\' + address + \'&format=json\', function(data) {\n' +
    '    var point = eval(\'[\' + data.response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos + \']\');\n' +
    '    var myMap = new ymaps.Map(\'map\', {\n' +
    '            center: point,\n' +
    '            zoom: 9\n' +
    '        });\n' +
    '    myMap.geoObjects.add(new ymaps.Placemark(point));\n' +
    '});' +
    '</script>';
});

Handlescripts.registerHelper('vkGroupWidget', function(options) {
  var vk_id = options[0];
  if (MDSCommon.isBlank(vk_id)) {
    return '';
  }
  return  '<script>VK.Widgets.Group("vk_groups_' + vk_id + '", {mode: 3}, ' + vk_id + ');</script>';
});

Handlescripts.registerHelper('vkGroupWidget', function(options) {
  var vk_id = options[0];
  if (MDSCommon.isBlank(vk_id)) {
    return '';
  }
  return  '<script>VK.Widgets.Group("vk_groups_' + vk_id + '", {mode: 3}, ' + vk_id + ');</script>';
});

Handlescripts.registerHelper('okGroupWidget', function(options) {
  var ok_id = options[0];
  if (MDSCommon.isBlank(ok_id)) {
    return '';
  }
  return  '<script>OK.CONNECT.insertGroupWidget("ok_group_widget_' + ok_id + '", ' + ok_id + ', \'{"width":200,"height":230}\');</script>';
});

if (typeof Handlebars !== 'undefined') {
  Handlebars.registerHelper('host', function(url) {
    var m = url.match(/^\w+:\/\/([^/]+)/);
    if (!m) {
      return url;
    }
    return m[1];
  });
}

/**
 * Add JSON-LD for Google Search Engine
 * @param {Object} data - Data received for root from MyDataSpace backend.
 */
function addJsonLD(data) {
  var script = document.createElement('script');
  script.type = 'application/ld+json';
  script.text = JSON.stringify({
    "@context": "http://schema.org",
    "@id": "https://myda.space/" + data.root,
    "@type": "Dataset",
    "name":  MDSCommon.findValueByName(data.fields, 'name'),
    "description": MDSCommon.findValueByName(data.fields, 'description'),
    "keywords": MDSCommon.findValueByName(data.fields, 'tags')
  });
  document.querySelector('head').appendChild(script);
}

function getCodepenIDByURL(url) {
  var regex = /^https?:\/\/codepen.io\/(\w+)\/pen\/(\w+)/;
  var m = regex.exec(url);
  if (!m) {
    return null;
  }
  return m[1] + '/' + m[2];
}

function getCodepenURL(id) {
  var parts = id.split('/');
  return 'https://codepen.io/' + parts[0] + '/pen/' + parts[1];
}

function getPathnameParts(pathname) {
  var pathnameParts = pathname.split('/').filter(function(part) { return part !== ''; });
  if (pathnameParts[0].length <= 2) {
    pathnameParts.shift();
  }
  return pathnameParts;
}

function getRequestFromLocation(loc) {
  var pathnameParts = getPathnameParts(loc.pathname);
  var searchParams = MDSCommon.parseQuery(loc.search);
  return {
    root: pathnameParts[0] === 'root' ? '11111' : pathnameParts[0],
    path: '',
    version: searchParams.v
  };
}

function getURLLanguagePrefix(language) {
  return MDSCommon.isBlank(language) || language === 'en' ? '' : '/' + language;
}

function showWaitingCloak() {
  document.getElementById('waiting_cloak').style.display = 'block';
}

function hideWaitingCloak() {
  document.getElementById('waiting_cloak').style.display = 'none';
}

RootHelper = {
  validateLookForm: function() {
    document.getElementById('look_modal__title_err').innerText = '';
    document.getElementById('look_modal__codepen_err').innerText = '';

    var title = document.getElementById('look_modal__title').value;
    var codepen = document.getElementById('look_modal__codepen').value;

    if (MDSCommon.isBlank(title)) {
      document.getElementById('look_modal__title_err').innerText = tr$('title_cant_be_blank');
      return false;
    }

    if (title.length > 250) {
      document.getElementById('look_modal__title_err').innerText = tr$('too_long_title');
      return false;
    }

    switch (document.getElementById('look_modal').data('look-type')) {
      case 'codepen':
        if (MDSCommon.isBlank(codepen)) {
          document.getElementById('look_modal__codepen_err').innerText = tr$('codepen_url_cant_be_blank');
          return false;
        }
        var codepenID = getCodepenIDByURL(codepen);
        if (!codepenID) {
          document.getElementById('look_modal__codepen_err').innerText = tr$('invalid_codepen_pen_url');
          return false;
        }
        break;
      case 'table':
        break;
      case 'list':
        break;
    }
    return true;
  }
};<commit_msg>feat: yandex maps widget<commit_after>var TAGS_TO_FILTERS = {
  lang: 'language',
  ctry: 'country',
  cat: 'category',
  src: 'datasource'
};

var CATEGORY_ICONS = {
  biz: 'briefcase',
  economy: 'area-chart',
  health: 'heart',
  edu: 'graduation-cap',
  ecology: 'leaf',
  culture: 'paint-brush',
  security: 'shield',
  transport: 'car',
  geo: 'map',
  state: 'university',
  tourism: 'plane'
};

function isEmptyPathnameIgnoreLanguage(pathname) {
  var pathnameParts = pathname.split('/').filter(function(part) { return part !== ''; });
  return pathnameParts.length === 0 || pathnameParts.length === 1 && pathnameParts[0].length <= 2;
}

function search_parseQuery() {
  var ret = '';
  var params = MDSCommon.parseQuery(window.location.search);
  if (MDSCommon.isPresent(params.tags)) {
    var tags = params.tags.split(',');
    tags.forEach(function(tag) {
      if (tag[0] !== '@') {
        ret += '#';
      }
      ret += tag + ' ';
    });
  }
  if (MDSCommon.isPresent(params.q)) {
    ret += params.q;
  }
  return ret;
}

function search_parseSearchString(search, useFilterTags) {
  var tags = [];
  var newSearch = '';
  var filters = {};
  var parts = search.split(/\s+/);
  for (var i in parts) {
    var part = parts[i];
    if (part[0] === '#') {
      var filter2val = part.split(':');
      if (filter2val.length === 1) {
        tags.push(part.substring(1));
      } else {
        filter = useFilterTags ?filter2val[0].substring(1) : TAGS_TO_FILTERS[filter2val[0].substring(1)];
        if (filter) {
          filters[filter] = filter2val[1];
        }
      }
    } else {
      if (newSearch !== '') {
        newSearch += ' ';
      }
      newSearch += part;
    }
  }

  return {
    search: newSearch,
    filters: filters,
    tags: tags
  }
}

function search_getQueryFromSearchString(search) {
  var options = search_parseSearchString(search, true);
  var ret = '';
  for (var filter in options.filters) {
    if (ret === '') {
      ret += 'tags='
    } else {
      ret += ','
    }
    ret += filter + ':' + options.filters[filter];
  }

  options.tags.forEach(function(tag) {
    if (ret === '') {
      ret += 'tags='
    } else {
      ret += ','
    }
    ret += tag;
  });

  if (MDSCommon.isPresent(options.search)) {
    if (ret !== '') {
      ret += '&'
    }
    ret += 'q=' + options.search;
  }

  if (ret === '') {
    return '';
  }
  return '?' + ret;
}

function getHtmlFromTemplate(template, data) {
  var ret = '';
  var state = '';
  var statement;
  for (var i = 0; i < template.length; i++) {
    var c = template[i];
    switch (c) {
      case '{':
        switch (state) {
          case 'left_brace':
            state = 'statement';
            statement = '';
            break;
          case '':
            state = 'left_brace';
            break;
          default:
            throw new Error('Unexpected character');
        }
        break;
      case '}':
        switch (state) {
          case 'statement':
            state = 'right_brace';
            break;
          case 'right_brace':
            ret += data[statement];
            statement = null;
            state = '';
            break;
          case '':
            ret += c;
            break;
          default:
            throw new Error('Unexpected character');
        }
        break;
      default:
        switch (state) {
          case 'statement':
            var code = c.charCodeAt(0);
            if (c === '_' || c === '-' || c === '.' ||
                code >= 'a'.charCodeAt(0) && code <= 'z'.charCodeAt(0) ||
                code >= 'A'.charCodeAt(0) && code <= 'Z'.charCodeAt(0) ||
                code >= '0'.charCodeAt(0) && code <= '9'.charCodeAt(0)) {
              statement += c;
            } else if (c !== ' ') {
              throw new Error('Unexpected character');
            }
            break;
          case 'left_brace':
            state = '';
            ret += '{' + c;
            break;
          default:
            ret += c;
        }
        break;
    }
  }
  return ret;
}

function parseSnippetTemplate(template) {
  if (template == null) {
    throw new Error('Parameter template can not be null');
  }
  var parts = template.split('\n---\n');
  return {
    template: Handlebars.compile(parts[0]),
    scripts: Handlescripts.compile(parts[1] || '')
  };
}

function parseSingleScript(s, fields) {
  var state = 'helper_name';
  var helperName = '';
  var options = [];
  s += ' ';
  for (var i in s) {
    var c = s[i];
    switch (c) {
      case ' ':
        switch (state) {
          case 'space':
            break;
          case 'helper_name':
            state = 'space';
            break;
          case 'string':
            options[options.length-1] += c;
            break;
          case 'option':
            options[options.length-1] = fields[options[options.length-1]];
            state = 'space';
            break;
          default:
            throw new Error('Unexpected char' + c + ' in state ' + state);
            break;
        }
        break;
      case '"':
        switch (state) {
          case 'space':
            options.push('');
            state = 'string';
            break;
          case 'string':
            state = 'space';
            break;
          case 'helper_name':
          case 'option':
          default:
            throw new Error('Unexpected char' + c + ' in state ' + state);
            break;
        }
        break;
      default:
        switch (state) {
          case 'space':
            state = 'option';
            options.push(c);
            break;
          case 'string':
            options[options.length-1] += c;
            break;
          case 'helper_name':
            helperName += c;
            break;
          case 'option':
            options[options.length-1] += c;
            break;
          default:
            throw new Error('Unexpected char ' + c + ' in state ' + state);
            break;
        }
        break;
    }
  }
  return Handlescripts.helpers[helperName] ? Handlescripts.helpers[helperName](options) : '';
}

function parseScripts(scripts, fields) {
  return scripts.split('\n').filter(function(l) { return l.trim() !== ''; }).map(function(l) {
    return parseSingleScript(l, fields);
  });
}

Handlescripts = {
  helpers: {},
  registerHelper: function(name, fn) {
    Handlescripts.helpers[name] = fn;
  },
  registerSource: function(name, src) {
    if (typeof src !== 'string') {
      throw new Error('src must be string');
    }
    Handlescripts.helpers[name] = function() {
      return '<script>' +
      ' $.ajax({\n' +
      '    async: false,\n' +
      '    url: "' + src + '",\n' +
      '    dataType: "script"\n' +
      ' });' +
      '</script>';
    };

    // Handlescripts.helpers[name] = function() {
    //   return '<script>(function() {\n' +
    //     '    var req = new XMLHttpRequest();\n' +
    //     '    req.open("GET", "' + src + '", false);\n' +
    //     '    req.send();\n' +
    //     '    eval(req.responseText);\n' +
    //     '})();</script>';
    // };
  },

  compile: function(scripts) {
    return parseScripts.bind(Handlescripts, scripts);
  }
};

Handlescripts.registerSource('vk', 'https://vk.com/js/api/openapi.js?150');
Handlescripts.registerSource('ok', 'https://connect.ok.ru/connect.js');
Handlescripts.registerSource('ymaps', 'https://api-maps.yandex.ru/2.1/?lang=en_RU');

Handlescripts.registerHelper('ymapsAddr', function(options) {
  var address = encodeURIComponent(options[0] + ', ' + options[1]);
  return '<script>' +
    '$.getJSON(\'https://geocode-maps.yandex.ru/1.x/?geocode=' + address + '&format=json\', function(data) {\n' +
    '    var point = eval(\'[\' + data.response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos + \']\');\n' +
    '    var myMap = new ymaps.Map(\'map\', {\n' +
    '            center: point,\n' +
    '            zoom: 9\n' +
    '        });\n' +
    '    myMap.geoObjects.add(new ymaps.Placemark(point));\n' +
    '});' +
    '</script>';
});

Handlescripts.registerHelper('vkGroupWidget', function(options) {
  var vk_id = options[0];
  if (MDSCommon.isBlank(vk_id)) {
    return '';
  }
  return  '<script>VK.Widgets.Group("vk_groups_' + vk_id + '", {mode: 3}, ' + vk_id + ');</script>';
});

Handlescripts.registerHelper('vkGroupWidget', function(options) {
  var vk_id = options[0];
  if (MDSCommon.isBlank(vk_id)) {
    return '';
  }
  return  '<script>VK.Widgets.Group("vk_groups_' + vk_id + '", {mode: 3}, ' + vk_id + ');</script>';
});

Handlescripts.registerHelper('okGroupWidget', function(options) {
  var ok_id = options[0];
  if (MDSCommon.isBlank(ok_id)) {
    return '';
  }
  return  '<script>OK.CONNECT.insertGroupWidget("ok_group_widget_' + ok_id + '", ' + ok_id + ', \'{"width":200,"height":230}\');</script>';
});

if (typeof Handlebars !== 'undefined') {
  Handlebars.registerHelper('host', function(url) {
    var m = url.match(/^\w+:\/\/([^/]+)/);
    if (!m) {
      return url;
    }
    return m[1];
  });
}

/**
 * Add JSON-LD for Google Search Engine
 * @param {Object} data - Data received for root from MyDataSpace backend.
 */
function addJsonLD(data) {
  var script = document.createElement('script');
  script.type = 'application/ld+json';
  script.text = JSON.stringify({
    "@context": "http://schema.org",
    "@id": "https://myda.space/" + data.root,
    "@type": "Dataset",
    "name":  MDSCommon.findValueByName(data.fields, 'name'),
    "description": MDSCommon.findValueByName(data.fields, 'description'),
    "keywords": MDSCommon.findValueByName(data.fields, 'tags')
  });
  document.querySelector('head').appendChild(script);
}

function getCodepenIDByURL(url) {
  var regex = /^https?:\/\/codepen.io\/(\w+)\/pen\/(\w+)/;
  var m = regex.exec(url);
  if (!m) {
    return null;
  }
  return m[1] + '/' + m[2];
}

function getCodepenURL(id) {
  var parts = id.split('/');
  return 'https://codepen.io/' + parts[0] + '/pen/' + parts[1];
}

function getPathnameParts(pathname) {
  var pathnameParts = pathname.split('/').filter(function(part) { return part !== ''; });
  if (pathnameParts[0].length <= 2) {
    pathnameParts.shift();
  }
  return pathnameParts;
}

function getRequestFromLocation(loc) {
  var pathnameParts = getPathnameParts(loc.pathname);
  var searchParams = MDSCommon.parseQuery(loc.search);
  return {
    root: pathnameParts[0] === 'root' ? '11111' : pathnameParts[0],
    path: '',
    version: searchParams.v
  };
}

function getURLLanguagePrefix(language) {
  return MDSCommon.isBlank(language) || language === 'en' ? '' : '/' + language;
}

function showWaitingCloak() {
  document.getElementById('waiting_cloak').style.display = 'block';
}

function hideWaitingCloak() {
  document.getElementById('waiting_cloak').style.display = 'none';
}

RootHelper = {
  validateLookForm: function() {
    document.getElementById('look_modal__title_err').innerText = '';
    document.getElementById('look_modal__codepen_err').innerText = '';

    var title = document.getElementById('look_modal__title').value;
    var codepen = document.getElementById('look_modal__codepen').value;

    if (MDSCommon.isBlank(title)) {
      document.getElementById('look_modal__title_err').innerText = tr$('title_cant_be_blank');
      return false;
    }

    if (title.length > 250) {
      document.getElementById('look_modal__title_err').innerText = tr$('too_long_title');
      return false;
    }

    switch (document.getElementById('look_modal').data('look-type')) {
      case 'codepen':
        if (MDSCommon.isBlank(codepen)) {
          document.getElementById('look_modal__codepen_err').innerText = tr$('codepen_url_cant_be_blank');
          return false;
        }
        var codepenID = getCodepenIDByURL(codepen);
        if (!codepenID) {
          document.getElementById('look_modal__codepen_err').innerText = tr$('invalid_codepen_pen_url');
          return false;
        }
        break;
      case 'table':
        break;
      case 'list':
        break;
    }
    return true;
  }
};<|endoftext|>


<commit_before>// Excuse me main.js

(function () {
    $('.social').on('click', function () {
        return $('.share').toggleClass('active');
    });
    new GetShare({
        root: $('.twitter'),
        network: 'twitter',
        share: {
            url: 'http://excuseme.io/',
            message: 'Excuse Generator - http://excuseme.io'
        }
    });
}.call(this));

$(document).ready(function() {

    var excuseme,
        reloadButton  = $('.reload'),
        reloadSvg     = document.querySelector('svg'),
        reloadEnabled = true,
        rotation      = 0;

    var randomGenerator = function (length) {
        return Math.floor(Math.random() * length);
    };

    var reloadAnimation = function () {

    reloadEnabled = false;
    rotation -= 180;

    reloadSvg.style.webkitTransform = 'translateZ(0px) rotateZ( ' + rotation + 'deg )';
    reloadSvg.style.MozTransform  = 'translateZ(0px) rotateZ( ' + rotation + 'deg )';
    reloadSvg.style.transform  = 'translateZ(0px) rotateZ( ' + rotation + 'deg )';
    }

    reloadButton.click(function() {
        reloadAnimation();
        generateExcuse();
    });

    $.ajax({
        url: "quotes.json",
        dataType: 'json',
        success: function(data) {
            excuseme = data.excuseCreator;
            generateExcuse();
        },
        error: function() { // callback if there's an error
            console.log("error");
        }
    });

    var generateExcuse = function () {

        var leadIn = randomGenerator(excuseme.leadIn.length),
            perpetrator = randomGenerator(excuseme.perpetrator.length),
            delayFactor = randomGenerator(excuseme.delayFactor.length);

        console.log(leadIn, perpetrator, delayFactor);

        var sorry = excuseme.leadIn[leadIn] + " " +
                    excuseme.perpetrator[perpetrator] + " " +
                    excuseme.delayFactor[delayFactor];

        console.log(sorry);

        $(".excuse h1").fadeOut(function() {
            $(this).text(sorry).fadeIn();
        });

        $(".twitter-tweet-button").click(function() {
            var other = '" – Generate excuse on ',
                encodeText = encodeURIComponent('"' + $("h1").html() + other),
                encodeJ = encodeURIComponent("Jonathan_quach_"),
                encodeT = encodeURIComponent("thanhtran32"),
                width = 550,
                height = 400,
                top = ($(window).height() - height) / 2;
                left = ($(window).width() - width) / 2;

            var opts = 'status=1' +
                       ',width=' + width +
                       ',height=' + height +
                       ',top=' + top +
                       ',left=' + left;

            window.open("http://twitter.com/share?url=&text=" + encodeText +
                        "&related=" + encodeJ + "," + encodeT, "twitter", opts);
        });
    };

    $(document).keyup(function(e) {
        if (e.keyCode === 32 || e.keyCode === 82) {
            reloadAnimation();
            generateExcuse();
        } else if (e.keyCode === 84) {
            $(".twitter-tweet-button").click();
        } else if (e.keyCode === 83) {
            $(".twitter-share-button").click();
        }
    });
});

console.log("Sorry, still WIP");
<commit_msg>remove log<commit_after>// Excuse me main.js

(function () {
    $('.social').on('click', function () {
        return $('.share').toggleClass('active');
    });
    new GetShare({
        root: $('.twitter'),
        network: 'twitter',
        share: {
            url: 'http://excuseme.io/',
            message: 'Excuse Generator - http://excuseme.io'
        }
    });
}.call(this));

$(document).ready(function() {

    var excuseme,
        reloadButton  = $('.reload'),
        reloadSvg     = document.querySelector('svg'),
        reloadEnabled = true,
        rotation      = 0;

    var randomGenerator = function (length) {
        return Math.floor(Math.random() * length);
    };

    var reloadAnimation = function () {

    reloadEnabled = false;
    rotation -= 180;

    reloadSvg.style.webkitTransform = 'translateZ(0px) rotateZ( ' + rotation + 'deg )';
    reloadSvg.style.MozTransform  = 'translateZ(0px) rotateZ( ' + rotation + 'deg )';
    reloadSvg.style.transform  = 'translateZ(0px) rotateZ( ' + rotation + 'deg )';
    }

    reloadButton.click(function() {
        reloadAnimation();
        generateExcuse();
    });

    $.ajax({
        url: "quotes.json",
        dataType: 'json',
        success: function(data) {
            excuseme = data.excuseCreator;
            generateExcuse();
        },
        error: function() { // callback if there's an error
            console.log("error");
        }
    });

    var generateExcuse = function () {

        var leadIn = randomGenerator(excuseme.leadIn.length),
            perpetrator = randomGenerator(excuseme.perpetrator.length),
            delayFactor = randomGenerator(excuseme.delayFactor.length);

        console.log(leadIn, perpetrator, delayFactor);

        var sorry = excuseme.leadIn[leadIn] + " " +
                    excuseme.perpetrator[perpetrator] + " " +
                    excuseme.delayFactor[delayFactor];

        console.log(sorry);

        $(".excuse h1").fadeOut(function() {
            $(this).text(sorry).fadeIn();
        });

        $(".twitter-tweet-button").click(function() {
            var other = '" – Generate excuse on ',
                encodeText = encodeURIComponent('"' + $("h1").html() + other),
                encodeJ = encodeURIComponent("Jonathan_quach_"),
                encodeT = encodeURIComponent("thanhtran32"),
                width = 550,
                height = 400,
                top = ($(window).height() - height) / 2;
                left = ($(window).width() - width) / 2;

            var opts = 'status=1' +
                       ',width=' + width +
                       ',height=' + height +
                       ',top=' + top +
                       ',left=' + left;

            window.open("http://twitter.com/share?url=&text=" + encodeText +
                        "&related=" + encodeJ + "," + encodeT, "twitter", opts);
        });
    };

    $(document).keyup(function(e) {
        if (e.keyCode === 32 || e.keyCode === 82) {
            reloadAnimation();
            generateExcuse();
        } else if (e.keyCode === 84) {
            $(".twitter-tweet-button").click();
        } else if (e.keyCode === 83) {
            $(".twitter-share-button").click();
        }
    });
});
<|endoftext|>


<commit_before>// Set up the store
var preferences = {};

// Is local storage supported?
preferences.supported = function() {

    try {

        return window.localStorage !== undefined;

    } catch (e) {

        return false;

    }

};

// Get a key
preferences.get = function(key) {

    // Does the browser support local storage?
    if (this.supported()) {

        return window.localStorage[key];

    }

};

// Set a key
preferences.set = function(key, value) {

    // Does the browser support local storage?
    if (this.supported()) {

        return window.localStorage[key] = value;

    }

};

// Unset a key
preferences.unset = function(key) {

    // Does the browser support local storage?
    if (this.supported()) {

        return window.localStorage.removeItem(key)

    }

};

$(document).ready(function() {

    var BEER_O_CLOCK = 17; // 5 PM
    const GLASS_FULL = 100;

    var index
        full_query_string = window.location.href.split('?')[1],
        $hours = $('.countdown-hours > .digit'),
        $minutes = $('.countdown-minutes > .digit'),
        $seconds = $('.countdown-seconds > .digit');

    // Split it up into key value pairs
    full_query_string = typeof full_query_string == 'undefined' ? [] : full_query_string.split('&');

    // Loop through the query string and set up an object based on it
    query_string = {};

    for (index in full_query_string) {

        // Split up the key value pair
        item = full_query_string[index].split('=');

        // Add it to our object
        query_string[item[0]] = item[1];

    }

    // Allow overriding of beer o'clock for debug
    if (typeof query_string.t != 'undefined') {

        BEER_O_CLOCK = query_string.t;

    }

    // Is it the weekend? If so it's always beer o'clock!
    function is_weekend() {

        return false;

        var now = new Date;

        // Saturday = 6 and Sunday = 0
        return now.getDay() === 6 || now.getDay() === 0;

    }

    // Is it beer o'clock? i.e the weekend or after beer o'clock on the current day
    function is_beer_o_clock() {

        return is_weekend() || (new Date).getHours() >= BEER_O_CLOCK;

    }

    // Add leading zeros to numbers
    function leading_zero(number) {

        return number < 10 ? '0' + number : number;

    }

    // Format a Date object a bit more nicely
    function format_time(date) {

        var hours = leading_zero(date.getHours()),
            minutes = leading_zero(date.getMinutes()),
            seconds = leading_zero(date.getSeconds());

        return {
            hours: hours.toString().split(''),
            minutes: minutes.toString().split(''),
            seconds: seconds.toString().split('')
        };

    }

    // A Date object for when beer o'clock is
    function get_beer_o_clock() {

        var beer_o_clock = new Date;

        // If it's already past beer o'clock then we need to wait till tomorrow
        if (beer_o_clock.getHours() >= BEER_O_CLOCK) {

            beer_o_clock.setDate(beer_o_clock.getDate() + 1);

        }

        beer_o_clock.setHours(BEER_O_CLOCK);
        beer_o_clock.setMinutes(0);
        beer_o_clock.setSeconds(0);

        return beer_o_clock;

    }

    // How long till you can haz beer!
    function time_till_beer() {

        var beer_o_clock = get_beer_o_clock(),
            now = is_beer_o_clock() ? beer_o_clock : new Date;

        return new Date(beer_o_clock - now);

    }

    // How full should the beer glass be?
    function time_till_beer_percentage() {

        if (is_beer_o_clock()) {

            return GLASS_FULL;

        }

        var now = new Date / 1000,
            beer = get_beer_o_clock() / 1000;

        return parseInt(GLASS_FULL - (((beer - now) / 86400) * 100));

    }

    function update() {

        // Update the page content
        var time = time_till_beer();
        var pretty_time = format_time(time);

        // Update the hours display
        $.each($hours, function(index, value) {

            $hours[index].innerHTML = pretty_time.hours[index];

        });

        // Update the minutes display
        $.each($minutes, function(index, value) {

            $minutes[index].innerHTML = pretty_time.minutes[index];

        });

        // Update the seconds display
        $.each($seconds, function(index, value) {

            $seconds[index].innerHTML = pretty_time.seconds[index];

        });

        // Update the title
        if (is_beer_o_clock()) {

            document.title = "It's Beer o'clock now!";

        } else {

            var time_string = '';

            if (time.getHours() > 0) {

                time_string += time.getHours() + 'h ';

            }

            if (time.getMinutes() > 0) {

                time_string += time.getMinutes() + 'm ';

            }

            time_string += time.getSeconds() + 's ';

            document.title = time_string;
            window.location.hash = time_string;

        }

        // Fill up that beer glass!
        $(".tasty-beverage").css({
            height: time_till_beer_percentage() + '%'
        });

    }

	function professorburpsbubbleworks() {

        var $bubbles = $('.bubbles');
		var minBubbleCount = parseFloat($bubbles.attr('data-bubble-min-count')), // Minimum number of bubbles
		    maxBubbleCount = parseFloat($bubbles.attr('data-bubble-max-count')), // Maximum number of bubbles
    	    minBubbleSize = parseFloat($bubbles.attr('data-bubble-min-size')), // Smallest possible bubble diameter (px)
		    maxBubbleSize = parseFloat($bubbles.attr('data-bubble-max-size')); // Largest possible bubble diameter (px)

		// Generate our bubbles from the above options
		var bubbleCount = minBubbleCount + Math.floor(Math.random() * (maxBubbleCount + 1));

		for (var i = 0; i < bubbleCount; i++) {
			$bubbles.append('

');
		}

		// Make each bubble random
		$bubbles.find('> .bubble-container').each(function(){
			// Randomise their size
			var sizeRand = minBubbleSize + Math.floor(Math.random() * (maxBubbleSize + 1));

			// Randomly position the bubbles
			var posRand = Math.floor(Math.random() * 101);

			// Randomise the time they start rising
			var delayRand = Math.floor(Math.random() * 16);

			// Randomise their speed
			var speedRand = 3 + Math.floor(Math.random() * 9);

            // Cache the this selector
            var $this = $(this);

			// Stick the above to the bubble container
			$this.css({
				'left' : posRand + '%',

				'-webkit-animation-duration' : speedRand + 's',
				'-moz-animation-duration' : speedRand + 's',
				'-ms-animation-duration' : speedRand + 's',
				'animation-duration' : speedRand + 's',

				'-webkit-animation-delay' : delayRand + 's',
				'-moz-animation-delay' : delayRand + 's',
				'-ms-animation-delay' : delayRand + 's',
				'animation-delay' : delayRand + 's'
			});

			// And set the bubble size
			$this.children('.bubble').css({
				'width' : sizeRand + 'px',
				'height' : sizeRand + 'px'
			});
		});
	}

	// Activate the bubble cannon
    if ($('.bubbles').attr('data-bubbles') === 'true') {
    	professorburpsbubbleworks();
    }

    // Update the clock
    update();
    setInterval(update, 1000);

});<commit_msg>Removing this as it's buggy in non chrome.<commit_after>// Set up the store
var preferences = {};

// Is local storage supported?
preferences.supported = function() {

    try {

        return window.localStorage !== undefined;

    } catch (e) {

        return false;

    }

};

// Get a key
preferences.get = function(key) {

    // Does the browser support local storage?
    if (this.supported()) {

        return window.localStorage[key];

    }

};

// Set a key
preferences.set = function(key, value) {

    // Does the browser support local storage?
    if (this.supported()) {

        return window.localStorage[key] = value;

    }

};

// Unset a key
preferences.unset = function(key) {

    // Does the browser support local storage?
    if (this.supported()) {

        return window.localStorage.removeItem(key)

    }

};

$(document).ready(function() {

    var BEER_O_CLOCK = 17; // 5 PM
    const GLASS_FULL = 100;

    var index
        full_query_string = window.location.href.split('?')[1],
        $hours = $('.countdown-hours > .digit'),
        $minutes = $('.countdown-minutes > .digit'),
        $seconds = $('.countdown-seconds > .digit');

    // Split it up into key value pairs
    full_query_string = typeof full_query_string == 'undefined' ? [] : full_query_string.split('&');

    // Loop through the query string and set up an object based on it
    query_string = {};

    for (index in full_query_string) {

        // Split up the key value pair
        item = full_query_string[index].split('=');

        // Add it to our object
        query_string[item[0]] = item[1];

    }

    // Allow overriding of beer o'clock for debug
    if (typeof query_string.t != 'undefined') {

        BEER_O_CLOCK = query_string.t;

    }

    // Is it the weekend? If so it's always beer o'clock!
    function is_weekend() {

        return false;

        var now = new Date;

        // Saturday = 6 and Sunday = 0
        return now.getDay() === 6 || now.getDay() === 0;

    }

    // Is it beer o'clock? i.e the weekend or after beer o'clock on the current day
    function is_beer_o_clock() {

        return is_weekend() || (new Date).getHours() >= BEER_O_CLOCK;

    }

    // Add leading zeros to numbers
    function leading_zero(number) {

        return number < 10 ? '0' + number : number;

    }

    // Format a Date object a bit more nicely
    function format_time(date) {

        var hours = leading_zero(date.getHours()),
            minutes = leading_zero(date.getMinutes()),
            seconds = leading_zero(date.getSeconds());

        return {
            hours: hours.toString().split(''),
            minutes: minutes.toString().split(''),
            seconds: seconds.toString().split('')
        };

    }

    // A Date object for when beer o'clock is
    function get_beer_o_clock() {

        var beer_o_clock = new Date;

        // If it's already past beer o'clock then we need to wait till tomorrow
        if (beer_o_clock.getHours() >= BEER_O_CLOCK) {

            beer_o_clock.setDate(beer_o_clock.getDate() + 1);

        }

        beer_o_clock.setHours(BEER_O_CLOCK);
        beer_o_clock.setMinutes(0);
        beer_o_clock.setSeconds(0);

        return beer_o_clock;

    }

    // How long till you can haz beer!
    function time_till_beer() {

        var beer_o_clock = get_beer_o_clock(),
            now = is_beer_o_clock() ? beer_o_clock : new Date;

        return new Date(beer_o_clock - now);

    }

    // How full should the beer glass be?
    function time_till_beer_percentage() {

        if (is_beer_o_clock()) {

            return GLASS_FULL;

        }

        var now = new Date / 1000,
            beer = get_beer_o_clock() / 1000;

        return parseInt(GLASS_FULL - (((beer - now) / 86400) * 100));

    }

    function update() {

        // Update the page content
        var time = time_till_beer();
        var pretty_time = format_time(time);

        // Update the hours display
        $.each($hours, function(index, value) {

            $hours[index].innerHTML = pretty_time.hours[index];

        });

        // Update the minutes display
        $.each($minutes, function(index, value) {

            $minutes[index].innerHTML = pretty_time.minutes[index];

        });

        // Update the seconds display
        $.each($seconds, function(index, value) {

            $seconds[index].innerHTML = pretty_time.seconds[index];

        });

        // Update the title
        if (is_beer_o_clock()) {

            document.title = "It's Beer o'clock now!";

        } else {

            var time_string = '';

            if (time.getHours() > 0) {

                time_string += time.getHours() + 'h ';

            }

            if (time.getMinutes() > 0) {

                time_string += time.getMinutes() + 'm ';

            }

            time_string += time.getSeconds() + 's ';

            document.title = time_string;
            // window.location.hash = time_string;

        }

        // Fill up that beer glass!
        $(".tasty-beverage").css({
            height: time_till_beer_percentage() + '%'
        });

    }

	function professorburpsbubbleworks() {

        var $bubbles = $('.bubbles');
		var minBubbleCount = parseFloat($bubbles.attr('data-bubble-min-count')), // Minimum number of bubbles
		    maxBubbleCount = parseFloat($bubbles.attr('data-bubble-max-count')), // Maximum number of bubbles
    	    minBubbleSize = parseFloat($bubbles.attr('data-bubble-min-size')), // Smallest possible bubble diameter (px)
		    maxBubbleSize = parseFloat($bubbles.attr('data-bubble-max-size')); // Largest possible bubble diameter (px)

		// Generate our bubbles from the above options
		var bubbleCount = minBubbleCount + Math.floor(Math.random() * (maxBubbleCount + 1));

		for (var i = 0; i < bubbleCount; i++) {
			$bubbles.append('

');
		}

		// Make each bubble random
		$bubbles.find('> .bubble-container').each(function(){
			// Randomise their size
			var sizeRand = minBubbleSize + Math.floor(Math.random() * (maxBubbleSize + 1));

			// Randomly position the bubbles
			var posRand = Math.floor(Math.random() * 101);

			// Randomise the time they start rising
			var delayRand = Math.floor(Math.random() * 16);

			// Randomise their speed
			var speedRand = 3 + Math.floor(Math.random() * 9);

            // Cache the this selector
            var $this = $(this);

			// Stick the above to the bubble container
			$this.css({
				'left' : posRand + '%',

				'-webkit-animation-duration' : speedRand + 's',
				'-moz-animation-duration' : speedRand + 's',
				'-ms-animation-duration' : speedRand + 's',
				'animation-duration' : speedRand + 's',

				'-webkit-animation-delay' : delayRand + 's',
				'-moz-animation-delay' : delayRand + 's',
				'-ms-animation-delay' : delayRand + 's',
				'animation-delay' : delayRand + 's'
			});

			// And set the bubble size
			$this.children('.bubble').css({
				'width' : sizeRand + 'px',
				'height' : sizeRand + 'px'
			});
		});
	}

	// Activate the bubble cannon
    if ($('.bubbles').attr('data-bubbles') === 'true') {
    	professorburpsbubbleworks();
    }

    // Update the clock
    update();
    setInterval(update, 1000);

});<|endoftext|>


<commit_before>(function (){
	var app = angular.module('comic', []);
	var started = false;

	app.config(function($locationProvider){
		$locationProvider.html5Mode(true).hashPrefix('#');

	});

	app.controller('PanelController', function ($scope, $http, $location) {
		var com = this;
		var scrolling = false;

		$http.get('/data.json').
			success(function (data) {
				com.comics = data.panels;
			}).
			error(function () {
				console.log('error');
			});

		// get comics
		var comics = document.getElementsByTagName('article');

		// frame loop
		function step() {
			// this checks if the page has jumped to a hash location yet
			var hash = window.location.hash;
			hash.substr(1, hash.length)
			var target = document.getElementById(hash);

			// check to see if the scroll of the page equals where we want to scroll to yet
			// if not we can't update the hash based on where we are on the page or we will
			// overwrite what's there
			var check = -1;
			if(target) {
				check = target.offsetTop;
			}

			if(started && document.body.scrollTop == check) {
				var hashId = "";

				for( var i = 0, len = comics.length; i < len; i++) {
					if(document.body.scrollTop >= comics[i].offsetTop) {
						hashId = comics[i].id;
					}
				}

				// make sure this works on most devices
				var hash = window.location.hash;
				var hashCompare = hash.substr(1, hash.length);

				// this will occasionaly cause jank
				if (hashId != hashCompare) {
					history.replaceState(null, null, "#" + hashId);
				}

			}

			window.requestAnimationFrame(step);
		}

		window.requestAnimationFrame(step);

	});

	app.directive('endDirective', function ($sce, $location, $anchorScroll, $timeout) {
		return function(scope, element, attrs) {
			// render out description with html
			scope.descriptionHtml = $sce.trustAsHtml(scope.comic.description);

			// take hash in url and jump to desired comic url is still a little wonky looking
			if (scope.$last){
				var hash = window.location.hash;
				$location.replace();
				$location.hash('');
				$location.hash(hash.substr(1, hash.length));
				$anchorScroll();
				started = true;
			}
		};
	});
})();<commit_msg>no url hash accounted for<commit_after>(function (){
	var app = angular.module('comic', []);
	var started = false;

	app.config(function($locationProvider){
		$locationProvider.html5Mode(true).hashPrefix('#');

	});

	app.controller('PanelController', function ($scope, $http, $location) {
		var com = this;
		var scrolling = false;

		$http.get('/data.json').
			success(function (data) {
				com.comics = data.panels;
			}).
			error(function () {
				console.log('error');
			});

		// get comics
		var comics = document.getElementsByTagName('article');

		// frame loop
		function step() {
			// this checks if the page has jumped to a hash location yet
			var hash = window.location.hash;
			hash.substr(1, hash.length)
			var target = document.getElementById(hash);

			// check to see if the scroll of the page equals where we want to scroll to yet
			// if not we can't update the hash based on where we are on the page or we will
			// overwrite what's there
			var check = -1;
			if(target && window.location.hash) {
				check = target.offsetTop;
			}
			else if (!window.location.hash) {
				check = 0;
			}

			if( started || document.body.scrollTop == check) {
				started = true;
				var hashId = "";

				for( var i = 0, len = comics.length; i < len; i++) {
					if(document.body.scrollTop >= comics[i].offsetTop) {
						hashId = comics[i].id;
					}
				}

				// make sure this works on most devices
				var hash = window.location.hash;
				var hashCompare = hash.substr(1, hash.length);

				// this will occasionaly cause jank
				if (hashId != hashCompare) {
					history.replaceState(null, null, "#" + hashId);
				}

			}

			window.requestAnimationFrame(step);
		}

		window.requestAnimationFrame(step);

	});

	app.directive('endDirective', function ($sce, $location, $anchorScroll, $timeout) {
		return function(scope, element, attrs) {
			// render out description with html
			scope.descriptionHtml = $sce.trustAsHtml(scope.comic.description);

			// take hash in url and jump to desired comic url is still a little wonky looking
			if (scope.$last){
				var hash = window.location.hash;
				$location.replace();
				$location.hash('');
				$location.hash(hash.substr(1, hash.length));
				$anchorScroll();
			}
		};
	});
})();<|endoftext|>


<commit_before>function setup() {
    createCanvas(windowWidth, windowHeight);

    word = 'SEVENTYFIVE'

    words = [
        'UNITED STATES',
        'MEXICO',
        'BRAZIL',
        'IRAN',
        'ISLAMIC REPUBLIC',
        'TURKEY',
        'EGYPT',
        'NIGERIA',
        'CONGO',
        // 'DEMOCRATIC REPUBLIC',
        'ETHIOPIA',
        'TANZANIA',
        'CHINA',
        'PAKISTAN',
        'PHILLIPPINES',
        'VIETNAM',
        'INDONESIA',
        'THAILAND',
        'MYANMAR',
        'BANGLADESH',
        // 'RUSSIAN FEDERATION'
        'RUSSIA',
        'RURAL',
        'LOW INCOME',
        'ELDERLY',
        'ILLITERATE',
        'FEMALE',
        'INCENTIVES',
        'AFFORDABILITY',
        'USER CAPABILITY',
        'INFRASTRUCTURE'
    ];

    currentLetter = '';
    letterCount = 0;
    letterWordRepeat = 2;
    letterFadeDuration = 1000;

    currentWord = '';
    wordCount = 0;
    wordDuration = 90;

    titleHeight = width * .125
    titleColor = 255;
    titleDuration = 15000;

    captionHeight = max(width * .015, 14)
    captionDuration = 1000;

    backgroundColor = 255;

    ended = false;

    textFont('Helvetica Neue, Helvetica, Arial, sans-serif')
    textStyle(BOLD)
    textSize(titleHeight)

    noStroke();

    setupSequence();
}

function setupSequence() {
    MOTION.removeAll();

    titleLetters = []

    titleLettersSequence = new MOTION.Sequence();

    titleLettersSequence.add(new MOTION.Tween(captionDuration)
            .add('captionColor', [0, 255]))
        // .add('titleColor', [0, 255]))

    titleLettersSequence.add(new MOTION(titleDuration))

    titleLettersSequence
        .onStart(function() {
            backgroundColorTween = new MOTION.Tween('backgroundColor', [0, 255], this.duration()).play()
        }).onEnd(function() {
            ended = false;
            lettersSequence.play()
        })

    letters = [];
    letters.offset = textWidth(word) / 2;

    letters.x = width / 2 - letters.offset;
    letters.y = height / 2;

    for (var i = 0; i < word.length; i++) {
        var letter = word.charAt(i);
        var letterWords = [];

        for (var j in words)
            for (var k in words[j])
                if (words[j][k] === letter)
                    for (var l = 0; l < letterWordRepeat; l++)
                        letterWords.push({
                            word: words[j],
                            index: k,
                            offset: textWidth(words[j].substring(0, k))
                        })

        letters.push({
            letter: letter,
            offset: textWidth(word.substring(0, i)),
            words: shuffle(letterWords)
        })
    }

    lettersSequence = new MOTION.Sequence();

    for (var i in letters) {
        for (var j in letters[i].words) {
            var m = new MOTION(wordDuration).onStart(function() {
                currentLetter = this.letter;
                currentWord = this.word;
            });
            m.letter = letters[i];
            m.word = letters[i].words[j];

            lettersSequence.add(m)
        }
    }

    lettersSequence
        .onStart(function() {
            backgroundColorTween = new MOTION.Tween('backgroundColor', [255, 0], this.duration()).play()
            titleColorTween = new MOTION.Sequence()
                .add(new MOTION.Tween('titleColor', [255, 0], letterFadeDuration))
                .add(new MOTION.Tween('titleColor', [0, 255], this.duration() - letterFadeDuration))
                .play()
        })
        .onEnd(function() {
            ended = true;
            titleLettersSequence.play();
        })
        .play()

    // titleLettersSequence.play().onEnd(function() {});
}

function pauseSequence() {
    lettersSequence.pause();
    titleColorTween.pause();
    backgroundColorTween.pause();
}

function resumeSequence() {
    if (!lettersSequence.isPlaying()) {
        lettersSequence.resume();
        titleColorTween.resume();
        backgroundColorTween.resume();
    }
}

function draw() {
    MOTION.update(millis());

    background(backgroundColor);
    // blur(3);
    //     Filters.filterImage(Filters.convolute, image,
    //   [ 1/9, 1/9, 1/9,
    //     1/9, 1/9, 1/9,
    //     1/9, 1/9, 1/9 ]
    // );

    if (!ended) {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(1, letters.x, letters.y)
        text(currentWord.word, letters.x + currentLetter.offset - currentWord.offset, letters.y)

        fill(255)
        text(currentLetter.letter, letters.x + currentLetter.offset, letters.y)
    } else {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(word, letters.x, letters.y)

        textSize(captionHeight)
        textAlign(CENTER);
        fill(captionColor)
        text('percent of the 4.4 billion people offline worldwide are in 20 countries\nincluding the U.S., which has 50 million; 1 out of 6 people...', width / 2, letters.y + captionHeight*2)
    }
}

function mouseMoved() {
    if (ended) return false;

    if (mouseY > height / 2 - titleHeight && mouseY < height / 2)
        pauseSequence();
    else
        resumeSequence();
}

function touchStarted() {
    pauseSequence();
}

function touchEnded() {
    resumeSequence();
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o) { //v1.0
    for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

/*! Normalized address bar hiding for iOS & Android (c) @scottjehl MIT License */
(function(win) {
    var doc = win.document;

    // If there's a hash, or addEventListener is undefined, stop here
    if (!win.navigator.standalone && !location.hash && win.addEventListener) {

        //scroll to 1
        win.scrollTo(0, 1);
        var scrollTop = 1,
            getScrollTop = function() {
                return win.pageYOffset || doc.compatMode === "CSS1Compat" && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
            },

            //reset to 0 on bodyready, if needed
            bodycheck = setInterval(function() {
                if (doc.body) {
                    clearInterval(bodycheck);
                    scrollTop = getScrollTop();
                    win.scrollTo(0, scrollTop === 1 ? 0 : 1);
                }
            }, 15);

        win.addEventListener("load", function() {
            setTimeout(function() {
                //at load, if user hasn't scrolled more than 20 or so...
                if (getScrollTop() < 20) {
                    //reset to hide addr bar at onload
                    win.scrollTo(0, scrollTop === 1 ? 0 : 1);
                }
            }, 0);
        }, false);
    }
})(this);
<commit_msg>add resizing<commit_after>function setup() {
    createCanvas(windowWidth, windowHeight);

    word = 'SEVENTYFIVE'

    words = [
        'UNITED STATES',
        'MEXICO',
        'BRAZIL',
        'IRAN',
        'ISLAMIC REPUBLIC',
        'TURKEY',
        'EGYPT',
        'NIGERIA',
        'CONGO',
        // 'DEMOCRATIC REPUBLIC',
        'ETHIOPIA',
        'TANZANIA',
        'CHINA',
        'PAKISTAN',
        'PHILLIPPINES',
        'VIETNAM',
        'INDONESIA',
        'THAILAND',
        'MYANMAR',
        'BANGLADESH',
        // 'RUSSIAN FEDERATION'
        'RUSSIA',
        'RURAL',
        'LOW INCOME',
        'ELDERLY',
        'ILLITERATE',
        'FEMALE',
        'INCENTIVES',
        'AFFORDABILITY',
        'USER CAPABILITY',
        'INFRASTRUCTURE'
    ];

    currentLetter = '';
    letterCount = 0;
    letterWordRepeat = 2;
    letterFadeDuration = 1000;

    currentWord = '';
    wordCount = 0;
    wordDuration = 90;

    titleHeight = width * .125
    titleColor = 255;
    titleDuration = 15000;

    captionHeight = max(width * .015, 14)
    captionDuration = 1000;

    backgroundColor = 255;

    ended = false;

    textFont('Helvetica Neue, Helvetica, Arial, sans-serif')
    textStyle(BOLD)
    textSize(titleHeight)

    noStroke();

    setupAnimation();
}

function setupAnimation() {
    MOTION.removeAll();

    titleLetters = []

    titleLettersSequence = new MOTION.Sequence();

    titleLettersSequence.add(new MOTION.Tween(captionDuration)
            .add('captionColor', [0, 255]))
        // .add('titleColor', [0, 255]))

    titleLettersSequence.add(new MOTION(titleDuration))

    titleLettersSequence
        .onStart(function() {
            backgroundColorTween = new MOTION.Tween('backgroundColor', [0, 255], this.duration()).play()
        }).onEnd(function() {
            ended = false;
            lettersSequence.play()
        })

    letters = [];
    letters.offset = textWidth(word) / 2;

    letters.x = width / 2 - letters.offset;
    letters.y = height / 2;

    for (var i = 0; i < word.length; i++) {
        var letter = word.charAt(i);
        var letterWords = [];

        for (var j in words)
            for (var k in words[j])
                if (words[j][k] === letter)
                    for (var l = 0; l < letterWordRepeat; l++)
                        letterWords.push({
                            word: words[j],
                            index: k,
                            offset: textWidth(words[j].substring(0, k))
                        })

        letters.push({
            letter: letter,
            offset: textWidth(word.substring(0, i)),
            words: shuffle(letterWords)
        })
    }

    lettersSequence = new MOTION.Sequence();

    for (var i in letters) {
        for (var j in letters[i].words) {
            var m = new MOTION(wordDuration).onStart(function() {
                currentLetter = this.letter;
                currentWord = this.word;
            });
            m.letter = letters[i];
            m.word = letters[i].words[j];

            lettersSequence.add(m)
        }
    }

    lettersSequence
        .onStart(function() {
            backgroundColorTween = new MOTION.Tween('backgroundColor', [255, 0], this.duration()).play()
            titleColorTween = new MOTION.Sequence()
                .add(new MOTION.Tween('titleColor', [255, 0], letterFadeDuration))
                .add(new MOTION.Tween('titleColor', [0, 255], this.duration() - letterFadeDuration))
                .play()
        })
        .onEnd(function() {
            ended = true;
            titleLettersSequence.play();
        })
        .play()

    // titleLettersSequence.play().onEnd(function() {});
}

function pauseSequence() {
    lettersSequence.pause();
    titleColorTween.pause();
    backgroundColorTween.pause();
}

function resumeSequence() {
    if (!lettersSequence.isPlaying()) {
        lettersSequence.resume();
        titleColorTween.resume();
        backgroundColorTween.resume();
    }
}

function draw() {
    MOTION.update(millis());

    background(backgroundColor);
    // blur(3);
    //     Filters.filterImage(Filters.convolute, image,
    //   [ 1/9, 1/9, 1/9,
    //     1/9, 1/9, 1/9,
    //     1/9, 1/9, 1/9 ]
    // );

    if (!ended) {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(1, letters.x, letters.y)
        text(currentWord.word, letters.x + currentLetter.offset - currentWord.offset, letters.y)

        fill(255)
        text(currentLetter.letter, letters.x + currentLetter.offset, letters.y)
    } else {
        textSize(titleHeight)
        textAlign(LEFT);

        fill(titleColor)
        text(word, letters.x, letters.y)

        textSize(captionHeight)
        textAlign(CENTER);
        fill(captionColor)
        text('percent of the 4.4 billion people offline worldwide are in 20 countries\nincluding the U.S., which has 50 million; 1 out of 6 people...', width / 2, letters.y + captionHeight*2)
    }
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
  setupAnimation()
}

function mouseMoved() {
    if (ended) return false;

    if (mouseY > height / 2 - titleHeight && mouseY < height / 2)
        pauseSequence();
    else
        resumeSequence();
}

function touchStarted() {
    pauseSequence();
}

function touchEnded() {
    resumeSequence();
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o) { //v1.0
    for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

/*! Normalized address bar hiding for iOS & Android (c) @scottjehl MIT License */
(function(win) {
    var doc = win.document;

    // If there's a hash, or addEventListener is undefined, stop here
    if (!win.navigator.standalone && !location.hash && win.addEventListener) {

        //scroll to 1
        win.scrollTo(0, 1);
        var scrollTop = 1,
            getScrollTop = function() {
                return win.pageYOffset || doc.compatMode === "CSS1Compat" && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
            },

            //reset to 0 on bodyready, if needed
            bodycheck = setInterval(function() {
                if (doc.body) {
                    clearInterval(bodycheck);
                    scrollTop = getScrollTop();
                    win.scrollTo(0, scrollTop === 1 ? 0 : 1);
                }
            }, 15);

        win.addEventListener("load", function() {
            setTimeout(function() {
                //at load, if user hasn't scrolled more than 20 or so...
                if (getScrollTop() < 20) {
                    //reset to hide addr bar at onload
                    win.scrollTo(0, scrollTop === 1 ? 0 : 1);
                }
            }, 0);
        }, false);
    }
})(this);
<|endoftext|>