/*
 * Javascript для заглавной страницы: блок новостей, блок "Онлайн"
 */

var newsTimer = null, activeNew, newsTab = 'mainNews';

var onlineBlock = {
    isMoving:     false,
    offset:       0,
    moreNext:     true,
    morePrevious: true,
    cellWidth:    117,
    cellCount:    8
};

var tableCallback = {
    viewSimpleResults: function() {},
    viewLastMatches: function() {},
    viewTeamStats: function() {},
    viewPlayerStats: function() {}
};

function getLastMatches()
{
    var select = document.getElementById('tournamentType');
    var value  = select.options[select.selectedIndex].value;
    (new ResultsTable(tableCallback)).viewLastMatches(value);

    return false;
}

function getResultsTable(useRound)
{
    var selYear = document.getElementById('tournamentYear');
    var year    = selYear.options[selYear.selectedIndex].value;
    if (!useRound) {
        (new ResultsTable(tableCallback)).viewSimpleResults(year);
    } else {
        var selRound = document.getElementById('tournamentRound');
        var round    = selRound.options[selRound.selectedIndex].value;
        (new ResultsTable(tableCallback)).viewSimpleResults(year, round);
    }

    return false;
}

function getTeamStatsTable(turnirName)
{
    var select = document.getElementById('youth' == turnirName? 'youthTeamCriteria': 'champTeamCriteria');
    var type   = select.options[select.selectedIndex].value;
    (new StatsTable(tableCallback)).viewTeamStats(turnirName, type);

    return false;
}

function getPlayerStatsTable(turnirName)
{
    var select = document.getElementById('youth' == turnirName? 'youthPlayerCriteria': 'champPlayerCriteria');
    var type   = select.options[select.selectedIndex].value;
    (new StatsTable(tableCallback)).viewPlayerStats(turnirName, type);

    return false;
}

