/**
 *  Скрипты для работы с трансляцией
 */

var LoadupJSBroadcast = {

    is_play: false,
    duration: 0,
    duration_redraw_interval: null,
    currentTime: false,
    beginDate: null,

    sendSyncData: function (data)
    {
        if (js_debug && console)
            console.log('LoadupJSBroadcast.sendSyncData(', data, ')');

        this.redrawData(data);
    },

    sendPassProtected: function ()
    {
        hideChat();
    },

    sendPassSend: function (param)
    {
        loadChat(param[0], param[1])
    },

    sendOnDelete: function ()
    {
        document.location.reload();
    },

    sendNoModerated: function ()
    {
        document.location.reload();
    },

    sendPlay: function (beginDate)
    {
        this.beginDate = beginDate;
        $('broadcast_begin_date').update(this.formatDate(beginDate));
        this.is_play = true;
        if ( this.duration == -1)
            this.duration = 0;
        this.drawDuration();
        if (this.duration_redraw_interval)
            window.clearInterval(this.duration_redraw_interval);
        $('broadcast_play_activity').show();
        $('broadcast_play_end').hide();
        this.duration_redraw_interval =  setInterval(this.redrawDuration.bind(this), 15000);
    },

    drawDuration: function()
    {
        $('broadcast_play_duration').update(this.getTimeFromSeconds(this.duration));
    },

    redrawDuration: function()
    {
       if (this.duration > -1)
       {
            this.duration += 15;
            this.drawDuration();
       }
    },

    sendMaxOnliners: function (data)
    {
        $('broadcast_count_views_max').update(data.max);
        if (data.maxDate)
            $('broadcast_count_views_max_date').update(this.formatDate(data.maxDate));
    },

    sendOnliners: function (count)
    {
        $('broadcast_count_views').update(count);
    },

    sendStop: function ()
    {
        this.is_play = false;
        $('broadcast_play_activity').hide();
        $('broadcast_play_end').show();
        this.duration = 0;
        if (this.duration_redraw_interval)
            window.clearInterval(this.duration_redraw_interval);
    },

    getTimeFromSeconds: function (time) {
        var secs = time % 60;
        var mins = (time - secs) / 60;
        var hours = (time - mins * 60 - secs) / 60;

        return (hours ? hours + " " + str_hour + " " : "") + ( mins ? mins + " " + str_min : "") + (!mins && !hours ? " " + secs + " " + str_sec : "") ;
    },


    formatDate: function(time, format)
    {
        var u = new Date(time * 1000);

        if (isNaN(u.getTime()))
            return '';

        var t = new Date(Number(this.currentTime) * 1000);
        var y = new Date(t - 1000 * 24 * 60 * 60);
        var isToday     = (u.getDate() == t.getDate()) && (u.getMonth() == t.getMonth()) && (u.getYear() ==t.getYear());
        var isYesterday = (u.getDate() == y.getDate()) && (u.getMonth() == y.getMonth()) && (u.getYear() ==y.getYear());

        var min  = u.getMinutes()+'';
        var hour = u.getHours()+'';

        min  = min.length == 2 ? min : '0'+min;
        hour = hour.length == 2 ? hour : '0'+hour;

        if (isToday)
            return str_today + ' ' + hour+':'+min;

        if (isYesterday)
            return str_yesterday + ' '+hour+':'+min;

        day  = u.getDate()+'';
        mon  = u.getMonth()+'';
        year = u.getFullYear()+'';

        day  = day.length == 2 ? day : '0'+day;
        mon  = mon.length == 2 ? mon : '0'+mon;

        if (!format)
            format = 'd.m.y h:I';

        return format.replace(/d/g, day).replace(/m/g, mon).replace(/y/g, year).replace(/h/g, hour).replace(/I/g, min);
    },

    // перерисовать новые данные
    redrawData: function (data)
    {
        if ('title' in data)
        {
            var title = data.title ? data.title : '';
            $('broadcast_title').down('span').update(title.escapeHTML());
        }

        if ('description' in data)
        {
            var description = data.description ? data.description : '';
            $('broadcast_description').down('span').update(description.escapeHTML());
        }

        if ('rubric_link' in data)
        {
            var rlink = $('broadcast_rubric').down('a');
            rlink.update(data.rubric_name.escapeHTML());
            rlink.href = data.rubric_link.escapeHTML();
        }
    },

    sendCodeProtected: function(code)
    {
        $('broadcast_player').sendCodeProtected(code);
    },

    codeProtectedReject: function()
    {

    }
}

