<commit_before>
(function ($){
  var app = $.app;
  var IMG_WIDTH = 100;

  function mainColumn() {}

  function startProgress() {
    $('#progressbar', '#search_column').show();
    $('input[name=search]').attr('disabled', 'disabled');
  }

  function makeProgress(total, progress) {
    var degree = (progress/total)*360;
    app.progress_ctx.beginPath();
    app.progress_ctx.clearRect(
      0,0,$.app.progress_canvas.width,$.app.progress_canvas.height);

    app.progress_ctx.strokeStyle = 'rgba(190, 190, 190, 0.4)';
    app.progress_ctx.lineWidth = 1;
    app.progress_ctx.arc(75,75,50,Math.PI*(270/180),Math.PI*(360+270)/180);
    app.progress_ctx.stroke();
    app.progress_ctx.closePath();

    app.progress_ctx.beginPath();
    app.progress_ctx.strokeStyle = 'rgba(190, 190, 190, 0.4)';
    app.progress_ctx.lineWidth = 1;
    app.progress_ctx.arc(75,75,70,Math.PI*(270/180),Math.PI*(360+270)/180);
    app.progress_ctx.stroke();
    app.progress_ctx.closePath();

    app.progress_ctx.beginPath();
    app.progress_ctx.strokeStyle = 'rgba(210, 210, 210, 0.9)';
    app.progress_ctx.lineWidth = 18;
    app.progress_ctx.arc(75,75,60,Math.PI*(270/180),Math.PI*(degree+270)/180);

    app.progress_ctx.shadowOffsetX = 0;
    app.progress_ctx.shadowOffsetY = 0;
    app.progress_ctx.shadowBlur = 5;
    app.progress_ctx.shadowColor = 'rgba(160,160,160,0.7)';

    app.progress_ctx.stroke();

    app.progress_ctx.closePath();
  }

  function completeProgress() {
    $('#progressbar', '#search_column').fadeOut();
    $('input[name=search]').attr('disabled', '');
  }

  function showSearchResults() {
    $('#shelf', '#search_column').hide();
    $('#search_results', '#search_column').empty();
    $('#search_results', '#search_column').show();
  }

  function showShelf() {
    $('#shelf', '#search_column').show();
    $('#search_results', '#search_column').hide();
  }

  function populateShelf(url, artist, album){
    var shelf = $('#shelf', '#search_column');
    var artworkNum = Math.floor(shelf.width()/IMG_WIDTH);
    var margin = (shelf.width()-(artworkNum*IMG_WIDTH))/(artworkNum*2);
    var artwork = $('')
      .attr('src', url)
      .attr('title', album+'\n'+artist)
      .data('meta', { album : album, artist : artist })
      .css('margin', Math.floor(margin)-1)
      .fadeIn()
      .click(function () {
        showSearchResults();
        var query = 'al:'+$(this).data('meta').album;
        populateSearchResults(query);
        $('input[name=search]').val(query);
      });
    $('#shelf', '#search_column').append(artwork);
  }

  function populateSearchResults(query) {
    var results = $.app.Storage.search(query);
    _(results).each(function (muFile) {
      $('#search_results', '#search_column')
        .append($.app.utils.getSongEntryHTML(muFile, true));
    });

    $('#search_results', '#search_column').find('.entry_action')
      .click(function () {
        var muFile = $(this).data('muFile');
        var player_entry = $.app.utils.getSongEntryHTML(muFile, false);
        $.app.Playlist.attachEntryControls(player_entry);
        $.app.Playlist.add(player_entry)
      });
    $('#search_column #search_results').find('.album_name')
      .click(function () {
        var muFile = $(this).data('muFile');
        showSearchResults();
        var query = 'al:'+muFile.album;
        populateSearchResults(query);
        $('input[name=search]').val(query);
      });
    $('#search_column #search_results').find('.artist_name')
      .click(function () {
        var muFile = $(this).data('muFile');
        showSearchResults();
        var query = 'ar:'+muFile.artist
        populateSearchResults(query);
        $('input[name=search]').val(query);
      });
  }

  function init() {
    app.localArtworks = loadArtworkMap();
    _.each(app.localArtworks, function (artwork, key){
      populateShelf(key, artwork.artist, artwork.album);
    });

    $('input[name=search]').keyup(function (e) {

      var text = $(this).val();

      if(!text || (text && text.length < 4)) {
        showShelf();
        return;
      }
      showSearchResults();
      populateSearchResults(text);

    })
    .focusin(function (e){
      if($(this).val() == 'Search...'){ $(this).val(''); }
    })
    .focusout(function (e){
      if($(this).val() == ''){
        $(this).val('Search...');
        showShelf();
      }
    });

    $('#addall', '#search_column').click(function () {
      $('#search_results .entry', '#search_column').each(function () {
        var muFile = $(this).find('.entry_action').data('muFile');
        var player_entry = $.app.utils.getSongEntryHTML(muFile, false);
        $.app.Playlist.attachEntryControls(player_entry);
        $.app.Playlist.add(player_entry);
      });
    });

    $('#clear_search', '#search_column').click(function (){
      $('input[name=search]').focus().val('');
      showShelf();
    });
  }

  function storeArtworkMap() {
    window.localStorage.setItem(
      '__artwork_map__', JSON.stringify(app.localArtworks));
  }

  function loadArtworkMap() {
    var artworks =
      JSON.parse(window.localStorage.getItem('__artwork_map__'));
    return (_.isNull(artworks) ? {} : artworks);
  }

  app.mainColumn = mainColumn;
  app.mainColumn.init = init;
  app.mainColumn.storeArtworkMap = storeArtworkMap;
  app.mainColumn.loadArtworkMap = loadArtworkMap;
  app.mainColumn.populateShelf = populateShelf;
  app.mainColumn.showShelf = showShelf;
  app.mainColumn.showSearchResults = showSearchResults;
  app.mainColumn.startProgress = startProgress;
  app.mainColumn.makeProgress = makeProgress;
  app.mainColumn.completeProgress = completeProgress;

})(jQuery);
<commit_msg>Remember the scrollTop of album grid when switching it with search results. (Fixes #15)<commit_after>
(function ($){
  var app = $.app;
  var IMG_WIDTH = 100;

  function mainColumn() {}

  function startProgress() {
    $('#progressbar', '#search_column').show();
    $('input[name=search]').attr('disabled', 'disabled');
  }

  function makeProgress(total, progress) {
    var degree = (progress/total)*360;
    app.progress_ctx.beginPath();
    app.progress_ctx.clearRect(
      0,0,$.app.progress_canvas.width,$.app.progress_canvas.height);

    app.progress_ctx.strokeStyle = 'rgba(190, 190, 190, 0.4)';
    app.progress_ctx.lineWidth = 1;
    app.progress_ctx.arc(75,75,50,Math.PI*(270/180),Math.PI*(360+270)/180);
    app.progress_ctx.stroke();
    app.progress_ctx.closePath();

    app.progress_ctx.beginPath();
    app.progress_ctx.strokeStyle = 'rgba(190, 190, 190, 0.4)';
    app.progress_ctx.lineWidth = 1;
    app.progress_ctx.arc(75,75,70,Math.PI*(270/180),Math.PI*(360+270)/180);
    app.progress_ctx.stroke();
    app.progress_ctx.closePath();

    app.progress_ctx.beginPath();
    app.progress_ctx.strokeStyle = 'rgba(210, 210, 210, 0.9)';
    app.progress_ctx.lineWidth = 18;
    app.progress_ctx.arc(75,75,60,Math.PI*(270/180),Math.PI*(degree+270)/180);

    app.progress_ctx.shadowOffsetX = 0;
    app.progress_ctx.shadowOffsetY = 0;
    app.progress_ctx.shadowBlur = 5;
    app.progress_ctx.shadowColor = 'rgba(160,160,160,0.7)';

    app.progress_ctx.stroke();

    app.progress_ctx.closePath();
  }

  function completeProgress() {
    $('#progressbar', '#search_column').fadeOut();
    $('input[name=search]').attr('disabled', '');
  }

  function showSearchResults() {
    $('#shelf', '#search_column').hide();
    $('#search_results', '#search_column').empty();
    $('#search_results', '#search_column').show();
  }

  function showShelf() {
    var shelf = $('#shelf', '#search_column').show();
    var scTop = shelf.data('scrollTop');
    if(scTop) {
      shelf.scrollTop(scTop);
      shelf.removeData('scrollTop');
    }
    $('#search_results', '#search_column').hide();
  }

  function populateShelf(url, artist, album){
    var shelf = $('#shelf', '#search_column');
    var artworkNum = Math.floor(shelf.width()/IMG_WIDTH);
    var margin = (shelf.width()-(artworkNum*IMG_WIDTH))/(artworkNum*2);
    var artwork = $('')
      .attr('src', url)
      .attr('title', album+'\n'+artist)
      .data('meta', { album : album, artist : artist })
      .css('margin', Math.floor(margin)-1)
      .fadeIn()
      .click(function () {
        var shelf = $(this).parent();
        shelf.data('scrollTop', shelf.scrollTop());
        showSearchResults();
        var query = 'al:'+$(this).data('meta').album;
        populateSearchResults(query);
        $('input[name=search]').val(query);
      });
    $('#shelf', '#search_column').append(artwork);
  }

  function populateSearchResults(query) {
    var results = $.app.Storage.search(query);
    _(results).each(function (muFile) {
      $('#search_results', '#search_column')
        .append($.app.utils.getSongEntryHTML(muFile, true));
    });

    $('#search_results', '#search_column').find('.entry_action')
      .click(function () {
        var muFile = $(this).data('muFile');
        var player_entry = $.app.utils.getSongEntryHTML(muFile, false);
        $.app.Playlist.attachEntryControls(player_entry);
        $.app.Playlist.add(player_entry)
      });
    $('#search_column #search_results').find('.album_name')
      .click(function () {
        var muFile = $(this).data('muFile');
        showSearchResults();
        var query = 'al:'+muFile.album;
        populateSearchResults(query);
        $('input[name=search]').val(query);
      });
    $('#search_column #search_results').find('.artist_name')
      .click(function () {
        var muFile = $(this).data('muFile');
        showSearchResults();
        var query = 'ar:'+muFile.artist
        populateSearchResults(query);
        $('input[name=search]').val(query);
      });
  }

  function init() {
    app.localArtworks = loadArtworkMap();
    _.each(app.localArtworks, function (artwork, key){
      populateShelf(key, artwork.artist, artwork.album);
    });

    $('input[name=search]').keyup(function (e) {

      var text = $(this).val();

      if(!text || (text && text.length < 4)) {
        showShelf();
        return;
      }
      showSearchResults();
      populateSearchResults(text);

    })
    .focusin(function (e){
      if($(this).val() == 'Search...'){ $(this).val(''); }
    })
    .focusout(function (e){
      if($(this).val() == ''){
        $(this).val('Search...');
        showShelf();
      }
    });

    $('#addall', '#search_column').click(function () {
      $('#search_results .entry', '#search_column').each(function () {
        var muFile = $(this).find('.entry_action').data('muFile');
        var player_entry = $.app.utils.getSongEntryHTML(muFile, false);
        $.app.Playlist.attachEntryControls(player_entry);
        $.app.Playlist.add(player_entry);
      });
    });

    $('#clear_search', '#search_column').click(function (){
      $('input[name=search]').focus().val('');
      showShelf();
    });
  }

  function storeArtworkMap() {
    window.localStorage.setItem(
      '__artwork_map__', JSON.stringify(app.localArtworks));
  }

  function loadArtworkMap() {
    var artworks =
      JSON.parse(window.localStorage.getItem('__artwork_map__'));
    return (_.isNull(artworks) ? {} : artworks);
  }

  app.mainColumn = mainColumn;
  app.mainColumn.init = init;
  app.mainColumn.storeArtworkMap = storeArtworkMap;
  app.mainColumn.loadArtworkMap = loadArtworkMap;
  app.mainColumn.populateShelf = populateShelf;
  app.mainColumn.showShelf = showShelf;
  app.mainColumn.showSearchResults = showSearchResults;
  app.mainColumn.startProgress = startProgress;
  app.mainColumn.makeProgress = makeProgress;
  app.mainColumn.completeProgress = completeProgress;

})(jQuery);
<|endoftext|>


<commit_before>"use strict";

String.prototype.capitalise = function() {
    return this.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};

function CSVToArray(strData, strDelimiter) {
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = ",";

    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(
    (
    // Delimiters.
    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

    // Quoted fields.
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

    // Standard fields.
    "([^\"\\" + strDelimiter + "\\r\\n]*))"),
        "gi");

    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [
        []
    ];

    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;

    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec(strData)) {

        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[1];

        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (
            strMatchedDelimiter.length &&
            (strMatchedDelimiter != strDelimiter)) {

            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push([]);

        }

        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[2]) {

            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[2].replace(
                new RegExp("\"\"", "g"),
                "\"");

        } else {

            // We found a non-quoted value.
            var strMatchedValue = arrMatches[3];

        }

        // Now that we have our value string, let's add
        // it to the data array.
        arrData[arrData.length - 1].push(strMatchedValue);
    }

    // Return the parsed data.
    return (arrData);
}

