(function() {
     var unloadWarnings = [];

     function noticePageMove() {
         alert(unloadWarnings.join('\n'));
     }

     function confirmPageMove(event) {
         event = event || window.event;
         return event.returnValue = unloadWarnings.join('\n');
     }

     window.addBeforeUnloadMessage = function(msg) {
         unloadWarnings.push(msg);
         if (unloadWarnings.length == 1) {
             if (window.opera) {
                 window.addEventListener('unload', noticePageMove, false );
             } else {
                 // fx(etc)
                 if (window.addEventListener) {
                     window.addEventListener('beforeunload', confirmPageMove, false );
                 // ie
                 } else if (window.attachEvent) {
                     window.attachEvent('onbeforeunload', confirmPageMove);
                 }
             }
         }
     };
     window.removeBeforeUnloadMessage = function(msg) {
         if (msg) {
             for (var i = 0, n = unloadWarnings.length; i < n; i++) {
                 if (msg == unloadWarnings[i]) {
                     unloadWarnings.splice(i, 1);
                     break;
                 }
             }
         } else {
             unloadWarnings.pop();
         }
         if (unloadWarnings.length == 0) {
             if (window.opera) {
                 window.removeEventListener('unload', noticePageMove, false);
             } else {
                 // fx(etc)
                 if (window.addEventListener) {
                     window.removeEventListener('beforeunload', confirmPageMove, false);
                 // ie
                 } else if (window.attachEvent) {
                     window.detachEvent('onbeforeunload', confirmPageMove);
                 }
             }
         }
     };
 })();

function setRememberCookieNew(elementName)
{
    var remAutoCheckbox = document.getElementById(elementName);

    if (remAutoCheckbox == undefined) {
        return;
    }
    if (remAutoCheckbox.checked) {
        var d = new Date();
        var expire = d.getTime() + (7 * 1000 * 60 * 60 * 24);
        d.setTime(expire);
        var expires = d.toGMTString();
        document.cookie = 'rememberauto=1; expires=' + expires + '; path=/;';
    } else {
        // remove auto login remember cookie
        document.cookie = 'rememberauto=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/;';
    }
}

function clearBox(box)
{
    if (box.value == box.defaultValue) {
        box.value = '';
    }
}

popupWins = new Array();
function windowOpener(url, name, args)
{
    if (typeof popupWins[name] != 'object') {
        popupWins[name] = window.open(url, name, args);
    } else {
        if (popupWins[name].closed) {
            popupWins[name] = window.open(url, name, args);
        }
    }
    popupWins[name].focus();
}
function MM_openBrWindow(theURL, winName, features)
{// v2.0
    windowOpener(theURL, winName, features);
}

function get_cookie(name){
    return $.cookie(name) || '';
}

function deleteMyProfileCookie()
{
    var today = new Date();
    today.setYear( today.getYear() - 1 );
    document.cookie = Stickam._COOKIE.PROFILE.KEY + '=;expires=' + today.toGMTString();
}

function logoutScript()
{
    var f = document.getElementById('logoutForm');
    deleteMyProfileCookie();
    f.submit();
}

function embedSWF(swfUrl, id, flashvars, params, attributes, opt)
{
    if (typeof swfobject == 'undefined') {
        alert('writeSWF: invalid swfobject');
        return;
    }
    if (!swfUrl) {
        alert('writeSWF: invalid swfUrl');
        return;
    }
    if (!id) {
        alert('writeSWF: invalid id');
        return;
    }
    if (document.domain.indexOf('stickam.jp') == -1 && id.indexOf('external') == -1) {
        alert('writeSWF: missing "external"');
    }
    if (!flashvars) {
        flashvars = {};
    }
    if (!params) {
        params = {};
    }
    if (!attributes) {
        attributes = {};
    }
    if (typeof attributes.width == 'undefined') {
        attributes.width = '100%';
    } else if (!/^\d+%$/.test(attributes.width)) {
        attributes.width = parseInt(attributes.width);
    }
    if (typeof attributes.height == 'undefined') {
        attributes.height = '100%';
    } else if (!/^\d+%$/.test(attributes.height)) {
        attributes.height = parseInt(attributes.height);
    }
    if (!opt) {
        opt = {};
    }
    if (typeof opt.version == 'undefined') {
        opt.version = '10.0.45';
    }
    if (typeof opt.expressInstallSwfurl == 'undefined') {
        opt.expressInstallSwfurl = '/lib/swfobject/expressInstall.swf';
    }

    var element = $(typeof id === 'string' ? '#' + id : id);
    // 6.0.65未満だとExpressInstallが使えないため、リンクを出す
    if (!swfobject.hasFlashPlayerVersion('6.0.65') && element.children().size() == 0) {
        var img = '<a href="http://get.adobe.com/jp/flashplayer/" target="_blank"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" width="112" height="33" alt="Adobe Flash Playerをダウンロード" /></a>';
        element.append(img);
    }
    swfobject.embedSWF(swfUrl,
                       id,
                       attributes.width,
                       attributes.height,
                       opt.version,
                       opt.expressInstallSwfurl,
                       flashvars,
                       params,
                       attributes);
}