$(document).ready(function() {

    var lastMatchesLoaded = false,
        champStatsLoaded  = false,
        youthStatsLoaded  = false;

    var onlineCallback = {
        generateHtml: function(ary) {
            var prefix = 'en' == onlineBlock.lang? 'http://www.rfpl.org/': '/';
            var html   = '';
            for (var i = 0; i < ary.length; i++) {
                html += '<td' + (ary[i].date_changed? ' class="datechanged"': '') + '><div><p class="time"><a href="' + prefix + ary[i].stage_url + '">'
                html += ary[i].stage_name + ' ' + ary[i].datetime + '</a>';
                if (ary[i].online_progress) {
                    html += '   &nbsp;&nbsp;<a href="' + prefix + 'reports/id' + ary[i].id + '" class="online">ON-LINE</a>';
                } else if (ary[i].online_finished) {
                    html += '   &nbsp;&nbsp;<a href="' + prefix + 'reports/id' + ary[i].id + '">' + ('en' == onlineBlock.lang? 'finished': 'завершён') + '</a>';
                }
                html += '</p><div class="comands"><a href="' + prefix + 'reports/id' + ary[i].id + '">';
                html += '<span>' + (null !== ary[i].online_goal1? '<span>' + ary[i].online_goal1 + '</span>': '');
                html += '<strong>' + ary[i].club1_name + '</strong></span>';
                html += '<span>' + (null !== ary[i].online_goal2? '<span>' + ary[i].online_goal2 + '</span>': '');
                html += '<strong>' + ary[i].club2_name + '</strong></span>';
                html += '</a></div></div></td>';
            }
            return html;
        },
        nextWeek: function(result) {
            if (!result || !result.date) {
                onlineBlock.moreNext = false;
                onlineBlock.isMoving = false;
            } else {
                onlineBlock.lastDate  = result.date;
                onlineBlock.count    += result.list.length;
                $('tr', $scrollList).append(this.generateHtml(result.list));
                $scrollList.animate(
                    {left: '-=' + onlineBlock.cellWidth + 'px'},
                    function () {
                        onlineBlock.isMoving = false;
                        onlineBlock.offset++;
                    }
                );
            }
        },
        previousWeek: function(result) {
            if (!result || !result.date) {
                onlineBlock.morePrevious = false;
                onlineBlock.isMoving     = false;
            } else {
                onlineBlock.firstDate  = result.date;
                onlineBlock.count     += result.list.length;
                onlineBlock.offset    += result.list.length;
                var left = parseInt($scrollList.css('left'));
                $('tr', $scrollList).prepend(this.generateHtml(result.list));
                $scrollList.css('left', left - onlineBlock.cellWidth * result.list.length);
                $scrollList.animate(
                    {left: '+=' + onlineBlock.cellWidth + 'px'},
                    function () {
                        onlineBlock.isMoving = false;
                        onlineBlock.offset--;
                    }
                );
            }
        }
    };

    function activate_new(obj){
        activeNew=obj;
        id = obj.attr("picture");
        title = obj.attr("title");
        href = obj.attr("href");
        $("#mainImg").attr("src", '/show.php?size=large&id='+id);
        $("#mainNewsTitle").html(title);
        $("#mainNewsHref1").attr("href", href);
        $("#mainNewsHref2").attr("href", href);
        $(".newsCont li").removeClass("active");
        obj.parent().addClass("active");
    }

    function start_news_timer() {
        newsTimer=setInterval(function(){
            if (activeNew.parent().next().length) {
                activate_new($(".nlist", activeNew.parent().next()));
            } else {
                switchNewsTab('mainNews' == newsTab? 'clubNews': 'mainNews');
            }
        }, 2000);
    }

    function switchNewsTab(tabId) {
        // убираем класс active у всех табов
        $('.newsBox .tabs li').removeClass('active');
        // ставим класс active вновь выбранному
        $('#' + tabId + 'Trigger').parents().slice(1,2).addClass('active');

        clearInterval(newsTimer);
        newsTab = tabId;
        if ('mainNews' == newsTab) {
            $('#mainNews').css('display', '');
            $('#mainNews li').removeClass('active');
            $('#clubNews').css('display', 'none');
        } else {
            $('#mainNews').css('display', 'none');
            $('#clubNews').css('display', '');
            $('#clubNews li').removeClass('active');
        }
        activate_new($('#' + newsTab + " .nlist").eq(0));
        start_news_timer();

        return false;
    }

    $(".nlist").each(function(){
        $(this).mouseover(function(){
            activate_new($(this));
            clearInterval(newsTimer);
        });
        $(this).mouseout(function(){
            start_news_timer();
        });
    });

    if($(".nlist").length){
        activeNew=$('#' + newsTab + " .nlist").eq(0);
        activeNew.parent().addClass("active");
        start_news_timer();
    }

    $('.newsBox .tabs a').bind('click', function(event) {
        switchNewsTab($(this).attr('id').replace(/Trigger$/, ''));
        return false;
    });

    var $scrollBox  = $('.resultsScrollBox');
    var $scrollList = $('.list', $scrollBox);
    $('.pointL', $scrollBox).live('click', function() {
        // находимся на первом элементе и недели кончились, либо ещё не закончилась анимация
        if ((0 == onlineBlock.offset && !onlineBlock.morePrevious)
            || onlineBlock.isMoving
        ) {
            return;
        }
        onlineBlock.isMoving = true;
        // находимся не на первом элементе
        if (0 < onlineBlock.offset) {
            $scrollList.animate(
                {left: '+=' + onlineBlock.cellWidth + 'px'},
                function () {
                    onlineBlock.isMoving = false;
                    onlineBlock.offset--;
                }
            );
        // находимся на первом элементе, подгружаем предыдущую неделю
        } else {
            (new Online(onlineCallback)).previousWeek(onlineBlock.firstDate, onlineBlock.lang);
        }
    });

    $('.pointR', $scrollBox).live('click', function() {
        // находимся на последнем элементе и недели кончились, либо ещё не закончилась анимация
        if ((onlineBlock.offset >= onlineBlock.count - onlineBlock.cellCount)
            && !onlineBlock.moreNext || onlineBlock.isMoving
        ) {
            return;
        }
        onlineBlock.isMoving = true;
        // находимся не на последнем элементе
        if (onlineBlock.offset < onlineBlock.count - onlineBlock.cellCount) {
            $scrollList.animate(
                {left: '-=' + onlineBlock.cellWidth + 'px'},
                function () {
                    onlineBlock.isMoving = false;
                    onlineBlock.offset++;
                }
            );
        // находимся на последнем элементе, подгружаем следующую неделю
        } else {
            (new Online(onlineCallback)).nextWeek(onlineBlock.lastDate, onlineBlock.lang)
        }
    });

    $('#SixLastMtchTrigger').bind('click', function(event) {
        if (!lastMatchesLoaded) {
            getLastMatches();
            lastMatchesLoaded = true;
        }
    });
    $('#ChampStatsTrigger').bind('click', function(event) {
        if (!champStatsLoaded) {
            getTeamStatsTable('champ');
            getPlayerStatsTable('champ');
            champStatsLoaded = true;
        }
    });
    $('#YouthStatsTrigger').bind('click', function(event) {
        if (!youthStatsLoaded) {
            getTeamStatsTable('youth');
            getPlayerStatsTable('youth');
            youthStatsLoaded = true;
        }
    });

    getResultsTable(false);
});