Object.size = function(obj) {
    var size = 0;
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

var pop = new XMLHttpRequest();
pop.open("get", "http://tsitu.github.io/MH-Tools/data/populations2.csv", true);
pop.onreadystatechange = function() {
	if (pop.readyState == 4) {
		processPop();
	}
}
pop.send();

var popCSV = new Array();
var popArray = new Array();
function processPop() {
	var popText = pop.responseText;

	popCSV = CSVToArray(popText);
	//console.log(popCSV);
	var popCSVLength = Object.size(popCSV);
	//console.log(popCSVLength);

	//Creating popArray
	for(var i=1; i<popCSVLength; i++) {
		var row = popCSV[i];
		var location = row[0];
		var phase = row[1];
		var cheese = row[2];
		var charm = row[3];
		var mouseName = row[4];
		mouseName = mouseName.capitalise();
		var population = row[5];

		if (popArray[mouseName] == undefined) popArray[mouseName] = new Array(); //If mouse doesn't exist in array
		if (popArray[mouseName][location] == undefined) popArray[mouseName][location] = new Array();
		if (popArray[mouseName][location][phase] == undefined) popArray[mouseName][location][phase] = new Array();
		if (popArray[mouseName][location][phase][cheese] == undefined) popArray[mouseName][location][phase][cheese] = new Array();
		popArray[mouseName][location][phase][cheese][charm] = population;
	}

	loadMouseDropdown();
}

function loadMouseDropdown() {
	var popArrayLength = Object.size(popArray);
	var suggests = [];

	for (var i=0; i<popArrayLength; i++) {
		suggests.push(Object.keys(popArray)[i]);
		suggests.push(Object.keys(popArray)[i].toLowerCase());
	}

	$("#map").asuggest(suggests);

}

window.onload = function () {
	/*document.getElementById("map").onchange = function () {
    	var mapText = document.getElementById("map").value;
	    //console.log(mapText);
	    processMap(mapText);
	};*/

	document.getElementById("map").onkeyup = function () {
    	var mapText = document.getElementById("map").value;
	    //console.log(mapText);
	    processMap(mapText);
	};
}

function processMap(mapText) {
	var mouseArray = mapText.split("\n");
	var mouseArrayLength = Object.size(mouseArray);

	var interpretedAs = document.getElementById("interpretedAs");
	var mouseList = document.getElementById("mouseList");

	var interpretedAsText = "Rectify:
";
	var mouseListText = '';

	var bestLocationArray = new Array();

	for (var i=0; i<mouseArrayLength; i++) {
		var mouseName = mouseArray[i];
		if (mouseName.length == 0) return;
		mouseName = mouseName.capitalise();
		mouseName = mouseName.trim();
		var indexOfMouse = mouseName.indexOf(" Mouse");
		if (indexOfMouse >= 0) {
			mouseName = mouseName.slice(0,indexOfMouse);
		}

		if (popArray[mouseName] == undefined) { //Mouse name not recognised
			interpretedAsText += "
" + mouseName+"
";
			mouseListText += "
" + mouseName + "
";
		} else {

			var mouseLocationCheese = new Array();

			mouseListText += "
" + mouseName + "	";

			var mouseLocation = Object.keys(popArray[mouseName]);
			var noLocations = Object.size(popArray[mouseName]); //console.log(noLocations);
			var mouseListTextRow2 = '
	';

			for (var j=0; j<noLocations; j++) {
				var locationName = mouseLocation[j];

				var mousePhase = Object.keys(popArray[mouseName][locationName]);
				var noPhases = Object.size(popArray[mouseName][locationName]);

				for (var k=0; k<noPhases; k++) {
					var phaseName = mousePhase[k];

					var mouseCheese = Object.keys(popArray[mouseName][locationName][phaseName]);
					var noCheeses = Object.size(popArray[mouseName][locationName][phaseName]);

					for (var l=0; l<noCheeses; l++) {
						var cheeseName = mouseCheese[l];

						var mouseCharm = Object.keys(popArray[mouseName][locationName][phaseName][cheeseName]);
						var noCharms = Object.size(popArray[mouseName][locationName][phaseName][cheeseName]);

						for (var m=0; m<noCharms; m++) {
							var charmName = mouseCharm[m]

							var locationPhaseCheeseCharm = locationName;

							var URLString = 'best_setup.html?';
							//Replace apostrophes with %27
							URLString+= "location="+locationName;

							if (phaseName != "-") locationPhaseCheeseCharm += " (" + phaseName + ")";
							if (cheeseName.indexOf("/") < 0) locationPhaseCheeseCharm += " " + cheeseName;
							if (charmName != "-") locationPhaseCheeseCharm += " " + charmName;

							var attractionRate = parseFloat(popArray[mouseName][locationName][phaseName][cheeseName][charmName]);

							if (bestLocationArray[locationPhaseCheeseCharm] == undefined) {
								bestLocationArray[locationPhaseCheeseCharm] = attractionRate;

							} else {
								bestLocationArray[locationPhaseCheeseCharm] += attractionRate;
							}

							mouseLocationCheese[locationPhaseCheeseCharm] = attractionRate;

						}
					}
				}
			}

			var sortedMLC = sortBestLocation (mouseLocationCheese); //console.log(sortedMLC);
			var sortedMLCLength = Object.size(sortedMLC);

			for (var l=0; l<sortedMLCLength; l++) {
					mouseListText += "" + sortedMLC[l][0] + "	";// console.log(l);
					mouseListTextRow2 += "" + sortedMLC[l][1] + "	";

			}

			mouseListText += "
";
			mouseListTextRow2 += "
";
			mouseListText += mouseListTextRow2;
		}
	}

	interpretedAs.innerHTML = interpretedAsText;
	mouseList.innerHTML = mouseListText;

	var sortedLocation = sortBestLocation (bestLocationArray);
	printBestLocation(sortedLocation);
}

function sortBestLocation (bestLocationArray) {

	var sortedLocation = new Array();

	var bLALength = Object.size(bestLocationArray);
	var bLAKeys = Object.keys(bestLocationArray);

	for (var i=0; i<bLALength; i++) {
		var locationCheese = bLAKeys[i];
		//sortedLocation[bestLocationArray[locationCheese]] = locationCheese;
		sortedLocation.push([locationCheese, bestLocationArray[locationCheese]])
	}

	sortedLocation.sort(function(a,b) {return b[1]-a[1]});

	return sortedLocation;
}

function printBestLocation (sortedLocation) {

	var bestLocation = document.getElementById("bestLocation");
	var bestLocationHTML = '';

	var sortedLocationLength = Object.size(sortedLocation);

	for (var i=0; i<sortedLocationLength; i++) {
		bestLocationHTML += "
" + sortedLocation[i][0] + "	" + sortedLocation[i][1].toFixed(2) + "
";
	}

	bestLocation.innerHTML = bestLocationHTML;

}<commit_msg>Fixed newlines affecting parsing and uncommented onchange event<commit_after>"use strict";

String.prototype.capitalise = function() {
    return this.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};

function CSVToArray(strData, strDelimiter) {
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = ",";

    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(
    (
    // Delimiters.
    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

    // Quoted fields.
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

    // Standard fields.
    "([^\"\\" + strDelimiter + "\\r\\n]*))"),
        "gi");

    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [
        []
    ];

    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;

    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec(strData)) {

        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[1];

        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (
            strMatchedDelimiter.length &&
            (strMatchedDelimiter != strDelimiter)) {

            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push([]);

        }

        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[2]) {

            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[2].replace(
                new RegExp("\"\"", "g"),
                "\"");

        } else {

            // We found a non-quoted value.
            var strMatchedValue = arrMatches[3];

        }

        // Now that we have our value string, let's add
        // it to the data array.
        arrData[arrData.length - 1].push(strMatchedValue);
    }

    // Return the parsed data.
    return (arrData);
}

