var Channels = new Array();
var Program  = new Array();
var Ratings = new Array();
var StopPressed = false;
var GlTimer, AjaxTimer, CurrentChannel, CurrentMode = 'tvnow', BestCache = '', i;
var jsimg='<div><img src="/i/ajax/tvajax.gif" style="position:relative;left:195px;" alt="Загрузка..." align="center" /></div>';


function initRatings(data) {
    Ratings = data;
}

function initTvProgram()
{
    Channels[-1] = -1;
    var tmpi = 0;
    $('#channel-icons .frame').each(function(i1,val){if ($(val).hasClass('tv')) { Channels[tmpi] = $(val).attr('id').toString().substring(4); tmpi++;} });
    CurrentChannel = 2;

    $('#tv-arrow-right a').bind('click', function(e){StopPressed = true;cRight();});
    $('#tv-arrow-left a').bind('click', function(e){StopPressed = true;cLeft();});

    $('#tv-arrow-right a').bind('mousedown', function(e){cRightFast();});
    $('#tv-arrow-left a').bind('mousedown',  function(e){cLeftFast();});

    $('#tv-arrow-right a, #tv-arrow-left a').bind('mouseout', function(e){globalStop();});
    $('#tv-arrow-right a, #tv-arrow-left a').bind('mouseup', function(e){globalStop();});

    showRating();
};

function ajaxClear()
{
    clearTimeout(AjaxTimer);
    AjaxTimer = setTimeout('ajaxLoad()', 400);
}

function showRating() {
    var cid = Channels[CurrentChannel];
    if (!cid)
        return;
    var r = typeof Ratings[cid] == "undefined" ? 0 : Ratings[cid];
    var stars = $('#tv-program .stars').children();
    for (i = 1; i <= stars.length; i++) {
        var star = $(stars[i-1]);
        star.removeClass('star').removeClass('star-d').addClass( i * 10 <= r ? 'star' : 'star-d' );
        if (star.attr('href'))
            star.attr('href', star.attr('href').replace(/channel=\d*/, 'channel=' + cid));
    }
}

function ajaxLoad(showAll)
{
    showRating();
    if (typeof(Program[Channels[CurrentChannel]]) == 'undefined')
    {
        if ($('#tvblock').html() != jsimg && CurrentMode == 'tvnow')
        {
            $('#tvblock').html('').html(jsimg);
        }
        var data = {'canal_id':Channels[CurrentChannel]};
        if (showAll == true) data['show_all'] = 1;
        $.getJSON('/json/', data,
            function (data)
            {
                Program[data.channel_id] = data.program;
                if (data.channel_id == Channels[CurrentChannel]) showChannel(data.is_all);
            }
        );
    }
    else
    {
        showChannel();
    }
}

function showChannel(is_all)
{
    if (CurrentMode == 'tvnow')
    {
        $('#tvblock').html('');
        var tmpp = Program[Channels[CurrentChannel]];
        for (var i = 0; i < tmpp.length; i++)
        {
            $('<dt />').html(tmpp[i].programtime).appendTo('#tvblock');
            var tmph = $('<dd />').html(tmpp[i].name);
            if (tmpp[i].anons)
            {
                $('<a href="" id="tva_'+Channels[CurrentChannel]+'_'+i+'">&nbsp;<img src="/i/plus.gif" alt=" + " /></a>').appendTo(tmph);
                tmph.appendTo('#tvblock');
                $('<dd id="tvdd_'+Channels[CurrentChannel]+'_'+i+'" class="closed">').html('<b>'+tmpp[i].anons+'</b>').insertAfter($('<dt id="tvdt_'+Channels[CurrentChannel]+'_'+i+'" class="closed">').html('&nbsp;').appendTo('#tvblock'));
                $('#tva_'+Channels[CurrentChannel]+'_'+i).bind('click', function(){var id=this.id.substr(4);$('#tvdt_'+id+', #tvdd_'+id).removeClass('closed');$('#tva_'+id).html('');return false;});
            }
            else
            {
                tmph.appendTo('#tvblock');
            }
        }
        if (tmpp.length == 0) $('<dd>Дальнейшей программы на сегодня нет</dd>').appendTo('#tvblock');
        if ((is_all == '' && tmpp.length >= 3) || (tmpp.length <= 3 && tmpp.length > 0))
        {
            $('<dd><a href="javascript:void(0);" onclick="showAll()" id="showall">Показать всю программу на сегодня</a></dd>').appendTo('#tvblock');
        }
    }
}

function showAll()
{
    delete(Program[Channels[CurrentChannel]]);
    ajaxLoad(1);
}

