var MAX_PAGE_NUM = 8;

function getPlayerName() {
    return $("#playerName").text();
}

function getLOLBoxYYUID() {
    return getCookie('lolboxyyuid');
}

function getServerName() {
    return $("#serverName").text();
}


function getBoxServerName() {
    return getCookie('boxServerName');
}

function getBoxPlayerName() {
    return getCookie('boxPlayerName');
}


function getIsInMyFavorite() {
    return $.trim($("#isInMyFavorite").text());
}

function getCookie(cookieName) {
    var cookieString = document.cookie;
    var start = cookieString.indexOf(cookieName + '=');
    // 加上等号的原因是避免在某些 Cookie 的值里有
    // 与 cookieName 一样的字符串。
    if (start == -1) // 找不到
        return null;
    start += cookieName.length + 1;
    var end = cookieString.indexOf(';', start);
    if (end == -1)
        return cookieString.substring(start);
    return   cookieString.substring(start, end);
}

function updateSideBarSelection(matchID) {
    $('.hover').removeClass('hover');
    $('#cli' + matchID).addClass('hover');
}

function highLightCurrentPlayer() {
    var pn = $("#playerName").text();
    $('div[class="team-name"] a').each(function() {
        var pnTemp = $.trim($(this).parent().find('img').attr('data-playername'));
        if (pn === pnTemp) {
            $(this).css('font-weight', 'bold');
        }
    });

    var boxPlayerName = getBoxPlayerName();
    $('div[class="team-name"]').each(function() {
        var pnTemp = $.trim($(this).find('img').attr('data-playername'));
        if (boxPlayerName === pnTemp) {
            $(this).parent().parent().addClass('current-player');
        }
    });
}

function loadMatchDetail(matchId, serverName, playerName) {
    updateSideBarSelection(matchId);

    $('#matchDetail').html('<img src="images/loading.gif" width="400" height="400">');

    var isFavoriteMatch = getIsInMyFavorite();

    $.ajax(
        {
            url: "http://lolbox.duowan.com/matchList/ajaxMatchDetail2.php",
            data: {matchId: matchId, serverName: serverName, playerName: playerName, favorate: isFavoriteMatch},
            cache: true,
            success: function (data, textStatus) {
                if (textStatus == 'success') {
                    window.location.hash = matchId;

                    /*
                      注意这里不要使用
                      $('#matchDetail').html(data);
                      这个方法在 IE 6.0.2900.5512 080413-2111 多次调用后会导致 IE 崩溃。
                     */
                    if (data) {
                      $('#matchDetail').get(0).innerHTML = data;
                    }

                    if (SnsShare) {
                        SnsShare.init();
                    }

                    if (window.tipsWin) {
                        tipsWin.tooltips.init();
                    }

                    addAnchorIconsToMatchList();
                    prepareCertifiedLiveAnchorHover();

                    highLightCurrentPlayer();

                    setupACHShare();

                    if (window.wan) {
                        wan.init();
                    }
                }

            },
            error: function () {
                $('#matchDetail').html('<p style="padding:50px">盒子未找到此场比赛的详情信息。</p>');
                $('.detailTip').html('');
            }
        });
}


function myFavorateMatches(action, timestamp) {
    var boxPlayerName = decodeURI(getCookie('boxPlayerName'));
    var boxServerName = decodeURI(getCookie('boxServerName'));
    //alert(action + boxServerName + boxPlayerName);
    $.ajax(
        {
            url: "http://lolbox.duowan.com/webApi.php",
            data: {serverName: boxServerName, playerName: boxPlayerName, action: action, timestamp: timestamp},
            cache: false,
            success: function (msg) {
                //alert(msg);
                if (msg == 1) {
                    // location.reload();
                } else if (msg == -1) {
                    alert('非法操作，请至少登陆一次游戏！');
                } else if (msg == -2) {
                    alert('超过战绩收藏最大数24场！');
                } else if (msg == 0) {
                    alert('收藏的比赛不存在');
                }
            },
            error: function () {
            }
        });
}