var BroadcastClass = Class.create();
BroadcastClass.prototype = {

    flash_vars: {},
    flash_params: {},
    so: null,
    // кол-во юзеров
    count_view: 0,
    // начало трансляции
    begin_date: '',
    // длительность
    play_time: '',
    // статус трансляции
    status: null,
    // попап жалобы
    popup_id: 'complaint_div',

    sync_status_timer: null,
    pass: null,

    initialize: function(id, type, status, bgcolor) {
        this.id = id;
        this.type = type;
        this.status = status;
        this.bgcolor = bgcolor;
    },

    is_play: function() {
        return this.type == 'play';
    },

    is_save: function() {
        return this.type == 'save';
    },

    addFlashVar: function(name, value) {
        this.flash_vars[name] = value;
    },

    addFlashParam: function(name, value) {
        this.flash_params[name] = value;
    },

    drawFlash: function(file) {
        var h = 330;

        $("flashcontent").setStyle(
            {height : h + 'px'}
        );

        this.so = new SWFObject(file, "broadcast_player", 400, h, "8", this.bgcolor);
        for (val in this.flash_vars)
            this.so.addVariable(val, this.flash_vars[val]);
        for (val in this.flash_params)
            this.so.addParam(val, this.flash_params[val]);

        this.so.write("flashcontent");
    },



    setNoPlay: function()
    {
        this.status = 4;
    },


    // not work in IE
    complaint: function(obj)
    {
        pp_control.runPopup(obj, this.popup_id, {
            showTimeout: 0,
            noMouseEvent: true
        });
    },

    complaint_send: function(form)
    {
        var param = {
            id: escape(this.id)
        };

        for (var i=0; i<form.elements.length; i++)
            param[form.elements[i].name] = form.elements[i].value;

        var obj = this;
        new Ajax.Request('/broadcast/ajax/complaint/send/',
        {
            method: 'post',
            parameters: param,
            asynchronous:true,
            onSuccess: function (transport, ret)
            {
                var time = new Date();
                if (!ret.captcha_error) {
                    pp_control.hidePopup(obj.popup_id);
                    $('broadcast_complaint_link').hide();
                    if ($('captcha_key')) {
                        $('error_kod').hide();
                        UpdateImage('captcha_img', '/profile/captcha?'+time.getTime());
                    }
                }
                else
                {
                    if ($('captcha_key')) {
                        $('error_kod').show();
                        $('captcha_key').focus();
                        UpdateImage('captcha_img', '/profile/captcha?'+time.getTime());
                    }
                }
            }
        });
    },

    passSend: function(pass)
    {
        this.pass = pass;
        this.start_sync_status_timer();
    },

    setModerated: function(status, el)
    {
        if (status != 'no' && status != 'close')
            return;

        var matter = "";

        if (status == 'no')
        {
            matter = window.prompt("Причина блокировки?", "");

            if (matter == undefined || matter == null || matter == "")
            {
                return false;
            }
        }

        $(el).update('... обработка');
        new Ajax.Request('/broadcast/ajax/moderate/' + status + '/', {
            method: 'post',
            parameters: { id : this.id, matter : matter },
            onSuccess: function (transport)
            {
                $(el).update('Завершено');
                if (transport.headerJSON && transport.headerJSON.msg)
                    alert(transport.headerJSON.msg);
            }
        });
    },

    sendChatMess: function(mess)
    {
        $('broadcast_player').sendMessage(mess);
    }
}

// Все ссылки должны открываться в новом окне.
function setLinkTargets()
{
    var links = document.getElementsByTagName('A');
    var className = '';
    for (var i = 0; i < links.length; i++)
    {
        className = ' '+links[i].className+' ';
        if (!className.match(' currentw '))
            links[i].target = '_blank';
        else
            links[i].target = '_self';
    }
    var forms = document.getElementsByTagName('FORM');
    for (i = 0; i < forms.length; i++)
    {
        if (forms[i].className == 'SearchForm')
            forms[i].target = '_blank';
    }

    $('LoadVideoButton').onclick = function() {window.open('/video/upload/')};
}

var broadcastListInterval = null;
function startBroadcastListUpdater(func)
{
    broadcastListInterval = setInterval(func, 60000);
}

function debug(mess)
{
    $('debug').innerHTML += mess + "<br>";
}

function showBroadcastCreatePopup(obj, popup_offsetx, popup_offsety)
{
    var id = 'broadcast_create_popup';
    if(!popup_offsetx)
        popup_offsetx = -220;
    if(!popup_offsety)
        popup_offsety = 0;
    clonePosition($('broadcast_create_popup'), obj, {offsetLeft: popup_offsetx, offsetRight: popup_offsety} );
    $('broadcast_create_popup').show();
}

function showComplaintPopup(obj, popup_offsetx, popup_offsety)
{
    var id = 'complaint_div';
    if(!popup_offsetx)
        popup_offsetx = 300;
    if(!popup_offsety)
        popup_offsety = -300;
    clonePosition($(id), obj, {offsetLeft: popup_offsetx, offsetTop: popup_offsety} );

    // kostil'
    pp_control.runPopup(
            obj
          , id
          , {showTimeout: 0, noMouseEvent: true}
    );
    $(id).show();
}
