<commit_before>/* global jQuery */
(function($){

    'use strict';

    $.savantForm = function(el, options){

        var base = this;

        base.$el = $(el);
        base.el = el;

        base.$el.data("savantForm", base);

        base.init = function(){
            base.options = $.extend({},$.savantForm.defaultOptions, options);

            $('form.savant-form').submit(function( event ) {
                document.cookie = "savant=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
                document.cookie = "savantcheckboxes=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
                document.cookie = "savantradios=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
            });

            var savant = base.getCookie("savant");
            var savantcheckboxes = base.getCookie("savantcheckboxes");
            var savantradios = base.getCookie("savantradios");

            if(savant !== "")
                base.restoreFields(savant);

            if(savantcheckboxes !== "")
                base.restoreCheckboxes(savantcheckboxes);

            if(savantradios !== "")
                base.restoreRadios(savantradios);

            $('.savant-form input, .savant-form textarea').focus(function(){
                base.persistFields();
                base.persistCheckboxes();
                base.persistRadios();
            });

            $('.savant-form input, .savant-form textarea').focusout(function(){
                base.persistFields();
                base.persistCheckboxes();
                base.persistRadios();
            });

            $('.savant-form input, .savant-form textarea, .savant-form select').change(function(){
                base.persistFields();
                base.persistCheckboxes();
                base.persistRadios();
            });

            $('.savant-form input').keyup(function(e){
                base.persistFields();
                base.persistCheckboxes();
                base.persistRadios();
            });
        };

        base.setCookie = function(name, cvalue) {
            var d = new Date();
            d.setTime(d.getTime() + (base.options.expiresin * 1000));
            var expires = "expires="+d.toUTCString();
            document.cookie = name + "=" + cvalue + "; " + expires;
        };

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

            return "";
        };

        base.persistFields = function()
        {
            var values = JSON.stringify($(".savant-form textarea, .savant-form input[type='text'], .savant-form input[type='email'], .savant-form input[type='password'], .savant-form select, .savant-form input[type='date'], .savant-form input[type='color'], .savant-form input[type='range'], .savant-form input[type='month'], .savant-form input[type='week'], .savant-form input[type='time'], .savant-form input[type='datetime'], .savant-form input[type='datetime-local'], .savant-form input[type='search'], .savant-form input[type='tel'], .savant-form input[type='url'], savant-form input[type='number']").map(function(){return $(this).val(); }).get());

            base.setCookie("savant", values);
        };

        base.restoreFields = function(data){
            var json = $.parseJSON(data);
            var textfields = $(".savant-form textarea, .savant-form input[type='text'], .savant-form input[type='email'], .savant-form input[type='password'], .savant-form select, .savant-form input[type='date'], .savant-form input[type='color'], .savant-form input[type='range'], .savant-form input[type='month'], .savant-form input[type='week'], .savant-form input[type='time'], .savant-form input[type='datetime'], .savant-form input[type='datetime-local'], .savant-form input[type='search'], .savant-form input[type='tel'], .savant-form input[type='url'], savant-form input[type='number']").toArray();

            for(var x = 0; x < json.length; x++){
                if(json[x] && !$(textfields[x]).hasClass('savant-skip')){
                    $(textfields[x]).val(json[x]);
                }
            }
        };

        base.persistCheckboxes = function()
        {
             var values = JSON.stringify($(".savant-form input[type='checkbox']").map(function(){return this.checked;}).get());

             base.setCookie("savantcheckboxes", values);
        };

        base.restoreCheckboxes = function(data){
            var json = $.parseJSON(data);
            var checkboxes = $('.savant-form input[type="checkbox"]').toArray();

            for(var x = 0; x < json.length; x++){
                if(json[x] && !$(checkboxes[x]).hasClass('savant-skip')){
                    $(checkboxes[x]).attr('checked', true);
                }
            }
        };

        base.persistRadios = function()
        {
             var values = JSON.stringify($(".savant-form input[type='radio']").map(function(){return this.checked;}).get());

             base.setCookie("savantradios", values);
        };

        base.restoreRadios = function(data){
            var json = $.parseJSON(data);
            var radios = $('.savant-form input[type="radio"]').toArray();

            for(var x = 0; x < json.length; x++){
                if(json[x] && !$(radios[x]).hasClass('savant-skip'))
                    $(radios[x]).attr('checked', true);
            }
        };

        base.init();
    };

    $.savantForm.defaultOptions = {
        expiresin: 300
    };

    $.fn.savantForm = function(options){
        return this.each(function(){
            (new $.savantForm(this, options));
        });
    };
})(jQuery);
<commit_msg>Removed a line I didn't need.<commit_after>(function($){

    'use strict';

    $.savantForm = function(el, options){

        var base = this;

        base.$el = $(el);
        base.el = el;

        base.$el.data("savantForm", base);

        base.init = function(){
            base.options = $.extend({},$.savantForm.defaultOptions, options);

            $('form.savant-form').submit(function( event ) {
                document.cookie = "savant=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
                document.cookie = "savantcheckboxes=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
                document.cookie = "savantradios=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
            });

            var savant = base.getCookie("savant");
            var savantcheckboxes = base.getCookie("savantcheckboxes");
            var savantradios = base.getCookie("savantradios");

            if(savant !== "")
                base.restoreFields(savant);

            if(savantcheckboxes !== "")
                base.restoreCheckboxes(savantcheckboxes);

            if(savantradios !== "")
                base.restoreRadios(savantradios);

            $('.savant-form input, .savant-form textarea').focus(function(){
                base.persistFields();
                base.persistCheckboxes();
                base.persistRadios();
            });

            $('.savant-form input, .savant-form textarea').focusout(function(){
                base.persistFields();
                base.persistCheckboxes();
                base.persistRadios();
            });

            $('.savant-form input, .savant-form textarea, .savant-form select').change(function(){
                base.persistFields();
                base.persistCheckboxes();
                base.persistRadios();
            });

            $('.savant-form input').keyup(function(e){
                base.persistFields();
                base.persistCheckboxes();
                base.persistRadios();
            });
        };

        base.setCookie = function(name, cvalue) {
            var d = new Date();
            d.setTime(d.getTime() + (base.options.expiresin * 1000));
            var expires = "expires="+d.toUTCString();
            document.cookie = name + "=" + cvalue + "; " + expires;
        };

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

            return "";
        };

        base.persistFields = function()
        {
            var values = JSON.stringify($(".savant-form textarea, .savant-form input[type='text'], .savant-form input[type='email'], .savant-form input[type='password'], .savant-form select, .savant-form input[type='date'], .savant-form input[type='color'], .savant-form input[type='range'], .savant-form input[type='month'], .savant-form input[type='week'], .savant-form input[type='time'], .savant-form input[type='datetime'], .savant-form input[type='datetime-local'], .savant-form input[type='search'], .savant-form input[type='tel'], .savant-form input[type='url'], savant-form input[type='number']").map(function(){return $(this).val(); }).get());

            base.setCookie("savant", values);
        };

        base.restoreFields = function(data){
            var json = $.parseJSON(data);
            var textfields = $(".savant-form textarea, .savant-form input[type='text'], .savant-form input[type='email'], .savant-form input[type='password'], .savant-form select, .savant-form input[type='date'], .savant-form input[type='color'], .savant-form input[type='range'], .savant-form input[type='month'], .savant-form input[type='week'], .savant-form input[type='time'], .savant-form input[type='datetime'], .savant-form input[type='datetime-local'], .savant-form input[type='search'], .savant-form input[type='tel'], .savant-form input[type='url'], savant-form input[type='number']").toArray();

            for(var x = 0; x < json.length; x++){
                if(json[x] && !$(textfields[x]).hasClass('savant-skip')){
                    $(textfields[x]).val(json[x]);
                }
            }
        };

        base.persistCheckboxes = function()
        {
             var values = JSON.stringify($(".savant-form input[type='checkbox']").map(function(){return this.checked;}).get());

             base.setCookie("savantcheckboxes", values);
        };

        base.restoreCheckboxes = function(data){
            var json = $.parseJSON(data);
            var checkboxes = $('.savant-form input[type="checkbox"]').toArray();

            for(var x = 0; x < json.length; x++){
                if(json[x] && !$(checkboxes[x]).hasClass('savant-skip')){
                    $(checkboxes[x]).attr('checked', true);
                }
            }
        };

        base.persistRadios = function()
        {
             var values = JSON.stringify($(".savant-form input[type='radio']").map(function(){return this.checked;}).get());

             base.setCookie("savantradios", values);
        };

        base.restoreRadios = function(data){
            var json = $.parseJSON(data);
            var radios = $('.savant-form input[type="radio"]').toArray();

            for(var x = 0; x < json.length; x++){
                if(json[x] && !$(radios[x]).hasClass('savant-skip'))
                    $(radios[x]).attr('checked', true);
            }
        };

        base.init();
    };

    $.savantForm.defaultOptions = {
        expiresin: 300
    };

    $.fn.savantForm = function(options){
        return this.each(function(){
            (new $.savantForm(this, options));
        });
    };
})(jQuery);
<|endoftext|>