function getMyProfileCookie()
{
    var myProfile = $.cookie(Stickam._COOKIE.PROFILE.KEY);
    if (myProfile) {
        // valid
        Stickam.setUserMenu(myProfile.split(Stickam._COOKIE.PROFILE.SEPARATOR));
        return false;
    }

    $.getJSON('/mypage/getUserData',
              {},
              function(data) {
                var arr = new Array();
                if (data.loggedIn) {
                       arr = [data.user.screen_name,
                              data.user.username,
                              data.user.unread_messages,
                              data.user.is_mystyle,
                              data.user.is_yy,
                              data.user.is_professional,
                              data.user.unread_req_messages,
                              data.user.community,
                              data.user.birthday];
                    $.cookie(Stickam._COOKIE.PROFILE.KEY, arr.join(Stickam._COOKIE.PROFILE.SEPARATOR), {expires: new Date(new Date().getTime() + 120 * 1000), path: '/'});
                } else {
                    $.cookie('token', null, {path: '/', domain: (location.hostname.match(/stickam.+$/)||[])[0]});
                }
                Stickam.setUserMenu(arr);
              }
    );
    return true;
}

Stickam = {
    _COOKIE: {
        PROFILE: {SEPARATOR: '\t',
                  KEY: 'myProf',
                  INDEX: {SCREEN_NAME: 0,
                          USERNAME: 1,
                          UNREAD_MESSAGES: 2,
                          PREMIUM_MYSTYLE: 3,
                          PREMIUM_YY: 4,
                          PREMIUM_PRO: 5,
                          UNREAD_REQ_MESSAGES: 6,
                          COMMUNITY: 7,
                          BIRTHDAY: 8}}
    },
    is_toppage: function()
    {
        return Boolean(location.pathname.match(/^\/$/));
    },
    hasAuthCookie: function()
    {
        if ($.cookie('token')) {
            return true;
        }
        if ($.cookie('auto')) {
            return true;
        }
        return false;
    },
    sticker: {
        add: function()
        {
            $('#nextBtn').click(function() { Stickam.sticker.next(1); });
            $('#backBtn').click(Stickam.sticker.before);
            Stickam.sticker.auto(); // スクロールのタイマー
        }
    },
    setUserMenu: function(profile) {
        var index = Stickam._COOKIE.PROFILE.INDEX;
        var textHtml = '';
        var premiumLink = '';

        if (!$.cookie('token')) {
            textHtml = '<p>こんにちは、ゲストさん</p>';
        } else {
            if (!(profile[index.PREMIUM_MYSTYLE] === 'yes' || profile[index.PREMIUM_YY] === 'yes' || profile[index.PREMIUM_PRO] === 'yes')) {
                premiumLink = '（<a href="/premium?from=headerLink" class="premiumLink">プレミアム未登録</a>）';
            }

            textHtml = '<p><a href="/profile/' + profile[index.USERNAME] + '"></a>さん' + premiumLink + '</p>';

            if (!$('#header').hasClass('premium')) {
                textHtml += '<a class="mail" href="/message/">' + profile[index.UNREAD_MESSAGES] + '</a>';

                if (Number(profile[index.UNREAD_MESSAGES]) && 0 < Number(profile[index.UNREAD_REQ_MESSAGES])) {
                    textHtml += '<a title="お友達リクエスト' + profile[index.UNREAD_REQ_MESSAGES] + '件" class="friendRequestMail" href="/friend/request">' + profile[index.UNREAD_REQ_MESSAGES] + '</a>';
               }
            }
        }

        $('#user-menu').html(textHtml);
        $('#user-menu p a:first').text(profile[index.SCREEN_NAME]);
    },
    headerBtns: function()
    {
        if (!Stickam.hasAuthCookie()) {
            $('#loginButton').html('<a href="/login" class="btn-login">ログイン</a>');
            $('#mypageButton').html('<a href="/signup" class="btn-join">新規会員登録</a>');
            $('#liveButton').html('<a href="javascript:void(0);" onClick="alert(\'ライブを開始するにはログインが必要です\')">ライブ開始</a>');

            if ($.cookie(Stickam._COOKIE.PROFILE.KEY)) {
                deleteMyProfileCookie();
            }
        } else {
            $('#loginButton').html('<form id="logoutForm" action="/logout" method="POST"><input id="token" type="hidden" name="token" value="' + get_cookie('token') + '" /><a href="javascript:logoutScript()" class="btn-logout">ログアウト</a></form>');
            $('#mypageButton').html('<a href="/mypage" class="btn-mypage">マイページ</a>');
            var setLiveButton = function(comm) {
                var liveClass = '';
                if (comm) {
                    liveClass = ' class="btn-community"';
                }
                $('#liveButton').html('<a' + liveClass + '>ライブ開始</a>')
                    .click(function() {
                        var success = false;
                        $.ajax({type: 'GET',
                                url: '/mypage/getUserProfile',
                                async: false,
                                cache: false,
                                dataType: 'json',
                                success: function(data) {
                                    try {
                                        var jasrac_report = data.messageAlert[0].jasrac_live_record_alert;
                                        if (9 < jasrac_report) {
                                            location.href = '/live/report';
                                        } else {
                                            var strScrollbarsOption = 'resizable=yes,width=550,height=630';
                                            if (window.screen.height < 630) {
                                                strScrollbarsOption = 'scrollbars=yes,' + strScrollbarsOption;
                                            }
                                            MM_openBrWindow('/chat', 'host', strScrollbarsOption);
                                        }
                                    } catch (e) {
                                        // dataが期待してる値以外の場合、
                                        // cookieが削除された場合、
                                        // eval()の処落ちないように
                                        location.href = '/login';
                                    }
                                }
                        });
                    });
            };
            var myProfile = $.cookie(Stickam._COOKIE.PROFILE.KEY);
            if (myProfile) {
                var arr = myProfile.split(Stickam._COOKIE.PROFILE.SEPARATOR);
                setLiveButton(arr[Stickam._COOKIE.PROFILE.INDEX.COMMUNITY]);
            } else {
                $.getJSON('/mypage/getUserData', {}, function(data) { setLiveButton(data.user.community); });
            }
        }
    },
    toDurationString: function(delta_ms)
    { // TODO: より汎用的にする。現状トップ以外に使えない。
        if (delta_ms < 1 * 1000) {
            return '';
        }
        var left = '';
        var duration = new Date(delta_ms);
        if (duration.getUTCFullYear() - 1970 != 0) {
            left += (duration.getUTCFullYear() - 1970) + '年';
        } else if (duration.getUTCMonth() != 0) {
            left += (duration.getUTCMonth()) + 'ヶ月';
        } else if (duration.getUTCDate() - 1 != 0) {
            left += (duration.getUTCDate() - 1) + '日';
        } else if (duration.getUTCHours() != 0) {
            left += duration.getUTCHours() + '時間';
        } else {
            (duration.getUTCMinutes() != 0) && (left += duration.getUTCMinutes() + '分');
            left += ('0' + duration.getUTCSeconds()).slice(-2) + '秒';
        }
        return left;
    },
    global: function(global){
        return function(){ return global; };
    }(this),
    namespace: function(namespace)
    {
        var name, obj = Stickam.global();
        namespace = namespace.split('.');
        for (var i = 0, f = namespace.length; i < f; i++)
        {
            name = namespace[i];
            obj = obj[name] = obj[name] || {};
        };
        return obj;
    },
    insertSearchWord: function() {
        $('form#headerSearch input.words').val((decodeURI(location.search).match(/\bkeyword=(.*?)(?:&|$)/)||[])[1]);
        $('form#headerSearch select').val((decodeURI(location.search).match(/\bmedia_type=(.*?)(?:&|$)/)||[])[1]);

        $('form#headerSearch').submit(function() {
            var selected_type = $('form#headerSearch select').val();

            location.href = ['/search/',
                             (selected_type === 'user' ? 'user' : 'media'),
                             '?keyword=',
                             encodeURI($('form#headerSearch input.words').val()),
                             (selected_type !== 'user' ? '&media_type=' + selected_type : '')].join('');

            return false;
        });
    },
    activity: {
        constant: {
            ACTIONS: {live: {MESSAGE: 'ライブを開始しました',
                             CLASS_NAME: 'action-full'},
                      chat: {MESSAGE: 'わいわいチャットに参加しました',
                             CLASS_NAME: 'action-full'},
                      join: {MESSAGE: 'ライブに参加しました',
                             CLASS_NAME: 'action-slender'},
                      login: {MESSAGE: 'ログインしました',
                              CLASS_NAME: 'action-full'}},
            DELAY: 1000 * 0.5,
            HTML: {BUTTON: {PLAY: '再開',
                            STOP: '停止'}},
            MOVE_SELECTORS: ['#headerPremium-in-right, #headerMain, #headerMenu, #headerSticker, #container, #footer-in, #profile #externalButton, #profile #mystyleBanner, #profile #liveMember',
                             '#common-activity-background',
                             '#common-activity-button',
                             '#common-activity'],
            REQUEST_INTERVAL: 1000 * 60 * 2,
            RETRY_REQUEST_INTERVAL: 1000 * 15,
            RUN_INTERVAL_MIN: 1000 * 1,
            LIMITED_SMALL_SCREEN: 1200,
            SHOW_TYPES: [{type: 'session',
                          type_ja: 'ステータス'}],
            STYLE: {'#headerPremium-in-right, #headerMain, #headerMenu, #headerSticker, #container, #footer-in, #profile #externalButton, #profile #mystyleBanner, #profile #liveMember': {SHOW: {'padding-right': '220px'},
                                                                                                                                                                                           HIDE: {'padding-right': '0'}},
                    '#common-activity': {SHOW: {'right': '0px'},
                                         HIDE: {'right': '-240px'}},
                    '#common-activity-background': {SHOW: {'right': '0px'},
                                                    HIDE: {'right': '-250px'}},
                    '#common-activity-button': {SHOW: {'margin-left': '-10px',
                                                       'width': '15px'},
                                                HIDE: {'margin-left': '-20px',
                                                       'width': '20px'}},
                    '#common-activity .contents': {SMALL_SCREEN: {'background-color': '#FFF'},
                                                   NORMAL_SCREEN: {'background-color': ''}}},
            URL: '/api/activity'},
        data_list: [],
        is_run: true,
        latest_request_time: 0,
        run_id: 0,
        get_id: 0,
        show_types: [],
        getDiffTime: function() {
            return Stickam.activity.constant.REQUEST_INTERVAL - new Date().getTime() + Stickam.activity.latest_request_time;
        },
        isShow: function() {
            return parseInt($('#common-activity').css('right')) === 0;
        },
        getHideTypes: function() {
            var hide_types = $.jStorage.get('activity.hide_types');
            return hide_types instanceof Array ? hide_types : [];
        },
        setShowTypes: function() {
            var hide_types = Stickam.activity.getHideTypes();

            Stickam.activity.show_types = (function() {
                var show_types = new Array();
                $.each(Stickam.activity.constant.SHOW_TYPES, function(i, show_type) {
                    if ($.inArray(show_type.type, hide_types) === -1) {
                        show_types.push(show_type.type);
                    }
                });
                return show_types;
            })();
        },
        setClass: function(types) {
            if ($.inArray('show', types) !== -1) {
                if (!Stickam.activity.isShow()) {
                    $('#common-activity-button').addClass('closed');
                } else {
                    $('#common-activity-button').removeClass('closed');
                }
            }

            if ($.inArray('run', types) !== -1) {
                if (Stickam.activity.is_run) {
                    $('button#common-activity-play').addClass('ui-icon-pause');
                    $('button#common-activity-play').removeClass('ui-icon-play');
                } else {
                    $('button#common-activity-play').addClass('ui-icon-play');
                    $('button#common-activity-play').removeClass('ui-icon-pause');
                }
            }
        },
        init: function() {
            Stickam.activity.setShowTypes();
            Stickam.activity.is_run = $.jStorage.get('activity.is_run') !== false;

            // iframeはswfを重なった場合に下に隠れてしまう対策
            // wmode="opaque"はChromeにおいて日本語入力できなくなるため非使用
            // IE7においてborder:noneが効かないためframeborder="0"は必須
            $(['<iframe id="common-activity-background" frameborder="0"></iframe>',
               '<div id="common-activity">',
               '<div id="common-activity-button"></div>',
               '<div class="contents">',
               '<div id="site-activity" class="section">',
               '<div class="head">',
               '<h2>サイトアクティビティ</h2>',
               '<button id="common-activity-close" class="ui-icon-closed">閉じる</button>',
               '<button id="common-activity-play" class="ui-icon-pause"></button>',
               '</div>',
               '<ul class="list"></ul>',
               '</div>',
               '</div>',
               '</div>'].join('')).appendTo(document.body);

            Stickam.activity.setClass(['run', 'show']);

            Stickam.activity.resize(true);
            $(window).resize(function() {
                Stickam.activity.resize(false);
            });

            $('button#common-activity-play').click(function() {
                Stickam.activity.is_run = !Stickam.activity.is_run;
                $.jStorage.set('activity.is_run', Stickam.activity.is_run);

                Stickam.activity.setClass(['run']);
                $(this).html(Stickam.activity.constant.HTML.BUTTON[Stickam.activity.is_run ? 'STOP' : 'PLAY']);
                Stickam.activity.run();
            })
                .html(Stickam.activity.constant.HTML.BUTTON[Stickam.activity.is_run ? 'STOP' : 'PLAY']);

            $('#common-activity-button, button#common-activity-close').click(function() {
                var is_hide_to_show = !Stickam.activity.isShow();
                $.jStorage.set('activity.is_show', is_hide_to_show);

                var move_selectors_length = Stickam.activity.constant.MOVE_SELECTORS.length;

                $.each(Stickam.activity.constant.MOVE_SELECTORS, function(i, selector) {
                    $(selector).animate(Stickam.activity.constant.STYLE[selector][is_hide_to_show ? 'SHOW' : 'HIDE'], function() {
                        if (i !== move_selectors_length - 1) {
                            return true;
                        }

                        Stickam.activity.setClass(['show']);

                        // 最終取得から十分に時間が経過している場合、すでに取得情報を空にする
                        if (!Stickam.activity.getDiffTime()) {
                            Stickam.activity.data_list = [];
                        }

                        // 同時に実行されるDOM要素の移動を分散しスムーズにさせるためdelayを設ける
                        setTimeout(Stickam.activity.run, Stickam.activity.constant.DELAY);
                    });
                });
            });

            // TODO:SHOW_TYPE追加時は要デザイン
            if (1 < Stickam.activity.constant.SHOW_TYPES.length) {
                $('#site-activity div.head').after('<ul class="tab"></ul>');

                $.each(Stickam.activity.constant.SHOW_TYPES, function(i, show_type) {
                    $('<li></li>').appendTo('#site-activity ul.tab');
                    $('<button></button>').click(function() {
                        var hide_types = Stickam.activity.getHideTypes();
                        var index = $.inArray(show_type.type, hide_types);
                        if (index !== -1) {
                            hide_types = hide_types.splice(0, index).concat(hide_types.slice(index + 1));
                        } else {
                            hide_types.push(show_type.type);
                        }

                        $.jStorage.set('activity.hide_types', hide_types);
                        Stickam.activity.setShowTypes();
                    })
                        .html(show_type.type_ja)
                        .appendTo('#site-activity ul.tab li:last-child');
                });
            }

            return true;
        },
        resize: function(is_init) {
            $('#common-activity-background').css({'height': $(window).height() + 'px'});
            $('#common-activity-button').animate({'top': Math.ceil(($(window).height() - parseInt($('#common-activity-button').css('height'))) / 2) + 'px'}, is_init ? 0 : '');
            // TODO:新しいsectionが増えるたときは#common-activity .contentsの高さを元に別途高さを指定する
            $('#common-activity .contents, #site-activity').css({'height': ($(window).height() - parseInt($('#common-activity .contents').css('border-top-width')) * 2 - parseInt($('#common-activity .contents').css('padding-top')) * 2) + 'px'});

            $('#common-activity .contents').css(Stickam.activity.constant.STYLE['#common-activity .contents'][$(window).width() < Stickam.activity.constant.LIMITED_SMALL_SCREEN ? 'SMALL_SCREEN' : 'NORMAL_SCREEN']);
        },
        render: function(data) {
            if (!data) {
                return;
            }

            var list_selector = '#site-activity ul.list';

            var activity_date = new Date(data.time * 1000);
            var times = new Array();
            $.each([activity_date.getHours(), activity_date.getMinutes(), activity_date.getSeconds()], function(i, val) {
                times[i] = val < 10 ? '0' + val : val;
            });

            $(['<li>',
               '<div class="user">',
               '<a href="/profile/', data.username, '" class="thumb" title="', data.display_name, 'さんのプロフィールページへ">',
               '<img src="', data.profile_image, '" alt="', data.display_name, '" />',
               '</a>',
               '</div>',
               '<div class="', Stickam.activity.constant.ACTIONS[data.subtype].CLASS_NAME, '">',
               Stickam.activity.constant.ACTIONS[data.subtype].MESSAGE,
               '<p>',
               '</p>',
               '<p class="date">', times.join(':'), '</p>',
               '</div>',
               (data.host ? ['<div class="target">',
                             '<a href="/profile/', data.host.username, '" class="thumb" title="', data.host.display_name, 'さんのプロフィールページへ">',
                             '<img src="', data.host.profile_image, '" alt="', data.host.display_name, '" />',
                             '</a>',
                             '</div>'].join('') : ''),
               '</li>'].join('')).hide()
                .prependTo(list_selector)
                .slideDown(function() {
                    // 表示領域から消えたものは削除
                    // callbackでremoveすること(slideDown中にliのheightが定まらないため)
                    $(list_selector + ' li:gt(' + Math.ceil($(list_selector).parent().height() / $(list_selector + ' li').height()) + ')').remove();
                });
        },
        run: function() {
            // (停止設定|非表示)中は処理しない
            if (!Stickam.activity.is_run || !Stickam.activity.isShow()) {
                // 再実行する際に二重実行しないようにクリア
                if (Stickam.activity.run_id) {
                    clearTimeout(Stickam.activity.run_id);
                    Stickam.activity.run_id = 0;
                }
                return;
            }

            // 表示するデータがない場合は処理せず再取得
            if (!Stickam.activity.data_list.length) {
                Stickam.activity.get();
                return;
            }

            Stickam.activity.render((function() {
                if (!Stickam.activity.data_list.length) {
                    return null;
                }

                var data = Stickam.activity.data_list.pop();
                return $.inArray(data.type, Stickam.activity.show_types) !== -1 ? data : arguments.callee();
            })());

            Stickam.activity.run_id = setTimeout(arguments.callee, (function() {
                var data_length = Stickam.activity.data_list.length;
                if (!data_length) {
                    return Stickam.activity.constant.RUN_INTERVAL_MIN;
                }

                // run間隔が規定時間未満の場合は、規定時間内に処理できる量にデータ長を調整する
                var diff_time = Stickam.activity.getDiffTime();
                var interval = diff_time / data_length;
                if (interval < Stickam.activity.constant.RUN_INTERVAL_MIN) {
                    Stickam.activity.data_list = Stickam.activity.data_list.splice(data_length - Math.floor(data_length * interval / Stickam.activity.constant.RUN_INTERVAL_MIN));
                    interval = Stickam.activity.constant.RUN_INTERVAL_MIN;
                }

                return interval;
            })());
        },
        get: function() {
            // (停止設定|非表示|再取得待機)中は取得しない
            if (!Stickam.activity.is_run || !Stickam.activity.isShow() || Stickam.activity.get_id) {
                return;
            }

            // 表示すべきデータがあったら取得せずに表示する
            if (Stickam.activity.data_list.length) {
                Stickam.activity.run();
                return;
            }

            // 最終取得時間から一定時間経過していない場合は待機(規定時間後まで取得しない)
            var diff_time = Stickam.activity.getDiffTime()
            if (0 <= diff_time) {
                Stickam.activity.get_id = setTimeout(arguments.callee, diff_time);
                return;
            }

            Stickam.activity.latest_request_time = new Date().getTime();

            $.getJSON(Stickam.activity.constant.URL,
                      {},
                      function(response) {
                        Stickam.activity.data_list = response;
                      })
                .error(function() {
                    // 取得失敗時は指定時間後にリトライできるように最終取得時間を調整
                    Stickam.activity.latest_request_time -= (Stickam.activity.constant.REQUEST_INTERVAL - Stickam.activity.constant.RETRY_REQUEST_INTERVAL);
                })
                .complete(function(){
                    Stickam.activity.get_id = 0;
                    Stickam.activity.run();
                });
        }
    }};