Object.size = function(obj) {
    var size = 0;
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

var pop = new XMLHttpRequest();
pop.open("get", "http://tsitu.github.io/MH-Tools/data/populations2.csv", true);
pop.onreadystatechange = function() {
	if (pop.readyState == 4) {
		processPop();
	}
}
pop.send();

var popCSV = new Array();
var popArray = new Array();
function processPop() {
	var popText = pop.responseText;

	popCSV = CSVToArray(popText);
	//console.log(popCSV);
	var popCSVLength = Object.size(popCSV);
	//console.log(popCSVLength);

	//Creating popArray
	for(var i=1; i<popCSVLength; i++) {
		var row = popCSV[i];
		var location = row[0];
		var phase = row[1];
		var cheese = row[2];
		var charm = row[3];
		var mouseName = row[4];
		mouseName = mouseName.capitalise();
		var population = row[5];

		if (popArray[mouseName] == undefined) popArray[mouseName] = new Array(); //If mouse doesn't exist in array
		if (popArray[mouseName][location] == undefined) popArray[mouseName][location] = new Array();
		if (popArray[mouseName][location][phase] == undefined) popArray[mouseName][location][phase] = new Array();
		if (popArray[mouseName][location][phase][cheese] == undefined) popArray[mouseName][location][phase][cheese] = new Array();
		popArray[mouseName][location][phase][cheese][charm] = population;
	}

	loadMouseDropdown();
}

function loadMouseDropdown() {
	var popArrayLength = Object.size(popArray);
	var suggests = [];

	for (var i=0; i<popArrayLength; i++) {
		suggests.push(Object.keys(popArray)[i]);
		suggests.push(Object.keys(popArray)[i].toLowerCase());
	}

	$("#map").asuggest(suggests);

}

window.onload = function () {
	document.getElementById("map").onchange = function () {
    	var mapText = document.getElementById("map").value;
	    //console.log(mapText);
	    processMap(mapText);
	};

	document.getElementById("map").onkeyup = function () {
    	var mapText = document.getElementById("map").value;
	    //console.log(mapText);
	    processMap(mapText);
	};
}

function processMap(mapText) {
	var mouseArray = mapText.split("\n");
	var mouseArrayLength = Object.size(mouseArray);

	var interpretedAs = document.getElementById("interpretedAs");
	var mouseList = document.getElementById("mouseList");

	var interpretedAsText = "Rectify:
";
	var mouseListText = '';

	var bestLocationArray = new Array();

	for (var i=0; i<mouseArrayLength; i++) {
		var mouseName = mouseArray[i];
		if (mouseName.length == 0) continue;
		mouseName = mouseName.capitalise();
		mouseName = mouseName.trim();
		var indexOfMouse = mouseName.indexOf(" Mouse");
		if (indexOfMouse >= 0) {
			mouseName = mouseName.slice(0,indexOfMouse);
		}

		if (popArray[mouseName] == undefined) { //Mouse name not recognised
			interpretedAsText += "
" + mouseName+"
";
			mouseListText += "
" + mouseName + "
";
		} else {

			var mouseLocationCheese = new Array();

			mouseListText += "
" + mouseName + "	";

			var mouseLocation = Object.keys(popArray[mouseName]);
			var noLocations = Object.size(popArray[mouseName]); //console.log(noLocations);
			var mouseListTextRow2 = '
	';

			for (var j=0; j<noLocations; j++) {
				var locationName = mouseLocation[j];

				var mousePhase = Object.keys(popArray[mouseName][locationName]);
				var noPhases = Object.size(popArray[mouseName][locationName]);

				for (var k=0; k<noPhases; k++) {
					var phaseName = mousePhase[k];

					var mouseCheese = Object.keys(popArray[mouseName][locationName][phaseName]);
					var noCheeses = Object.size(popArray[mouseName][locationName][phaseName]);

					for (var l=0; l<noCheeses; l++) {
						var cheeseName = mouseCheese[l];

						var mouseCharm = Object.keys(popArray[mouseName][locationName][phaseName][cheeseName]);
						var noCharms = Object.size(popArray[mouseName][locationName][phaseName][cheeseName]);

						for (var m=0; m<noCharms; m++) {
							var charmName = mouseCharm[m]

							var locationPhaseCheeseCharm = locationName;

							var URLString = 'best_setup.html?';
							//Replace apostrophes with %27
							URLString+= "location="+locationName;

							if (phaseName != "-") locationPhaseCheeseCharm += " (" + phaseName + ")";
							if (cheeseName.indexOf("/") < 0) locationPhaseCheeseCharm += " " + cheeseName;
							if (charmName != "-") locationPhaseCheeseCharm += " " + charmName;

							var attractionRate = parseFloat(popArray[mouseName][locationName][phaseName][cheeseName][charmName]);

							if (bestLocationArray[locationPhaseCheeseCharm] == undefined) {
								bestLocationArray[locationPhaseCheeseCharm] = attractionRate;

							} else {
								bestLocationArray[locationPhaseCheeseCharm] += attractionRate;
							}

							mouseLocationCheese[locationPhaseCheeseCharm] = attractionRate;

						}
					}
				}
			}

			var sortedMLC = sortBestLocation (mouseLocationCheese); //console.log(sortedMLC);
			var sortedMLCLength = Object.size(sortedMLC);

			for (var l=0; l<sortedMLCLength; l++) {
					mouseListText += "" + sortedMLC[l][0] + "	";// console.log(l);
					mouseListTextRow2 += "" + sortedMLC[l][1] + "	";

			}

			mouseListText += "
";
			mouseListTextRow2 += "
";
			mouseListText += mouseListTextRow2;
		}
	}

	interpretedAs.innerHTML = interpretedAsText;
	mouseList.innerHTML = mouseListText;

	var sortedLocation = sortBestLocation (bestLocationArray);
	printBestLocation(sortedLocation);
}

function sortBestLocation (bestLocationArray) {

	var sortedLocation = new Array();

	var bLALength = Object.size(bestLocationArray);
	var bLAKeys = Object.keys(bestLocationArray);

	for (var i=0; i<bLALength; i++) {
		var locationCheese = bLAKeys[i];
		//sortedLocation[bestLocationArray[locationCheese]] = locationCheese;
		sortedLocation.push([locationCheese, bestLocationArray[locationCheese]])
	}

	sortedLocation.sort(function(a,b) {return b[1]-a[1]});

	return sortedLocation;
}

function printBestLocation (sortedLocation) {

	var bestLocation = document.getElementById("bestLocation");
	var bestLocationHTML = '';

	var sortedLocationLength = Object.size(sortedLocation);

	for (var i=0; i<sortedLocationLength; i++) {
		bestLocationHTML += "
" + sortedLocation[i][0] + "	" + sortedLocation[i][1].toFixed(2) + "
";
	}

	bestLocation.innerHTML = bestLocationHTML;

}<|endoftext|>


<commit_before>var nColumns = 4;
var bot1score=9999;
var bot2score=9999;
var gameNumber = 1;
var curBot=0;
var startTimeMillis;
var timerIsRunning;
var lastElapsedTime;
var hiddenAnswer = [1,2,3,4];       // what the user is trying to guess
var guessTr = null;        // null => is no "Guess" row; game is not running.
var lastGuess = [];        // what the user thinks is the answer.
var oldGuesses = [];       // guessTr row history displayed on screen
var messageTd;             //  block that holds user messages.
var boardTable;            // table that holds guesses and buttons
var blackLineTr;           // table row after guessTr
colorImages  = ['Image/redball.gif',    'Image/blueball.gif',    'Image/brownball.gif',
                'Image/greenball.gif',  'Image/yellowball.gif',  'Image/pinkball.gif' ];

// --------------------------------------------------------
// called when user clicks "New Game".
function newGame(){
	ans();
    resetGame();
    gameNumber++;
    runTimer();
}

// --------------------------------------------------------
// return a string like "01:22" giving min, since game began.
function elapsedTimeAsString(){
    var d = new Date();
    var diff = d.getTime() - startTimeMillis;
    var h = Math.floor( diff/3600000 );
    var m = Math.floor( diff/60000 ) % 60;
    var s = Math.floor( diff/1000. ) % 60;
    if (h==0) {h="";} else {h=h+":";}
    if (m<10) {m="0"+m;}
    if (s<10) {s="0"+s;}
    return ""+h+m+":"+s;
}

// --------------------------------------------------------
// display a message where the user can see it.
function showMessage(aString){
    messageTd.innerHTML = aString;
}

// --------------------------------------------------------
// Confirm that the user wants to quit the game, and if so
// show the hidden answer.
function showAnswer(){
    if ( guessTr == null ){
        alert("The game is stopped and the answer is visible.\n" +
              "Click the 'New Game' link to start another.");
        return;
    }
    if (confirm("Would you like to quit this game\n and see the answer?")){
        for (var c=0; c<nColumns; c++){
            getColumnNImage(c).src = colorImages[hiddenAnswer[c]];
        }
        guessTr.childNodes[2*nColumns-1].innerHTML = "Answer";
        oldGuesses.push(guessTr);
        guessTr = null;
        timerIsRunning = false;
        showMessage("The game is over.");
    }
}

// --------------------------------------------------------
// Tell the user what the rules are.
function showHelp(i){

		resetGame();
		curBot=i;

    	var x = document.getElementById("myTextarea" +i).value;
		x = x.trim();
		var n = x.indexOf("function");

		if(n==0){
		 x = x.replace("function","");
		 x = x.replace("bot()","");
		 x = x.trim();
		 x= x.slice(1,x.length-1);
		 }

		 //alert(x);

		//eval(x);
		var tmpFunc = new Function(x);

		tmpFunc();

}

// --------------------------------------------------------
// Sets up the globals and start game. Called from
function init(){
    boardTable  = document.getElementById('boardTable');
    blackLineTr = document.getElementById('blackLineTr');
    messageTd   = document.getElementById('messageTd');
    document.getElementById('blackHorizontalTd').setAttribute('colspan',
                                                              2*nColumns);
    resetGame();

    // --- initial annwer display ---
    // var notice = "Answer is ";
    // for (var c=0; c<nColumns; c++){
    //   notice += hiddenAnswer[c] + " ";
    // }
    // alert(notice);
}

// --------------------------------------------------------
// return a random integer r, where 0<= r <= (n-1)
function getRandom(n){
    return Math.floor( n * Math.random() );
}

// --------------------------------------------------------
// clear all old guesses, reset timer, start timer.
function resetGame(){
showMessage("");
    while (oldGuesses.length>0){
        boardTable.deleteRow( oldGuesses.pop().rowIndex );
    }
    for (var column=0; column<nColumns; column++){
        lastGuess[column] = -1;
       // hiddenAnswer[column] = getRandom( colorImages.length );
		//hiddenAnswer[column]= 3;

        //
    }

    //0-6

    timerIsRunning = true;
    var d = new Date();
    startTimeMillis = d.getTime();
    createOrClearGuessTr();
}

function ans(){

hiddenAnswer[0] = getRandom( 6 );
hiddenAnswer[1] = getRandom( 6 );
hiddenAnswer[2] = getRandom( 6 );
hiddenAnswer[3] = getRandom( 6 );
resetGame();
}

// --------------------------------------------------------
// This is called within a document.write() command from
// the .html page when it first loads.
// It returns the ...	 HTML for an array of
// button images that the user can click on to specify his guess.
// Clicking on a button will call click(column,color), where
//  column = (0,1,2,..,nColumns-1) ,
//  color = (0,...,colorImages.length-1)
function getButtonArrayHTML(){
    var result = "";

    return result;
}

// --------------------------------------------------------
// If the row where the user submits his guess isn't available, create it.
// If it is there, initialize it.
//   This function is the one that seems to have the biggest problems
//   on various different browsers, particularly the issue of how to add
//   rows to a table.  Here's how this one works, following (mostly)
//   the DOM spec (except for innerHTML, which I only call on tableData).
//      * foo document.createElement('foo')        # to make TD's, TR's, etc.
//      * tableData.innerHTML = ...                # to add images, links
//      * tableRow.appendChild(tableData)          # put data in row
//      * tbody = boardTable.getElementsByTagName('tbody')[0];   # get tbody
//      * tbody.insertAfter(tableRow,otherRow)     # put row in table
//   (whew!)
function createOrClearGuessTr(){
    if (guessTr != null){
        for (var c=0; c<nColumns; c++){
            // images are at indeces 0,2,4,...
            guessTr.childNodes[2*c].childNodes[0].src = 'Image/whitepixel.gif';
        }
        return;
    }
    guessTr = document.createElement('tr');
    var td;
    for (var column=0; column<nColumns; column++){
        td = document.createElement('td');
        td.innerHTML="";
        guessTr.appendChild(td);
        if (column<nColumns-1){
            td = document.createElement('td');
            td.innerHTML="";
            guessTr.appendChild(td);
        }
    }
    td = document.createElement('td');

    td.align = "right";
    guessTr.appendChild(td);
    var tbody = boardTable.getElementsByTagName('tbody')[0];
    tbody.insertBefore(guessTr, blackLineTr);
}

// --------------------------------------------------------
// One of the image buttons was clicked; change the corresponding picture.
function click(column,color){
    if ( guessTr == null ){
        alert("The game is stopped; you can't make guesses now.\n" +
              "Click 'New Game' to start another.");
        return;
    }
    getColumnNImage(column).src = colorImages[color];
    lastGuess[column] = color;
}

// --------------------------------------------------------
// Return the image corresponding to the N'th column of the puzzle from guessTr
function getColumnNImage(column){
    return guessTr.childNodes[2*column].childNodes[0];
}

// --------------------------------------------------------
// Show the user the hints by replacing the "Guess" link with
// the given number of black and grey images.
function drawAndPopGuessResult(black, grey){
    guessTd = guessTr.childNodes[2*nColumns-1];
    var htmlResult = "";
    for (var i=0; i<black; i++){
        htmlResult += "" +
            "";
    }
    for (var i=0; i<grey; i++){
        htmlResult += "" +
            "";
    }
    htmlResult += ""+(oldGuesses.length+1);
    guessTd.innerHTML = htmlResult;
    oldGuesses.push(guessTr);
    guessTr = null;
}

// --------------------------------------------------------
// return true if one of the columns where the user gueses colors is empty
function isAColumnEmpty(){
    for (var c=0; c<nColumns; c++){
        if ( lastGuess[c]<0 ){
            alert(" Please pick a color for each column\n" +
                  " by clicking on the small circles\n" +
                  " before submitting your guess.");
            return true;
        }
    }
    return false;
}

// --------------------------------------------------------
// The user clicked 'Guess'; time to count how many black and grey
// hints should be displayed.
// Each correct color in correct column gives a black marker.
// Each correct color in wrong column gives a grey marker.
// No guess or answer can match more than one marker.
function checkGuess(){
    if (isAColumnEmpty()) {return;}
    var guessCopy  = [];
    var answerCopy = [] ;
    var nBlack = 0;
    var nGrey  = 0;
    // Make copies of the guesses and answers;
    // it's easiest to do this counting by erasing ones we've counted.
    for (var c=0; c<nColumns; c++){
        guessCopy[c]  = lastGuess[c];
        answerCopy[c] = hiddenAnswer[c];
    }
    // count number of black markers.
    for (var c=0; c<nColumns; c++){
        if ( answerCopy[c] == guessCopy[c] ){
            nBlack++;
            answerCopy[c] = -10;  // don't match this again
            guessCopy[c] = -11;   // or this again.
        }
    }
    // count number of grey markers
    for (var ca=0; ca<nColumns; ca++){
        for (var cg=0; cg<nColumns; cg++){
            if ( answerCopy[ca] == guessCopy[cg] ){
                nGrey++;
                answerCopy[ca] = -10;  // don't match this again
                guessCopy[cg] = -11;   // or this again.
            }
        }
    }
    drawAndPopGuessResult(nBlack, nGrey);
    for (var c=0; c<nColumns; c++){
        lastGuess[c] = -1;
    }
    if (nBlack == nColumns){         // was this guess correct?
        showMessage("Correct.
" +
                    "Number of guesses = "+ oldGuesses.length + "
"  );

					if(curBot ==1){
					bot1score = oldGuesses.length;
					}
					else{
					bot2score = oldGuesses.length;
					}

    }
    else {
        createOrClearGuessTr();
		return [nBlack, nGrey];
    }

}

function beat()
 {
  //alert('Bot 1 competed!!');
  //showHelp(1);

  //showHelp(2);

  b1();
  b2();
  //setTimeout(showHelp(2), 10000000000);

}

function pausecomp(millis)
 {
  var date = new Date();
  var curDate = null;
  do { curDate = new Date(); }
  while(curDate-date < millis);
}

function showRes(){
	winner = "";
	if (bot1score>bot2score){
		result = "Bot2 win";
		winner = "bot2";
	}
	if (bot1score==bot2score){
		result = "Draw";
		winner = "none"
	}
	if (bot1score<bot2score){
		result = "Bot1 win";
		winner = "bot1";
	}
	alert("Bot 1 steps " + bot1score + ", Bot 2 steps " + bot2score + ", " + result );
	return winner;
}

function bot1(){
	for(var i1 = 0; i1 < 6; i1++){
		  for(var i2 = 0; i2 < 6; i2++){

			  for(var i3 = 0; i3 < 6; i3++){

				  for(var i4 = 0; i4 < 6; i4++){
					  aguess(i1,i2,i3,i4);
				  }
			  }
		  }
		}

}

function bot2(){
				for(var i1 = 0; i1 < 6; i1++){
					dance:
					  for(var i2 = 0; i2 < 6; i2++){

						  for(var i3 = 0; i3 < 6; i3++){

							  for(var i4 = 0; i4 < 6; i4++){
								 rel= aguess(i1,i2,i3,i4);
								  if(rel[0] == 0 && rel[1]==0)
									break dance;

							  }
						  }
					  }
					}

}

function bot3(){

					var arr1=new Array();
					index =0;
					 for(var j = 0; j < 6; j++){

						  rel= aguess(j,j,j,j);
						  if(rel[0] + rel[1]==1){
							arr1[index] =j;
							index++;
						  }
						  else if (rel[0] + rel[1]==2){
							arr1[index] =j;
							index++;
							arr1[index] =j;
							index++;
						  }
						  else if (rel[0] + rel[1]==3){
							arr1[index] =j;
							index++;
							arr1[index] =j;
							index++;
							arr1[index] =j;
							index++;
						  }
						  else if (rel[0] + rel[1]==4){
							arr1[index] =j;
							index++;
							arr1[index] =j;
							index++;
							arr1[index] =j;
							index++;
							arr1[index] =j;
							index++;
						  }
						  else{}

						}

						aguess(arr1[0],arr1[1],arr1[2],arr1[3]);
						aguess(arr1[0],arr1[1],arr1[3],arr1[2]);
						aguess(arr1[0],arr1[2],arr1[1],arr1[3]);
						aguess(arr1[0],arr1[2],arr1[3],arr1[1]);
						aguess(arr1[0],arr1[3],arr1[1],arr1[2]);
						aguess(arr1[0],arr1[3],arr1[2],arr1[1]);
						aguess(arr1[1],arr1[0],arr1[2],arr1[3]);
						aguess(arr1[1],arr1[0],arr1[3],arr1[2]);
						aguess(arr1[1],arr1[2],arr1[0],arr1[3]);
						aguess(arr1[1],arr1[2],arr1[3],arr1[0]);
						aguess(arr1[1],arr1[3],arr1[0],arr1[2]);
						aguess(arr1[1],arr1[3],arr1[2],arr1[0]);
						aguess(arr1[2],arr1[0],arr1[2],arr1[3]);
						aguess(arr1[2],arr1[0],arr1[3],arr1[1]);
						aguess(arr1[2],arr1[1],arr1[0],arr1[3]);
						aguess(arr1[2],arr1[1],arr1[3],arr1[0]);
						aguess(arr1[2],arr1[3],arr1[0],arr1[1]);
						aguess(arr1[2],arr1[3],arr1[1],arr1[0]);
						aguess(arr1[3],arr1[0],arr1[2],arr1[1]);
						aguess(arr1[3],arr1[0],arr1[1],arr1[2]);
						aguess(arr1[3],arr1[1],arr1[0],arr1[2]);
						aguess(arr1[3],arr1[1],arr1[2],arr1[0]);
						aguess(arr1[3],arr1[2],arr1[0],arr1[1]);
						aguess(arr1[3],arr1[2],arr1[1],arr1[0]);

}

function aguess(i1,i2,i3,i4){
					lastGuess[0]=i1;
							  lastGuess[1]=i2;
							  lastGuess[2]=i3;
							  lastGuess[3]=i4;
							  getColumnNImage(0).src = colorImages[lastGuess[0]];
							  getColumnNImage(1).src = colorImages[lastGuess[1]];
							  getColumnNImage(2).src = colorImages[lastGuess[2]];
							  getColumnNImage(3).src = colorImages[lastGuess[3]];
							rel = checkGuess();
							return rel;
}<commit_msg>deploy38<commit_after>var nColumns = 4;
var bot1score=9999;
var bot2score=9999;
var gameNumber = 1;
var curBot=0;
var startTimeMillis;
var timerIsRunning;
var lastElapsedTime;
var hiddenAnswer = [1,2,3,4];       // what the user is trying to guess
var guessTr = null;        // null => is no "Guess" row; game is not running.
var lastGuess = [];        // what the user thinks is the answer.
var oldGuesses = [];       // guessTr row history displayed on screen
var messageTd;             //  block that holds user messages.
var boardTable;            // table that holds guesses and buttons
var blackLineTr;           // table row after guessTr
colorImages  = ['Image/redball.gif',    'Image/blueball.gif',    'Image/brownball.gif',
                'Image/greenball.gif',  'Image/yellowball.gif',  'Image/pinkball.gif' ];

// --------------------------------------------------------
// called when user clicks "New Game".
function newGame(){
	ans();
    resetGame();
    gameNumber++;
    runTimer();
}

// --------------------------------------------------------
// return a string like "01:22" giving min, since game began.
function elapsedTimeAsString(){
    var d = new Date();
    var diff = d.getTime() - startTimeMillis;
    var h = Math.floor( diff/3600000 );
    var m = Math.floor( diff/60000 ) % 60;
    var s = Math.floor( diff/1000. ) % 60;
    if (h==0) {h="";} else {h=h+":";}
    if (m<10) {m="0"+m;}
    if (s<10) {s="0"+s;}
    return ""+h+m+":"+s;
}

// --------------------------------------------------------
// display a message where the user can see it.
function showMessage(aString){
    messageTd.innerHTML = aString;
}

// --------------------------------------------------------
// Confirm that the user wants to quit the game, and if so
// show the hidden answer.
function showAnswer(){
    if ( guessTr == null ){
        alert("The game is stopped and the answer is visible.\n" +
              "Click the 'New Game' link to start another.");
        return;
    }
    if (confirm("Would you like to quit this game\n and see the answer?")){
        for (var c=0; c<nColumns; c++){
            getColumnNImage(c).src = colorImages[hiddenAnswer[c]];
        }
        guessTr.childNodes[2*nColumns-1].innerHTML = "Answer";
        oldGuesses.push(guessTr);
        guessTr = null;
        timerIsRunning = false;
        showMessage("The game is over.");
    }
}

// --------------------------------------------------------
// Tell the user what the rules are.
function showHelp(i){

		resetGame();
		curBot=i;

    	var x = document.getElementById("myTextarea" +i).value;
		x = x.trim();
		var n = x.indexOf("function");

		if(n==0){
		 x = x.replace("function","");
		 x = x.replace("bot()","");
		 x = x.trim();
		 x= x.slice(1,x.length-1);
		 }

		 //alert(x);

		//eval(x);
		var tmpFunc = new Function(x);

		tmpFunc();

}

// --------------------------------------------------------
// Sets up the globals and start game. Called from
function init(){
    boardTable  = document.getElementById('boardTable');
    blackLineTr = document.getElementById('blackLineTr');
    messageTd   = document.getElementById('messageTd');
    document.getElementById('blackHorizontalTd').setAttribute('colspan',
                                                              2*nColumns);
    resetGame();

    // --- initial annwer display ---
    // var notice = "Answer is ";
    // for (var c=0; c<nColumns; c++){
    //   notice += hiddenAnswer[c] + " ";
    // }
    // alert(notice);
}

// --------------------------------------------------------
// return a random integer r, where 0<= r <= (n-1)
function getRandom(n){
    return Math.floor( n * Math.random() );
}

// --------------------------------------------------------
// clear all old guesses, reset timer, start timer.
function resetGame(){
showMessage("");
    while (oldGuesses.length>0){
        boardTable.deleteRow( oldGuesses.pop().rowIndex );
    }
    for (var column=0; column<nColumns; column++){
        lastGuess[column] = -1;
       // hiddenAnswer[column] = getRandom( colorImages.length );
		//hiddenAnswer[column]= 3;

        //
    }

    //0-6

    timerIsRunning = true;
    var d = new Date();
    startTimeMillis = d.getTime();
    createOrClearGuessTr();
}

function ans(){

hiddenAnswer[0] = getRandom( 6 );
hiddenAnswer[1] = getRandom( 6 );
hiddenAnswer[2] = getRandom( 6 );
hiddenAnswer[3] = getRandom( 6 );
resetGame();
}

// --------------------------------------------------------
// This is called within a document.write() command from
// the .html page when it first loads.
// It returns the ...	 HTML for an array of
// button images that the user can click on to specify his guess.
// Clicking on a button will call click(column,color), where
//  column = (0,1,2,..,nColumns-1) ,
//  color = (0,...,colorImages.length-1)
function getButtonArrayHTML(){
    var result = "";

    return result;
}

// --------------------------------------------------------
// If the row where the user submits his guess isn't available, create it.
// If it is there, initialize it.
//   This function is the one that seems to have the biggest problems
//   on various different browsers, particularly the issue of how to add
//   rows to a table.  Here's how this one works, following (mostly)
//   the DOM spec (except for innerHTML, which I only call on tableData).
//      * foo document.createElement('foo')        # to make TD's, TR's, etc.
//      * tableData.innerHTML = ...                # to add images, links
//      * tableRow.appendChild(tableData)          # put data in row
//      * tbody = boardTable.getElementsByTagName('tbody')[0];   # get tbody
//      * tbody.insertAfter(tableRow,otherRow)     # put row in table
//   (whew!)
function createOrClearGuessTr(){
    if (guessTr != null){
        for (var c=0; c<nColumns; c++){
            // images are at indeces 0,2,4,...
            guessTr.childNodes[2*c].childNodes[0].src = 'Image/whitepixel.gif';
        }
        return;
    }
    guessTr = document.createElement('tr');
    var td;
    for (var column=0; column<nColumns; column++){
        td = document.createElement('td');
        td.innerHTML="";
        guessTr.appendChild(td);
        if (column<nColumns-1){
            td = document.createElement('td');
            td.innerHTML="";
            guessTr.appendChild(td);
        }
    }
    td = document.createElement('td');

    td.align = "right";
    guessTr.appendChild(td);
    var tbody = boardTable.getElementsByTagName('tbody')[0];
    tbody.insertBefore(guessTr, blackLineTr);
}

// --------------------------------------------------------
// One of the image buttons was clicked; change the corresponding picture.
function click(column,color){
    if ( guessTr == null ){
        alert("The game is stopped; you can't make guesses now.\n" +
              "Click 'New Game' to start another.");
        return;
    }
    getColumnNImage(column).src = colorImages[color];
    lastGuess[column] = color;
}

// --------------------------------------------------------
// Return the image corresponding to the N'th column of the puzzle from guessTr
function getColumnNImage(column){
    return guessTr.childNodes[2*column].childNodes[0];
}

// --------------------------------------------------------
// Show the user the hints by replacing the "Guess" link with
// the given number of black and grey images.
function drawAndPopGuessResult(black, grey){
    guessTd = guessTr.childNodes[2*nColumns-1];
    var htmlResult = "";
    for (var i=0; i<black; i++){
        htmlResult += "" +
            "";
    }
    for (var i=0; i<grey; i++){
        htmlResult += "" +
            "";
    }
    htmlResult += ""+(oldGuesses.length+1);
    guessTd.innerHTML = htmlResult;
    oldGuesses.push(guessTr);
    guessTr = null;
}

// --------------------------------------------------------
// return true if one of the columns where the user gueses colors is empty
function isAColumnEmpty(){
    for (var c=0; c<nColumns; c++){
        if ( lastGuess[c]<0 ){
            alert(" Please pick a color for each column\n" +
                  " by clicking on the small circles\n" +
                  " before submitting your guess.");
            return true;
        }
    }
    return false;
}

// --------------------------------------------------------
// The user clicked 'Guess'; time to count how many black and grey
// hints should be displayed.
// Each correct color in correct column gives a black marker.
// Each correct color in wrong column gives a grey marker.
// No guess or answer can match more than one marker.
function checkGuess(){
    if (isAColumnEmpty()) {return;}
    var guessCopy  = [];
    var answerCopy = [] ;
    var nBlack = 0;
    var nGrey  = 0;
    // Make copies of the guesses and answers;
    // it's easiest to do this counting by erasing ones we've counted.
    for (var c=0; c<nColumns; c++){
        guessCopy[c]  = lastGuess[c];
        answerCopy[c] = hiddenAnswer[c];
    }
    // count number of black markers.
    for (var c=0; c<nColumns; c++){
        if ( answerCopy[c] == guessCopy[c] ){
            nBlack++;
            answerCopy[c] = -10;  // don't match this again
            guessCopy[c] = -11;   // or this again.
        }
    }
    // count number of grey markers
    for (var ca=0; ca<nColumns; ca++){
        for (var cg=0; cg<nColumns; cg++){
            if ( answerCopy[ca] == guessCopy[cg] ){
                nGrey++;
                answerCopy[ca] = -10;  // don't match this again
                guessCopy[cg] = -11;   // or this again.
            }
        }
    }
    drawAndPopGuessResult(nBlack, nGrey);
    for (var c=0; c<nColumns; c++){
        lastGuess[c] = -1;
    }
    if (nBlack == nColumns){         // was this guess correct?
        showMessage("Correct.
" +
                    "Number of guesses = "+ oldGuesses.length + "
"  );

					if(curBot ==1){
					bot1score = oldGuesses.length;
					}
					else{
					bot2score = oldGuesses.length;
					}

    }
    else {
        createOrClearGuessTr();
		return [nBlack, nGrey];
    }

}

function beat()
 {
  //alert('Bot 1 competed!!');
  //showHelp(1);

  //showHelp(2);

  b1();
  b2();
  //setTimeout(showHelp(2), 10000000000);

}

function pausecomp(millis)
 {
  var date = new Date();
  var curDate = null;
  do { curDate = new Date(); }
  while(curDate-date < millis);
}

function showRes(){
	winner = "";
	if (bot1score>bot2score){
		result = "Bot2 win";
		winner = "bot2";
	}
	if (bot1score==bot2score){
		result = "Draw";
		winner = "none"
	}
	if (bot1score<bot2score){
		result = "Bot1 win";
		winner = "bot1";
	}
	alert("Bot 1 steps " + bot1score + ", Bot 2 steps " + bot2score + ", " + result );
	return winner;
}

function aguess(i1,i2,i3,i4){
					lastGuess[0]=i1;
							  lastGuess[1]=i2;
							  lastGuess[2]=i3;
							  lastGuess[3]=i4;
							  getColumnNImage(0).src = colorImages[lastGuess[0]];
							  getColumnNImage(1).src = colorImages[lastGuess[1]];
							  getColumnNImage(2).src = colorImages[lastGuess[2]];
							  getColumnNImage(3).src = colorImages[lastGuess[3]];
							rel = checkGuess();
							return rel;
}<|endoftext|>


<commit_before>function Population(size) {
	this.agents = new Array(size);
	for (i = 0; i < size; i++) {
		var prob = Math.random();
		if (prob < 0.33) {
			this.agents[i] = new Agent(new Genome(1,0,0)); // 1/3rd has pure random strategy
		}
		else if (prob >= 0.33 && prob < 0.67) {
			this.agents[i] = new Agent(new Genome(0,1,0)); // 1/3rd has pure greedy strategy
		}
		else this.agents[i] = new Agent(new Genome(0,0,1)); // 1/3rd has pure human strategy
	}
	this.size = size; // amount of agents
}

// DECLARATIONS
// "T" for tournament, "R" for roulette wheel
var parentmethod = "T";
// choose tournament_size individuals from the population
var t_size = 10;
// t_prob is probability of picking best from tournament, or second best, etc.
var t_prob = 0.25;
var c_prob = 0.1; //chance for cross-over

/** Two algorithms for parent selection, either tournament or roulette wheel,
depends on parentmethod.
*/
Population.prototype.parentselection = function() {
	var parents = new Array(this.size);
	// TOURNAMENT SELECTION
	if (parentmethod == "T") {
		for (p = 0; p < this.size; p++) {
				// Choose t_size individuals from population at random
				var selection = new Array(t_size);
				for (i = 0; i < t_size; i ++) {
					selection[i] = this.agents[Math.round(Math.random() * this.size)];
					//console.log(selection[i])
				}
				// picking the winner is dependent of t_size
				// if t_size changes, then there are more options to pick
				// not only best, second best and third best
				pick_prob = Math.random();
				var total = 1;
				for (i = 0; i < t_size; i++) {
					// probability of choosing ith best individual
					if (pick_prob >= (total-this.t_winner(i))) {
						//choose ith best individual
						parents[p] = selection[this.getWinner(selection,i)];
						break;
					}
					// for (i+1)th best individual, prob needs be between
					// ith best and ith+(i+1)th best
					else total = total-this.t_winner(i);
				}
		}
	}
	// ROULETTE WHEEL SELECTION
	else if (parentmethod == "R") {
		var total_fitness = 0;
		var proportional_fitness = new Array(this.size);
		// calculate accumulative fitness
		for (i = 0; i < this.size; i++) {
			total_fitness = total_fitness + this.agents[i].fitness;
			//console.log(this.agents[i].fitness);
		}
		// for each agent, calculate the proportion of total fitness
		for (i = 0; i < this.size; i++) {
			if (i == 0) {
				proportional_fitness[i] = this.agents[i].fitness/total_fitness;
			}
			// each proportion has its own unique range, so add up from previous
			else proportional_fitness[i] = proportional_fitness[i-1] + this.agents[i].fitness/total_fitness;
		}
		// for each parent, pick random nr between 0-1 and see which proportion it is
		for (p = 0; p < this.size; p++) {
			pick_prob = Math.random();
			for (q = 0; q < this.size; q++) {
				// if it's smaller, then it's in range of proportion
				//(the first one to comply breaks the for-loop)
				if (pick_prob < proportional_fitness[q]) {
					parents[p] = this.agents[q];
					break;
				}
			}
		}
	}
	// return parents selected
	return parents;
};

/* Calculates probability to select nth best parent:
Choose the best individual with prob p,
Second best p*(1-p), third best p*((1-p)^2)
*/
Population.prototype.t_winner = function (n) {
	return (t_prob * ((1-t_prob)^n));
};

/** Returns the parent with the highest fitness (or nth highest,
depending on var best)
*/
Population.prototype.getWinner = function(pool,best) {
	var original = pool;
	var orderfitness = new Array(t_size);
	for (j = 0; j < t_size; j++) {
		// Fast bug-fix, don't know if this the right solution.
		if (pool[j] != null) {
			orderfitness[j] = pool[j].fitness;
		}
		else {
			orderfitness[j] = 0;
		}
	}
	// sort fitness based on high first, low last
	orderfitness.sort(function(a, b){return b-a});
	for (k = 0; k < t_size; k++) {
		// compare which original agent had the nth best fitness
		// Quick bug-fix, don't know if it's the right thing to do.
		if (original[k] != null) {
			if (orderfitness[best] == original[k].fitness){
				// index of pool member with nth best fitness
				return k;
			}
		}
	}
	console.log("No corresponding agent to best fitness")
	return 0;
};

/** Cross-over function
Takes two parents and with probability c_prob slices their genes
and recombines them to make two children
*/
Population.prototype.crossover = function(mother, father) {
	var children = new Array(2);
	children[0] = mother; //first copy parents
	children[1] = father;
	var r,g,h,r2,g2,h2;
	var cross = Math.random();
	var cross2 = Math.random();
	//cross-over between all genes
	if (cross < this.c_prob && cross2 < this.c_prob) {
		 r = mother.Genome.random;
		 g = father.Genome.greedy;
		 h = mother.Genome.human;
		 r2 = father.Genome.random;
		 g2 = mother.Genome.greedy;
		 h2 = father.Genome.human;
	}
	//cross-over after first gene
	else if (cross < this.c_prob) {
		r = mother.Genome.random;
		g = father.Genome.greedy;
		h = father.Genome.human;
		r2 = father.Genome.random;
		g2 = mother.Genome.greedy;
		h2 = mother.Genome.human;
	}
	//cross-over after second gene
	else if (cross < this.c_prob2) {
		r = mother.Genome.random;
		g = mother.Genome.greedy;
		h = father.Genome.human;
		r2 = father.Genome.random;
		g2 = father.Genome.greedy;
		h2 = mother.Genome.human;
	}
	//no cross-over, children are same as parents
	else {
		return children[0], children[1];
	}
	//normalize so genome adds up to 1 again;
	norm = r + g + h;
	r = r/norm;
	g = g/norm;
	h = h/norm;
	norm2 = r2 + g2 + h2;
	r2 = r2/norm2;
	g2 = g2/norm2;
	h2 = h2/norm2;
	children[0].Genome.update(r,g,h);
	children[1].Genome.update(r2,g2,h2);
	return [children[0], children[1]];
};

/** This function replaces the agents in the population by the children
created through parent selection, cross-over and mutation
*/
Population.prototype.update = function() {
	console.log("Start updating..")
	//update entire population
	//first parent selection, then create new children
	var par = new Array(this.size);
	var children = new Array(this.size);
	console.log("Parent selection")
	par = this.parentselection();
	console.log("Crossover")
	for (i = 0; i < this.size; i+2) {
		//console.log("children = " + i + " and " + (i+1))
		var newChildren = this.crossover(par[i],par[i+1]);
		children[i]   = newChildren[0];
		children[i+1] = newChildren[1];
	}
	console.log("Mutation")
	for (i = 0; i < this.size; i++) {
		children[i].genome.mutation();
	}
	this.agents = children; //update population
	console.log("End updating..")
};
<commit_msg>Relocate mutation function to population.js<commit_after>function Population(size) {
	this.agents = new Array(size);
	for (i = 0; i < size; i++) {
		var prob = Math.random();
		if (prob < 0.33) {
			this.agents[i] = new Agent(new Genome(1,0,0)); // 1/3rd has pure random strategy
		}
		else if (prob >= 0.33 && prob < 0.67) {
			this.agents[i] = new Agent(new Genome(0,1,0)); // 1/3rd has pure greedy strategy
		}
		else this.agents[i] = new Agent(new Genome(0,0,1)); // 1/3rd has pure human strategy
	}
	this.size = size; // amount of agents
}

// DECLARATIONS
// "T" for tournament, "R" for roulette wheel
var parentmethod = "T";
// choose tournament_size individuals from the population
var t_size = 10;
// t_prob is probability of picking best from tournament, or second best, etc.
var t_prob = 0.25;
var c_prob = 0.1; //chance for cross-over
var mutation_prob = 0.25;
var mutation_amount = 0.05;

/** Two algorithms for parent selection, either tournament or roulette wheel,
depends on parentmethod.
*/
Population.prototype.parentselection = function() {
	var parents = new Array(this.size);
	// TOURNAMENT SELECTION
	if (parentmethod == "T") {
		for (p = 0; p < this.size; p++) {
				// Choose t_size individuals from population at random
				var selection = new Array(t_size);
				for (i = 0; i < t_size; i ++) {
					selection[i] = this.agents[Math.round(Math.random() * this.size)];
					//console.log(selection[i])
				}
				// picking the winner is dependent of t_size
				// if t_size changes, then there are more options to pick
				// not only best, second best and third best
				pick_prob = Math.random();
				var total = 1;
				for (i = 0; i < t_size; i++) {
					// probability of choosing ith best individual
					if (pick_prob >= (total-this.t_winner(i))) {
						//choose ith best individual
						parents[p] = selection[this.getWinner(selection,i)];
						break;
					}
					// for (i+1)th best individual, prob needs be between
					// ith best and ith+(i+1)th best
					else total = total-this.t_winner(i);
				}
		}
	}
	// ROULETTE WHEEL SELECTION
	else if (parentmethod == "R") {
		var total_fitness = 0;
		var proportional_fitness = new Array(this.size);
		// calculate accumulative fitness
		for (i = 0; i < this.size; i++) {
			total_fitness = total_fitness + this.agents[i].fitness;
			//console.log(this.agents[i].fitness);
		}
		// for each agent, calculate the proportion of total fitness
		for (i = 0; i < this.size; i++) {
			if (i == 0) {
				proportional_fitness[i] = this.agents[i].fitness/total_fitness;
			}
			// each proportion has its own unique range, so add up from previous
			else proportional_fitness[i] = proportional_fitness[i-1] + this.agents[i].fitness/total_fitness;
		}
		// for each parent, pick random nr between 0-1 and see which proportion it is
		for (p = 0; p < this.size; p++) {
			pick_prob = Math.random();
			for (q = 0; q < this.size; q++) {
				// if it's smaller, then it's in range of proportion
				//(the first one to comply breaks the for-loop)
				if (pick_prob < proportional_fitness[q]) {
					parents[p] = this.agents[q];
					break;
				}
			}
		}
	}
	// return parents selected
	return parents;
};

/* Calculates probability to select nth best parent:
Choose the best individual with prob p,
Second best p*(1-p), third best p*((1-p)^2)
*/
Population.prototype.t_winner = function (n) {
	return (t_prob * ((1-t_prob)^n));
};

/** Returns the parent with the highest fitness (or nth highest,
depending on var best)
*/
Population.prototype.getWinner = function(pool,best) {
	var original = pool;
	var orderfitness = new Array(t_size);
	for (j = 0; j < t_size; j++) {
		// Fast bug-fix, don't know if this the right solution.
		if (pool[j] != null) {
			orderfitness[j] = pool[j].fitness;
		}
		else {
			orderfitness[j] = 0;
		}
	}
	// sort fitness based on high first, low last
	orderfitness.sort(function(a, b){return b-a});
	for (k = 0; k < t_size; k++) {
		// compare which original agent had the nth best fitness
		// Quick bug-fix, don't know if it's the right thing to do.
		if (original[k] != null) {
			if (orderfitness[best] == original[k].fitness){
				// index of pool member with nth best fitness
				return k;
			}
		}
	}
	console.log("No corresponding agent to best fitness")
	return 0;
};

/** Cross-over function
Takes two parents and with probability c_prob slices their genes
and recombines them to make two children
*/
Population.prototype.crossover = function(mother, father) {
	var children = new Array(2);
	children[0] = mother; //first copy parents
	children[1] = father;
	var r,g,h,r2,g2,h2;
	var cross = Math.random();
	var cross2 = Math.random();
	//cross-over between all genes
	if (cross < this.c_prob && cross2 < this.c_prob) {
		 r = mother.Genome.random;
		 g = father.Genome.greedy;
		 h = mother.Genome.human;
		 r2 = father.Genome.random;
		 g2 = mother.Genome.greedy;
		 h2 = father.Genome.human;
	}
	//cross-over after first gene
	else if (cross < this.c_prob) {
		r = mother.Genome.random;
		g = father.Genome.greedy;
		h = father.Genome.human;
		r2 = father.Genome.random;
		g2 = mother.Genome.greedy;
		h2 = mother.Genome.human;
	}
	//cross-over after second gene
	else if (cross < this.c_prob2) {
		r = mother.Genome.random;
		g = mother.Genome.greedy;
		h = father.Genome.human;
		r2 = father.Genome.random;
		g2 = father.Genome.greedy;
		h2 = mother.Genome.human;
	}
	//no cross-over, children are same as parents
	else {
		return children[0], children[1];
	}
	//normalize so genome adds up to 1 again;
	norm = r + g + h;
	r = r/norm;
	g = g/norm;
	h = h/norm;
	norm2 = r2 + g2 + h2;
	r2 = r2/norm2;
	g2 = g2/norm2;
	h2 = h2/norm2;
	children[0].Genome.update(r,g,h);
	children[1].Genome.update(r2,g2,h2);
	return [children[0], children[1]];
};

Population.prototype.mutation = function (agent) {
	var probs = new Array(6);
	var random, greedy, human;
	for (i = 0; i < 10; i++) {
		probs[i] = Math.random();
	}
	if (probs[0] <= mutation_prob) {
		if (probs[1] < 0.5) {
			random = agent.Genome.random + mutation_amount;
		}
		else random = agent.Genome.random - mutation_amount;
	}
	if (probs[2] <= mutation_prob) {
		if (probs[3] < 0.5) {
			greedy = agent.Genome.greedy + mutation_amount;
		}
		else greedy = agent.Genome.greedy - mutation_amount;
	}
	if (probs[4] <= mutation_prob) {
		if (probs[5] < 0.5) {
			human = agent.Genome.human + mutation_amount;
		}
		else human = agent.Genome.human - mutation_amount;
	}
	var normalization = random + alphabeta + human;
	agent.Genome.update(random/normalization, greedy/normalization, human/normalization);
	return agent;
};

/** This function replaces the agents in the population by the children
created through parent selection, cross-over and mutation
*/
Population.prototype.update = function() {
	console.log("Start updating..")
	//update entire population
	//first parent selection, then create new children
	var par = new Array(this.size);
	var children = new Array(this.size);
	console.log("Parent selection")
	par = this.parentselection();
	console.log("Crossover")
	for (i = 0; i < this.size; i+2) {
		//console.log("children = " + i + " and " + (i+1))
		var newChildren = this.crossover(par[i],par[i+1]);
		children[i]   = newChildren[0];
		children[i+1] = newChildren[1];
	}
	console.log("Mutation")
	for (i = 0; i < this.size; i++) {
		children[i] = this.mutation(children[i]);
	}
	this.agents = children; //update population
	console.log("End updating..")
};
<|endoftext|>


<commit_before>// Wrap an HTMLElement around each element in an HTMLElement array.
HTMLElement.prototype.wrap = function(elms) {
    // Convert `elms` to an array, if necessary.
    if (!elms.length) elms = [elms];

    // Loops backwards to prevent having to clone the wrapper on the
    // first element (see `child` below).
    for (var i = elms.length - 1; i >= 0; i--) {
        var child = (i > 0) ? this.cloneNode(true) : this;
        var el    = elms[i];

        // Cache the current parent and sibling.
        var parent  = el.parentNode;
        var sibling = el.nextSibling;

        // Wrap the element (is automatically removed from its current
        // parent).
        child.appendChild(el);

        // If the element had a sibling, insert the wrapper before
        // the sibling to maintain the HTML structure; otherwise, just
        // append it to the parent.
        if (sibling) {
            parent.insertBefore(child, sibling);
        } else {
            parent.appendChild(child);
        }
    }
};

/*
    Usage
    ------
    Four parameters you can use:
    'parent'     = parent element object or id
    'wrapper_id' = the attribute that you need this innerwrapped element to have

    Example
    -------
    wrapInner(parent, 'wrapper_id');
*/

function wrapInner(parent, wrapperID) {
    wrapper = document.createElement('div');
    if (typeof parent === "string") { parent = document.getElementById(parent); }
    var div = parent.appendChild(wrapper).setAttribute('id', wrapperID);
    while (parent.firstChild !== wrapper) {
        wrapper.appendChild(parent.firstChild);
    }
}

function initResponsiveHeader() {
    responsiveHeaderHTML = '\
     \

 \

 \

SNUL
 \

 \

 \

 \
                     \

 \

User Login
 \

 \

 \
    ';
    responsiveHeader = $(responsiveHeaderHTML);
    headerContainer = $('#header');
    responsiveHeader.insertAfter(headerContainer);
}

function initResponsiveContainers() {
    scrollerContainerID = "scroller";
    naviPusherID = "navi-pusher";
    responsiveContainerID = "responsive-container";
    // initiate contstruction
    wrapInner(document.body, responsiveContainerID);
    wrapInner(responsiveContainerID, scrollerContainerID);
    wrapInner(scrollerContainerID, naviPusherID);

    $('').insertBefore("#navi-pusher");
    $('

').insertAfter()
}

function isKorean(){
    return $('body').hasClass('EXLCurrentLang_ko_KR');
}

function convertResponsiveMenu(desktopMenu) {
    $('
Main Menu
').insertBefore(desktopMenu.find('a:first-child'));
    return desktopMenu;
}

function createResponsiveMenu() {
    if (isKorean()) {
        return convertResponsiveMenu($('#korean-main-menu'));
    } else {
        return convertResponsiveMenu($('#english-main-menu'));
    }
}

$(document).ready(function () {
    // Responsive Header
    initResponsiveHeader();
    // Responsive Containers
    initResponsiveContainers();
    // Responsive Menu
    responsiveMenu = createResponsiveMenu();
});<commit_msg>Deploying changes<commit_after>// Wrap an HTMLElement around each element in an HTMLElement array.
HTMLElement.prototype.wrap = function(elms) {
    // Convert `elms` to an array, if necessary.
    if (!elms.length) elms = [elms];

    // Loops backwards to prevent having to clone the wrapper on the
    // first element (see `child` below).
    for (var i = elms.length - 1; i >= 0; i--) {
        var child = (i > 0) ? this.cloneNode(true) : this;
        var el    = elms[i];

        // Cache the current parent and sibling.
        var parent  = el.parentNode;
        var sibling = el.nextSibling;

        // Wrap the element (is automatically removed from its current
        // parent).
        child.appendChild(el);

        // If the element had a sibling, insert the wrapper before
        // the sibling to maintain the HTML structure; otherwise, just
        // append it to the parent.
        if (sibling) {
            parent.insertBefore(child, sibling);
        } else {
            parent.appendChild(child);
        }
    }
};

/*
    Usage
    ------
    Four parameters you can use:
    'parent'     = parent element object or id
    'wrapper_id' = the attribute that you need this innerwrapped element to have

    Example
    -------
    wrapInner(parent, 'wrapper_id');
*/

function wrapInner(parent, wrapperID) {
    wrapper = document.createElement('div');
    if (typeof parent === "string") { parent = document.getElementById(parent); }
    var div = parent.appendChild(wrapper).setAttribute('id', wrapperID);
    while (parent.firstChild !== wrapper) {
        wrapper.appendChild(parent.firstChild);
    }
}

function initResponsiveHeader() {
    responsiveHeaderHTML = '\
     \

 \

 \

SNUL
 \

 \

 \

 \
                     \

 \

User Login
 \

 \

 \
    ';
    responsiveHeader = $(responsiveHeaderHTML);
    headerContainer = $('#header');
    responsiveHeader.insertAfter(headerContainer);
}

function initResponsiveContainers() {
    scrollerContainerID = "scroller";
    naviPusherID = "navi-pusher";
    responsiveContainerID = "responsive-container";
    // initiate contstruction
    wrapInner(document.body, responsiveContainerID);
    wrapInner(responsiveContainerID, scrollerContainerID);
    wrapInner(scrollerContainerID, naviPusherID);

    $('').insertBefore("#navi-pusher");
    $('

').insertAfter()
}

function isKorean(){
    return $('body').hasClass('EXLCurrentLang_ko_KR');
}

function convertResponsiveMenu(desktopMenu) {
    $('
Main Menu
').insertBefore(desktopMenu.find('a:first-child'));
    return desktopMenu;
}

function createResponsiveMenu() {
    if (isKorean()) {
        return convertResponsiveMenu($('#korean-main-menu'));
    } else {
        return convertResponsiveMenu($('#english-main-menu'));
    }
}

var responsiveMenu = {};

$(document).ready(function () {
    // Responsive Header
    initResponsiveHeader();
    // Responsive Containers
    initResponsiveContainers();
    // Responsive Menu
    responsiveMenu = createResponsiveMenu();
});<|endoftext|>


<commit_before>/*
    Date: 2016-01-06

	BUG FIX:2016-01-12: jquery-1.7.2 returned ALL titles, not just the "channel" title.
*/
//
var currentFeed = {
    // reset when click('.feedLink')
    RSS           : "https://cordova.apache.org/feed.xml",
    entries       : [],
    // reset when getFeed();
    title         : "",
    description   : "",
    length        : "",
    lastBuildDate : "",
    selectedStory : ""
};

var readerApp = {
    self : {},
    needFeed : true,
    //
    init : function () {
        console.log("readerApp.init");
    },
    getFeed : function(externalElements) {
        externalElements['status']('Contacting Server ...');
        $.get(currentFeed.RSS, function(data, errorCode) {
            externalElements['status']('Got Feed.');
            // let's see if it will parse
            try {
                var xml           = $( data );
                externalElements['status']('xml make object okay');
            }
            catch(err) {
                externalElements['status']('Cannot create xml Object.');
                navigator.notification.alert("Sorry, I can't parse this RSS format. I'll fix soon, if I can.",
                    function () {},
                    'Bad XML format',
                    'Done'
                );
                return;
            }
            //
            var title         = xml.find( "title" );
            //$('#dbug').html(title + '
' + title[0]);
            var mtitle        = xml.closest( "title" );
            $('#dbug').html(mtitle[0]);
            var xtitle        = title[0][0]; // bug in jquery - 2016-01-12
            var description   = xml.find( "description" );
            var items         = xml.find( "item" );
            var lastBuildDate = xml.find( "lastBuildDate" );
            // assign
            currentFeed.title         = xtitle; // title.text();
            currentFeed.description   = description.text();
            currentFeed.lastBuildDate = lastBuildDate.text();
            currentFeed.length        = items.length;
            externalElements['status']('title:' + xtitle + ":" + items.length);
            // Parse our object
            currentFeed.entries = [];
            $.each(items, function(i, v) {
                entry = {
                    title:$(v).find("title").text(),
                    link:$(v).find("link").text(),
                    description:$.trim($(v).find("description").text())
                };
                currentFeed.entries.push(entry);
            });
            externalElements['draw'](currentFeed);
            externalElements['status']('Done.');
        });
    },
    getStory : function (displayFunc) {
        var theStory = currentFeed.entries[currentFeed.selectedStory];
        // fire only if we have a valid reference for theStory and a displayFunc.
        if (theStory && displayFunc) {
            displayFunc(theStory);
        }
    },
}
<commit_msg>update<commit_after>/*
    Date: 2016-01-06

	BUG FIX:2016-01-12: jquery-1.7.2 returned ALL titles, not just the "channel" title.
*/
//
var currentFeed = {
    // reset when click('.feedLink')
    RSS           : "https://cordova.apache.org/feed.xml",
    entries       : [],
    // reset when getFeed();
    title         : "",
    description   : "",
    length        : "",
    lastBuildDate : "",
    selectedStory : ""
};

var readerApp = {
    self : {},
    needFeed : true,
    //
    init : function () {
        console.log("readerApp.init");
    },
    getFeed : function(externalElements) {
        externalElements['status']('Contacting Server ...');
        $.get(currentFeed.RSS, function(data, errorCode) {
            externalElements['status']('Got Feed.');
            // let's see if it will parse
            try {
                var xml           = $( data );
                externalElements['status']('xml make object okay');
            }
            catch(err) {
                externalElements['status']('Cannot create xml Object.');
                navigator.notification.alert("Sorry, I can't parse this RSS format. I'll fix soon, if I can.",
                    function () {},
                    'Bad XML format',
                    'Done'
                );
                return;
            }
            //
            var title         = xml.find( "title" );
            //$('#dbug').html(title + '
' + title[0]);
            var mtitle        = xml.closest( "title" );
            $('#dbug').html(mtitle);
            var xtitle        = title[0]; // bug in jquery - 2016-01-12
            var description   = xml.find( "description" );
            var items         = xml.find( "item" );
            var lastBuildDate = xml.find( "lastBuildDate" );
            // assign
            currentFeed.title         = xtitle; // title.text();
            currentFeed.description   = description.text();
            currentFeed.lastBuildDate = lastBuildDate.text();
            currentFeed.length        = items.length;
            externalElements['status']('title:' + xtitle + ":" + items.length);
            // Parse our object
            currentFeed.entries = [];
            $.each(items, function(i, v) {
                entry = {
                    title:$(v).find("title").text(),
                    link:$(v).find("link").text(),
                    description:$.trim($(v).find("description").text())
                };
                currentFeed.entries.push(entry);
            });
            externalElements['draw'](currentFeed);
            externalElements['status']('Done.');
        });
    },
    getStory : function (displayFunc) {
        var theStory = currentFeed.entries[currentFeed.selectedStory];
        // fire only if we have a valid reference for theStory and a displayFunc.
        if (theStory && displayFunc) {
            displayFunc(theStory);
        }
    },
}
<|endoftext|>


<commit_before>'use strict';

function draw_boxen(args){
    canvas_draw_path({
      'style': 'stroke',
      'vertices': [
        {
          'type': 'rect',
           'radius': args['radius'],
           'startAngle': args['startAngle'],
           'x': args['x'],
           'y': args['y'],
         },
      ],
    });
}

function draw_logic(){
    // If mouse down, draw current unsaved box.
    if(core_mouse['down']){
        draw_boxen({
          'radius': core_mouse['x'] - core_mouse['down-x'],
          'startAngle': core_mouse['y'] - core_mouse['down-y'],
          'x': core_mouse['down-x'],
          'y': core_mouse['down-y'],
        });
    }

    // Draw saved boxen.
    for(var box in boxen){
        draw_boxen({
          'radius': boxen[box]['width'],
          'startAngle': boxen[box]['height'],
          'x': boxen[box]['x'],
          'y': boxen[box]['y'],
        });
    }
}

function repo_escape(){
    boxen = [];
}

function repo_init(){
    core_repo_init({
      'info': 'Click + Drag
ESC = Clear',
      'mousebinds': {
        'mouseup': {
          'todo': function(){
              boxen.push({
                'height': core_mouse['y'] - core_mouse['down-y'],
                'width': core_mouse['x'] - core_mouse['down-x'],
                'x': core_mouse['down-x'],
                'y': core_mouse['down-y'],
              });
          },
        },
      },
      'title': 'RTS-Boxing.htm',
    });
    canvas_init();
}

function resize_logic(){
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.strokeStyle = '#fff';
}

var boxen = [];
<commit_msg>replaced repo_escape() with clear button<commit_after>'use strict';

function clear_boxen(){
    boxen = [];
    core_escape();
}

function draw_boxen(args){
    canvas_draw_path({
      'style': 'stroke',
      'vertices': [
        {
          'type': 'rect',
           'radius': args['radius'],
           'startAngle': args['startAngle'],
           'x': args['x'],
           'y': args['y'],
         },
      ],
    });
}

function draw_logic(){
    // If mouse down, draw current unsaved box.
    if(core_mouse['down']){
        draw_boxen({
          'radius': core_mouse['x'] - core_mouse['down-x'],
          'startAngle': core_mouse['y'] - core_mouse['down-y'],
          'x': core_mouse['down-x'],
          'y': core_mouse['down-y'],
        });
    }

    // Draw saved boxen.
    for(var box in boxen){
        draw_boxen({
          'radius': boxen[box]['width'],
          'startAngle': boxen[box]['height'],
          'x': boxen[box]['x'],
          'y': boxen[box]['y'],
        });
    }
}

function repo_init(){
    core_repo_init({
      'info': 'Click + Drag
<input onclick=clear_boxen() type=button value="Clear Boxen">',
      'mousebinds': {
        'mouseup': {
          'todo': function(){
              boxen.push({
                'height': core_mouse['y'] - core_mouse['down-y'],
                'width': core_mouse['x'] - core_mouse['down-x'],
                'x': core_mouse['down-x'],
                'y': core_mouse['down-y'],
              });
          },
        },
      },
      'title': 'RTS-Boxing.htm',
    });
    canvas_init();
}

function resize_logic(){
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.strokeStyle = '#fff';
}

var boxen = [];
<|endoftext|>