if (typeof Stickam === "undefined" || !Stickam ) {
    Stickam = {};
}

Stickam.headerOnairShow = {
    // Cookie,id が被らない為の接頭辞
    BASENAME: 'tvp',
    // ポップアップの表示時アニメーションの所用時間（秒）
    UPTIME: 2,
    // ポップアップの非表示時アニメーションの所用時間（秒）
    DOWNTIME: 2,
    // ポップアップの表示時間（秒）
    STAYTIME: 5,
    IMAGES: {
        tv: {
            title: '/images/ja/onair_show_title.gif',
            bg: '/images/ja/onair_show_bg.gif'
        },
        yy: {
            title: '/images/ja/yytv/onair_yyshow_title.gif',
            bg: '/images/ja/yytv/onair_yyshow_bg.gif'
        }
    },
    popups: [],
    process: function(idx) {
        var popup = this.popups[idx];
        var self = this;
        popup.animate(
            {top: '0px'},
            {duration: self.UPTIME * 1000,
             complete: function() {
                          setTimeout(
                              'Stickam.headerOnairShow.slideDown(' + idx + ')',
                              self.STAYTIME * 1000
                          );
                       }
            }
        );
    },
    slideDown: function(idx) {
        var popup = this.popups[idx];
        var self = this;
        popup.animate(
            {top: '250px'},
            {duration: self.DOWNTIME * 1000,
             complete: function() {
                           $(this).html('');
                           $(self.popups[idx].parent()).remove();
                       }
            }
        );
    }
};


// 配信中の番組をポップアップする
(function() {
    var player = {is_display: false,
                  is_yy: false,
                  is_tv: false,
                  event_username: '',
                  temp_event_username: '',
                  is_corporation: false};

    function onSuccess(result) {
        var myObj = Stickam.headerOnairShow;

        var includedTv = false;
        var cnt_pu = 0;

        for (var i = 0; i < result.onair_cnt; ++i) {
            var r = result[i];

            // TVを含んでいるかどうか？
            if (r.tv === 'yes') {
                includedTv = true;
                player.temp_event_username = r.user_name;

                player.is_corporation = r.is_corporation;
            }

            // 既にポップアップ通知したイベントは再通知しない
            var name = myObj.BASENAME + r.event_id;
            if ($.cookie(name)) {
                continue;
            }
            $.cookie(name, '1', {expires: 1/*day*/, path: '/'});

            // ポップアップ
            var bg_img_src    = (r.tv !== 'yes' && r.type) ? myObj.IMAGES[r.type].bg : myObj.IMAGES.tv.bg;
            var title_img_src = (r.tv !== 'yes' && r.type) ? myObj.IMAGES[r.type].title : myObj.IMAGES.tv.title;
            var alert_screen_name =
                $('<span/>')
                .css({
                    display: 'block',
                    width: '70%',
                    overflow: 'hidden',
                   'white-space': 'nowrap',
                   'text-overflow': 'ellipsis',
                   '-o-text-overflow': 'ellipsis',
                   fontWeight: 'bold'
                })
                .text(r.screen_name)
            var alert_title =
                $('<span/>')
                .css({
                    display: 'block',
                    width: '70%',
                    width: '100%',
                    overflow: 'hidden',
                   'white-space': 'nowrap',
                   'text-overflow': 'ellipsis',
                   '-o-text-overflow': 'ellipsis',
                   fontWeight: 'bold'
                })
                .text(r.title)
            var popup_alert =
                $('<div/>')
                .attr('id', name + '_alert')
                .css({position: 'relative',
                      width: '166px',
                      height: '78px',
                      top: '250px',
                      margin: '0',
                      padding: '7px 7px 0',
                      background: 'url(' + bg_img_src + ') top'})
                .append($('<a/>')
                        .attr({'href': '/', 'target': '_blank'})
                        .css({display: 'block',
                              paddingTop: '25px',
                              background: 'url(' + title_img_src + ') top no-repeat'})
                        .append($('<span/>')
                                .css({display: 'block',
                                      fontSize: '100%',
                                      color: '#06C',
                                      paddingLeft: '3px'})
                                .append(alert_screen_name)
                                .append($('<span/>').text('さんのTV')
                                                         .css({float: 'right', position: 'absolute', top: '30px', left: '120px'}))
                                .append(alert_title)
                                .append('が始まりました！')
                                .hover(function() {$(this).css({color: '#F60', textDecoration: 'none'     , cursor: 'pointer'});},
                                       function() {$(this).css({color: '#06C', textDecoration: 'underline', cursor: 'default'});})
                        )
                );

            var popup_background =
                $('<div/>')
                .attr('id', name + '_background')
                .css({position: 'fixed',
                      width: '180px',
                      height: '85px',
                      right: '0',
                      bottom: '0',
                      margin: '20px 10px 0 0',
                      overflow: 'hidden',
                      zIndex: 10 - i})
                .append(popup_alert);

            alert_screen_name.ellipsis(true);
            alert_title.ellipsis(true);

            $(document.body).append(popup_background);

            myObj.popups[cnt_pu] = popup_alert;

            setTimeout(
                'Stickam.headerOnairShow.process(' + cnt_pu + ')',
                1000 * (cnt_pu * (myObj.UPTIME + myObj.DOWNTIME + myObj.STAYTIME))
            );
            cnt_pu++;
        }

        // 番組中ならばサイトロゴ変更
        if (0 < result.onair_cnt) {
            var className = '';
            if (includedTv) {
                className = 'stickamlogo_onair';

                if (!player.is_display || !player.is_tv || (player.temp_event_username !== player.event_username)) {
                    player.is_tv      = true;
                    player.is_display = true;

                    player.event_username = player.temp_event_username;

                    // openchat_wrapper の内容変更
                    if (Stickam.is_toppage()) { // global.js should be loaded
                        if (player.is_corporation) {
                            displayCorporationContents(player.event_username);
                        } else {
                            displayOpenchat();
                        }
                    }
                }

            } else {
                className = 'stickamlogo_yy_onair';
            }
            $('#stickamlogo').addClass(className);
        } else {
            $('#stickamlogo').removeClass('stickamlogo_onair stickamlogo_yy_onair');
        }
    }

    var timer;
    function set_timer(time) {
        if (timer) {
            clearInterval(timer);
        }

        time = Stickam.is_toppage() ? 2 * 60 * 1000 : time ? time : 30 * 60 * 1000;

        timer = setInterval((function() {
                    $.getJSON('/api/getOnairEvent', function(json){onSuccess(json);});
                    return arguments.callee;
                })(), time);
    }

    function displayOpenchat() {
        if (!$('#openchat_external').size()) {
            $('#openchat_wrapper').html('<div id="openchat_external" />');

            embedSWF('/flash/stickam/openChat_surfer.swf?v=00.01.30',
                     'openchat_external',
                     {staticServer: 'static.stickam.jp'
                      },
                     {allowScriptAccess: 'always',
                      quality: 'high',
                      allowfullscreen: 'true',
                      wmode: 'window',
                      menu: 'false',
                      flashvars: 'token=' + $.cookie('token')},
                     {width: 750,
                      height: 426,
                      hspace: 0,
                      vspace: 0});
        }

        return false;
    }

    function displayCorporationContents(username) {
        $.getJSON('/api/corporation/' + username + '/top', function(json){
            if (json.contents) {
                $('#openchat_wrapper').html(json.contents);
            } else {
                displayOpenchat();
            }
        });
    }

    set_timer();
})();