(function() {
    var dbclick = 0;
    var stickerMoveAutoTimer;

    Stickam.sticker.auto = function () {
        stickerMoveAutoTimer = setInterval(Stickam.sticker.next, 7 * 1000);
    };

    Stickam.sticker.next = function(flag) {
        if (dbclick) {
            return false;
        }
        if (flag) {
            clearInterval(stickerMoveAutoTimer);
            Stickam.sticker.auto();
        }
        dbclick = 1;

        var html = $('.stickerList-in:first').html();
        $('#stickerList')
            .animate({'left': '-=886px'}, 750 , function() {
                         $('.stickerList-in:first').remove();
                         $('#stickerList')
                             .append('<li class="stickerList-in">' + html + '</li>')
                               .animate({'left': '+=886px'}, 0, function() { dbclick = 0; });
                     });
        return true;
    };

    Stickam.sticker.before = function() {
        if (dbclick) {
            return false;
        }
        dbclick = 1;

        var html = $('.stickerList-in:last').html();
        $('.stickerList-in:last').remove();
        $('#stickerList')
            .prepend('<li class="stickerList-in">' + html + '</li>')
                .animate({'left': '-=886px'}, 0)
                   .animate({'left': '+=886px'}, 750, function() { dbclick = 0; });
        return true;
    };
})();

