/* Main tournaments script */
$(document).ready(function(){
    // Load bg image
    var img = new Image();
    img.src = '/images/tournament/gamebg.png';
    
    // Init Round tables
    initRound('.round-tourney');
    
    // Init Swiss tables
    initSwiss('.swiss-tourney');
})

function initSwiss(clsName)
{
    $(clsName).each(function(i){
        var playersNum = $(this).find('TR').size()-1;
        var tData = $(this).attr('rel').split('.');
        var toursNum = parseInt(tData[0]);
        var victoryPoint = tData[1];
        var lossPoint = tData[2];
        
        // Change nickname cell style
        $(this).find('TR TD:first-child').addClass('player-name');
        $(this).find('TR TD:nth-child(2)').addClass('player-icq');
        $(this).find('TR TD:nth-child(n+3)').addClass('pair-cell');
        $(this).find('TR TH:nth-child(n+3)').addClass('th-center');

        // Counting results
        var results = new Array();
        var places = new Array();
        var positions = new Array();
        $(this).find('TR:nth-child(n+2)').each(function(i){
            var sum = 0;
            var games = 0;
            var wins = 0;
            $(this).find('TD:nth-child(n+3)').filter('TD:not(:nth-child(n+' + (toursNum + 3) + '))').each(function(i){
                if($(this).html() != '')
                {
                    //alert('here');
                    sum = parseFloat($(this).html());
                }
            })
            $(this).find('TD:eq(' + (toursNum + 2) + ')').html(sum);
            results[i] = sum;
            places[i] = i+1;
            positions[i] = 1;
        });
        
        // Counting Buhgoltz's coefficient
        var bCoeff = new Array();
        $(this).find('TR:nth-child(n+2)').each(function(i){
            var coeff = 0;
            $(this).find('TD:nth-child(n+3)').filter('TD:not(:nth-child(n+' + (toursNum + 3) + '))').each(function(j){
                if($(this).html() != '')
                {
                    var indx = parseInt($(this).attr("rel")) - 1;
                    coeff += results[indx];
                }
            })
            $(this).find('TD:eq(' + (toursNum + 3) + ')').html(coeff);
            bCoeff[i] = coeff;
        });
        
        // Getting places
        var tmp = 0;
        for(i=0;i<=playersNum;i++)
        {
            for(j=playersNum;j>=0;j--)
            {
                if(i==j) continue;
                if((results[j] > results[i] && places[j] > places[i]) || (results[j] < results[i] && places[j] < places[i]))
                {
                    tmp = places[i];
                    places[i] = places[j];
                    places[j] = tmp;
                }
                
                // Places switch (depends on Buhgoltz)
                if((results[j] == results[i] && bCoeff[j] > bCoeff[i] && places[j] > places[i]) || (results[j] == results[i] && bCoeff[j] < bCoeff[i] && places[j] < places[i]))
                {
                    tmp = places[i];
                    places[i] = places[j];
                    places[j] = tmp;
                }
            }
        }
        for(i=0;i<=playersNum;i++)
        {
            for(j=0;j<=playersNum;j++)
            {
                if(i==j) continue;
                if(results[i] == results[j] && bCoeff[i] == bCoeff[j])
                {
                    if(places[i] < places[j]) places[j] = places[i];
                    if(places[j] < places[i]) places[i] = places[j];
                    positions[i]++;
                } 
            }
        }
        //alert(places);
        for(i=0;i<playersNum;i++)
        {
            if(places[i] == 1)
            {
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:last').addClass('leader-cell').addClass('places-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (toursNum + 2) + ')').addClass('leader-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (toursNum + 3) + ')').addClass('leader-cell');
            }
            if(places[i] == 2)
            {
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:last').addClass('silver-cell').addClass('places-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (toursNum + 2) + ')').addClass('silver-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (toursNum + 3) + ')').addClass('silver-cell');
            }
            if(places[i] == 3)
            {
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:last').addClass('bronze-cell').addClass('places-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (toursNum + 2) + ')').addClass('bronze-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (toursNum + 3) + ')').addClass('bronze-cell');
            }
            if(positions[i] != 1) places[i] = places[i] + '-' + parseInt(places[i] + positions[i] - 1);
        }
        for(i=0;i<playersNum;i++)
        {
            $(this).find('TR:eq(' + (i+1) + ')').find('TD:last').html(places[i]).addClass('places-cell');
        }
        
        // Filling empty cells        
        $(this).find("TD:empty").html('&nbsp;');

        // Results style setting
        $(this).find("TD[rel]").each(function(){
            var cellX = $(this).prevAll('TD').size()-1;
            if(cellX > toursNum) return false;
            
            if($(this).html() == cellX) $(this).addClass('cell-winner');
            $(this).append('<div>' + $(this).attr('rel') + '</div>');
        });
        
        
        // Hover actions modelling
        $(this).find('.pair-cell').hover(
            function(){
                // Get coords
                var cellX = $(this).prevAll('TD').size()-1;
                if(cellX > toursNum) return false;
                if(!$(this).attr('rel') || $(this).attr('rel') == '') return false;
                
                // Get PlayerName
                var player = $(this).prevAll('TD:last').html();
                player = player.replace(/\d+\.\s/, '');

                // Get opponent name
                var opponent = $(this).parent().parent().find('TR:eq(' + $(this).attr('rel') + ')').children('TD:first').html();
                opponent = opponent.replace(/\d+\.\s/, '');
                
                // Show game details
                var pos = $(this).position();
                var top = parseInt(pos.top) - 69;
                var left = parseInt(pos.left) - 95;
                
                // Checking for host
                if($(this).hasClass('host'))
                {
                    var game = player + '&nbsp;&mdash;&nbsp;' + opponent;
                    var host = player;
                    $(this).addClass('pair-host-selected');
                    $(this).parent().parent().find('TR:eq(' + $(this).attr('rel') + ')').children('TD:eq(' + (cellX + 1) + ')').addClass('pair-join-selected');
                }
                else
                {
                    var game = opponent + '&nbsp;&mdash;&nbsp;' + player;
                    var host = opponent;
                    $(this).addClass('pair-join-selected');
                    $(this).parent().parent().find('TR:eq(' + $(this).attr('rel') + ')').children('TD:eq(' + (cellX + 1) + ')').addClass('pair-host-selected');
                }
                $('.pair').html(game);
                $('.whohost').html('хост: ' + host);
                $('.game').css({ 'top': top + 'px', 'left': left + 'px' }).show();
            },
            function(){
                $('.game').hide();
                $(this).parent().parent().find('TR TD:nth-child(n+3)').removeClass('pair-join-selected pair-host-selected');
            }
        );
    });    
}

