(function () {
    if (!window.console) {
        window.console = {};
    }
    // union of Chrome, FF, IE, and Safari console methods
    var m = [
        "log", "info", "warn", "error", "debug", "trace", "dir", "group",
        "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd",
        "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"
    ];
    // define undefined methods as noops to prevent errors
    for (var i = 0; i < m.length; i++) {
        if (!window.console[m[i]]) {
            window.console[m[i]] = function () {
            };
        }
    }
})();


if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str) {
        return this.indexOf(str) == 0;
    };
}


if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (elt /*, from*/) {
        var len = this.length >>> 0;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
            ? Math.ceil(from)
            : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++) {
            if (from in this &&
                this[from] === elt)
                return from;
        }
        return -1;
    };
}

/*
 Reference
 - http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects
 */
var sort_by = function (field, reverse, primer) {

    var key = primer ?
        function (x) {
            return primer(x[field])
        } :
        function (x) {
            return x[field]
        };

    reverse = [-1, 1][+!!reverse];

    return function (a, b) {
        return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
    }
};


var gFieldNameList = [
    'times',
    'win_rate',
    'kda_score',
    'k',
    'ddpm',
    'gpm',
    'mk10m'
];

var gChampionsStatRecords = null; // keep origin for filtering
var gLastOrderFieldName = gFieldNameList[0];
var gLastOrderBy = 'asc'; // 从大到小

var serverName = encodeURIComponent(getURLParam("serverName"));
var playerName = encodeURIComponent(getURLParam("playerName"));
var userId = getURLParam("userId");
var gameZone = getURLParam("gameZone");
var baseUrl = "http://lolbox.duowan.com/new/api/index.php";
var snFull;

function switchOrderBy(orderBy) {
    return (orderBy === 'asc') ? 'desc' : 'asc';
}

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


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 formatKDA(data) {
    return data.averageKDA[0] + '/' + data.averageKDA[1] + '/' + data.averageKDA[2];
}

function formatEarn(data) {
    var averageEarn = parseInt(data.averageEarn[0]);
    if (averageEarn > 1000) {
        averageEarn = (averageEarn / 1000.0).toFixed(1) + 'k';
    } else {
        averageEarn = averageEarn.toString();
    }
    return averageEarn;
}

function composeURLChampionImgByName(name) {
    return 'http://img.lolbox.duowan.com/champions/' + name + '_26x26.jpg'
}


function contains(haystack, needle) {
    return haystack.indexOf(needle) >= 0;
}

function resetOrderStyle() {
    $('th span')
        .removeClass('u-sort--desc')
        .removeClass('u-sort--asc')
        .removeClass('u-sort--normal')
        .addClass('u-sort--normal');
}

function parseArrayAsFloat(obj) {
    return parseFloat(obj[0]);
}

