/*
* implement this for IE6
* https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
* */
if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun/*, thisArg*/) {
        'use strict';

//        if (this === void 0 || this === null) {
        if (this === null) {
            throw new TypeError();
        }

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== 'function') {
            throw new TypeError();
        }

        var res = [];
        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
        for (var i = 0; i < len; i++) {
            if (i in t) {
                var val = t[i];

                // NOTE: Technically this should Object.defineProperty at
                //       the next index, as push can be affected by
                //       properties on Object.prototype and Array.prototype.
                //       But that method's new, and collisions should be
                //       rare, so use the more-compatible alternative.
                if (fun.call(thisArg, val, i, t)) {
                    res.push(val);
                }
            }
        }

        return res;
    };
}

var gResults = null; // keep origin for filtering
var gResultsUsing = null;

var gPageIndex = 0;
var gTotalItems = 0;
var gTotalPages = 0;
var ITEMS_PER_PAGE = 10;

var gSorting = {
    defaultSortByField: 'present_rate',

    // low to high
    present_rate: false,
    win_rate: true
};

/*
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));
    }
};


function updateTable() {
    gTotalItems = gResultsUsing.length;
    gTotalPages = Math.ceil(gTotalItems / ITEMS_PER_PAGE);

    if (gResultsUsing.length) {
        if (gPageIndex > (gTotalPages - 1)) {
            return;
        }
    }

    var output = '';
    for (var i = 0; i < ITEMS_PER_PAGE; i++) {
        var offset = i + gPageIndex * ITEMS_PER_PAGE;
        var item = gResultsUsing[offset];

        if (item) {
            var firstColumn;
            var championPresentRate = item.champion_present_rate;
            var champion = championPresentRate.champion;
            if (offset >= 0 && offset <= 2) {
                firstColumn = '<td align="center" class="type1"><img src="http://img.lolbox.duowan.com/icon-herorank-top' + (offset + 1) + '.jpg" /></td>';
            } else {
                firstColumn = '<td align="center" class="type1">' + (offset + 1) + '</td>';
            }

            output += '<tr>' +
                firstColumn +
                '<td valign="middle" class="type2"><span class="hero-name"><img src="' + champion.url_img['28x28'] + '" alt="' + champion['name'] + ' image" />' + champion['title'] + '</span></td>' +
                '<td align="center" class="type3">' + championPresentRate['present_rate'].toFixed(2) + '%</td>' +
                '<td align="center" class="type4">' + championPresentRate['win_rate'].toFixed(2) + '%</td>' +
                '<td align="center" class="type5">' + championPresentRate['total_present'] + '</td>' +
                '<td align="center" class="type6"><a href="heroTop10Players.html?hero=' + champion['name'] + '">查看榜单</a></td>' +
                '</tr>';
        }
    }

    if (!output) {
        output += '<tr><td colspan="6" align="center" style="padding-top: 80px; font-weight: bolder; font-size: 30px; color: #c00;">没有找到匹配英雄</td></tr>';
    }

    $('#rankListBody').html(output);

    updatePaginator();
}

function paginatorJump() {
    var index = Number(document.getElementById('go').value) - 1;
    if (index > -1 && index < gTotalPages) {
        gPageIndex = index;
        updateTable();
    } else {
        $('#rankListBody').html('<tr><td colspan="6">输入页数不正确</td></tr>');
    }
}

function filterChampion(name) {
    if (!name) {
        gResultsUsing = gResults;
        updateTable();
        return;
    }

    function filterFn(item) {
        var nameLower = name.toLowerCase();
        return item['nameUS'].toLowerCase().indexOf(nameLower) >= 0 ||
            item['nameCN'].toLowerCase().indexOf(nameLower) >= 0 ||
            item['titleCN'].indexOf(nameLower) >= 0;
    }

    gResultsUsing = gResults.filter(filterFn);
    updateTable();
}

function updatePaginator() {
    var output = '';
    output += '<a>第' + (gPageIndex + 1) + '/' + gTotalPages + '页</a>';
    if (gPageIndex > 0) {
        output += '<a title="上一页" class="pre-next" rel="prev" href="#" onclick="javascript:gPageIndex--;updateTable();">上一页</a>';
    }
    if (gPageIndex < (gTotalPages - 1)) {
        output += '<a title="下一页" class="pre-next" rel="next" href="#" onclick="javascript:gPageIndex++;updateTable();">下一页</a>';
    }
    output += '<a class="current">第 <input type="text" id="go" size=1 value="' + (Number(gPageIndex) + 1) + '"/>页 </a> <a href="#" class="page-go" onclick="javascript:paginatorJump();"> Go </a> ';
    $('#pages').html(output);
}

function parseQueryString(qs)
{
    if (!qs) {
        var parser = document.createElement('a');
        parser.href = window.location.toString();
        qs = parser.search;
        qs = qs.replace(/^\?/, '');
    }

    var d = {};
    var a = qs.split('&');
    for (var i in a)
    {
        var b = a[i].split('=');
        d[decodeURIComponent(b[0])] = decodeURIComponent(b[1]);
    }

    return d;
}

function isIE() {
    var ua = window.navigator.userAgent;
    return ua.indexOf("MSIE ") > 0;
}

function loadRankData(tabRank) {
    $('#rankListBody').html('<tr><td colspan="6" align="center"><img src="img/loading.gif" width="400" height="400"></td></tr>');

    var data;
    var url = "http://api.lolbox.duowan.com/api/v2/rank/champion_present_rate/" + tabRank + '/';
    if (!isIE) {
        data = parseQueryString();
    } else {
        data = {};
    }
    data['rank'] = tabRank;

    $.ajax({
        url: url,
        dataType:'jsonp',
        success:function (resp) {
            var results = resp.results;
            if (!results || !results.length) {
                $('#rankListBody').html('<tr><td colspan="6">暂无数据，请稍后重试</td></tr>');
                return;
            }

            for(var i=0;i<results.length;i++) {
                var item = results[i],
                    championPresentRate = item.champion_present_rate;
                item.present_rate = championPresentRate.present_rate;
                item.total_present = championPresentRate.total_present;
                item.win_rate = championPresentRate.win_rate;
            }

            gResults = results;
            gResultsUsing = results;
            resortResult();
        },
        error:function () {
            $('#rankListBody').html('<tr><td colspan="6">获取数据失败，请稍后重试！</td></tr>');
        }
    });
}

function resortResult(fieldName) {
    if (!fieldName) {
        fieldName = gSorting.defaultSortByField;
    }

    var reverse = gSorting[fieldName];
    var sortBy = sort_by(fieldName, reverse, parseFloat)
    gResultsUsing.sort(sortBy);
    updateTable();

    updateSortByFieldNameTextStyle(fieldName);
}

function updateSortByFieldNameTextStyle(fieldName) {
    $('#presentRate').css('font-weight', 'normal');
    $('#winRate').css('font-weight', 'normal');
    $("#" + fieldName).css('font-weight', 'bolder');
}

$(document).ready(function () {
    $('.box-bd').keyup(function(event) {

        if (event.keyCode == 13) {
            var elementID = document.activeElement.id;

            if (elementID == "searchKey") {
                var keyword = document.getElementById('searchKey').value;
                filterChampion(keyword);
            } else if (elementID == "go") {
                paginatorJump();
            }

        }
    });

    $('#searchKey').focus(function () {
        if (this.value == '搜索英雄') {
            this.value = '';
        }
    });

    $('#btnSearch').bind("click", function (event) {
        var keyword = document.getElementById('searchKey').value;
        filterChampion(keyword);
    });


    // binding for tab onClicked
    $('.mod-tabs-trigger li').bind('click', function (event) {
        $(this).siblings().removeClass('selected').end().addClass('selected');

        gPageIndex = 0;

        gSorting.present_rate = false;
        gSorting.win_rate = true;
        var tabRank = $(this).attr('data-type');
        loadRankData(tabRank);
    });


    // binding for sortBy onClicked
    $(".m-rank-herotable").on('click', '.sort', function(event) {
        var fieldName = $(this).attr('id');

        if ($(this).hasClass('sort--up')) {
            $(this).removeClass("sort--up").addClass('sort--down');

            gSorting[fieldName] = false;
        } else if ($(this).hasClass('sort--down')) {
            $(this).removeClass("sort--down").addClass('sort--up');

            gSorting[fieldName] = true;
        }

        resortResult(fieldName);

        event.preventDefault();
    });


    $("#icon-note").hover(function () {
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    });

    gPageIndex = 0;
    loadRankData('all');

    $('.fnMenu')
        .on('click', '.refresh', function(evt){
            evt.preventDefault();
            window.location.reload();
        })
        .on('click', '.back', function(evt){
            evt.preventDefault();
            window.history.back();
        });
});