function getJiathisConifg(title, honourKey) {
    if (!title) return null;

    var boxPlayerName = getBoxPlayerName();

    if (boxPlayerName && boxPlayerName != '') {
        title = title.replace('我', '我（' + decodeURI(boxPlayerName) + '）');
    }

    var jiathis_config = {
        sm: "tsina,tqq,renren",
        url: document.location.toString(),
        title: "#无盒子 不开撸# " + title,
        summary: " ",
        data_track_clickback: true,
        appkey: {
            "tsina": "3629014272",
            "tqq": "801220649",
            "qzone": "100302822"
        },
        pic: 'http://img.lolbox.duowan.com/icon_' + honourKey + '_120x120.png',
        ralateuid: {
            "tsina": "2909042820"
        },
        evt: {
            "share": 'closeShare'
        }
    };
    return jiathis_config;
}

function screenshot() {
    $('.share').removeClass('hover');
    setTimeout(function () {
        var serverName = getServerName();
        var playerName = getPlayerName();
        window.location.href = 'lolboxphoto://' + serverName + '_' + playerName + '_玩家战绩';
    }, 200);
}

function setupShare() {
    $('.box .box-hd .btns-fast .share').hover(function () {
        var playerName = getBoxPlayerName() || getPlayerName();
        jiathis_config = {
            title: "#无盒子 不开撸# 我是" + decodeURIComponent(playerName) + "，我在使用LOL盒子。来看看我的比赛成绩吧！",
            appkey: {
                "tsina": "3629014272",
                "tqq": "801220649",
                "qzone": "100302822"
            },
            summary: " ",
            ralateuid: {
                "tsina": "2909042820"
            }
        };
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    });

}


function StrRangeCompute(str) {
    var d = document.getElementById('__dvCompute');
    d.innerHTML = str;
    return { w: d.offsetWidth, h: d.offsetHeight };
}

function normalizePlayerName(playerName) {
    playerName = playerName.replace(/斗鱼TV/i, "");
    playerName = playerName.replace(/龙珠/i, "");
    playerName = playerName.replace(/战旗TV/i, "");
    var maxWidth = 96;
    var range = StrRangeCompute(playerName);
    if (range.w > maxWidth) {
        var p = playerName[0];
        for (var i = 1; i < playerName.length; i++) {
            var _range = StrRangeCompute(p + playerName[i]);
            if (_range.w > maxWidth)
                return p + '...';
            else
                p = p + playerName[i];
        }
    }
    return playerName;
}