function initRound(clsName)
{
    // Getting players num
    $(clsName).each(function(i){
        var playersNum = $(this).find('TR').size()-1;
        var infoAttr = $(this).attr('rel');
        if(infoAttr)
        {
            infoAttr = infoAttr.split(':');
        }
        
        // Getting points settings
        var pointsSet = $(this).attr('points');
        if(pointsSet)
        {
            pointsSet = pointsSet.split(':');    
        }
        
        // Getting mode
        var mode = $(this).attr('mode');

        // Change nickname cell style
        $(this).find('TR TD:first-child').addClass('player-name');
        $(this).find('TR TD:nth-child(2)').addClass('player-icq');
        $(this).find('TR TD:nth-child(n+3)').filter('TD:not(:nth-child(n+' + (playersNum + 3) + '))').addClass('pair-cell');
        $(this).find('TR TH:nth-child(n+3)').addClass('th-center');
        $(this).find('TR TH:nth-child(n+' + (3+playersNum) + ')').addClass('th-results');
        $(this).find('TR TD:nth-child(n+' + (3+playersNum) + ')').addClass('td-results');
        //$(this).find('TR:nth-child(2+n)').find('TD:eq(' + (playersNum + 3) + ')').addClass('points-cell');
        
        // Change results style
        $(this).find('TR TD').each(function(i){
            var cellX = $(this).prevAll('TD').size()-1;
            var cellY = $(this).parent().prevAll('TR').size();
            if(cellX == cellY) $(this).addClass('self');
            
            var opponent = $(this).parent().parent().children('TR:nth-child(' + (cellX + 1) + ')').children('TD:nth-child(' + (cellY+2) + ')');
            
            if($(this).html() == opponent.html()) $(this).addClass('cell-draw');
            if(parseInt($(this).html()) > parseInt(opponent.html())) $(this).addClass('cell-winner');
            if(parseInt($(this).html()) < parseInt(opponent.html())) $(this).addClass('cell-loser');
        });
        
        // Counting results
        var results = new Array();    // Games results
        var places = new Array();     // Places array
        var positions = new Array();  // Number of equals
        var playerWins = new Array(); // Victories number
        var bergerCoeff = new Array(); // Berger's coefficient
        
        $(this).find('TR:nth-child(n+2)').each(function(i){
            var sum = 0;
            var games = 0;
            var wins = 0;
            $(this).find('TD:nth-child(n+3)').filter('TD:not(:nth-child(n+' + (playersNum + 3) + '))').each(function(i){
                if($(this).html() != '' && $(this).html() != '—')
                {
                    var value = parseFloat($(this).html());
                    
                    var cellX = $(this).prevAll('TD').size()-1; 
                    var cellY = $(this).parent().prevAll('TR').size();
                    var opponentValue = $(this).parent().parent().children('TR:nth-child(' + (cellX + 1) + ')').children('TD:nth-child(' + (cellY + 2) + ')').html();
                    opponentValue = parseFloat(opponentValue);
                    
                    if(mode)
                    {
                        if(mode == 'duel') wins += value;
                    }
                    else
                    {
                        if(value > opponentValue) 
                        {
                            wins++;
                        }
                    }
                    
                    if(pointsSet)
                    {
                        if(value > opponentValue) sum += parseInt(pointsSet[2]);
                        if(value == opponentValue) sum += parseInt(pointsSet[1]);
                        if(value < opponentValue) sum += parseInt(pointsSet[0]);
                    }
                    else
                    {
                        sum += value;    
                    }
                    games++;
                }
            })
            $(this).find('TD:eq(' + (playersNum + 3) + ')').html(sum);
            $(this).find('TD:eq(' + (playersNum + 2) + ')').html(games + '/' + wins);
            results[i] = sum;
            places[i] = i+1;
            positions[i] = 1;
            playerWins[i] = wins;
        });
        
        // Counting Berger's coefficient
        $(this).find('TR:nth-child(n+2)').each(function(i){
            var coeff = 0;
            $(this).find('TD:nth-child(n+3)').filter('TD:not(:nth-child(n+' + (playersNum + 3) + '))').each(function(j){
                if($(this).html() != '' && $(this).html() != '—')
                {
                    var value = parseFloat($(this).html());
                    
                    var cellX = $(this).prevAll('TD').size()-1; 
                    var cellY = $(this).parent().prevAll('TR').size();
                    var opponentValue = $(this).parent().parent().children('TR:nth-child(' + (cellX + 1) + ')').children('TD:nth-child(' + (cellY + 2) + ')').html();
                    opponentValue = parseFloat(opponentValue);
                    
                    if(value > opponentValue) coeff += results[j];
                    if(value == opponentValue) coeff += results[j]/2;
                }
            })
            $(this).find('TD:eq(' + (playersNum + 3) + ')').append('/' + coeff);
            bergerCoeff[i] = coeff;
        });
        
        // Check for tough rings
        var equals = getToughEquals(results, $(this));
        
        if(equals.length > 0)
        {
            var tmpTable = $(this).html();
            for(h=0;h<equals.length;h++)
            {
                var eq = equals[h][0];
                var ex = equals[h][1];
                if(eq.length <= 2) 
                {
                    continue;
                }
                
                
                
                // Check if somebody has the highest Berger
                var maxwins = 0;
                var wLeader = -1;
                for(g=0;g<eq.length;g++)
                {
                    // Set the tmp results against the excluded ones
                    for(z=0;z<ex.length;z++)
                    {
                        $(this).find('TR:nth-child(' + (parseInt(eq[g]) + 2) + ')').find('TD:nth-child(' + (parseInt(ex[z]) + 3) + ')').html('100');
                        $(this).find('TR:nth-child(' + (parseInt(ex[z]) + 2) + ')').find('TD:nth-child(' + (parseInt(eq[g]) + 3) + ')').html('-1');
                    }
                    
                    if(playerWins[parseInt(eq[g])] > maxwins)
                    {
                        maxwins = playerWins[parseInt(eq[g])];
                        if(g!=0) wLeader = parseInt(eq[g]);
                    }
                    if(playerWins[parseInt(eq[g])] < maxwins && g == 1)
                    {
                        wLeader = parseInt(eq[0]);
                    }
                }
                
                if(wLeader != -1)
                {
                    for(g=0;g<eq.length;g++)
                    {
                        if(eq[g] == wLeader) continue; 
                        $(this).find('TR:nth-child(' + (wLeader + 2) + ')').find('TD:nth-child(' + (parseInt(eq[g]) + 3) + ')').html('100');
                        $(this).find('TR:nth-child(' + (parseInt(eq[g]) + 2) + ')').find('TD:nth-child(' + (wLeader + 3) + ')').html('-1');
                    }
                }
                else
                {
                    // Check if somebody has the highest Berger
                    var maxb = 0;
                    var bergerLeader = -1;
                    for(g=0;g<eq.length;g++)
                    {
                        if(bergerCoeff[parseInt(eq[g])] > maxb)
                        {
                            maxb = bergerCoeff[parseInt(eq[g])];
                            if(g!=0) bergerLeader = parseInt(eq[g]);
                        }
                        if(bergerCoeff[parseInt(eq[g])] < maxb && g == 1)
                        {
                            bergerLeader = parseInt(eq[0]);
                        }
                    }
                    
                    if(bergerLeader != -1)
                    {
                        for(g=0;g<eq.length;g++)
                        {
                            if(eq[g] == bergerLeader) continue; 
                            $(this).find('TR:nth-child(' + (bergerLeader + 2) + ')').find('TD:nth-child(' + (parseInt(eq[g]) + 3) + ')').html('100');
                            $(this).find('TR:nth-child(' + (parseInt(eq[g]) + 2) + ')').find('TD:nth-child(' + (bergerLeader + 3) + ')').html('-1');
                        }
                    }
                    else
                    {
                        for(g=0;g<eq.length;g++)
                        {
                            for(f=0;f<eq.length;f++)
                            {
                                if(f == g) continue;
                                $(this).find('TR:nth-child(' + (parseInt(eq[g]) + 2) + ')').find('TD:nth-child(' + (parseInt(eq[f]) + 3) + ')').html('100');
                            }
                        }
                    }
                }
            }
        }
        
        // Getting places
        var tmp = 0;
        for(i=0;i<playersNum;i++)
        {
            for(j=playersNum-1;j>=0;j--)
            {
                if(i==j) continue;
                
                // Places switch (depends on result)
                if((results[j] > results[i] && places[j] > places[i]) || (results[j] < results[i] && places[j] < places[i]))
                {
                    tmp = places[i];
                    places[i] = places[j];
                    places[j] = tmp;
                    continue;
                }
                
                // Places switch (depends on one-on-one match)
                var mRes1 = $(this).find('TR:nth-child(' + (i + 2) + ')').find('TD:nth-child(' + (j + 3) + ')').html();
                var mRes2 = $(this).find('TR:nth-child(' + (j + 2) + ')').find('TD:nth-child(' + (i + 3) + ')').html();
                if(mRes1 != '' && mRes2 != '')
                {
                    mRes1 = parseFloat(mRes1);
                    mRes2 = parseFloat(mRes2);
                    if((results[j] == results[i] && mRes2 > mRes1 && places[j] > places[i]) || (results[j] == results[i] && mRes2 < mRes1 && places[j] < places[i]))
                    {
                        tmp = places[i];
                        places[i] = places[j];
                        places[j] = tmp;
                        continue;
                    }
                }
                
                // Places switch (depends on wins number)
                if(mRes1 == mRes2)
                {
                    if((results[j] == results[i] && playerWins[j] > playerWins[i] && places[j] > places[i]) || (results[j] == results[i] && playerWins[j] < playerWins[i] && places[j] < places[i]))
                    {
                        tmp = places[i];
                        places[i] = places[j];
                        places[j] = tmp;
                        continue;
                    }
                }
                
                // Places switch (depends on Berger)
                if(playerWins[j] == playerWins[i] && mRes1 == mRes2)
                {
                    if((results[j] == results[i] && bergerCoeff[j] > bergerCoeff[i] && places[j] > places[i]) || (results[j] == results[i] && bergerCoeff[j] < bergerCoeff[i] && places[j] < places[i]))
                    {
                        tmp = places[i];
                        places[i] = places[j];
                        places[j] = tmp;
                    }
                }
            }
        }
        
        // Counting positions number
        for(i=0;i<=playersNum;i++)
        {
            for(j=0;j<=playersNum;j++)
            {
                if(i==j) continue;
                var mRes1 = $(this).find('TR:nth-child(' + (i + 2) + ')').find('TD:nth-child(' + (j + 3) + ')').html();
                var mRes2 = $(this).find('TR:nth-child(' + (j + 2) + ')').find('TD:nth-child(' + (i + 3) + ')').html();
                if(mRes1 != '' && mRes2 != '')
                {
                    mRes1 = parseFloat(mRes1);
                    mRes2 = parseFloat(mRes2);
                }
                else
                {
                    mRes1 = 0;
                    mRes2 = 0;
                }
                if(results[i] == results[j] && playerWins[i] == playerWins[j] && mRes1 == mRes2 && bergerCoeff[i] == bergerCoeff[j])
                {
                    if(places[i] < places[j]) places[j] = places[i];
                    if(places[j] < places[i]) places[i] = places[j];
                    positions[i]++;
                } 
            }
        }

        // Restore table after counting
        if(equals.length > 0)
        {
            $(this).html(tmpTable)
        }
        
        // Setting classes
        for(i=0;i<playersNum;i++)
        {
            if(places[i] == 1)
            {
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:last').addClass('leader-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (playersNum + 2) + ')').addClass('leader-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (playersNum + 3) + ')').addClass('leader-cell');
            }
            if(places[i] == 2)
            {
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:last').addClass('silver-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (playersNum + 2) + ')').addClass('silver-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (playersNum + 3) + ')').addClass('silver-cell');
            }
            if(places[i] == 3)
            {
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:last').addClass('bronze-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (playersNum + 2) + ')').addClass('bronze-cell');
                $(this).find('TR:eq(' + (i+1) + ')').find('TD:eq(' + (playersNum + 3) + ')').addClass('bronze-cell');
            }
            if(positions[i] != 1) places[i] = places[i] + '-' + parseInt(places[i] + positions[i] - 1);
        }
        for(i=0;i<playersNum;i++)
        {
            $(this).find('TR:eq(' + (i+1) + ')').find('TD:last').html(places[i]);
        }
        
        
        // Administration
        $(this).find('TR TD:nth-child(n+3)').dblclick(function(){
            if($(this).hasClass('self')) return false;
            
            // Get coords
            var cellX = $(this).prevAll('TD').size()-1;
            var cellY = $(this).parent().prevAll('TR').size();
            if(cellX > playersNum) return false;
            
            var psw = prompt('Пароль');
            var result = prompt('Результат');
            var resultOpp = prompt('Результат оппонента');
            
            // Set results
            $(this).html(result);
            $(this).parent().parent().children('TR:nth-child(' + (cellX + 1) + ')').children('TD:nth-child(' + (cellY+2) + ')').html(resultOpp);
            
            // Remove styles
            $(clsName).find('TD,TH,TR').attr('class', '');
            $(clsName).find('TD,TH,TR').dblclick(function(){});
            $(clsName).find('TR:nth-child(2+n)').find('TD:last').html('');
            $(clsName).find('TR:nth-child(2+n)').find('TD:eq(' + (playersNum + 2) + ')').html('');
            $(clsName).find('TR:nth-child(2+n)').find('TD:eq(' + (playersNum + 3) + ')').html('');
            $(clsName).find('.addon').remove();
            $('.game').hide();
            
            $('#content H1:first').remove();
            var content = $('#content').html();
            
            $.post(
                '/lib/table_update.php',
                { psw: psw, content: content, url: document.location.href },
                function(data)
                {
                    if(data == '-1')
                    {
                        alert('Неверный пароль');
                        top.location.href = document.location.href;
                    }
                    else
                    {
                        alert('Данные успешно сохранены');
                        top.location.href = document.location.href;
                    }
                }
            );
        });
        
        // Setting additional info
        if($(this).attr('addon'))
        {
            var field = $(this).attr('addon');
            $(this).find('td').each(function(){
                if($(this).attr(field))
                $(this).append('<div class="addon">' + $(this).attr(field) + '</div>');    
            });
        }
        
        // Hover actions modelling
        $(this).find('TR TD:nth-child(n+3)').mouseenter(
            function(){
                if($(this).hasClass('self')) return false;
                
                // Get coords
                var cellX = $(this).prevAll('TD').size()-1;
                var cellY = $(this).parent().prevAll('TR').size();
                if(cellX > playersNum) return false;
                
                // Get PlayerName
                var player = $(this).prevAll('TD:last').html();
                player = player.replace(/\d+\.\s/, '');

                // Get opponent name
                var opponent = $(this).parent().parent().children('TR:nth-child(' + (cellX + 1) + ')').children('TD:first').html();
                opponent = opponent.replace(/\d+\.\s/, '');
                
                // Show game details
                var pos = $(this).position();
                var top = parseInt(pos.top) - parseInt($('.game').height()) + 1;
                var left = parseInt(pos.left) - Math.round(parseInt($('.game').width()) / 2) + 4 + Math.round(parseInt($(this).width()) / 2);
                
                // Checking for host
                var playerX = cellX;
                if(cellX > cellY) playerX--;
                if((cellY % 2 == 0 && playerX % 2 == 0) || (cellY % 2 == 1 && playerX % 2 == 1))
                {
                    var game = player + '&nbsp;&mdash;&nbsp;' + opponent;
                    var host = player;
                    $(this).addClass('pair-host-selected');
                    $(this).parent().parent().children('TR:nth-child(' + (cellX + 1) + ')').children('TD:nth-child(' + (cellY+2) + ')').addClass('pair-join-selected');
                }
                else
                {
                    var game = opponent + '&nbsp;&mdash;&nbsp;' + player;
                    var host = opponent;
                    $(this).addClass('pair-join-selected');
                    $(this).parent().parent().children('TR:nth-child(' + (cellX + 1) + ')').children('TD:nth-child(' + (cellY+2) + ')').addClass('pair-host-selected');
                }
                

                $('.pair').html(game);
                $('.whohost').html('хост: ' + host);
                
                // Additional info
                if(infoAttr)
                {
                    $('.whohost').html(infoAttr[1] + ': ' + $(this).attr(infoAttr[0]));
                }
                $('.game').css({ 'top': top + 'px', 'left': left + 'px' }).show();
                
            }).mouseleave(function(){
                $('.game').hide();
                $(this).parent().parent().find('TR TD:nth-child(n+3)').removeClass('pair-join-selected pair-host-selected');
            }
        );
        
        $(this).mouseleave(function(){
            $('.game').hide();
        });
        
        $(this).find('tbody td:nth-col(' + (playersNum + 4) + ')').textAlign('/');
        $(this).find('tbody td:nth-col(' + (playersNum + 3) + ')').textAlign('/');
    });
    
}