// レンダリング優先のためdocument.write()で出力している
if ($.jStorage.get('activity.is_show') !== false) {
    // 古いローカルキャッシュを使用しないように同時に更新の行なわれるglobal.cssのバージョンを便宜的に用いてリクエストを行なう
    $.each($('link'), function() {
        var href = $(this).attr('href');
        if (/global.css/.test(href)) {
            document.write('<link rel="stylesheet" href="' + (href.match(/\/\d+/)||[''])[0] + '/css/ja/common_activity_closed.css" type="text/css" />');
            return false;
        }
    });
}

$(document).ready(function() {
    // footerがあるページのみcommon-activityを表示する
    $('div#footer p#copyright').size() && Stickam.activity.init() && Stickam.activity.run();

    var host = $.support.hrefNormalized ? null : location.protocol + '//' + location.host;
    $('a').each(function() {
        var i, href = $(this).attr('href');
        if ((host != null) && (href.indexOf(host) === 0)) {
            href = href.substring(host.length);
        };
        if (/^(https?:\/\/)|(\/bnrRedirect\.html\?bnrUrl=https?%3[aA]%2[fF]%2[fF])/.test(href)) {
            $(this).click(function(){
                window.open(href);
                return false;
            });
        }
    });
    $.jStorage.set('lastVisit', new Date().getTime());
});