function getMatchID() {
    var matchID = null;
    var fragment = window.location.hash;
    if (fragment) {
        matchID = fragment.replace(/^#/, '');
    } else {
        var idName = $('.recent-list li:first').attr('id');
        if (idName) {
            matchID = idName.replace(/^#/, '').replace(/^cli/, '');
        }
    }
    return matchID;
}

function setupInteractiveSideBar() {
    $('.recent-list li').click(function() {
        var matchID = $(this).attr('id').replace(/^cli/, '');
        loadMatchDetail(matchID, getServerName(), getPlayerName());
    });
}

function gotoSpecifyPage() {
    var newPageNum = parseInt($('.zj-cur').val());
    if (newPageNum > MAX_PAGE_NUM) {
        newPageNum = MAX_PAGE_NUM;
    }

    var isFavoriteMatch = getIsInMyFavorite();
    var url;
    var urlPrefix;
    if (isFavoriteMatch == '1') {
        urlPrefix = 'http://lolbox.duowan.com/favorateMatchList.php';
    } else {
        urlPrefix = 'http://lolbox.duowan.com/matchList.php';
    }
    url = urlPrefix + '?serverName=' + encodeURI(getServerName()) +
        '&playerName=' + encodeURI(getPlayerName()) +
        '&page=' + newPageNum;
    window.location = url;
}

function setupInteractivePagination() {
    $('.go-page').click(function() {
        gotoSpecifyPage();
    });

    $('.zj-page').keyup(function(event) {
        if (event.keyCode == 13) {
            gotoSpecifyPage();
        }
    });

}

window.gCachePlayerInfo = !window.gCachePlayerInfo ? {} : window.gCachePlayerInfo;

tipsWin.tooltips.open = function (el) {
    tipsWin.tooltips.status = 1;

    var $this = $(el),
        _indent = parseInt($this.attr("data-indent")),
        userId = $this.attr("user-id"),
        gameZone = $this.attr("game-zone");
    if (!$("#data-layer .layer").get(_indent - 1)) {
        return;
    }
    /*定位浮层角标*/
    var pointY = $this.offset().top;
    $( '#mod-tips-s1 .arrow' ).css( 'top', (pointY-95 ) );
    /*获取浮层结构代码*/
    var _html = $("#data-layer .layer").eq(_indent - 1).html();
    this.html(_html);
    
    $.ajax({
        url: 'http://api.lolbox.duowan.com/api/v2/player/'+gameZone+'/'+userId+'/',
        dataType: 'jsonp'
    }).done(function(resp) {
        var data = resp && resp.player_list && resp.player_list[0];
        var tierRank = data.tier_rank, tierName;

        if (tierRank && tierRank['tier'] && tierRank['tier']['const'] > 0) {
          tierName = tierRank['tier']['name_cn'] + ' ' + tierRank['rank']['name'];
        } else {
          tierName = '-';
        }

        // var dpsTem='<div class="tip-level"><div class="ch_level level_'+chLevel+'"></div><p style="'+posClass+'">'+heroData.position+'</p></div><div class="tip-topright"><p><em class="zj-zdl zj-s"></em>' + data.player_zdl + '</p><p class="zj-blue">' + data.tier + ' ' + data.rank + '</p></div>';
        var dpsTem='<div class="tip-level"></div><div class="tip-topright"><p><em class="zj-zdl zj-s"></em>' + data.box_score + '</p><p class="zj-blue">' + tierName + '</p></div>';
        /*填写你的内容*/
        $('#mod-tips-s1').find(".tip-topright-wrap").html(dpsTem);

        if (tipsWin.tooltips.status == 1) {
            $('#mod-tips-s1').show();
        }
    });

    
};

function getURLParam(name) {
    var value = location.search.match(new RegExp("[?&]" + name + "=([^&]*)(&?)", "i"));
    return value ? decodeURIComponent(value[1]) : value;
}

function loadMatch() {
    var serverName = getServerName();
    var playerName = getPlayerName();
    var matchID = getMatchID();
    if (matchID && serverName && playerName) {
        loadMatchDetail(matchID, serverName, playerName);
    }
}

/*
分享 boxTitle “杀人如麻”之类荣誉，完整荣誉列表见 include/honourReds.php
 */
function setupACHShare() {
    var currHonourReds = $.parseJSON($('#currentHonourReds').text());

    var AchShare = function (selector, title) {
        var _top = $(selector).offset().top + 26;
        var _top2 = $(selector).offset().top - 80;
        var _left = $(selector).offset().left - 20;
        var _title = title;
        var $share = $('.ach-share');
        var $text = $share.find('strong');
        var $arrow = $share.find('.arrow');
        if (_top < 280) {
            $share.show().css({'top': _top, 'left': _left});
            $text.text(_title);
            $arrow.removeClass('b').addClass('t');
        } else if (_top > 280) {
            $share.show().css({'top': _top2 + 20, 'left': _left});
            $text.text(_title);
            $arrow.removeClass('t').addClass('b');
        }
    };

    var boxPlayerName = getBoxPlayerName();

    window.achShareTimer = null;

    if (boxPlayerName) {
        $('*[data-playername="' + decodeURI(boxPlayerName) + '"]').parent().find('.zj-s').each(function() {
            $(this).mouseenter(function() {
                var honourKey = $(this).attr('data-honour-key');
                var honour = currHonourReds[honourKey];
                if (!honour) {
                    $('.ach-share').hide();
                    return;
                }
                $(this).attr('title', '');

                AchShare(this, honour.title);
                jiathis_config = getJiathisConifg(honour.content, honourKey);
            });

            $(this).on('mouseleave', '', function(event) {
                achShareTimer =  setTimeout(function() {
                    $('.ach-share').hide();
                }, 300);

                event.preventDefault();
            });
        });

        $('.ach-share').mouseenter(function() {
            clearTimeout(achShareTimer);
        });

        $('.ach-share').mouseleave(function() {
            $(this).hide();
        });
    }
}


$(document).ready(function () {
    setupShare();

    setupInteractiveSideBar();
    setupInteractivePagination();

    loadMatch();

    // 初始化10个英雄 tips 窗口
    tipsWin.tooltips.init();
});