function updateTableDataOrderByFieldName(fieldName) {
    if (!gChampionsStatRecords) {
        return;
    }

    if (!contains(gFieldNameList, fieldName)) {
        return;
    }

    resetOrderStyle();

    if (gLastOrderFieldName === fieldName) {
        gLastOrderBy = switchOrderBy(gLastOrderBy);
    }
    gLastOrderFieldName = fieldName;

    if (gLastOrderBy === 'desc') {
        $('th[data-field-name="' + fieldName + '"] span')
            .removeClass('u-sort--normal')
            .addClass('u-sort--desc');
    } else {
        $('th[data-field-name="' + fieldName + '"] span')
            .removeClass('u-sort--normal')
            .addClass('u-sort--asc');
    }

    var reverse;
    if (gLastOrderBy === 'desc') {
        reverse = false;
    } else {
        reverse = true;
    }

    var parseFunc;
    if (contains(['averageKDA', 'averageDamage', 'averageEarn'], fieldName)) {
        parseFunc = parseArrayAsFloat;
    } else {
        parseFunc = parseFloat;
    }

    gChampionsStatRecords.sort(sort_by(fieldName, reverse, parseFunc));

    var output = '<thead>' +
        '<tr>' +
        '<th class="col1"></th>' +
        '<th class="col2"></th>' +
        '<th class="col3"></th>' +
        '<th class="col4"></th>' +
        '<th class="col5"></th>' +
        '<th class="col6"></th>' +
        '<th class="col7"></th>' +
        '<th class="col8"></th>' +
        '</tr>' +
        '</thead>';

    for (var i = 0; i < gChampionsStatRecords.length; i++) {
        var championStat = gChampionsStatRecords[i],
            champion = championStat.champion;
        // var championPoints = championStat.championPoints, level = championPoints.level ? championPoints.level : 0,levelMsg = level == 0 ? '无' : '';

        output += '<tr>' +
            '<td class=col1><span class="avatar"><img data-id='+ i +' champion-name="' + champion.display_name + '" src="' + composeURLChampionImgByName(champion.name) + '" alt="' + champion.display_name + '" title="' + champion.display_name + '" /></span></td>' +
            '<td class=col2>' + championStat.times + '</td>' +
            '<td class=col3>' + championStat.win_rate + '%' + '</td>' +
            '<td class=col4>' + championStat.kda_score + '</td>' +

            '<td class=col5>' + championStat.k.toFixed(1) + '/' + championStat.d.toFixed(1) + '/' + championStat.a.toFixed(1) + '</td>' +
            '<td class=col6>' + championStat.ddpm + '</td>' +
            '<td class=col7>' + championStat.gpm + '</td>' +
            '<td class=col8>' + championStat.mk10m + '</td>' +
            // '<td class="more-hero-level"><span>-</span></td>' +
            '</tr>';
            //(英雄成先用-代替)//'<td class="more-hero-level"><span class="ch_level level_'+level+'">'+levelMsg+'</span></td>' +
    }

    if (document.getElementById('m-myhero-table-data')) {
        $('#m-myhero-table-data').html(output);
    }

    fixedFieldDataAverageMinionsKilled();
}

/*
 部分玩家 "场均10分钟补兵" 暂缺数据，需要替换 "0" 为 "-"
 */
function fixedFieldDataAverageMinionsKilled() {
    $('#m-myhero-table-data td:last-child').each(function () {
        var old = $(this).text();
        if (old === '0') {
            $(this).text('-');
        }
    });
}

function loadData() {
    var url = "http://api.lolbox.duowan.com/api/v2/player/"+gameZone+"/" + userId + '/champions/';
    var href = "generalRecord.html?serverName="+serverName+"&playerName="+playerName + '&userId='+userId+'&gameZone='+gameZone;
    $("#player").attr("href", href).html(getURLParam("playerName"));

    if (gChampionsStatRecords) {
        updateTableDataOrderByFieldName('times');
        return;
    }

    $.ajax(
        {
            url: url,
            type:"GET",
            dataType: 'jsonp'
        })
        .done(function (resp) {
            var list = resp && resp.champion_performance_list;
            if (resp && list) {
                if(list.length == 0) {
                    $(".m-myhero-table--nodata").show();
                    return;
                } else {
                    // snFull = resp.snFull;
                    $("#countHeros").html(list.length);
                    gChampionsStatRecords = list;
                    updateTableDataOrderByFieldName('times');
                }
            } else {
                $('#m-myhero-table').html('<p style="margin-top:145px;text-align:center;">暂无数据，请稍后重试</p>');
                return;
            }
            
        })
        .fail(function (data) {
            $('#m-myhero-table').html('<p>获取数据失败，请稍后重试！</p>');
        });
}


function setupInteractiveSorting() {
    $('.u-sort').click(function () {
        var fieldName = $(this).parent().attr('data-field-name');
        updateTableDataOrderByFieldName(fieldName)
    })
}

function setupVirtualScrollBar() {
    // 显示虚拟滚动条
    $("#m-myhero-table").niceScroll({cursorcolor: "#D9D9D9", cursorwidth: "8", cursoropacitymin: 1, cursorborder: 'none'});
}