function cLeft(chk)
{
    if (chk && StopPressed) return;
    if ((CurrentChannel <= 2 && CurrentChannel > 0) || (CurrentChannel > Channels.length - 3 && CurrentChannel < Channels.length + 1))
    {
        $('#mainframe').animate({'left':'-=56px'}, 'fast');
    }
    else if (CurrentChannel >= 3)
    {
        $('#tvp_'+(Channels[CurrentChannel-4])+' img').css({'display':'inline'});
        $('#tvp_'+(Channels[CurrentChannel-4])).animate({'width':'56px'}, 'fast');
    }
    else return;
    ajaxClear();
    CurrentChannel--;
};

function cRight(chk)
{
    if (chk && StopPressed) {return;}
    if ((CurrentChannel >= 0 && CurrentChannel < 2) || (CurrentChannel > Channels.length - 4 && CurrentChannel < Channels.length - 1))
    {
        $('#mainframe').animate({'left':'+=56px'}, 'fast');
    }
    else if (CurrentChannel >= 2 && CurrentChannel <= Channels.length - 4)
    {
        $('#tvp_'+Channels[CurrentChannel-3]).animate({'width':'0px'}, 'fast');
        $('#tvp_'+(Channels[CurrentChannel-3])+' img').css({'display':'none'});
    }
    else return;
    ajaxClear();
    CurrentChannel++;
};

function globalStop(l)
{
    clearTimeout(GlTimer);
    StopPressed = true;
};

function cRightFast()
{
    StopPressed = false;
    GlTimer = setTimeout('cRightFastTimer()', 400);
};
function cRightFastTimer()
{
    if (StopPressed) {clearTimeout(GlTimer);return;}
    if (!StopPressed) cRight(true);
    if (!StopPressed) GlTimer = setTimeout('cRightFastTimer()', 150);
};
function cLeftFast()
{
    StopPressed = false;
    GlTimer = setTimeout('cLeftFastTimer()', 400);
};
function cLeftFastTimer()
{
    if (StopPressed) {clearTimeout(GlTimer);return;}
    if (!StopPressed) cLeft(true);
    if (!StopPressed) GlTimer = setTimeout('cLeftFastTimer()', 150);
};

function changeMode(mode)
{
    CurrentMode = mode;
    if (mode == 'best')
    {
        $('#tv-widjet').addClass('closed');
        $('#selector').attr('id', 'selector-invert');
        $('#best').replaceWith('<span id="best">'+$('#best').html()+'</span>');
        $('#tvnow').replaceWith('<a href="javascript:void(0);" onclick="changeMode(\'tvnow\');" id="tvnow" >'+$('#tvnow').html()+'</a>');
        if (BestCache != '')
        {
            showBest();
        }
        else
        {
            $('#tvblock').html(jsimg);
            $.getJSON('/json/', {'what':'best'},
                function (data)
                {
                    var tmp = $('<div><br/></div>');
                    BestCache = '';
                    for (i = 0; i < data.best.length; i++)
                    {
                        $('<dt />').html(data.best[i].programtime).appendTo(tmp);
                        $('<dd />').html(data.best[i].name_ru+': '+data.best[i].name+'<a href="" class="bestplus" id="tva_'+data.best[i].program_id+'">&nbsp;<img src="/i/plus.gif" alt=" + " /></a>').appendTo(tmp);
                        $('<dd id="tvdd_'+data.best[i].program_id+'" class="closed">').html('<b>'+data.best[i].anons+'</b>').insertAfter($('<dt id="tvdt_'+data.best[i].program_id+'" class="closed">').html('&nbsp;').appendTo(tmp));
                    }
                    BestCache = tmp.html();
                    showBest();
                }
            );
         }
    }
    else
    {
        $('#tv-widjet').removeClass('closed');
        $('#selector-invert').attr('id', 'selector');
        $('#tvnow').replaceWith('<span id="tvnow">'+$('#tvnow').html()+'</span>');
        $('#best').replaceWith('<a href="javascript:void(0);" onclick="changeMode(\'best\');" id="best" >'+$('#best').html()+'</a>');
        $('#tvblock').html('');
        ajaxLoad();
    }
}
function showBest()
{
    if (CurrentMode == 'best')
    {
        $('#tvblock').html(BestCache);
        $('.bestplus').bind('click', function(){var id=this.id.substr(4);$('#tvdt_'+id+', #tvdd_'+id).toggleClass('closed');$('#tva_'+id).html('&nbsp;<img src="/i/'+($('#tvdt_'+id).hasClass('closed') ? 'plus.gif" alt=" + "' : 'minus.gif" alt=" - "')+' />');return false;});
    }
}