<commit_before>(function($) {

	$(function() {

		// Глобальные переменные
		var fieldSize,
			difficultySelect,
			countRow = 1,
		 	countColum = 1,
		 	globalCountR = 0,
			win = false,
			init = true,
			smart = false,
			init2,
			arrElems = [],
			checkElems = [],
			arrColum = [];

		// Переменные для быстрого изменения
		var text_Gamer = 'Текущий ход: Ваш ход',
			text_Ai = 'Текущий ход: Думаю...',
			text_startGame = 'Играть еще раз',
			speed_AiMove = 600;

		// Блок с настройками игры
		var settingsBlock = $('#settings');

		// Генерация поля для игры
		$(document).on('click','.startgame', function(event) {
			event.preventDefault();

			$('#field').remove();
			$(settingsBlock).hide(400);
			$(this).remove();
			$('.text-result').remove();

			//Получение данных для генерации
			fieldSize = parseInt($('#settings-field-size').find('a.active').attr('data-fieldsize'));
			difficultySelect = parseInt($('#settings-difficulty').find('a.active').attr('data-difficulty'));

			// Генерация поля для игры
			var field = $('
');
			for(var i = 1; i <= fieldSize * fieldSize; i++){
				var el = $('

');
				arrElems.push(el);
				$(el).appendTo(field);
			}

			// Деление на строки
			$(arrElems).each(function(index) {
				index++;
				var resultInt = isInteger(index / fieldSize);
				if(resultInt){
					$(this).attr('data-row', countRow);
					for(var i = 0; i < fieldSize; i++){
						$(arrElems[--index]).attr('data-row', countRow);
					}
					countRow++;
				}
			});

			// Деление на колонки
			for(var i = 0; i < fieldSize; i++){
				arrColum.push(arrElems[i]);
			}
			$(arrColum).each(function(index) {
				var innerI = globalCountR;
				$(this).attr('data-colum', countColum)
				for(var i = 0; i < fieldSize; i++){
					$(arrElems[innerI]).attr('data-colum', countColum);
					innerI = innerI + fieldSize;
				}

				globalCountR++;
				innerI = innerI + index;
				countColum++;
			});

			// Добавление поля с игрой и текста в DOM + анимация
			$(field).css({
				'position' : 'relative',
				top: -600
			});

			$('#stats-game').before($(field));

			$(field).animate({
				top: 0
			}, 600, function(){
				$(field).css({
					'-moz-transform' : 'rotate(-0deg)',
					'-webkit-transform' : 'rotate(-0deg)',
					'transform' : 'rotate(-0deg)',
					'-moz-transition' : '0.3s',
					'-o-transition' : '0.3s',
					'-webkit-transition' : '0.3s',
					'transition' : '0.3s'
				});
			});

			$('
' + text_Gamer + '
').prependTo($('#wrapper-game'));

			// Расчет ширины поля в зависимости от настроек
			var width = $('.cell').width() * fieldSize;
			$('#field, .whose-move').css('width', width+10);

		});

		// Функция проверки на целое число (для корректного деления на строки)
		function isInteger(fieldSize) {
  			return (fieldSize ^ 0) === fieldSize;
		};

		// Клик игрока по полю
		$(document).on('click', '.cell', function(event) {
			event.preventDefault();
			if(!$(this).hasClass('there') && !$(field).hasClass('endgame') && init){
				$(this).addClass('there');
				$(this).attr('data-mark', 'x');
				$(this).find('span').text('×');

				init = false;
				victory('x');
				$('.whose-move').text(text_Ai);

				//Запустить анализатор хода для AI
				if(!$(field).hasClass('endgame')){
					setTimeout(analizator, speed_AiMove);
				}
			}
		});

		// Переключение активности для кнопок настроек
		$('#settings-difficulty, #settings-field-size').find('a').on('click', function(event) {
			event.preventDefault();
			$(this).parent().parent('div').find('a').removeClass('active');
			$(this).addClass('active');
		});

		// Проверка на победу
		function victory(sign) {
			$(arrElems).each(function (index) {
				if($(this).hasClass('there')){
					for(var i = 0; i < 4; i++){
						if(!win){
							innerVictory(this, i);
						}
					}

					// Функция будет вызываться из цикла и проверит все возможные комбинации
					function innerVictory(elem, line) {
						var dataRow = $(elem).attr('data-row');
						var dataColum = $(elem).attr('data-colum');
						var combo;
						var mark = $(elem).attr('data-mark');

						for(var i = 0; i < fieldSize; i++){
							if(line == 0){
								dataColum--;
							}
							else if(line == 1){
								dataRow--;
							}
							else if(line == 2){
								dataColum--;
								dataRow--;
							}
							else if(line == 3){
								dataColum++;
								dataRow--;
							}

							combo  = $('div[data-colum ="' + dataColum + '"][data-row ="' + dataRow + '"][data-mark ="' + mark + '"]');
							if(typeof(combo)  !== 'undefined' && $(combo).hasClass('there')){
								checkElems.push(combo);
								if($(checkElems).length == (fieldSize - 1)){
									checkElems.push(elem);
								}
							}
						}

						if($(checkElems).length === fieldSize){
							$(checkElems).each(function() {
								$(this).css('background', '#FEFFEC');
							})
							messWin(sign);
						}

						checkElems = [];
					};
				}
			});

			// Ничья
			if($('.cell.there').length == (fieldSize * fieldSize) && !$('#field').hasClass('endgame')){
				messWin();
				return false;
			}
		};

		// Анализатор ходов соперника
		function analizator() {
			smart = false;
			init2 = true;
			var mark;
			for(var i = 0; i < 2; i++){
				i == 0 ? mark = 'n' : mark = 'x';
				$('.there[data-mark="' + mark + '"]').each(function() {
					for(var i = 0; i < 4; i++){
						if(init2)
							innerAnalizator(this, i);
					}
				});
			}

			function innerAnalizator(elem, line) {
				var dataRow = $(elem).attr('data-row');
				var dataColum = $(elem).attr('data-colum');
				var warning;

				outer:
				for(var i = 0; i < fieldSize; i++){
					if(line == 0){
						dataColum--;
					}
					else if(line == 1){
						dataRow--;
					}
					else if(line == 2){
						dataColum--;
						dataRow--;
					}
					else if(line == 3){
						dataColum++;
						dataRow--;
					}

					warning  = $('div[data-colum ="' + dataColum + '"][data-row ="' + dataRow + '"][data-mark ="' + mark + '"]');
					if($(warning).length >= 1 && $(warning).hasClass('there')){
						checkElems.push(warning);
						if($(checkElems).length == (fieldSize - 2)){
							checkElems.push($(elem));
							for(var i=0; i<checkElems.length; i++){
								var dataRow = $(checkElems[i]).attr('data-row');
								var dataColum = $(checkElems[i]).attr('data-colum');

								if(line == 0){
									var thisElem = $('div[data-row ="' + dataRow + '"]').not('.there');
									if(thisElem.length > 0){
										smartAi(thisElem);
										break outer;
									}
								}
								else if(line == 1){
									var thisElem = $('div[data-colum ="' + dataColum + '"]').not('.there');
									if(thisElem.length > 0){
										smartAi(thisElem);
										break outer;
									}
								}
								else if(line == 2){
										var r = 1;
										var c = 1;
									for(var i = 1; i <= fieldSize; i++){
										r = i;
										c = i;
										var thisElem = $('div[data-colum ="' + c + '"][data-row ="' + r + '"]').not('.there');
										if(thisElem.length > 0){
											smartAi(thisElem);
											break outer;
										}
									}
								}
								else if(line == 3){
										var r = 1;
										var c = fieldSize+1;
									for(var i = 1; i <= fieldSize; i++){
										r = i;
										c--;
										var thisElem = $('div[data-colum ="' + c + '"][data-row ="' + r + '"]').not('.there');
										if(thisElem.length > 0){
											smartAi(thisElem);
											break outer;
										}
									}
								}
							}
						}
					}
				}
				checkElems = [];
			}

			if(!smart && !win){
				randomAi();
			}
		};

		// Рандомный AI
		function randomAi() {
			var max = fieldSize * fieldSize -1;
			var min = 0;
			var rand = min - 0.5 + Math.random()*(max-min+1)
			rand = Math.round(rand);

			if(!$(arrElems[rand]).hasClass('there')){
				$(arrElems[rand]).find('span').text('○');
				$(arrElems[rand]).addClass('there');
				$(arrElems[rand]).attr('data-mark', 'n');

				init = true;
				$('.whose-move').text(text_Gamer);
				victory('n');
			}
			else{
				randomAi();
			}
		};

		// Умный AI
		function smartAi(elem) {
			var rand = difficultyRand();
			if(rand !== 5){
				$(elem).addClass('there');
				$(elem).attr('data-mark', 'n');
				$(elem).find('span').text('○');

				init = true;
				init2 = false;
				smart = true;
				$('.whose-move').text(text_Gamer)
				victory('n');
			}
			else{
				randomAi();
				init2 = false;
				smart = true;
			}
		};

		// Шанс ошибки хода AI
		function difficultyRand() {
			var min = 1,
				difficultyMax;
			if(difficultySelect == false){
				difficultyMax = 5;
			}
			else if(difficultySelect == true){
				difficultyMax = 4;
			}
			var rand = min - 0.5 + Math.random() * (difficultyMax - min + 1);
			return rand = Math.round(rand);
		}

		// Сообщение о результах игры
		function messWin(s) {
			var messInt;
			if(s == 'x'){
				$(field).before('
Результат: Победа!
');
				messInt = 2;
			}
			else if(s == 'n'){
				$(field).before('
Результат: Поражение!
');
				messInt = 3;
			}
			else{
				$(field).before('
Результат: Ничья!
');
				messInt = 4;
			}

			$.ajax({
				type: "POST",
				url: "php/stats.php",
				data:({s: messInt}),
				success: function(response){
<<<<<<>>>>>> f10d70175e2f9601633f98b5ed26e1a7365921cc
				}
			});

			win = true;

			$('#field').addClass('endgame');
			$('.whose-move').remove();
			$(field).after($('' + text_startGame + ''));
			$(settingsBlock).show(400);
			resetData();
		};

		//
		function infoGraph() {

			$('#info-grid > div > span').css('height', 0);

			var allGame = $('.text-stats-all').text();
			allGame = allGame.split(' ');
			allGame = allGame[allGame.length -1];

			var allGameLine1 = $('.text-stats-win').text();
			allGameLine1 = allGameLine1.split(' ');
			allGameLine1 = allGameLine1[allGameLine1.length -1];

			var allGameLine2 = $('.text-stats-defeat').text();
			allGameLine2 = allGameLine2.split(' ');
			allGameLine2 = allGameLine2[allGameLine2.length -1];

			var allGameLine3 = $('.text-stats-draw').text();
			allGameLine3 = allGameLine3.split(' ');
			allGameLine3 = allGameLine3[allGameLine3.length -1];

			var heightL1 = allGameLine1 / allGame * 100;
			heightL1 = heightL1.toFixed() + '%';
			var heightL2 = allGameLine2 / allGame * 100;
			heightL2 = heightL2.toFixed() + '%';
			var heightL3 = allGameLine3 / allGame * 100;
			heightL3 = heightL3.toFixed() + '%';

			$('.info-graph-line-1').animate({
				height : heightL1
			}, 400).html('' + heightL1 + '');

			$('.info-graph-line-2').animate({
				height : heightL2
			}, 400).html('' + heightL2 + '');

			$('.info-graph-line-3').animate({
				height : heightL3
			}, 400).html('' + heightL3 + '');
		};
		infoGraph();

		// Сброс глобальных переменных в начальное состояние
		function resetData() {
			fieldSize,
			difficultySelect,
			countRow = 1,
		 	countColum = 1,
		 	globalCountR = 0,
			win = false,
			init = true,
			smart = false,
			init2,
			arrElems = [],
			checkElems = [],
			arrColum = [];
		};

	});

})(jQuery);
<commit_msg>Delete script.js<commit_after><|endoftext|>


<commit_before>function lightbox(){
    var img = document.getElementsByClassName('post-image');
    var link;

    /*
     * Load all the big images in the thread
    */
    for (var i = 0; i < img.length; i++) {
      link = img[i].parentElement.href;
      document.getElementById('thread').insertAdjacentHTML('afterbegin', '');
    }

    for(var i = 0; i < img.length; i++){
        /*
         *  When the pointer is on an image
         *  the image appears in the lightbox
        */
        img[i].addEventListener('mouseover', function(){
            link = this.parentElement.href;
            document.getElementById('thread').insertAdjacentHTML('afterbegin', '

');
        }, false);

        /*
         *  When pointer is out: Remove the lightbox from the DOM
         */
        img[i].addEventListener('mouseout', function(){
            document.getElementById('lightbox').parentNode.removeChild(document.getElementById('lightbox'));
        }, false);

    }

}

function expandIMG(){
    /*
     *  It creates a button
     *  in the bottom bar which can be used
     *  to load all the original images in the thread
    */

    var bottomBar = document.getElementsByClassName('threadlinks');
    for(var i = 0; i < bottomBar.length; i++){
        bottomBar[i].insertAdjacentHTML('afterbegin', '[  Expand images  ]  ');
    }

    var botton = document.getElementById('expand-img');
    var img = document.getElementsByClassName('post-image');
    botton.addEventListener('click', function(){
        for(var i = 0; i < img.length; i++){
            img[i].click();
        }
    });
}

window.addEventListener('load', function(){
    lightbox();
    expandIMG();
});
<commit_msg>Use let instead of var<commit_after>function lightbox(){
    let img = document.getElementsByClassName('post-image');
    let link;

    /*
     * Load all the big images in the thread
    */
    for (let i = 0; i < img.length; i++) {
      link = img[i].parentElement.href;
      document.getElementById('thread').insertAdjacentHTML('afterbegin', '');
    }

    for(let i = 0; i < img.length; i++){
        /*
         *  When the pointer is on an image
         *  the image appears in the lightbox
        */
        img[i].addEventListener('mouseover', function(){
            link = this.parentElement.href;
            document.getElementById('thread').insertAdjacentHTML('afterbegin', '

');
        }, false);

        /*
         *  When pointer is out: Remove the lightbox from the DOM
         */
        img[i].addEventListener('mouseout', function(){
            document.getElementById('lightbox').parentNode.removeChild(document.getElementById('lightbox'));
        }, false);

    }

}

function expandIMG(){
    /*
     *  It creates a button
     *  in the bottom bar which can be used
     *  to load all the original images in the thread
    */

    let bottomBar = document.getElementsByClassName('threadlinks');
    for(let i = 0; i < bottomBar.length; i++){
        bottomBar[i].insertAdjacentHTML('afterbegin', '[  Expand images  ]  ');
    }

    let botton = document.getElementById('expand-img');
    let img = document.getElementsByClassName('post-image');
    botton.addEventListener('click', function(){
        for(let i = 0; i < img.length; i++){
            img[i].click();
        }
    });
}

window.addEventListener('load', function(){
    lightbox();
    expandIMG();
});
<|endoftext|>


<commit_before>//============== Eventhandler ==================//

document.addEventListener('DOMContentLoaded', function() {		// warte darauf, dass der Inhalt geladen wurde
	document.addEventListener('keydown', function(event) {
		if (event.keyCode === 27) {								// Escape wurde gedrueckt
			hideZoom();											// verstecke das Bildfenster
		}
	}, false);

	document.getElementById('newcityform').addEventListener('submit', function(event) {
		var formemail  = document.getElementById('formemail');
		var emailerror = document.getElementById('emailerror');
		emailerror.style.visibility = 'hidden';
		if (formemail.value.substring(formemail.value.length-20,
									  formemail.value.length) != "@beuth-hochschule.de") {		// wenn die letzten 20 Zeichen nicht dem String entsprechen
			emailerror.style.visibility = 'visible';
			event.preventDefault();																// Abbruch
		}
	}, false);

	/*var trs = document.getElementsByTagName('tr');
	for (var x=0; x<trs.length; x++) {
		trs[x].addEventListener('mouseover', function() {
			var tds = this.getElementsByTagName('td');
			tds[10].style.visibility = 'visible';
		}, false);
		trs[x].addEventListener('mouseout', function() {
			var tds = this.getElementsByTagName('td');
			tds[10].style.visibility = 'hidden';
		}, false);
	}*/

	document.getElementById('newcityformlist').addEventListener('change', function(event) {
		checkSelect('newcityform');
	}, false);

	initialize();
}, false);

//============== Hauptfunktionen ===============//

function initialize() {
	window.setTimeout(slideshow, 1000);						// Slideshow mit einer Verzoegerung von 1000ms starten.
	var today = new Date();									// neues Datum erzeugen
	var dd = today.getDate();								// hole den Tag
	var mm = today.getMonth()+1;							// hole den Monat; +1 weil hier Januar mit 0 gezaehlt wird
	var yyyy = today.getFullYear();							// hole das Jahr
	var formdate = document.getElementById('formdate');		// formdate-input ansprechen
	    formdate.value = yyyy + "-" + mm + "-" + dd;		// formdate auf das heutige Datum setzen
	fillLists();											// alle Staedte-Listen auffuellen
}

function fillLists() {
	var trs = document.getElementById('table').getElementsByTagName('tr');
	for (var i=1; i<trs.length-1; i++) {
		addCities(document.getElementById('entry'+i+'list'));
	}
	addCities(document.getElementById('newcityformlist'));
}

function makeEditable(entry) {
	var tr = document.getElementById(entry);				// DIV mit angegebenem Namen ansprechen
	var td = tr.getElementsByTagName('td');					// dessen td-Elemente ansprechen
	for (var i = 0; i < td.length; i++) {					// fuer alle td-Elemente
		if (td[i].className === 'edit') {					// wenn die jeweilige Klasse bearbeitbar ist
			td[i].style.display = 'table-cell';				// dann zeige sie an
		} else if (td[i].className === 'editable') {		// wenn die jeweilige Klasse nicht bearbeitbar ist
			td[i].style.display = 'none';					// dann verstecke sie
		}
	}
}

function save(entry) {
	var tr = document.getElementById(entry);											// DIV mit angegebenem Namen ansprechen
	var td = tr.getElementsByTagName('td');												// dessen td-Elemente ansprechen
	    td[0].innerHTML = formatDate(td[1].getElementsByTagName('input')[0].value);		// td mit Index 0 auf bearbeitetes Feld setzen
	    td[2].innerHTML = td[3].getElementsByTagName('input')[0].value + " °C";		// usw...
	var td5 = td[5].getElementsByTagName('select')[0];									// td mit Index 5 abkuerzen
	    td[4].innerHTML = td5.options[td5.selectedIndex].innerHTML;
	    td[8].innerHTML = td[9].getElementsByTagName('input')[0].value;
	for (var i = 0; i < td.length; i++) {												// fuer alle td-Elemente
		if (td[i].className === 'edit') {												// wenn die jeweilige Klasse bearbeitbar ist
			td[i].style.display = 'none';												// dann verstecke sie
		} else if (td[i].className === 'editable') {									// wenn die jeweilige Klasse nicht bearbeitbar ist
			td[i].style.display = 'table-cell';											// dann zeige sie an
		}
	}
}

function deleteEntry(entry) {
	if (confirm("Eintrag wirklich löschen?")) {				// Wenn Ja/Nein-Dialog bestaetigt wurde
		var tr = document.getElementById(entry);			// DIV mit angegebenem Namen ansprechen
		var td = tr.getElementsByTagName('td');				// dessen td-Elemente ansprechen
		for (var i = 0; i < td.length; i++) {				// fuer alle td-Elemente
			td[i].style.display = 'none';					// verstecke alle Elemente (temporaer -
		}													//  spaeter werden sie in der DB geloescht)
	}
}

function slideshow() {
	var images = document.getElementById('slideshow').getElementsByTagName('img');		// spreche alle Bilder im DIV 'slideshow' an
	if (typeof(counter) != "number") {													// wenn Counter noch nicht gesetzt
		counter = 0;
	}
	counter++;																			// Index auf naechstes Bild setzen
	if (counter < images.length) {														// wenn noch nicht alle Bilder angezeigt werden
		fadeIn(0, images);																// starte das einblenden des Bildes
	} else {
		for (var x = 1; x<images.length; x++) {
			images[x].style.opacity = 0;
			images[x].style.filter = 'alpha(opacity=0)';
		}
		counter = 0;
		fadeIn(0, images);
	}
}

function fadeIn(step, obj) {
	obj[counter].style.opacity = step/100;												// setze die Transparenz des Objekts auf 1/100 von Step
	obj[counter].style.filter = 'alpha(opacity=' + step + ')';							// setze die Transparenz des Objekts auf 1/100 von Step

	step += 2;

	if (step <= 100) {
		window.setTimeout(function () { fadeIn(step, obj); }, 1);						// Objekt noch nicht ganz sichtbar, ruft sich selbst auf
	} else {
		window.setTimeout(slideshow, 8000);												// Objekt jetzt sichtbar, starte naechstes Objekt nach 8000ms
	}
}

function checkSelect(id) {
	var element = document.getElementById(id+"list");									// select mit angegebenem Namen ansprechen
	var i = element.selectedIndex;														// hole den Index des aktuell ausgewaehlten Eintrags
	var selValue = element.options[i].value;											// hole den Text des aktuell ausgewaehlten Eintrags
	if (selValue === "neuestadt") {														// wenn eine neue Stadt eingetragen werden soll
		var userInput = prompt("Geben Sie den Namen der neuen Stadt ein:");
		if (userInput != "" && userInput != null) {
			var opt = createOption(formatValue(userInput), userInput);					// erstelle neue Option mit der Benutzereingabe
			element.add(opt, element[i]);												// fuege neue Option hinzu
			element.options[i].selected = 'selected';									// selektiere den neuen Eintrag
		}
	}
}

function addCities(select) {															// damit man nicht alle Staedte mehrfach eintragen muss
	select.add(createOption('', 'Stadt', true));
	select.add(createOption('berlin', 'Berlin'));
	select.add(createOption('koeln', 'Köln'));
	select.add(createOption('frankfurt', 'Frankfurt'));
	select.add(createOption('hamburg', 'Hamburg'));
	select.add(createOption('muenchen', 'München'));
	select.add(createOption('neuestadt', 'Neue Stadt...'));
}

function showZoom(img) {
	var y = document.getElementById('zoomImage').src = img;
	document.getElementById('zoomwrap').style.visibility = 'visible';
}

function hideZoom() {
	var z = document.getElementById('zoomwrap').style.visibility = 'hidden';
}

//============== Helferfunktionen ==============//

function formatValue(str) {									// ersetze alle dt. Umlaute und gib das Wort in Kleinbuchstaben zurueck
	return str.toLowerCase().replace(/\u00e4/g, "ae").replace(/\u00f6/g, "oe").replace(/\u00fc/g, "ue").replace(/\u00df/g, "ss").replace(/ /g, "_");
}

function formatDate(date) {									// uebersetze ein Datum vom ISO 8601-Format in die dt. Schreibweise und gib es zurueck
	return date.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/i, "$3.$2.$1");
}

function createOption(value, text, disabled) {				// neue Option erstellen
	var option = document.createElement("option");
	    option.value = value;
	    option.text = text;
	    option.disabled = disabled ? true : false;			// kurzform fuer if() {..} else {...}
	return option;
};<commit_msg>Corrected event listener<commit_after>//============== Eventhandler ==================//

window.addEventListener('load', function() {					// warte darauf, dass der Inhalt geladen wurde
	document.addEventListener('keydown', function(event) {
		if (event.keyCode === 27) {								// Escape wurde gedrueckt
			hideZoom();											// verstecke das Bildfenster
		}
	}, false);

	document.getElementById('newcityform').addEventListener('submit', function(event) {
		var formemail  = document.getElementById('formemail');
		var emailerror = document.getElementById('emailerror');
		emailerror.style.visibility = 'hidden';
		if (formemail.value.substring(formemail.value.length-20,
									  formemail.value.length) != "@beuth-hochschule.de") {		// wenn die letzten 20 Zeichen nicht dem String entsprechen
			emailerror.style.visibility = 'visible';
			event.preventDefault();																// Abbruch
		}
	}, false);

	/*var trs = document.getElementsByTagName('tr');
	for (var x=0; x<trs.length; x++) {
		trs[x].addEventListener('mouseover', function() {
			var tds = this.getElementsByTagName('td');
			tds[10].style.visibility = 'visible';
		}, false);
		trs[x].addEventListener('mouseout', function() {
			var tds = this.getElementsByTagName('td');
			tds[10].style.visibility = 'hidden';
		}, false);
	}*/

	document.getElementById('newcityformlist').addEventListener('change', function(event) {
		checkSelect('newcityform');
	}, false);

	initialize();
}, false);

//============== Hauptfunktionen ===============//

function initialize() {
	window.setTimeout(slideshow, 1000);						// Slideshow mit einer Verzoegerung von 1000ms starten.
	var today = new Date();									// neues Datum erzeugen
	var dd = today.getDate();								// hole den Tag
	var mm = today.getMonth()+1;							// hole den Monat; +1 weil hier Januar mit 0 gezaehlt wird
	var yyyy = today.getFullYear();							// hole das Jahr
	var formdate = document.getElementById('formdate');		// formdate-input ansprechen
	    formdate.value = yyyy + "-" + mm + "-" + dd;		// formdate auf das heutige Datum setzen
	fillLists();											// alle Staedte-Listen auffuellen
}

function fillLists() {
	var trs = document.getElementById('table').getElementsByTagName('tr');
	for (var i=1; i<trs.length-1; i++) {
		addCities(document.getElementById('entry'+i+'list'));
	}
	addCities(document.getElementById('newcityformlist'));
}

function makeEditable(entry) {
	var tr = document.getElementById(entry);				// DIV mit angegebenem Namen ansprechen
	var td = tr.getElementsByTagName('td');					// dessen td-Elemente ansprechen
	for (var i = 0; i < td.length; i++) {					// fuer alle td-Elemente
		if (td[i].className === 'edit') {					// wenn die jeweilige Klasse bearbeitbar ist
			td[i].style.display = 'table-cell';				// dann zeige sie an
		} else if (td[i].className === 'editable') {		// wenn die jeweilige Klasse nicht bearbeitbar ist
			td[i].style.display = 'none';					// dann verstecke sie
		}
	}
}

function save(entry) {
	var tr = document.getElementById(entry);											// DIV mit angegebenem Namen ansprechen
	var td = tr.getElementsByTagName('td');												// dessen td-Elemente ansprechen
	    td[0].innerHTML = formatDate(td[1].getElementsByTagName('input')[0].value);		// td mit Index 0 auf bearbeitetes Feld setzen
	    td[2].innerHTML = td[3].getElementsByTagName('input')[0].value + " °C";		// usw...
	var td5 = td[5].getElementsByTagName('select')[0];									// td mit Index 5 abkuerzen
	    td[4].innerHTML = td5.options[td5.selectedIndex].innerHTML;
	    td[8].innerHTML = td[9].getElementsByTagName('input')[0].value;
	for (var i = 0; i < td.length; i++) {												// fuer alle td-Elemente
		if (td[i].className === 'edit') {												// wenn die jeweilige Klasse bearbeitbar ist
			td[i].style.display = 'none';												// dann verstecke sie
		} else if (td[i].className === 'editable') {									// wenn die jeweilige Klasse nicht bearbeitbar ist
			td[i].style.display = 'table-cell';											// dann zeige sie an
		}
	}
}

function deleteEntry(entry) {
	if (confirm("Eintrag wirklich löschen?")) {				// Wenn Ja/Nein-Dialog bestaetigt wurde
		var tr = document.getElementById(entry);			// DIV mit angegebenem Namen ansprechen
		var td = tr.getElementsByTagName('td');				// dessen td-Elemente ansprechen
		for (var i = 0; i < td.length; i++) {				// fuer alle td-Elemente
			td[i].style.display = 'none';					// verstecke alle Elemente (temporaer -
		}													//  spaeter werden sie in der DB geloescht)
	}
}

function slideshow() {
	var images = document.getElementById('slideshow').getElementsByTagName('img');		// spreche alle Bilder im DIV 'slideshow' an
	if (typeof(counter) != "number") {													// wenn Counter noch nicht gesetzt
		counter = 0;
	}
	counter++;																			// Index auf naechstes Bild setzen
	if (counter < images.length) {														// wenn noch nicht alle Bilder angezeigt werden
		fadeIn(0, images);																// starte das einblenden des Bildes
	} else {
		for (var x = 1; x<images.length; x++) {
			images[x].style.opacity = 0;
			images[x].style.filter = 'alpha(opacity=0)';
		}
		counter = 0;
		fadeIn(0, images);
	}
}

function fadeIn(step, obj) {
	obj[counter].style.opacity = step/100;												// setze die Transparenz des Objekts auf 1/100 von Step
	obj[counter].style.filter = 'alpha(opacity=' + step + ')';							// setze die Transparenz des Objekts auf 1/100 von Step

	step += 2;

	if (step <= 100) {
		window.setTimeout(function () { fadeIn(step, obj); }, 1);						// Objekt noch nicht ganz sichtbar, ruft sich selbst auf
	} else {
		window.setTimeout(slideshow, 8000);												// Objekt jetzt sichtbar, starte naechstes Objekt nach 8000ms
	}
}

function checkSelect(id) {
	var element = document.getElementById(id+"list");									// select mit angegebenem Namen ansprechen
	var i = element.selectedIndex;														// hole den Index des aktuell ausgewaehlten Eintrags
	var selValue = element.options[i].value;											// hole den Text des aktuell ausgewaehlten Eintrags
	if (selValue === "neuestadt") {														// wenn eine neue Stadt eingetragen werden soll
		var userInput = prompt("Geben Sie den Namen der neuen Stadt ein:");
		if (userInput != "" && userInput != null) {
			var opt = createOption(formatValue(userInput), userInput);					// erstelle neue Option mit der Benutzereingabe
			element.add(opt, element[i]);												// fuege neue Option hinzu
			element.options[i].selected = 'selected';									// selektiere den neuen Eintrag
		}
	}
}

function addCities(select) {															// damit man nicht alle Staedte mehrfach eintragen muss
	select.add(createOption('', 'Stadt', true));
	select.add(createOption('berlin', 'Berlin'));
	select.add(createOption('koeln', 'Köln'));
	select.add(createOption('frankfurt', 'Frankfurt'));
	select.add(createOption('hamburg', 'Hamburg'));
	select.add(createOption('muenchen', 'München'));
	select.add(createOption('neuestadt', 'Neue Stadt...'));
}

function showZoom(img) {
	var y = document.getElementById('zoomImage').src = img;
	document.getElementById('zoomwrap').style.visibility = 'visible';
}

function hideZoom() {
	var z = document.getElementById('zoomwrap').style.visibility = 'hidden';
}

//============== Helferfunktionen ==============//

function formatValue(str) {									// ersetze alle dt. Umlaute und gib das Wort in Kleinbuchstaben zurueck
	return str.toLowerCase().replace(/\u00e4/g, "ae").replace(/\u00f6/g, "oe").replace(/\u00fc/g, "ue").replace(/\u00df/g, "ss").replace(/ /g, "_");
}

function formatDate(date) {									// uebersetze ein Datum vom ISO 8601-Format in die dt. Schreibweise und gib es zurueck
	return date.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/i, "$3.$2.$1");
}

function createOption(value, text, disabled) {				// neue Option erstellen
	var option = document.createElement("option");
	    option.value = value;
	    option.text = text;
	    option.disabled = disabled ? true : false;			// kurzform fuer if() {..} else {...}
	return option;
}<|endoftext|>


<commit_before>/**
 * ownCloud - recorder
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Shawn <syu702@aucklanduni.ac.nz>
 * @copyright Shawn 2016
 */
/*
(function (document.getElementById, OC) {

	document.getElementById(document).ready(function () {
		document.getElementById('#hello').click(function () {
			alert('Hello from your script file');
		});

		document.getElementById('#echo').click(function () {
			var url = OC.generateUrl('/apps/recorder/echo');
			var data = {
				echo: document.getElementById('#echo-content').val()
			};

			document.getElementById.post(url, data).success(function (response) {
				document.getElementById('#echo-result').text(response.echo);
			});

		});
*/

document.addEventListener( 'DOMContentLoaded', function () {
    var ready = function ( fn ) {

        // Sanity check
        if ( typeof fn !== 'function' ) return;

        // If document is already loaded, run method
        if ( document.readyState === 'complete'  ) {
            return fn();
        }

        // Otherwise, wait until document is loaded
        // The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading. The state indicates that the DOMContentLoaded event has been fired.
        document.addEventListener( 'interactive', fn, false );

        // Alternative: The document and all sub-resources have finished loading. The state indicates that the load event has been fired.
        // document.addEventListener( 'complete', fn, false );

    };

}

// Example

ready(function() {
    // Do stuff...
            function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
                navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
            }

            var mediaConstraints = {
                audio: true
            };

        // alert("JS demo is applied!");
            document.getElementById('#start-recording').onclick = function () {
        // alert("Function start is called!");
                this.disabled = true;
                captureUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
            };

            document.getElementById('#stop-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.stop();
                mediaRecorder.stream.stop();

                document.getElementById('#pause-recording').disabled = true;
                document.getElementById('#start-recording').disabled = false;
            };

            document.getElementById('#pause-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.pause();

                document.getElementById('#resume-recording').disabled = false;
            };

            document.getElementById('#resume-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.resume();

                document.getElementById('#pause-recording').disabled = false;
            };

            document.getElementById('#save-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.save();
            };

            var mediaRecorder;

            function onMediaSuccess(stream) {
                var audio = document.createElement('audio');

                audio = mergeProps(audio, {
                    controls: true,
                    muted: true,
                    src: URL.createObjectURL(stream)
                });
                audio.play();

                audiosContainer.appendChild(audio);
                audiosContainer.appendChild(document.createElement('hr'));

                mediaRecorder = new MediaStreamRecorder(stream);
                mediaRecorder.stream = stream;
                mediaRecorder.mimeType = document.getElementById('audio-mimeType').value;
                mediaRecorder.audioChannels = !!document.getElementById('left-channel').checked ? 1 : 2;
                mediaRecorder.ondataavailable = function(blob) {
                    var a = document.createElement('a');
                    a.target = '_blank';
                    a.innerHTML = 'Open Recorded Audio No. ' + (index++) + ' (Size: ' + bytesToSize(blob.size) + ') Time Length: ' + getTimeLength(timeInterval);

                    a.href = URL.createObjectURL(blob);

                    audiosContainer.appendChild(a);
                    audiosContainer.appendChild(document.createElement('hr'));
                };

                var timeInterval = document.getElementById('#time-interval').value;
                if (timeInterval) timeInterval = parseInt(timeInterval);
                else timeInterval = 5 * 1000;

                // get blob after specific time interval
                mediaRecorder.start(timeInterval);

                document.getElementById('#stop-recording').disabled = false;
                document.getElementById('#pause-recording').disabled = false;
                document.getElementById('#save-recording').disabled = false;
            }

            function onMediaError(e) {
                console.error('media error', e);
            }

            var audiosContainer = document.getElementById('audios-container');
            var index = 1;

            // below function via: http://goo.gl/B3ae8c
            function bytesToSize(bytes) {
                var k = 1000;
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                if (bytes === 0) return '0 Bytes';
                var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
                return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
            }

            // below function via: http://goo.gl/6QNDcI
            function getTimeLength(milliseconds) {
                var data = new Date(milliseconds);
                return data.getUTCHours() + " hours, " + data.getUTCMinutes() + " minutes and " + data.getUTCSeconds() + " second(s)";
            }

            window.onbeforeunload = function() {
                document.getElementById('#start-recording').disabled = false;
            };
}, false );

/*	});

})(jQuery, OC);
*/<commit_msg>tweak<commit_after>/**
 * ownCloud - recorder
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Shawn <syu702@aucklanduni.ac.nz>
 * @copyright Shawn 2016
 */
/*
(function (document.getElementById, OC) {

	document.getElementById(document).ready(function () {
		document.getElementById('#hello').click(function () {
			alert('Hello from your script file');
		});

		document.getElementById('#echo').click(function () {
			var url = OC.generateUrl('/apps/recorder/echo');
			var data = {
				echo: document.getElementById('#echo-content').val()
			};

			document.getElementById.post(url, data).success(function (response) {
				document.getElementById('#echo-result').text(response.echo);
			});

		});
*/

document.addEventListener( 'DOMContentLoaded', function () {
    var ready = function ( fn ) {

        // Sanity check
        if ( typeof fn !== 'function' ) return;

        // If document is already loaded, run method
        if ( document.readyState === 'complete'  ) {
            return fn();
        }

        // Otherwise, wait until document is loaded
        // The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading. The state indicates that the DOMContentLoaded event has been fired.
        document.addEventListener( 'interactive', fn, false );

        // Alternative: The document and all sub-resources have finished loading. The state indicates that the load event has been fired.
        // document.addEventListener( 'complete', fn, false );

    };

}, false );

// Example

ready(function() {
    // Do stuff...
            function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
                navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
            }

            var mediaConstraints = {
                audio: true
            };

        // alert("JS demo is applied!");
            document.getElementById('#start-recording').onclick = function () {
        // alert("Function start is called!");
                this.disabled = true;
                captureUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
            };

            document.getElementById('#stop-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.stop();
                mediaRecorder.stream.stop();

                document.getElementById('#pause-recording').disabled = true;
                document.getElementById('#start-recording').disabled = false;
            };

            document.getElementById('#pause-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.pause();

                document.getElementById('#resume-recording').disabled = false;
            };

            document.getElementById('#resume-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.resume();

                document.getElementById('#pause-recording').disabled = false;
            };

            document.getElementById('#save-recording').onclick = function() {
                this.disabled = true;
                mediaRecorder.save();
            };

            var mediaRecorder;

            function onMediaSuccess(stream) {
                var audio = document.createElement('audio');

                audio = mergeProps(audio, {
                    controls: true,
                    muted: true,
                    src: URL.createObjectURL(stream)
                });
                audio.play();

                audiosContainer.appendChild(audio);
                audiosContainer.appendChild(document.createElement('hr'));

                mediaRecorder = new MediaStreamRecorder(stream);
                mediaRecorder.stream = stream;
                mediaRecorder.mimeType = document.getElementById('audio-mimeType').value;
                mediaRecorder.audioChannels = !!document.getElementById('left-channel').checked ? 1 : 2;
                mediaRecorder.ondataavailable = function(blob) {
                    var a = document.createElement('a');
                    a.target = '_blank';
                    a.innerHTML = 'Open Recorded Audio No. ' + (index++) + ' (Size: ' + bytesToSize(blob.size) + ') Time Length: ' + getTimeLength(timeInterval);

                    a.href = URL.createObjectURL(blob);

                    audiosContainer.appendChild(a);
                    audiosContainer.appendChild(document.createElement('hr'));
                };

                var timeInterval = document.getElementById('#time-interval').value;
                if (timeInterval) timeInterval = parseInt(timeInterval);
                else timeInterval = 5 * 1000;

                // get blob after specific time interval
                mediaRecorder.start(timeInterval);

                document.getElementById('#stop-recording').disabled = false;
                document.getElementById('#pause-recording').disabled = false;
                document.getElementById('#save-recording').disabled = false;
            }

            function onMediaError(e) {
                console.error('media error', e);
            }

            var audiosContainer = document.getElementById('audios-container');
            var index = 1;

            // below function via: http://goo.gl/B3ae8c
            function bytesToSize(bytes) {
                var k = 1000;
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                if (bytes === 0) return '0 Bytes';
                var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
                return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
            }

            // below function via: http://goo.gl/6QNDcI
            function getTimeLength(milliseconds) {
                var data = new Date(milliseconds);
                return data.getUTCHours() + " hours, " + data.getUTCMinutes() + " minutes and " + data.getUTCSeconds() + " second(s)";
            }

            window.onbeforeunload = function() {
                document.getElementById('#start-recording').disabled = false;
            };
});
/*	});

})(jQuery, OC);
*/<|endoftext|>


<commit_before>cssRules  = {
	$media : "screen and (max-width:800px)",
	".container>div" : {
		backgroundColor: "orange",
		margin: "10px",
		float: "left"
	},
	".container" : {
		border: "solid 1px blue",
		margin: "0px auto",
		width: "960px"
	},
	".header" : {
		height: "200px",
		width: "940px"
	},
	".main" : {
		width : "640px",
		height : "1000px",
	},
	".sidebar" : {
		width : "280px",
	},
	".footer" : {
		width : "940px",
	},
	".modal" : {
		position : "absolute",
	},
	"form>label " : {
		display : "block",
		padding : "10px",
	},
	"form>label>*" : {
		display : "inline-block",
		width : "400px",
		verticalAlign: "top",
	},
	"form>label>span" : {
		padding : "0px 20px",
		width : "100px",
		textAlign: "right"
	}
};

struct = {
	container : {
		$ : {
			classes : "criatr lska",
			id : "superDiv",
			css : {
				marginA : "30px 40px",
				margin : "30px {30 +20}",
				border : "solid {$bwidth + $ouVar + px} $lightColor $otherVar $tVar" //REGISTER VAR, WHEN UNDEFINED
			},
			$var1 : 465, //REGISTER VAR, WHEN UNDEFINED AND ASSIGN VALUE
			$var2 : "200px",
			$lightColor : "#FCADEB",
			$bwidth : 20
		},
		header : {
			$ : {
				dir: "CDA",//'ltr', //TRY/CATCH ERROR
				onclick : function(e){
					console.log(e,e.offsetX, e.x, e.clientX, e.layerX, e.movementX);
				},
				css : {
					margin : "40px 50px",
					fontFamily : "$fontFamily",
					background : "url('/img/headerbg.jpg') no-repeat center top $lightColor"
				}
			},
			logo : {},
			menu : {}
		},
		main : {
			article1 : {
				text : 'TEXT TEXT TEXT TEXT TEXT ',
				html : '|| HTML HTML HTML LINK \n  Super code ',
				a : {}
			},
			article2 : {
				form : t.form({
					$ : { // [$] IS ALWAYS USED FOR CONFIGURATION
						id : "superForm",
						url : "/jscode/",
						classes : "class1 class2 class3",
						inline : false,
						ajax : true,
						post : true
					},
					name : {
						type: "name",
						empty: false
					},
					email : {
						type : "email",
						label : "E-mail",
						validate : true,
						empty: false
					},
					phone :  {
						type : "phone",
						mask : "+00 00 0000 0000",
						validate : true,
						empty : false
					},
					birthday :  {
						type: "date"
					},
					message :  {
						type: "text",
						empty: false
					},
					submit : {
						label : "Send Form",
					},
					reset : {
						label : "Clear this form",
					}
				})
			},
			article3 : {},
			article4 : {},
			article5 : {}
		},
		sidebar : {
			ad1 : {
				img : {}
			},
			ad2 : {
				embed : {}
			},
			ad3 : {
				applet : {}
			}
		},
		"div#elmID.class1.class2" : {}, // TEST
		footer : {
			col1 : {},
			col2 : {},
			col3 : {}
		}
	},
	modal : {
		button : {
			$ : {
				onclick : function(e){console.log(e)},
				classes : "super classes",
				id : "inpID",
				text : "SUPER BUTTON",
				type : "submit"
			}
		}
	}
};

//t.init({a:64});
//t.it(struct, t.body);

//t.init({strict:false, sections:true});
t.init({strict:true, sections:false});
t.it(struct);

a = new t.Sheet(cssRules);

/*

		FUNCTIONS
		 TESTING

*/
//(function(){
//})()

<commit_msg>Update script.js<commit_after>cssRules  = {
	$media : "screen and (min-width:700px)",
	".container>div" : {
		backgroundColor: "orange",
		margin: "10px",
		float: "left"
	},
	".container" : {
		border: "solid 1px blue",
		margin: "0px auto",
		width: "960px"
	},
	".header" : {
		height: "200px",
		width: "940px"
	},
	".main" : {
		width : "640px",
		height : "1000px",
	},
	".sidebar" : {
		width : "280px",
	},
	".footer" : {
		width : "940px",
	},
	".modal" : {
		position : "absolute",
	},
	"form>label " : {
		display : "block",
		padding : "10px",
	},
	"form>label>*" : {
		display : "inline-block",
		width : "400px",
		verticalAlign: "top",
	},
	"form>label>span" : {
		padding : "0px 20px",
		width : "100px",
		textAlign: "right"
	}
};

struct = {
	container : {
		$ : {
			classes : "criatr lska",
			id : "superDiv",
			css : {
				marginA : "30px 40px",
				margin : "30px {30 +20}",
				border : "solid {$bwidth + $ouVar + px} $lightColor $otherVar $tVar" //REGISTER VAR, WHEN UNDEFINED
			},
			$var1 : 465, //REGISTER VAR, WHEN UNDEFINED AND ASSIGN VALUE
			$var2 : "200px",
			$lightColor : "#FCADEB",
			$bwidth : 20
		},
		header : {
			$ : {
				dir: "CDA",//'ltr', //TRY/CATCH ERROR
				onclick : function(e){
					console.log(e,e.offsetX, e.x, e.clientX, e.layerX, e.movementX);
				},
				css : {
					margin : "40px 50px",
					fontFamily : "$fontFamily",
					background : "url('/img/headerbg.jpg') no-repeat center top $lightColor"
				}
			},
			logo : {},
			menu : {}
		},
		main : {
			article1 : {
				text : 'TEXT TEXT TEXT TEXT TEXT ',
				html : '|| HTML HTML HTML LINK \n  Super code ',
				a : {}
			},
			article2 : {
				form : t.form({
					$ : { // [$] IS ALWAYS USED FOR CONFIGURATION
						id : "superForm",
						url : "/jscode/",
						classes : "class1 class2 class3",
						inline : false,
						ajax : true,
						post : true
					},
					name : {
						type: "name",
						empty: false
					},
					email : {
						type : "email",
						label : "E-mail",
						validate : true,
						empty: false
					},
					phone :  {
						type : "phone",
						mask : "+00 00 0000 0000",
						validate : true,
						empty : false
					},
					birthday :  {
						type: "date"
					},
					message :  {
						type: "text",
						empty: false
					},
					submit : {
						label : "Send Form",
					},
					reset : {
						label : "Clear this form",
					}
				})
			},
			article3 : {},
			article4 : {},
			article5 : {}
		},
		sidebar : {
			ad1 : {
				img : {}
			},
			ad2 : {
				embed : {}
			},
			ad3 : {
				applet : {}
			}
		},
		"div#elmID.class1.class2" : {}, // TEST
		footer : {
			col1 : {},
			col2 : {},
			col3 : {}
		}
	},
	modal : {
		button : {
			$ : {
				onclick : function(e){console.log(e)},
				classes : "super classes",
				id : "inpID",
				text : "SUPER BUTTON",
				type : "submit"
			}
		}
	}
};

//t.init({a:64});
//t.it(struct, t.body);

//t.init({strict:false, sections:true});
t.init({strict:true, sections:false});
t.it(struct);

a = new t.Sheet(cssRules);

/*

		FUNCTIONS
		 TESTING

*/
//(function(){
//})()

<|endoftext|>


<commit_before>cssRules  = {
	$media : "screen and (min-width:700px)",
	".container>div" : {
		backgroundColor: "orange",
		margin: "10px",
		float: "left"
	},
	".container" : {
		border: "solid 1px blue",
		margin: "0px auto",
		width: "960px"
	},
	".header" : {
		height: "200px",
		width: "940px"
	},
	".main" : {
		width : "640px",
		height : "1000px",
	},
	".sidebar" : {
		width : "280px",
	},
	".footer" : {
		width : "940px",
	},
	".modal" : {
		position : "absolute",
	},
	"form>label " : {
		display : "block",
		padding : "10px",
	},
	"form>label>*" : {
		display : "inline-block",
		width : "400px",
		verticalAlign: "top",
	},
	"form>label>span" : {
		padding : "0px 20px",
		width : "100px",
		textAlign: "right"
	}
};

struct = {
	container : {
		$ : {
			classes : "criatr lska",
			id : "superDiv",
			css : {
				marginA : "30px 40px",
				margin : "30px {30 +20}",
				border : "solid {$bwidth + $ouVar + px} $lightColor $otherVar $tVar" //REGISTER VAR, WHEN UNDEFINED
			},
			$var1 : 465, //REGISTER VAR, WHEN UNDEFINED AND ASSIGN VALUE
			$var2 : "200px",
			$lightColor : "#FCADEB",
			$bwidth : 20
		},
		header : {
			$ : {
				dir: "CDA",//'ltr', //TRY/CATCH ERROR
				onclick : function(e){
					console.log(e,e.offsetX, e.x, e.clientX, e.layerX, e.movementX);
				},
				css : {
					margin : "40px 50px",
					fontFamily : "$fontFamily",
					background : "url('/img/headerbg.jpg') no-repeat center top $lightColor"
				}
			},
			logo : {},
			menu : {}
		},
		main : {
			article1 : {
				text : 'TEXT TEXT TEXT TEXT TEXT ',
				html : '|| HTML HTML HTML LINK \n  Super code ',
				a : {}
			},
			article2 : {
				form : t.form({
					$ : { // [$] IS ALWAYS USED FOR CONFIGURATION
						id : "superForm",
						url : "/jscode/",
						classes : "class1 class2 class3",
						inline : false,
						ajax : true,
						post : true
					},
					name : {
						type: "name",
						empty: false
					},
					email : {
						type : "email",
						label : "E-mail",
						validate : true,
						empty: false
					},
					phone :  {
						type : "phone",
						mask : "+00 00 0000 0000",
						validate : true,
						empty : false
					},
					birthday :  {
						type: "date"
					},
					message :  {
						type: "text",
						empty: false
					},
					submit : {
						label : "Send Form",
					},
					reset : {
						label : "Clear this form",
					}
				})
			},
			article3 : {},
			article4 : {},
			article5 : {}
		},
		sidebar : {
			ad1 : {
				img : {}
			},
			ad2 : {
				embed : {}
			},
			ad3 : {
				applet : {}
			}
		},
		"div#elmID.class1.class2" : {}, // TEST
		footer : {
			col1 : {},
			col2 : {},
			col3 : {}
		}
	},
	modal : {
		button : {
			$ : {
				onclick : function(e){console.log(e)},
				classes : "super classes",
				id : "inpID",
				text : "SUPER BUTTON",
				type : "submit"
			}
		}
	}
};

//t.init({a:64});
//t.it(struct, t.body);

//t.init({strict:false, sections:true});
t.init({strict:true, sections:false});
t.it(struct);

a = new t.Sheet(cssRules);

/*

		FUNCTIONS
		 TESTING

*/
//(function(){
//})()

<commit_msg>Update script.js<commit_after>cssRules  = {
	$ : {
		media : "screen and (min-width:800px)",
		$bWidth : 5,
		$mainColor : "#FCADEB"
	},
	".container>div" : {
		backgroundColor: "orange",
		float : "left",
		margin: "10px"
	},
	".container" : {
		border: "solid 1px blue",
		margin: "0px auto",
		width: "960px"
	},
	".header" : {
		height: "200px",
		width: "940px"
	},
	".main" : {
		width : "640px",
		height : "1000px",
	},
	".sidebar" : {
		minHeight : "500px",
		width : "280px",
	},
	".footer" : {
		width : "940px",
	},
	".modal" : {
		position : "absolute",
	},
	"form>label " : {
		display : "block",
		padding : "10px",
	},
	"form>label>*" : {
		display : "inline-block",
		width : "400px",
		verticalAlign: "top",
	},
	"form>label>span" : {
		padding : "0px 20px",
		width : "100px",
		textAlign: "right"
	},
	"#anySelector>div>ul>li" : {
		border : "solid {$bWidth * 2 + px } $mainColor",
		backgroundColor : "$mainColor",
		color : "$mainColor",

	}
};

struct = {
	container : {
		$ : {
			classes : "criatr lska",
			id : "superDiv",
			css : {
				marginA : "30px 40px",
				margin : "30px {30 +20}",
				backgroundColor : "$lightColor",
				border : "solid {$bwidth + $ouVar} $lightColor $otherVar $tVar" //REGISTER VAR, WHEN UNDEFINED
			},
			$var1 : 465, //REGISTER VAR, WHEN UNDEFINED AND ASSIGN VALUE
			$var2 : "200px",
			$lightColor : "#FCADEB",
			$bwidth : 20
		},
		header : {
			$ : {
				dir: "ltr",//'ltr', //TRY/CATCH ERROR
				onclick : function(e){
					console.log(e,e.offsetX, e.x, e.clientX, e.layerX, e.movementX);
				},
				css : {
					margin : "40px 50px",
					fontFamily : "$fontFamily",
					background : "url('/img/headerbg.jpg') no-repeat center top $lightColor",
					color : "$lightColor"
				}
			},
			logo : {},
			menu : {}
		},
		main : {
			$ : {
				css : {
					backgroundColor : "$lightColor"
				}
			},
			article1 : {
				text : 'TEXT TEXT TEXT TEXT TEXT ',
				html : '|| HTML HTML HTML LINK \n  Super code ',
				a : {}
			},
			article2 : {
				form : t.form({
					$ : { // [$] IS ALWAYS USED FOR CONFIGURATION
						id : "superForm",
						url : "/jscode/",
						classes : "class1 class2 class3",
						inline : false,
						ajax : true,
						post : true
					},
					name : {
						type: "name",
						empty: false
					},
					email : {
						type : "email",
						label : "E-mail",
						validate : true,
						empty: false
					},
					phone :  {
						type : "phone",
						mask : "+00 00 0000 0000",
						validate : true,
						empty : false
					},
					birthday :  {
						type: "date"
					},
					message :  {
						type: "text",
						empty: false
					},
					submit : {
						label : "Send Form",
					},
					reset : {
						label : "Clear this form",
					}
				})
			},
			article3 : {},
			article4 : {},
			article5 : {}
		},
		sidebar : {
			ad1 : {
				img : {}
			},
			ad2 : {
				//embed : {}
			},
			ad3 : {
				//applet : {}
			}
		},
		"div#elmID.class1.class2" : {}, // TEST
		footer : {
			col1 : {},
			col2 : {},
			col3 : {}
		}
	},
	modal : {
		button : {
			$ : {
				onclick : function(e){console.log(e)},
				classes : "super classes",
				id : "inpID",
				text : "SUPER BUTTON",
				type : "submit"
			}
		}
	}
};

//t.init({a:64});
//t.it(struct, t.body);

//t.init({strict:false, sections:true});
t.init({strict:true, sections:false});
t.it(struct);

var a = new t.Sheet(cssRules);
console.info(document.styleSheets);

/*

		FUNCTIONS
		 TESTING

*/
//(function(){
//})()

(function(){
	var width = 960,
			margin = 10,
			nCols = 12,
			colW = width / nCols;

	for(i = 1; i <= nCols; i++){
		//console.info("col_" + i + "{", "width:", colW * i - (2*margin));
	}
})()

<|endoftext|>


<commit_before>var jsPlugin = (function(){
    "use strict";

    // Define keys that your table will use,
    // in the order you want them to be displayed.
    // First item is leftmost, last item is rightmost
    //TODO: Fix above sentence
    var keys = [
        "id",
        "time",
        "time2",
        "location",
        "location2"
    ];

    var tableClass = 'table';
//    tableClass += ' table-bordered';
    tableClass += ' table-condensed';

    // RESTful provider URI
//    var dataProvider = "http://js-plugin.herokuapp.com/api";
//    var dataProvider = "http://localhost:4370/api";
    var dataProvider = "http://nest.duckdns.org:2223/api";

    //---------------------------------------------
    //== No more configuration beyond this point ==
    //
    //=== Variables ===
    //Initialize other variables
    var dataSet;
    var doneTables = 0;
    var totalTables = 0;

    //=== Functions ===
    var makeRequest = function (table, server, page, sortField, sortAsc){
        console.log("Making request to "+ server+ ".");
        var r = new XMLHttpRequest();
        if (page === (null || undefined) && sortField === undefined && sortAsc === undefined){
            r.open("GET", server, true);
//            r.open("GET", server + "?p=2&ts=" + (+Date.now()), true);
            r.onreadystatechange =  function(){
                if(r.readyState !== 4 || r.status !== 200){
                    console.log("Request went sour");
                    return;
                }
                console.log("Request successful.");
                parseResponse(table, r.responseText);
            };
        }
        else if(sortField !== undefined && sortAsc !== undefined){
            r.open("GET", server + "?sort[field]=" + sortField + "&sort[asc]=" + sortAsc, true);
            r.onreadystatechange =  function(){
                if(r.readyState !== 4 || r.status !== 200){
                    console.log("Request went sour");
                    return;
                }
                console.log("Request successful.");
                parseResponse(table, r.responseText);
            };
        }
        r.send(null);
    };

    var parseResponse = function(table, response){
        console.log("Parsing response.");
        dataSet = JSON.parse(response);
        fillTable(table);
    };

    var createTable = function(){
        console.log("Creating Table.");
        var i = 0;
        var table = document.createElement("table");
        table.className = tableClass;
        var thead = document.createElement("thead");
        var tr = document.createElement("tr");

        for (i; i < keys.length; i+=1){
            var th = document.createElement("th");
            th.appendChild(document.createTextNode(keys[i]));
            tr.appendChild(th);
        }

        thead.appendChild(tr);
        table.appendChild(thead);
        console.log("Table created.");
        totalTables += 1;
        return table;
    };

    var fillTable = function(table){
        console.log("Filling table.");
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);

        var numRows = dataSet.length;

        var i = 0;
        while (i < numRows){
            var col = dataSet[i];
            var tr = document.createElement("tr");
            var colCells = Object.keys(col).length;

            var j = 0;
            while (j < colCells)
            {
                var td = document.createElement("td");
                td.appendChild(document.createTextNode(col[keys[j]]));
                tr.appendChild(td);
                j+=1;
            }

            tbody.appendChild(tr);
            i+=1;
        }
        var container = document.getElementsByClassName('container')[0];
        var tableContainer = document.createElement('div');
        tableContainer.className = 'table-container';
        tableContainer.appendChild(table);
        container.appendChild(tableContainer);
        tableDone();
    };

    var tableDone = function(){
        doneTables += 1;
        if (doneTables === totalTables){
            window.mySwipe = Swipe(document.getElementById('slider'),{
                continuous:false
            });
        }
    }

    //=== Logic ===

    var dataTable = createTable();
    console.log("dataProvider === " + dataProvider);
    makeRequest(dataTable, dataProvider);

    var secondTable = createTable();
    makeRequest(secondTable, dataProvider, null, "location2", true );

}());<commit_msg>Remove old data providers<commit_after>var jsPlugin = (function(){
    "use strict";

    // Define keys that your table will use,
    // in the order you want them to be displayed.
    // First item is leftmost, last item is rightmost
    //TODO: Fix above sentence
    var keys = [
        "id",
        "time",
        "time2",
        "location",
        "location2"
    ];

    var tableClass = 'table';
//    tableClass += ' table-bordered';
    tableClass += ' table-condensed';

    // RESTful provider URI
    var dataProvider = "http://nest.duckdns.org:2223/api";

    //---------------------------------------------
    //== No more configuration beyond this point ==
    //
    //=== Variables ===
    //Initialize other variables
    var dataSet;
    var doneTables = 0;
    var totalTables = 0;

    //=== Functions ===
    var makeRequest = function (table, server, page, sortField, sortAsc){
        console.log("Making request to "+ server+ ".");
        var r = new XMLHttpRequest();
        if (page === (null || undefined) && sortField === undefined && sortAsc === undefined){
            r.open("GET", server, true);
//            r.open("GET", server + "?p=2&ts=" + (+Date.now()), true);
            r.onreadystatechange =  function(){
                if(r.readyState !== 4 || r.status !== 200){
                    console.log("Request went sour");
                    return;
                }
                console.log("Request successful.");
                parseResponse(table, r.responseText);
            };
        }
        else if(sortField !== undefined && sortAsc !== undefined){
            r.open("GET", server + "?sort[field]=" + sortField + "&sort[asc]=" + sortAsc, true);
            r.onreadystatechange =  function(){
                if(r.readyState !== 4 || r.status !== 200){
                    console.log("Request went sour");
                    return;
                }
                console.log("Request successful.");
                parseResponse(table, r.responseText);
            };
        }
        r.send(null);
    };

    var parseResponse = function(table, response){
        console.log("Parsing response.");
        dataSet = JSON.parse(response);
        fillTable(table);
    };

    var createTable = function(){
        console.log("Creating Table.");
        var i = 0;
        var table = document.createElement("table");
        table.className = tableClass;
        var thead = document.createElement("thead");
        var tr = document.createElement("tr");

        for (i; i < keys.length; i+=1){
            var th = document.createElement("th");
            th.appendChild(document.createTextNode(keys[i]));
            tr.appendChild(th);
        }

        thead.appendChild(tr);
        table.appendChild(thead);
        console.log("Table created.");
        totalTables += 1;
        return table;
    };

    var fillTable = function(table){
        console.log("Filling table.");
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);

        var numRows = dataSet.length;

        var i = 0;
        while (i < numRows){
            var col = dataSet[i];
            var tr = document.createElement("tr");
            var colCells = Object.keys(col).length;

            var j = 0;
            while (j < colCells)
            {
                var td = document.createElement("td");
                td.appendChild(document.createTextNode(col[keys[j]]));
                tr.appendChild(td);
                j+=1;
            }

            tbody.appendChild(tr);
            i+=1;
        }
        var container = document.getElementsByClassName('container')[0];
        var tableContainer = document.createElement('div');
        tableContainer.className = 'table-container';
        tableContainer.appendChild(table);
        container.appendChild(tableContainer);
        tableDone();
    };

    var tableDone = function(){
        doneTables += 1;
        if (doneTables === totalTables){
            window.mySwipe = Swipe(document.getElementById('slider'),{
                continuous:false
            });
        }
    };

    //=== Logic ===

    var dataTable = createTable();
    console.log("dataProvider === " + dataProvider);
    makeRequest(dataTable, dataProvider);

    var secondTable = createTable();
    makeRequest(secondTable, dataProvider, null, "location2", true );

}());<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
        function toHex(n) {
            n = parseInt(n,10);
            if (isNaN(n)) return "00";
            n = Math.max(0,Math.min(n,255));
            return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16);
        }

        function floodfill(node, targetcolor, replacementcolor, pathWidth, pathHeight){
            var nodeimgdata = c.getImageData(node.x,node.y,1,1).data;
            var nodecolor = "#" + rgbToHex(nodeimgdata[0],nodeimgdata[1],nodeimgdata[2]);

            if(nodecolor == replacementcolor){
                return;
            }
            if(targetcolor == replacementcolor){
                return;
            }

            if(nodecolor != targetcolor){
                return;
            }
            if(node.x < 0 || node.x >= pathWidth * 30 || node.y < 0 || node.y >= pathHeight*30){
                return;
            }

            c.fillStyle = replacementcolor;
            c.fillRect(node.x, node.y, 6, 6);
            var westnode = {
                x:0,
                y:0
            };
            westnode.x = node.x - 6;
            westnode.y = node.y;
            var eastnode = {
                x:0,
                y:0
            };
            eastnode.x = node.x + 6;
            eastnode.y = node.y
            var northnode = {
                x:0,
                y:0
            };
            northnode.x = node.x;
            northnode.y = node.y - 6;
            var southnode = {
                x:0,
                y:0
            };
            southnode.x = node.x;
            southnode.y = node.y + 6;
            floodfill(westnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(eastnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(northnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(southnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            return;

        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

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

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

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

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 11, movingpointold.y*30 + l*movedirY + 11, 8, 8);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            //c.fillStyle = "#33CC33";
            c.fillStyle = "#FFFFFF";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            //c.fillStyle = "#CC0000";
            c.fillStyle = "#FFFFFF";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

            var startnode = {
                x:0,
                y:0
            };
            startnode.x = startpoint.x*30;
            startnode.y = startpoint.y*30;
            floodfill(startnode,"#FFFFFF","#0099FF", pathWidth, pathHeight);
            var imgdata = c.getImageData(0,0,1,1).data;

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
        function toHex(n) {
            n = parseInt(n,10);
            if (isNaN(n)) return "00";
            n = Math.max(0,Math.min(n,255));
            return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16);
        }

        function floodfill(node, targetcolor, replacementcolor, pathWidth, pathHeight){
            var nodeimgdata = c.getImageData(node.x,node.y,1,1).data;
            var nodecolor = "#" + rgbToHex(nodeimgdata[0],nodeimgdata[1],nodeimgdata[2]);

            if(nodecolor == replacementcolor){
                return;
            }
            if(targetcolor == replacementcolor){
                return;
            }

            if(nodecolor != targetcolor){
                return;
            }
            if(node.x < 0 || node.x >= pathWidth * 30 || node.y < 0 || node.y >= pathHeight*30){
                return;
            }

            c.fillStyle = replacementcolor;
            c.fillRect(node.x, node.y, 8, 8);
            var westnode = {
                x:0,
                y:0
            };
            westnode.x = node.x - 8;
            westnode.y = node.y;
            var eastnode = {
                x:0,
                y:0
            };
            eastnode.x = node.x + 8;
            eastnode.y = node.y
            var northnode = {
                x:0,
                y:0
            };
            northnode.x = node.x;
            northnode.y = node.y - 8;
            var southnode = {
                x:0,
                y:0
            };
            southnode.x = node.x;
            southnode.y = node.y + 8;
            floodfill(westnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(eastnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(northnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(southnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            return;

        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

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

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

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

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 11, movingpointold.y*30 + l*movedirY + 11, 8, 8);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            //c.fillStyle = "#33CC33";
            c.fillStyle = "#FFFFFF";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            //c.fillStyle = "#CC0000";
            c.fillStyle = "#FFFFFF";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

            var startnode = {
                x:0,
                y:0
            };
            startnode.x = startpoint.x*30;
            startnode.y = startpoint.y*30;
            floodfill(startnode,"#FFFFFF","#0099FF", pathWidth, pathHeight);
            var imgdata = c.getImageData(0,0,1,1).data;

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>

$(document).ready(function(){

    // Controla a interação do botão Seguir para o Topo

    jQuery(window).load(function() {
        jQuery("#backtotop").hide().removeAttr("href");
        if (jQuery(window).scrollTop() != "0") {
            jQuery("#backtotop").fadeIn("slow");
            if (basalstyle.HeaderFloat)
                jQuery("#header-frame").addClass("header-float");
        }
        var scrollDiv = jQuery("#backtotop");
        jQuery(window).scroll(function(){
            if (jQuery(window).scrollTop() == "0") {
                jQuery(scrollDiv).fadeOut("slow");
                if (basalstyle.HeaderFloat)
                    jQuery("#header-frame").removeClass("header-float");
            } else {
                jQuery(scrollDiv).fadeIn("slow")
                if (basalstyle.HeaderFloat)
                    jQuery("#header-frame").addClass("header-float");
            }
        });
    });

    $('#backtotop').click(function() {
        $('body,html').animate({scrollTop:0},2500,"easeOutQuart");
    });

    $( "article figure" ).each(function() {
        height_int = Math.ceil( $( this ).outerHeight() / 30);
        $( this ).addClass( 'min-h-' + height_int );
    });

});
<commit_msg>Aprimora o espaçamento dos blocos de código e tabela.<commit_after>

$(document).ready(function(){

    // Controla a interação do botão Seguir para o Topo

    jQuery(window).load(function() {
        jQuery("#backtotop").hide().removeAttr("href");
        if (jQuery(window).scrollTop() != "0") {
            jQuery("#backtotop").fadeIn("slow");
            if (basalstyle.HeaderFloat)
                jQuery("#header-frame").addClass("header-float");
        }
        var scrollDiv = jQuery("#backtotop");
        jQuery(window).scroll(function(){
            if (jQuery(window).scrollTop() == "0") {
                jQuery(scrollDiv).fadeOut("slow");
                if (basalstyle.HeaderFloat)
                    jQuery("#header-frame").removeClass("header-float");
            } else {
                jQuery(scrollDiv).fadeIn("slow")
                if (basalstyle.HeaderFloat)
                    jQuery("#header-frame").addClass("header-float");
            }
        });
    });

    $('#backtotop').click(function() {
        $('body,html').animate({scrollTop:0},2500,"easeOutQuart");
    });

    $( "article figure, article pre, article .table-wrapper" ).each(function() {
        height_int = Math.ceil( $( this ).outerHeight() / 30);
        $( this ).addClass( 'min-h-' + height_int );
    });

});
<|endoftext|>