function updateTipsWinData(data, tagAttachTo) {
    $(tagAttachTo).find('img').attr('title', '');

    var KDARating = parseFloat(data.averageKDARating);

    var averageDamage = data.averageDamage[0];
    var averageDamageRating;
    if (data.averageDamage[1]) {
        averageDamageRating = data.averageDamage[1];
    } else {
        averageDamageRating = 1;
    }

    var averageEarn = parseInt(data.averageEarn[0]);
    if (averageEarn > 1000) {
        averageEarn = (averageEarn / 1000.0).toFixed(1) + 'k';
    }
    var averageEarnRating;
    if (data.averageEarn[1]) {
        averageEarnRating = parseInt(data.averageEarn[1]);
    } else {
        averageEarnRating = 1;
    }

    var averageMinionsKilled = parseInt(data.averageMinionsKilled);

    $('#heropage-hero-sharetips .avatar img').attr('src', data.urlImg);
    $('#heropage-hero-sharetips .name').text(data.championNameCN);

    $('.data-winRate').text(data.winRate + '%');
    $('.data-winRate').removeClass('bold');
    if (data.winRate >= 80) {
        $('.data-winRate').addClass('bold');
    }

    $('.data-matchStat').text(data.matchStat);

    $('.data-averageKDA-rating').text(KDARating);

    var averageKDA = data.averageKDA[0] + '/' + data.averageKDA[1] + '/' + data.averageKDA[2]
    $('.data-averageKDA').text(averageKDA);

    $('.data-averageDamage').text(averageDamage);
    $('.data-averageDamage-rating').text("超越" + averageDamageRating + "%玩家");
    // reset CSS class
    $('.data-averageDamage').removeClass('color-red');
    $('.data-averageDamage-rating').removeClass('color-red');
    if (averageDamageRating >= 80) {
        $('.data-averageDamage').addClass('color-red');
        $('.data-averageDamage-rating').addClass('color-red')
    }


    $('.data-averageEarn').text(averageEarn);
    $('.data-averageEarn-rating').text("超越" + averageEarnRating + "%玩家");
    // reset CSS class
    $('.data-averageEarn').removeClass('color-red');
    $('.data-averageEarn-rating').removeClass('color-red');
    if (averageEarnRating >= 80) {
        $('.data-averageEarn').addClass('color-red');
        $('.data-averageEarn-rating').addClass('color-red');
    }

    $('.data-averageMinionsKilled').removeClass('color-red');
    if (averageMinionsKilled >= 70) {
        $('.data-averageMinionsKilled').addClass('color-red');
    }

    // 异常数据
    if (averageMinionsKilled == 0) {
        $('.data-averageMinionsKilled').text('-');
    } else {
        $('.data-averageMinionsKilled').text(averageMinionsKilled);
    }

    $('.share-link').attr('champion-name', data.championName);
    $('.screenshot').attr('champion-name', data.championName);

    // "草莓丶(艾欧尼亚)　刀锋意志　75%胜/28场　KDA:11/23/11　分钟输出:100　分钟经济:100　10分补兵:80 　来自L O L盒子"
    var text = [
        playerName,
        '(' + snFull + ')　',
        data.championNameCN,
        '　' + data.winRate + '%胜/' + data.matchStat + '场',
        '　KDA:' + averageKDA,
        '　分钟输出:' + averageDamage + '(>' + averageDamageRating + '%玩家)',
        '　分钟经济:' + averageEarn + '(>' + averageEarnRating + '%玩家)',
        '　十分钟补兵:' + averageMinionsKilled,
        '　来自L O L盒子'
    ].join('');

    $('#achievementInTextPlain').text(text)
}

function isMySelf() {
    var pn = decodeURI(playerName);
    var boxPn = decodeURI(getCookie('boxPlayerName'));
    return (boxPn && pn && boxPn == pn);
}

function allowShareUserHerselfDataOnly() {
    if (isMySelf()) {
        $('.share-link').show();
    } else {
        $('.share-link').hide();
    }
}

function toolTipChangeHasData(hasData) {
    allowShareUserHerselfDataOnly();

    if (hasData) {
        $(".heropage-hero-tooltips__wrap").show();
        $(".heropage-hero-tooltips--empty").hide();
    } else {
        $(".heropage-hero-tooltips__wrap").hide();
        $(".heropage-hero-tooltips--empty").show();
    }
}