// Check for round wins (1=>2=>3=>1)
function getToughEquals(results, object)
{
    var used = new Array();
    var equals = new Array();
    for(i=0;i<results.length-1;i++)
    {
        equals[i] = i;  // Set self
        for(j=results.length-1;j>i;j--)
        {
            // Check if player ID has been already logged by another player stack
            var br = false;
            for(k=0;k<used.length;k++)
            {
                if(used[k] == j) br = true;
            }
            if(br) continue;
            
            // Log player ID to player (i) stack
            if(results[j] == results[i])
            {
                equals[i] += '.' + j;
                used[used.length] = j;    
            }    
        }
    }
    
    // Submit equals to recursive checker 
    var neighbours = new Array();
    for(i=0;i<equals.length;i++)
    {
        var excludes = new Array();
        if(equals[i] == i) 
        {
            equals[i] = '';
            continue;
        };
        
        var set = equals[i].split('.');
        equals[i] = '';

        if(set.length <= 2) continue;
        neighbours[neighbours.length] = checkSetParity(set, object, excludes);
    }
    return neighbours;
}


// Recursive results equality checker
function checkSetParity(set, object, excludes)
{
    var summary = new Array();
    var size = set.length;
    for(i=0;i<size;i++)
    {
        summary[parseInt(set[i])] = 0;
        for(j=0;j<size;j++)
        {
            if(i==j) continue;
            var value = object.find('TR:nth-child(' + (parseInt(set[i]) + 2) + ')').find('TD:nth-child(' + (parseInt(set[j]) + 3) + ')').html();
            value = (value != '') ? parseFloat(value) : 0;
            summary[parseInt(set[i])] += value;
        }
    }
    
    // Checking for maximum
    var min = 1000; // minimal result
    var exclude = -1; // player to pop
    for(i=0;i<size;i++)
    {
        if(summary[set[i]] < min)
        {
            min = summary[set[i]];
            if(i != 0)
            {
                exclude = i;    
            }
        }    
        
        if(summary[set[i]] > min && i == 1)
        {
            if(i != 0)
            {
                exclude = 0;    
            }
        }    
    }
    
    // If there is minimal result then exclude it and repeat
    if(exclude != -1)
    {
        excludes[excludes.length] = set[exclude];
        var newSet = new Array();
        var k = 0;
        for(i=0;i<size;i++)
        {
            if(i != exclude) 
            {
                newSet[k] = set[i];    
                k++;
            }
        }
        var data = checkSetParity(newSet, object, excludes);
        set = data[0];
        excludes = data[1];
    }
    return new Array(set, excludes);
}