DatabaseJS

```
// DATABASE CODE ---------------------------------
 if (railWAM.loadDatabase === true && window.location.search.indexOf('blankspecial=RailWAMDatabase') !== -1) {
 // Get date of wiki creation
 var dateCreated,
 yearMin,
 monthMin,
 dayMin;
 $.get('http://bniceshottest.wikia.com/api.php?action=query&format=json&prop=revisions&titles=Main+Page&rvprop=timestamp&rvlimit=1&rvdir=newer').done(function(data){
 var pageId = Object.keys(data.query.pages)[0],
 dateProp = data.query.pages[pageId].revisions[0].timestamp.split('T')[0],
 split = dateProp.split('-');
 yearMin = split[0];
 monthMin = Number(split[1]) - 1;
 dayMin = split[2];
 dateCreated = Date.UTC(yearMin,monthMin,dayMin) / 1000;
 });

 // Create database page
 $('title').text($('title').text().replace('Blank page','RailWAM: WAM Database'));
 $('.wikia-page-header .header-column h1').text('RailWAM: ' + i18n.database);
 var bgColor = $('.WikiHeader .navbackground').css('background-color').replace('rgb','rgba').replace(')',',.05)');
 var listItems = 6;
 $('#mw-content-text').html(i18n.databaseWelcome + siteName + '.<div id="railwam-database-fields"><input id="railwam-database-field" type="text" placeholder="dd/mm/yyyy" style="background:' + bgColor + ';"><select id="railwam-database-select" class="railwam-database-hidden" style="background:' + bgColor + ';"><option value="7">Within last 7 days</option><option value="30">Within last 30 days</option><option value="60">Within last 60 days</option><option value="0">All time</option><option value="custom">Custom range</option></select><input id="railwam-database-custom-input" class="railwam-database-hidden" type="text" style="background:' + bgColor + ';" placeholder="days"><div id="railwam-database-searchbtn" style="background:' + $('.WikiHeader .navbackground').css('background-color').replace('rgb','rgba').replace(')',',.5)') + '; color:' + $('.WikiHeader .accent a').css('color') + ';">SEARCH</div></div><div id="railwam-database-errors"></div><ul id="railwam-database-radio"><li id="railwam-database-searchby" style="width:' + (100 / listItems) +'%;">Search by:</li><li class="railwam-database-radio-container" style="width:' + (100 / listItems) +'%;"><div class="railwam-database-radio-center"><input type="radio" name="railwam-database" value="date" id="railwam-database-date" checked><label for="railwam-database-date">date</label></input><div class="railwam-database-check"></div></div></li><li class="railwam-database-radio-container" style="width:' + (100 / listItems) +'%;"><div class="railwam-database-radio-center"><input type="radio" name="railwam-database" value="score" id="railwam-database-score"><label for="railwam-database-score">score</label></input><div class="railwam-database-check"></div></div></li><li class="railwam-database-radio-container" style="width:' + (100 / listItems) +'%;"><div class="railwam-database-radio-center"><input type="radio" name="railwam-database" value="rank" id="railwam-database-rank"><label for="railwam-database-rank">rank</label></input><div class="railwam-database-check"></div></div></li><li class="railwam-database-radio-container" style="width:' + (100 / listItems) +'%;"><div class="railwam-database-radio-center"><input type="radio" name="railwam-database" value="vertrank" id="railwam-database-vertrank"><label for="railwam-database-vertrank">vertical rank</label></input><div class="railwam-database-check"></div></div></li><li class="railwam-database-radio-container" style="width:' + (100 / listItems) +'%;"><div class="railwam-database-radio-center"><input type="radio" name="railwam-database" value="lastdays" id="railwam-database-lastdays"><label for="railwam-database-lastdays">last ## days</label></input><div class="railwam-database-check"></div></div></li></ul><div id="railwam-database-tablehead-container" style="background:' + $('.WikiHeader .navbackground').css('background-color') + '; color:' + $('.WikiHeader .accent a').css('color') + ';"><div class="railwam-database-tablehead">date (dd/mm/yyyy)</div><div class="railwam-database-tablehead">score</div><div class="railwam-database-tablehead">rank</div><div class="railwam-database-tablehead">vertical rank</div></div><div id="railwam-database-loading"><svg class="spinner block ember-initializing" width="30" viewBox="-15 -15 30 30" xmlns="http://www.w3.org/2000/svg" style="vertical-align:middle; margin-top:-3px; margin-right:5px;"> <g> <circle style="animation: dash 1s linear infinite; stroke:' + $('.WikiHeader .navbackground').css('background-color') + '; stroke-dasharray: 187; stroke-dashoffset: 0;" class="path stroke-theme-color" fill="none" stroke-width="1" stroke-linecap="round" r="10"></circle></g></svg><span id="railwam-database-loading-text"></span></div><div id="railwam-database-entries"></div>');

 $('.railwam-database-check').css({'background':$('.WikiaPage .WikiaPageBackground').css('background-color'),'box-shadow':'0 0 0 2px ' + $('.WikiaPage .WikiaPageBackground').css('background-color') + ', 0 0 0 4px ' + $('.WikiHeader .navbackground').css('background-color')});
 $('input[name="railwam-database"]:checked ~ .railwam-database-check').css({'background':$('.WikiHeader .navbackground').css('background-color')});

 // Radio input change
 $('input[name="railwam-database"]').change(function(){
 // CSS
 $('input[name="railwam-database"] ~ .railwam-database-check').css({'background':$('.WikiaPage .WikiaPageBackground').css('background-color')});
 $('input[name="railwam-database"]:checked ~ .railwam-database-check').css({'background':$('.WikiHeader .navbackground').css('background-color')});
 // Clear input field
 $('#railwam-database-field').val('');
 // Not ready to search
 notReadyToSearch();

 // Change placeholders
 switch ($('input[name="railwam-database"]:checked').val()) {
 case 'date':
 $('#railwam-database-field').attr('placeholder','dd/mm/yyyy');
 break;
 case 'score':
 $('#railwam-database-field').attr('placeholder','score');
 break;
 case 'rank':
 $('#railwam-database-field').attr('placeholder','rank');
 break;
 case 'vertrank':
 $('#railwam-database-field').attr('placeholder','vertical rank');
 break;
 case 'lastdays':
 $('#railwam-database-field').attr('placeholder','# of days');
 break;
 }

 var dontShowWithin = ['date','lastdays'];
 // Add Last ... on non-date types
 if ($.inArray($('input[name="railwam-database"]:checked').val(),dontShowWithin) === -1 && $("#railwam-database-select").hasClass('railwam-database-hidden') === true) {
 $('#railwam-database-select').animate({width:'toggle'},300);
 $('#railwam-database-select').removeClass('railwam-database-hidden');
 $('#railwam-database-field').css('width','70%');
 if ($('#railwam-database-select').val() === 'custom' && $('#railwam-database-custom-input').hasClass('railwam-database-hidden') === true) {
 $('#railwam-database-custom-input').animate({width:'toggle'},200);
 $('#railwam-database-custom-input').removeClass('railwam-database-hidden');
 }
 // Remove Last ... on date type
 } else if ($.inArray($('input[name="railwam-database"]:checked').val(),dontShowWithin) !== -1 && $("#railwam-database-select").hasClass('railwam-database-hidden') === false) {
 $('#railwam-database-select').animate({width:'toggle'},300);
 $('#railwam-database-select').addClass('railwam-database-hidden');
 $('#railwam-database-field').css({'width':'90%'});
 if ($('#railwam-database-custom-input').hasClass('railwam-database-hidden') === false) {
 $('#railwam-database-custom-input').animate({width:'toggle'},200);
 $('#railwam-database-custom-input').addClass('railwam-database-hidden');
 }
 }
 });

 $('#railwam-database-select').change(function() {
 // Show custom input box
 if ($(this).val() === 'custom' && $("#railwam-database-custom-input").hasClass('railwam-database-hidden') === true) {
 $('#railwam-database-custom-input').animate({width:'toggle'},200);
 $('#railwam-database-custom-input').removeClass('railwam-database-hidden');
 $('#railwam-database-field').css({'width':'65%'});
 $('#railwam-database-select').css({'width':'10%'});
 $('#railwam-database-select option[value="custom"]').text('Within last...');
 // Hide custom input box
 } else if ($(this).val() !== 'custom' && $("#railwam-database-custom-input").hasClass('railwam-database-hidden') === false) {
 $('#railwam-database-custom-input').animate({width:'toggle'},200);
 $('#railwam-database-custom-input').addClass('railwam-database-hidden');
 $('#railwam-database-field').css({'width':'70%'});
 $('#railwam-database-select').css({'width':'20%'});
 $('#railwam-database-select option[value="custom"]').text('Custom range');
 }
 });

 // Click search on enter
 $(document).keydown(function(key){
 if (key.keyCode === 13) {
 $('#railwam-database-searchbtn').click();
 }
 });

 // Backspace, Enter, Shift, Control, Delete, and Arrow keys
 var acceptedSpecialChars = [8,13,16,17,46,37,38,39,40];
 $('#railwam-database-field').keydown(function(key){
 if (key.keyCode === 13) {
 return;
 }

 if ($.inArray(key.keyCode,acceptedSpecialChars) === -1) {
 // Score type allows period (.)
 if ($('input[name="railwam-database"]:checked').val() !== 'score' || ($('input[name="railwam-database"]:checked').val() === 'score' && key.keyCode !== 190)) {
 // Numbers only
 if (String.fromCharCode(key.keyCode).match(/[^0-9]/g)) {
 key.preventDefault();
 displayError('Please enter a numeric value greater than or equal to 0.','char');
 // Enter slash after 2nd and 4th characters on date type
 } else if ($('input[name="railwam-database"]:checked').val() === 'date' && ($(this).val().length === 1 || $(this).val().length === 4)) {
 key.preventDefault();
 $(this).val($(this).val() + String.fromCharCode(key.keyCode) + '/');
 }
 }
 }

 // Different behaviors based on radio input value
 switch ($('input[name="railwam-database"]:checked').val()) {
 // Date checked
 case 'date':
 // Maximum length: 10
 if ($(this).val().length === 10 && $.inArray(key.keyCode,acceptedSpecialChars) === -1) {
 key.preventDefault();
 displayError('You have reached the maximum number of characters allowed for dates.','maxLengthDate');
 } else if ($(this).val().length === 9 && $.inArray(key.keyCode,acceptedSpecialChars) === -1) {
 readyToSearch();
 } else {
 notReadyToSearch();
 }
 break;
 // Score checked
 case 'score':
 // Maximum length: 7
 if ($(this).val().length === 7 && $.inArray(key.keyCode,acceptedSpecialChars) === -1) {
 key.preventDefault();
 displayError('You have reached the maximum number of characters allowed for scores.','maxLengthScore');
 } else if ($(this).val().length <= 1 && $.inArray(key.keyCode,acceptedSpecialChars) !== -1) {
 notReadyToSearch();
 } else {
 readyToSearch();
 }
 break;
 // Rank or Vertical Rank checked
 // Maximum length: 4
 if ($(this).val().length === 4 && $.inArray(key.keyCode,acceptedSpecialChars) === -1) {
 key.preventDefault();
 displayError('You have reached the maximum number of characters allowed for ranks.','maxLengthRank');
 } else if ($(this).val().length <= 1 && $.inArray(key.keyCode,acceptedSpecialChars) !== -1) {
 notReadyToSearch();
 } else {
 readyToSearch();
 }
 break;
 case 'lastdays':
 // Minimum length: 1
 if ($(this).val().length <= 1 && $.inArray(key.keyCode,acceptedSpecialChars) !== -1) {
 notReadyToSearch();
 } else {
 readyToSearch();
 }
 break;
 }
 });

 // Display an error
 function displayError(text,type) {
 if ($('#railwam-database-error-' + type).length === 0) {
 $('<div class="railwam-database-error" id="railwam-database-error-' + type + '" style="background:' + $('a').css('color') + '; color:' + $('.WikiHeader .accent a').css('color') + ';">' + text + '</div>').prependTo($('#railwam-database-errors')).slideDown(500).delay(5000).fadeOut(200, function() {
 $(this).remove();
 });
 }
 }

 // Validate search input
 function validateSearch() {
 $('.railwam-database-entrytable').remove();
 switch ($('input[name="railwam-database"]:checked').val()) {
 case 'date':
 var dateSplit = $('#railwam-database-field').val().split('/');
 var dateSec = Date.UTC(dateSplit[2],(dateSplit[1] - 1),dateSplit[0]) / 1000;
 if (dateSec <= timeSec && dateSec >= dateCreated) {
 searchByDate(dateSplit);
 } else {
 var maxDate = date.getUTCDate() + '/' + (date.getUTCMonth() + 1) + '/' + date.getUTCFullYear();
 var minDate = dayMin + '/' + (monthMin + 1) + '/' + yearMin;
 displayError('Please enter a date between ' + minDate + ' and ' + maxDate + '.','maxDate');
 }
 break;
 case 'score':
 if (Number($('#railwam-database-field').val()) >= 0 && Number($('#railwam-database-field').val()) < 100) {
 if ($('#railwam-database-select').val() === 'custom') {
 if (Number($('#railwam-database-custom-input').val()) === 0) {
 retrieveDataInRange((timeSec - dateCreated) / 86400);
 } else {
 retrieveDataInRange(Number($('#railwam-database-custom-input').val()));
 }
 } else if (Number($('#railwam-database-select').val()) === 0) {
 retrieveDataInRange((timeSec - dateCreated) / 86400);
 } else {
 retrieveDataInRange(Number($('#railwam-database-select').val()));
 }
 } else {
 displayError('Please enter a number greater than or equal to 0 and less than 100.','maxScore');
 }
 break;
 if (Number($('#railwam-database-field').val()) >= 1 && Number($('#railwam-database-field').val()) <= 5000) {
 retrieveDataInRange(Number($('#railwam-database-select').val()));
 } else {
 displayError('Please enter a number between 1 and 5000.','maxRank');
 }
 break;
 case 'lastdays':
 if (timeSec - (Number($('#railwam-database-field').val()) \* 86400) - dateCreated >= 0 && Number($('#railwam-database-field').val()) > 0) {
 retrieveDataInRange(Number($('#railwam-database-select').val()));
 } else {
 var maxDate = date.getUTCDate() + '/' + (date.getUTCMonth() + 1) + '/' + date.getUTCFullYear();
 var minDate = dayMin + '/' + (monthMin + 1) + '/' + yearMin;
 displayError('Please enter a date between ' + minDate + ' and ' + maxDate + '.','maxDate');
 }
 break;
 }
 }

 // Make search button clickable
 function readyToSearch() {
 $('#railwam-database-searchbtn').css({'background':$('.WikiHeader .navbackground').css('background-color'),'cursor':'pointer'});
 $('#railwam-database-searchbtn').off('click').click(function(){
 validateSearch();
 });
 }

 // Make search button not clickable
 function notReadyToSearch() {
 $('#railwam-database-searchbtn').css({'background':$('.WikiHeader .navbackground').css('background-color').replace('rgb','rgba').replace(')',',.5)'),'cursor':'auto'});
 $('#railwam-database-searchbtn').off('click');
 }

 // Search data by date
 function searchByDate(dateSplit) {
 var timesExec = 0;
 var dateSec = Date.UTC(dateSplit[2],(dateSplit[1] - 1),dateSplit[0]) / 1000;
 // Latest
 if (wamData[dateSec] === undefined && typeof wamData[dateSec] === 'undefined') {
 $.ajax({
 url:'https://query.yahooapis.com/v1/public/yql?q=select%20\*%20from%20json%20where%20url%3D%22http%3A%2F%2Fwww.wikia.com%2Fapi%2Fv1%2FWAM%2FWAMIndex%3Fwam\_day%3D' + (dateSec).toString() +'%26wiki\_id%3D' + wikiId + '%26sort\_column%3Dwam%26sort\_direction%3DASC%26limit%3D1%26fetch\_admins%3Dfalse%26fetch\_wiki\_images%3Dfalse%22&format=json&diagnostics=false&callback=',
 success:function(data) {
 wamData[dateSec] = data.query.results.json.wam\_index[dataId];
 dataComplete('database',$('#railwam-database-field').val(),dateSec);
 timesExec++;
 checkIfLoading(timesExec,2);
 },
 cache:false
 });
 }

 // Prev day
 if (wamData[dateSec - 86400] === undefined && typeof wamData[dateSec - 86400] === 'undefined') {
 $.ajax({
 url:'https://query.yahooapis.com/v1/public/yql?q=select%20\*%20from%20json%20where%20url%3D%22http%3A%2F%2Fwww.wikia.com%2Fapi%2Fv1%2FWAM%2FWAMIndex%3Fwam\_day%3D' + (dateSec - 86400).toString() +'%26wiki\_id%3D' + wikiId + '%26sort\_column%3Dwam%26sort\_direction%3DASC%26limit%3D1%26fetch\_admins%3Dfalse%26fetch\_wiki\_images%3Dfalse%22&format=json&diagnostics=false&callback=',
 success:function(data) {
 wamData[dateSec - 86400] = data.query.results.json.wam\_index[dataId];
 dataComplete('database',$('#railwam-database-field').val(),dateSec);
 timesExec++;
 checkIfLoading(timesExec,2);
 },
 cache:false
 });
 // If data from both days already exists
 } else if ((wamData[dateSec] && wamData[dateSec - 86400]) !== undefined && typeof (wamData[dateSec] && wamData[dateSec - 86400]) !== 'undefined') {
 dataComplete('database',$('#railwam-database-field').val(),dateSec);
 checkIfLoading(2,2);
 }
 }

 // Retrieve WAM data within last ## days
 function retrieveDataInRange(days) {
 areRequestsCanceled = false;
 var timesExec = 0;
 // Within "days" days starting yesterday
 for (i = 0; i < days; i++) {
 if (areRequestsCanceled === false) {
 (function (num) {
 date.setDate(date.getDate() - num);
 var entryDate = date.getUTCDate() + '/' + (date.getUTCMonth() + 1) + '/' + date.getUTCFullYear();
 date.setDate(date.getDate() + num);
 if (wamData[timeSec - (86400 \* num)] === undefined && typeof wamData[timeSec - (86400 \* num)] === 'undefined') {
 $.ajax({
 url:'https://query.yahooapis.com/v1/public/yql?q=select%20\*%20from%20json%20where%20url%3D%22http%3A%2F%2Fwww.wikia.com%2Fapi%2Fv1%2FWAM%2FWAMIndex%3Fwam\_day%3D' + (timeSec - (86400 \* num)).toString() +'%26wiki\_id%3D' + wikiId + '%26sort\_column%3Dwam%26sort\_direction%3DASC%26limit%3D1%26fetch\_admins%3Dfalse%26fetch\_wiki\_images%3Dfalse%22&format=json&diagnostics=false&callback=',
 success:function(data) {
 wamData[timeSec - (86400 \* num)] = data.query.results.json.wam\_index[dataId];
 dataComplete('database',entryDate,timeSec - (86400 \* num));
 timesExec++;
 checkIfLoading(timesExec,days \* 2);
 },
 cache:false
 });
 } else {
 timesExec++;
 }

 if (wamData[timeSec - (86400 \* num) - 86400] === undefined && typeof wamData[timeSec - (86400 \* num) - 86400] === 'undefined') {
 $.ajax({
 url:'https://query.yahooapis.com/v1/public/yql?q=select%20\*%20from%20json%20where%20url%3D%22http%3A%2F%2Fwww.wikia.com%2Fapi%2Fv1%2FWAM%2FWAMIndex%3Fwam\_day%3D' + (timeSec - (86400 \* num) - 86400).toString() +'%26wiki\_id%3D' + wikiId + '%26sort\_column%3Dwam%26sort\_direction%3DASC%26limit%3D1%26fetch\_admins%3Dfalse%26fetch\_wiki\_images%3Dfalse%22&format=json&diagnostics=false&callback=',
 success:function(data) {
 wamData[timeSec - (86400 \* num) - 86400] = data.query.results.json.wam\_index[dataId];
 dataComplete('database',entryDate,timeSec - (86400 \* num));
 timesExec++;
 checkIfLoading(timesExec,days \* 2);
 },
 cache:false
 });
 // If data from both days already exists
 } else if ((wamData[timeSec - (86400 \* num)] && wamData[timeSec - (86400 \* num) - 86400]) !== undefined && typeof (wamData[timeSec - (86400 \* num)] && wamData[timeSec - (86400 \* num) - 86400]) !== 'undefined') {
 dataComplete('database',entryDate,timeSec - (86400 \* num));
 timesExec++;
 checkIfLoading(timesExec,days \* 2);
 } else {
 timesExec++;
 }
 })(i);
 }
 }
 }

 // Check if data meets search specifications
 function shouldEntryShow(dateSec) {
 var wamValue;
 switch ($('input[name="railwam-database"]:checked').val()) {
 return false;
 case 'score':
 wamValue = wamData[dateSec].wam;
 break;
 case 'rank':
 wamValue = wamData[dateSec].wam\_rank;
 break;
 case 'vertrank':
 wamValue = wamData[dateSec].vertical\_wam\_rank;
 break;
 }

 // Add period to number if none is present
 var inputVal = $('#railwam-database-field').val();
 if (inputVal.indexOf('.') === -1) {
 inputVal += '.';
 }

 // Get number of decimal places in value
 var numOfPlaceholders = inputVal.toString().split('.')[1].length;
 inputVal = Number(inputVal);
 var maxVal = Math.round((inputVal + (1 / (Math.pow(10,numOfPlaceholders)))) \* Math.pow(10,numOfPlaceholders)) / Math.pow(10,numOfPlaceholders);
 if (wamValue >= inputVal && wamValue < maxVal ) {
 return true;
 } else {
 return false;
 }
 }

 // Show percentage indicator and remove it when finished
 var percentCompletion = 0;
 function checkIfLoading(times,max) {
 if (times === max) { // done
 percentCompletion = 0;
 $('#railwam-database-loading-text').text('');
 $('#railwam-database-loading').css('display','none');
 } else { // show percentage
 percentCompletion = Math.floor((times / max) \* 100);
 $('#railwam-database-loading-text').text(percentCompletion + '%');
 $('#railwam-database-loading').css('display','block');
 }
 }

 // Add a new database entry
 function newEntry(displayDate,dateSec,newScore,oldScore,newRank,oldRank,newVertRank,oldVertRank) {
 $('#railwam-database-entries').append('<div class="railwam-database-entrytable" id="railwam-entrytable-' + dateSec + '" railwam-date-id="' + dateSec + '"><div class="railwam-database-entrytable-column">' + displayDate + '</div><div class="railwam-database-entrytable-column">' + newScore + '<span class="railwam-database-entrytable-diff">' + calcDiff(newScore,oldScore) + '</span></div><div class="railwam-database-entrytable-column">' + newRank + '<span class="railwam-database-entrytable-diff">' + calcDiff(newRank,oldRank) + '</span></div><div class="railwam-database-entrytable-column">' + newVertRank + '<span class="railwam-database-entrytable-diff">' + calcDiff(newVertRank,oldVertRank) + '</span></div></div>');
 }
 }

```