/* 常用英雄 tips 窗口 */
function setupInteractiveTipsWin() {
    var enterTimeout, leaveTimeout, canBeClosed;

    $("#m-myhero-table").on('mouseenter', '.avatar', function (e) {
      var $el = $(this).find('img');
      var pos_left = $el.offset().left + $el.outerWidth() + 6;
      var pos_top = $el.offset().top + ($el.outerHeight() / 2) - 80;
      var name = $el.attr('champion-name');

      //为了防止hover层出底边界，对pos_top做特殊处理
      if(pos_top > 261) {
        pos_top = 272;
      }

      renderHeroHover(name).done(function(tdata) {
        clearTimeout(enterTimeout);
        clearTimeout(leaveTimeout);
        canBeClosed = true;
        if($(".hover-content")) $(".hover-content").remove();
        var $hContent = $("<div class='hover-content'></div>");

        if(tdata.status == 10402) {
          tdata.noData = true;
          tdata.tipMsg = "因长时间没有游戏，数据无法采集";
          $hContent.addClass("blank-content");         
        }

        //截图url
        var shotUrl = "http://lolbox.duowan.com/playerDetail/championsStatShareShot.php?serverName=" + self.serverName + "&playerName=" + self.playerName + "&ch=" + name + "&openmode=default";

        tdata.shotUrl = shotUrl;

        var template = _.template($("#heroHoverTemp").html());
        $hContent.html(template({
          data: tdata
        })).css({
          left: pos_left,
          top: pos_top
        });
        
        enterTimeout = setTimeout(function(){
          $('body').append($hContent);
          if (SnsShare) SnsShare.init();
        }, 100);
      }, function(msg){});
    });

    $("#m-myhero-table").on('mouseleave', '.avatar', function (e) {
       e.preventDefault();
      clearTimeout(enterTimeout);
      clearTimeout(leaveTimeout);

      leaveTimeout = setTimeout(function(){
        if(canBeClosed) $(".hover-content").remove();
      }, 150);

      $(".hover-content").on('mouseenter', function(e) {
        canBeClosed = false;
      }).on('mouseleave',function(e) {
          clearTimeout(leaveTimeout);
          leaveTimeout = setTimeout(function(){
            $(".hover-content").remove();
          }, 150);
      }); 
    });
}

function renderHeroHover(name) {
  //英雄浮窗数据获取url
  var b_url = baseUrl + "?_do=personal/mostusedchampion&serverName=" + serverName + "&playerName=" + playerName;
  var url = b_url + "&zhName=" + name + "&playerId=" + playerId;

  return $.ajax({
    url: url,
    type: 'GET',
    dataType: 'jsonp'
  });
}

function setupInteractiveAchievementCopy() {
    $('#heropage-hero-sharetips .copy').click(function () {
        if (window.clipboardData && window.clipboardData.setData !== undefined) {
            var achievement = $('#achievementInTextPlain').text();
            window.clipboardData.setData('Text', achievement);
            alert('复制成功');
        }

        event.preventDefault();
    });
}

function setupInteractiveScreenShot() {
    $('#heropage-hero-sharetips .screenshot').click(function () {

        var qs = $.param({
            serverName: serverName,
            playerName: playerName,
            ch: $(this).attr('champion-name')
        });
        var newURL = 'http://lolbox.duowan.com/playerDetail/championsStatShareShot.php?' + qs + '&openmode=default';
        window.open(newURL);

        event.preventDefault();
    });
}


function getShareButtonName(classNameList) {
    for (var i = 0; i < classNameList.length; i++) {
        var name = classNameList[i];
        if (!name.startsWith('item')) {
            return name;
        }
    }
}

function setupInteractiveShare() {
    $('.share-link a').click(function () {
        var classNameList = $(this).attr('class').split(' ');
        var btnName = getShareButtonName(classNameList);

        var qs = $.param({
            serverName: serverName,
            playerName: playerName,
            ch: $(this).parent().attr('champion-name'),
            shareVia: btnName
        });
        var newURL = '/playerDetail/championsStatShare.php?' + qs + '&openmode=default';
        window.open(newURL);
        event.preventDefault();
    });
}

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

    setupInteractiveSorting();

    // setupInteractiveTipsWin();

    setupInteractiveAchievementCopy();
    setupInteractiveScreenShot();
    setupInteractiveShare();

    //分享
    jiathis_config = {
        title: "#无盒子 不开撸# 我是" + playerName+"，我在使用LOL盒子。来看看我的战斗力有多少吧！",
        appkey: {
            "tsina": "3629014272",
            "tqq": "801220649",
            "qzone": "100302822"
        },
        summary: " ",
        ralateuid: {
            "tsina": "2909042820"
        }
    };
    if (playerMostUsedHero)
        jiathis_config.pic = 'http://lolbox.duowan.com/images/champions/' + playerMostUsedHero + '_120x120.png';
    if (SnsShare) SnsShare.init();
    
    loadData();
});

