User:LOL/sherdogtable.js

var mma = mma || {}; mma.getFights = function(src) { var fights = []; var srcLeft = src.indexOf(''); if (srcLeft === -1) { window.alert('Invalid page'); return; }   var srcRight = src.indexOf(' ', srcLeft); if (srcRight === -1) { window.alert('Invalid page'); return; }   var i = srcLeft; while ((i = src.indexOf(' -1) { var row = []; var k = i;       for (var j = 0; j < 7; j++) { k = src.indexOf('', k); k = src.indexOf(' ', l); row[j] = src.substring(l + 1, k).replace(/(^\s+|\s+$)/g, ''); }       fights.push(row); }   return fights; };

mma.sherdogTable = function { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest; } else { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); }   xmlhttp.onreadystatechange = function { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { var fights = mma.getFights(xmlhttp.responseText); var output = mma.getMMArecordbox(xmlhttp.responseText); output += '\n{|\n|-\n!Result\n!Opponent\n!Method\n!Event\n!Date\n!Round\n!Time\n!Location'; // Fetch locations var location = []; for (var i in fights) { var xhrLoc; if (window.XMLHttpRequest) { xhrLoc = new XMLHttpRequest; } else { xhrLoc = new ActiveXObject('Microsoft.XMLHTTP'); }               xhrLoc.onreadystatechange = function { if (xhrLoc.readyState === 4 && xhrLoc.status === 200) { location.push(mma.getLocation(xhrLoc.responseText)); }               };                xhrLoc.open('GET', 'http://www.sherdog.com' + fights[i][3]                        .replace(/^[^\uffff]+?href="([^"]+)"[^\uffff]+$/, '$1'),                        false);                xhrLoc.send;            }            for (var i = 0; i < fights.length; i++) {                // Format Result column                if (/[^A-Za-z]Win$/.test(fights[i][0])) {                    fights[i][0] = 'Win';                } else if (/[^A-Za-z]Loss$/.test(fights[i][0])) {                    fights[i][0] = 'Loss';                } else if (/[^A-Za-z]Draw$/.test(fights[i][0])) {                    fights[i][0] = 'Draw';                } else if (/[^A-Za-z]NC$/.test(fights[i][0])) {                    fights[i][0] = 'NC';                }                // Add links to fighters                fights[i][1] = '\s+$)/g, ) + ; // Remove redundancies in events fights[i][3] = mma.fixEvent(mma.removeTags(fights[i][3])                       .replace(/(^\s+|\s+$)/g, '')); }           for (var i = 0; i < fights.length; i++) { output += '\n|-'; for (var j in fights[i]) { output += '\n| ' + mma.removeTags(fights[i][j]) .replace(/(^\s+|\s+$)/gm, ''); }               output += '\n| ' + mma.wikifyLocation(location[i]); }           output += '\n|}'; document.getElementById('wpTextbox1').value += '\n\n' + output; }   };    var url = window.prompt('Enter the URL of the fighter\'s Sherdog profile',            'http://www.sherdog.com/fighter/'); xmlhttp.open('GET', url, true); xmlhttp.send; };

mma.fixEvent = function(s) { var m;   if ((m = /DEEP - (\d+) Impact/.exec(s)) !== null) { var v = parseInt(m[1], 10); var suffix; if (10 <= (v % 100) && (v % 100) <= 20) { suffix = 'th'; } else if (v % 10 === 1) { suffix = 'st'; } else if (v % 10 === 2) { suffix = 'nd'; } else if (v % 10 === 3) { suffix = 'rd'; } else { suffix = 'th'; }       return 'Deep: ' + m[1] + suffix + ' Impact'; }

var re = /^(.+?) - (.+)$/g; m = re.exec(s); if (m !== null) { if (/:/.test(s)) { return m[1] + ' \u2013 ' + m[2]; } else if (m[1].replace(/[^A-Z]/g, ) === m[2].replace(/[^A-Z]/g, )               && mma.getEventNumber(m[1], m[2]) !== null) { return mma.stripEventNumber(m[2]) + mma.getEventNumber(m[1], m[2]); } else if (mma.stripEventNumber(m[1]).toLowerCase === mma.stripEventNumber(m[2]).replace(/(.)(?:[^ ]+ |[^ ]+$)/g, '$1').toLowerCase               && mma.getEventNumber(m[1], m[2]) !== null) { return mma.stripEventNumber(m[2]) + mma.getEventNumber(m[1], m[2]); } else { return m[1] + ': ' + m[2]; }   }    return s; };

mma.getEventNumber = function(left, right) { var i, j;   for (i = left.length - 1; /\d/.test(left.substring(i, i + 1)); i--) { }   for (j = right.length - 1; /\d/.test(right.substring(j, j + 1)); j--) { }   var a = left.substring(i + 1); var b = right.substring(j + 1); var rv; if (a === '') { rv = b;   } else if (b === '') { rv = a;   } else if (a === b) { rv = a;   } else { return null; }   return (rv ===  ?  : ' ') + rv; };

mma.stripEventNumber = function(m) { var i;   for (i = m.length - 1; /\d/.test(m.substring(i, i + 1)); i--) { }   return m.substring(0, i + 1).replace(/(^\s+|\s+$)/g, ''); };

mma.getLocation = function(src) { var i = src.indexOf('SpacerLeftBottom8'); var j = src.indexOf('>', i) + 1; var k = src.indexOf(' ', j); var full = src.substring(j, k); var iTag = full.lastIndexOf('>'); if (iTag > -1) { full = full.substring(iTag + 1).replace(/(^\s+|\s+$)/g, ''); }   return full; };

mma.getMMArecordbox = function(src) { var keys = ['ko-wins', 'sub-wins', 'dec-wins', 'ko-losses', 'sub-losses', 'dec-losses']; var map = []; for (var i = 0; i < keys.length; i++) { map[keys[i]] = ''; }

var iWins = src.search(/]+>\s*Wins\s*<\/td>/); if (iWins > -1) { var iLeft = src.indexOf('<td', iWins + 1); var iRight = src.indexOf(' ', iLeft); var methodCount = mma.getMethodCount(src.substring(iLeft, iRight)); if (methodCount['(T)KOs'] !== undefined) { map['ko-wins'] = methodCount['(T)KOs']; }       if (methodCount['Submissions'] !== undefined) { map['sub-wins'] = methodCount['Submissions']; }       if (methodCount['Decisions'] !== undefined) { map['dec-wins'] = methodCount['Decisions']; }       if (methodCount['Other'] !== undefined) { keys.push('OTHER_WINS'); map['OTHER_WINS'] = methodCount['Other']; }   }    var iLosses = src.search(/]+>\s*Losses\s*<\/td>/); if (iLosses > -1) { var iLeft = src.indexOf('<td', iLosses + 1); var iRight = src.indexOf(' ', iLeft); var methodCount = mma.getMethodCount(src.substring(iLeft, iRight)); if (methodCount['(T)KOs'] !== undefined) { map['ko-losses'] = methodCount['(T)KOs']; }       if (methodCount['Submissions'] !== undefined) { map['sub-losses'] = methodCount['Submissions']; }       if (methodCount['Decisions'] !== undefined) { map['dec-losses'] = methodCount['Decisions']; }       if (methodCount['Other'] !== undefined) { keys.push('OTHER_LOSSES'); map['OTHER_LOSSES'] = methodCount['Other']; }   }    var output = ''; return output; };

mma.getMethodCount = function(s) { var rv = []; s = s.replace(/(<[^>]+>|\n)/g, ''); var methods = s.split(/\( *\d+(\.\d+)? *% *\)/);   for (var i = 0; i < methods.length; i++) { if (/^ *\d+ +/.test(methods[i])) { var mid = methods[i].search(/\d /) + 1; var count = methods[i].substring(0, mid).replace(/(^\s+|\s+$)/g, ''); var method = methods[i].substring(mid).replace(/(^\s+|\s+$)/g, ''); rv[method] = count; }   }    return rv; }

mma.wikifyLocation = function(loc) { if (/(Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|Florida|Georgia|Hawaii|Idaho|Illinois|Indiana|Iowa|Kansas|Kentucky|Louisiana|Maine|Maryland|Massachusetts|Michigan|Minnesota|Mississippi|Missouri|Montana|Nebraska|Nevada|New Hampshire|New Jersey|New Mexico|New York|North Carolina|North Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Rhode Island|South Carolina|South Dakota|Tennessee|Texas|Utah|Vermont|Virginia|Washington|West Virginia|Wisconsin|Wyoming)$/.test(loc)) { loc += ', United States'; } else if (/(British Columbia|Alberta|Saskatchewan|Manitoba|Ontario|Quebec|Nova Scotia|New Brunswick|Prince Edward Island|Newfoundland|Yukon|Northwest Territorids|Nunavut)/.test(loc)) { loc += ', Canada'; }   return loc.replace(/^([^,]+), ([^,]+), ([^,]+)$/, '$1, $2, $3') .replace(/^([^,]+), ([^,]+)$/, '$1, $2'); }; mma.recmethod = function { var columns = [ {name: 'Method', sherdogIndex: 2, templateIndex: 3}, {name: 'Round', sherdogIndex: 5, templateIndex: 6}, {name: 'Time', sherdogIndex: 6, templateIndex: 7} ];   for (var i in columns) { columns[i].index = -1; columns[i].regex = new RegExp('.+?\\b' + columns[i].name                   + '\\b'); }   var tb = document.getElementById('wpTextbox1'); var tableStart = tb.value.indexOf('\n{|'); var tableEnd = tb.value.indexOf('\n|}', tableStart); if (tableStart === -1 || tableEnd === -1) { tableStart = tb.value.indexOf('-start}}'); tableEnd = tb.value.indexOf('-end}}'); if (tableStart === -1 || tableEnd === -1) { tableStart = tb.value.indexOf('', tableStart); if (tableStart === -1 || tableEnd === -1) { window.alert('Record table not found.'); } else { for (var i in columns) { columns[i].index = columns[i].templateIndex; }           }        }    }    var i = tableStart; if (columns[0].index === -1) { // Find the lines that look like a column heading var count = 0; // Number of cells seen in this row so far while (i > -1) { var i1 = tb.value.indexOf('\n|', i + 1); var i2 = tb.value.indexOf('\n!', i + 1); if (i1 === -1) { i1 = tableEnd; }           if (i2 === -1) { i2 = tableEnd; if (i1 === i2) { // No more cells found in source break; }           }            i = Math.min(i1, i2); if (tb.value[i + 2] === '-') { count = 0; } else { for (var j = 0; j < columns.length; j++) { if (columns[j].regex.test(tb.value.substring(i, tb.value.indexOf('\n', i + 1)))) { columns[j].index = count; break; }               }                count++; }       }    }    for (var i in columns) { if (columns[i].index === -1) { window.alert('"' + columns[i].name + '" column not found.'); return; }   }    window.alert('Debug: Found Method/Round/Time at index ' + columns[0].index            + '/' + columns[1].index + '/' + columns[2].index); var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest; } else { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); }   xmlhttp.onreadystatechange = function { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { // Get fight data from external site var src = xmlhttp.responseText; var fights = mma.getFights(src); var fightIndex = 0; var count = 0;

// Column indices var OPPONENT = 1, DATE = 4; var i = tableStart; while ((i = tb.value.indexOf('\n|', i + 1)) > -1 && i < tableEnd) { if (tb.value[i + 2] === '-') { count = 0; } else { for (var j = 0; j < columns.length; j++) { if (count === columns[j].index) { var contentStart = i + 2; // Immediately after pipe var endLine = tb.value.indexOf('\n', i + 1); var content = tb.value.substring(contentStart, endLine); if (/^[^\|\[\{\n]+\|/.test(content)) { // Evil hack for "align=center|" contentStart = tb.value.indexOf('|',                                       contentStart) + 1; content = tb.value.substring(contentStart, endLine); }                           content = content.replace(/(^\s+|\s+$)/g, ''); if (fightIndex > 0 || content.length > 0                                   && !/\{\{ *[Nn]\/A *\}\}/.test(content)) { // Ignore empty cell -- probably future fight for (var k in fights[fightIndex]) { fights[fightIndex][k] = mma.removeTags(fights[fightIndex][k]) .replace(/(^\s+|\s+$)/gm, ''); }                               if (mma.removeWikilinks(content).toLowerCase                                        !== fights[fightIndex][columns[j]                                        .sherdogIndex].toLowerCase) { if (window.confirm('For the ' + columns[j].name + ' of the bout vs. ' + fights[fightIndex][OPPONENT] + ' on ' + fights[fightIndex][DATE] + ':\nChange "' + content + '" to "'                                           + fights[fightIndex][columns[j].sherdogIndex]                                            + '"?')) { tb.value = tb.value.substring(0, contentStart) + ' ' + fights[fightIndex][columns[j].sherdogIndex] + tb.value.substring(endLine); }                               }                                if (j + 1 === columns.length) { fightIndex++; }                           }                            break; }                   }                    count++; }           }            window.alert('MMA record method script finished.'); }   };    var url = window.prompt('Enter the URL of the fighter\'s Sherdog profile',            'http://www.sherdog.com/fighter/'); xmlhttp.open('GET', url, true); xmlhttp.send; }; mma.removeTags = function(s) { return s.replace(/<[^>]+>/g, ''); }; mma.removeWikilinks = function(s) { return s.replace(/\[\[([^\[\]\|]+)\]\]/g, '$1') .replace(/\[\[[^\[\]\|]+\|([^\[\]\|]+)\]\]/g, '$1'); }; $(function {   if (document.forms.editform) {        mw.util.addPortletLink('p-tb', 'javascript:mma.recmethod', 'MMA record method', 't-mmarecmethod', 'Synchronize method column with Sherdog in record tables', , );        mw.util.addPortletLink('p-tb', 'javascript:mma.sherdogTable', 'Create record table from Sherdog', 't-mmasherdogtable', 'Create a record table using a fighter profile from Sherdog', , );    } });