format = function (format) {
    var args = $.makeArray(arguments);
    return format.replace(/\{(\d+)\}/g, function (m, i) {
        return args[parseInt(i) + 1];
    });
}

var rate = 0;
var resTimeoutDic = {};

function pause(res, key) {
    if (resTimeoutDic[key] != undefined) {
        clearTimeout(resTimeoutDic[key]);
        resTimeoutDic[key] = undefined;
    }
    //tell backend to pause
    window.external.PauseDownload(key);
    res.find('.pauseImg').attr({ 'src': 'img/reStartDW.png', 'alt': '开始' });
    res.find('.pauseA').unbind('click').click(function () { downloadRes(res, key) });
    //res.find('.pauseA').attr({ 'src': 'img/reStartDW.png', 'alt': '开始' }).unbind('click').click(function () { downloadRes(res, key) });
    res.find('.stopA').unbind('click').click(function () { stopDownload(res, key) });
    res.find('span.status').html('已暂停');
}
function stopDownload(res, key) {
    if (resTimeoutDic[key] != undefined) {
        clearTimeout(resTimeoutDic[key]);
        resTimeoutDic[key] = undefined;
    }
    //tell backend to cancel
    window.external.CancelDownload(key);
    res.find('.resStatusActive').removeClass('resStatusActive');
    res.find(".downloadProgress").css("width", 0);

    var newbar = res.find('.resNew');
    newbar.find('.downloadA').unbind('click').click(function () { downloadRes(res, key) });
    newbar.addClass('resStatusActive');
}
function openRes(key)
{
    window.external.OpenWDRes(key);
}
function downloadRes(res, key, listKey) {
    //tell back end to start
    var listKey = res.parent().find('input[name="listKey"]').attr('value');
    window.external.StartDownload(key, listKey);

    res.find('.pauseImg').attr({ 'src': 'img/pauseDW.png', 'alt': '暂停' });
    res.find('.pauseA').unbind('click').click(function () { pause(res, key) });
    //res.find('.pauseA').attr({ 'src': 'img/pauseDW.png', 'alt': '暂停' }).unbind('click').click(function () { pause(res, key) });
    res.find('.stopA').unbind('click').click(function () { stopDownload(res, key) });
    var ingBar = res.find('.resIng');
    res.find('.resStatusActive').removeClass('resStatusActive');
    ingBar.addClass("resStatusActive");

    startUpdateDownloadbar(res, key);
}
function delRes(res, key) {
    if (resTimeoutDic[key] != undefined) {
        clearTimeout(resTimeoutDic[key]);
        resTimeoutDic[key] = undefined;
    }
    //tell back end to del
    window.external.DelRes(key);
    var delIngBar = res.find('.resDelIng');
    res.find('.resStatusActive').removeClass('resStatusActive');
    delIngBar.addClass('resStatusActive');
    startUpdateDelIngBar(res, key);
}
function updateRes(res, key) {
    //tell back end to update
    window.external.UpdateRes(key);
    var delIngBar = res.find('.resDelIng');
    res.find('.resStatusActive').removeClass('resStatusActive');
    delIngBar.addClass('resStatusActive');
    startUpdateDelIngBar(res, key);
}
function startUpdateDownloadbar(res, key) {
    resTimeoutDic[key] = setTimeout(function refreshProgress() {
        var status = $.parseJSON(window.external.GetResStatus(key));
        if (status.status == 'wait') {
            res.find('span.status').html('等待下载');
            resTimeoutDic[key] = setTimeout(refreshProgress, 1000);
        }
        else if (status.status == 'ing') {
            res.find('span.status').html('正在下载');
            res.find('.downloadProgress').css('width', status.ratio + "%");
            resTimeoutDic[key] = setTimeout(refreshProgress, 1000);
        }
        else if (status.status == 'ready') {
            res.find('.resStatusActive').removeClass('resStatusActive');
            var readyBar = res.find('.resReady');
            readyBar.find('.upA').hide();
            readyBar.find('.openA').unbind('click').click(function () {openRes(key)});
            readyBar.find('.delA').unbind('click').click(function () { delRes(res, key) });
            readyBar.addClass('resStatusActive');
        }
        else if (status.status == 'new') {
            res.find('.resStatusActive').removeClass('resStatusActive');
            var newbar = res.find('.resNew');
            newbar.find('.downloadA').unbind('click').click(function () { downloadRes(res, key) });
            newbar.addClass('resStatusActive');
        }
    }, 1000);
}
function startUpdateDelIngBar(res, key) {
    resTimeoutDic[key] = setTimeout(function refreshDelBar() {
        var status = $.parseJSON(window.external.GetResStatus(key));
        if (status.status == 'delIng' || status.status == 'toUpDel') {
            resTimeoutDic[key] = setTimeout(refreshDelBar, 1000);
        }
        else {
            refreshResStatus(res, key, status);
        }
    }, 1000);
}
function refreshResStatus(res, key, status) {
    res.find('.resStatusActive').removeClass('resStatusActive');

    if (status.status == 'new') {
        var newbar = res.find('.resNew');
        newbar.find('.downloadA').unbind('click').click(function () {downloadRes(res, key)});
        newbar.addClass('resStatusActive');
    }
    else if (status.status == 'pause') {
        res.find('.pauseImg').attr({ 'src': 'img/reStartDW.png', 'alt': '开始' });
        res.find('.pauseA').unbind('click').click(function () { downloadRes(res, key) });
        //res.find('.pauseA').attr({ 'src': 'img/reStartDW.png', 'alt': '开始' }).unbind('click').click(function () { downloadRes(res, key) });
        res.find('.stopA').unbind('click').click(function () { stopDownload(res, key) });
        res.find('span.status').html('已暂停');
        var ingBar = res.find('.resIng');
        ingBar.find(".downloadProgress").css("width", status.ratio + "%");
        ingBar.addClass('resStatusActive');
    }
    else if (status.status == 'ready') {
        var readyBar = res.find('.resReady');
        readyBar.find('.openA').click(function () { openRes(key) });
        readyBar.find('.upA').hide();
        readyBar.find('.delA').unbind('click').click(function () { delRes(res, key) });
        readyBar.addClass('resStatusActive');
    }
    else if (status.status == 'ing' || status.status == 'wait') {
        res.find('.pauseImg').attr({ 'src': 'img/pauseDW.png', 'alt': '暂停' });
        res.find('.pauseA').unbind('click').click(function () { pause(res, key) });
        //res.find('.pauseA').attr({ 'src': 'img/pauseDW.png', 'alt': '暂停' }).unbind('click').click(function () { pause(res, key) });
        res.find('.stopA').unbind('click').click(function () { stopDownload(res, key) });
        var ingBar = res.find('.resIng');
        ingBar.find(".downloadProgress").css("width", status.ratio + "%");
        ingBar.addClass('resStatusActive');
        startUpdateDownloadbar(res, key);
    }
    else if (status.status == 'toUp') {
        var readyBar = res.find('.resReady');
        readyBar.find('.openA').unbind('click').click(function () { openRes(key) });
        readyBar.find('.upA').unbind('click').click(function () { updateRes(res, key) }).show();
        readyBar.find('.delA').unbind('click').click(function () { delRes(res, key) });
        readyBar.addClass('resStatusActive');
    }
    else if (status.status == 'delIng' || status.status=='toUpDel') {
        var delIngBar = res.find('.resDelIng');
        delIngBar.addClass('resStatusActive');
        startUpdateDelIngBar(res, key);
    }
}
function refreshAllResStatus() {
    resTimeoutDic = {};
    $('div.resItem').each(function () {
        var res = $(this);
        var key = $(this).find('input[name="key"]').attr('value');
        var status = $.parseJSON(window.external.GetResStatus(key));
        refreshResStatus(res, key, status);
    });
}

//var st = {};
//GetResStatus(key) {
//    if (st[key] != undefined) {
//        st[key] = st[key] + 20;
//        if (st[key] < 100) {
//            return '{"status":"ing", "ratio":' + st[key] + '}';
//        }
//        else {
//            return '{"status":"ready","ratio":0}';
//        }
//    }
//    else {
//        st[key] = 0;
//        return '{"status":"new","ratio":0}';
//    }
//}

function resolveAlbumAndRender(res, ele) {
    var album;
    try
    {
        album = eval('(' + res + ')');
    }
    catch(e)
    {
        showNetError(e.message);
        return;
    }

    if (album.info) {
        var inf = album.info;

        $(".pageTitle").html(inf.name);
        var txt = '';
        
        txt += format('\
  <div class="album_in_scroll">\
    <div class="albumInfo">\
      <div><b>简介：</b><span>{1}</span></div>\
      <div><b>文件数：</b><span>{2}</span></div>\
      <div><b>分类：</b><span>{3}</span></div>\
      <input type="hidden" name="listKey" value="{4}" />\
    </div>\
    <div class="albumFont">文件列表：</div>', inf.name, inf.description, inf.totalResCnt, inf.paths[0], inf.key);

        for (var i = 0; i < album.reses.length; i++) {
            var res = album.reses[i];
            txt += format('\
<div class="resItem">\
      <div class="resTitle">{0}</div>\
      <input type="hidden" name="key" value="{1}"/>\
      <div class="resStatusBar">\
        <div class="resNew resStatusActive">\
          <div class="infBar"><span>大小</span><span>{2}M</span></div><div class="opsBar"><div style="display:inline" class="downloadA"><img src="img/download.png" alt="下载"/></div></div>\
        </div>\
        <div class="resReady"><div class="infBar"><span>大小</span><span>{2}M</span></div>\
          <div class="opsBar"><div style="display:inline" class="upA" ><img src="img/updateWD.png" alt="更新" style="display:none"/></div>\
            <div style="display:inline" class="openA" ><img src="img/openWD.png" alt="打开"/></div>\
          <div style="display:inline" class="delA" ><img src="img/delete.png" alt="删除"/></div></div>\
        </div>\
        <div class="resIng"><div class="infBar"><span class="downloadBar"><span class="downloadProgress" style="width:0;margin-left:0"></span></span><span class="status"></span></div>\
          <div class="opsBar"><div style="display:inline" class="pauseA"><img class="pauseImg"/></div><div style="display:inline" class="stopA" ><img alt="取消" src="img/stop.png"/></div></div>\
        </div>\
        <div class="resDelIng"><span>大小</span><span>{2}M</span><span>正在删除</span></div>\
      </div>\
    </div>', res.name, res.key, res.size/1000);
        }
        txt += '</div>';
        ele.html(txt);
        refreshAllResStatus();
    }
}
function resolveAlbumListAndRender(res, ele) {
    var albumList;
    try {
        albumList = eval('(' + res + ')');
    }
    catch (e) {
        showNetError(e.message);
        return;
    }

    if (albumList.info) {
        var inf = albumList.info;
        $(".pageTitle").html(inf.name);
        var txt = '';
        txt += format('\
  <div class="albumLink_in_scroll">');

        for (var i = 0; i < albumList.albumLinks.length; i++) {
            var albumLink = albumList.albumLinks[i];
            txt += format('\
<div class="albumLink">\
      <div class="albumImg"></div>\
      <input type="hidden" name="key" value="{0}" />\
      <div class="albumT">{1}</div>\
    </div>', albumLink.key, albumLink.name);
        }

        txt += '</div>';
        ele.html(txt);
        $('.albumLink').each(function () {
            $(this).click(function () {
                var key = $(this).find('input[name="key"]').attr('value');
                showAlbum(key);
            });
        });
    }
}
function resovleNavigateGroupAndRender(res, ele) {
    var naviGroup;
    try {
        var naviGroup = eval('(' + res + ')');
    }
    catch (e) {
        showNetError(e.message);
        return;
    }
    
    var txt = '';

    if (naviGroup.info) {
        if (naviGroup.albumLinkGroups) {
            var arr = $.grep(naviGroup.albumLinkGroups, function (ele, i) { return ele.Key == 'hottest' });
            if (arr.length > 0) {
                var links = arr[0].Value;
                txt += '<div>';
                $(links).each(function () {
                    txt += format('\
									<div class="albumLink">\
                        <div><img class="albumImg" src="{0}"/></div>\
                        <input type="hidden" name="key" value="{1}" />\
                        <p><span>名称</span><span>{2}</span></p>\
                        <p><span>简介</span><span>{3}</span></p>\
                      </div>', this.picURL, this.key, this.name, this.description);
                });
                txt += '</div>';
            }
        }
        if (naviGroup.albumListLinkGroups) {
            txt += '<div>';
            $(naviGroup.albumListLinkGroups).each(function () {
                $(this.Value).each(function () {
                    txt += format('\
								<div class="albumListLink">\
								<div><img class="albumImg" src="{0}"/></div>\
								<input type="hidden" name="key" value="{1}" />\
								<p><span>名称</span><span>{2}</span></p>\
								<p><span>简介</span><span>{3|</span></p>\
								</div>', this.picURL, this.key, this.name, this.description);
                });
            });
        };
        txt += '</div>';

        if (naviGroup.naviLinkGroups) {
            txt += '<div>';
            $(naviGroup.albumListLinkGroups).each(function () {
                $(this.Value).each(function () {
                    txt += format('\
								<div class="naviLink">\
								<div><img class="albumImg" src="{0}"/></div>\
								<input type="hidden" name="key" value="{1}" />\
								<p><span>名称</span><span>{2}</span></p>\
								<p><span>简介</span><span>{3|</span></p>\
								</div>', this.picURL, this.key, this.name, this.description);
                });
            });
        };
        txt += '</div>';
    }
    ele.html(txt);
    $('.albumLink').each(function () {
        $(this).click(function () {
            var key = $(this).find('input[name="key"]').attr('value');
            showAlbum(key);
        });
    });
    $('.albumListLink').each(function () {
        $(this).click(function () {
            var key = $(this).find('input[name="key"]').attr('value');
            showAlbumList(key);
        });
    });
    $('.naviLink').each(function () {
        $(this).click(function () {
            var key = $(this).find('input[name="key"]').attr('value');
            showNavi(key);
        });
    });
}

function updateRefreshButton(avail) {
    if (avail) {
        $(".refreshButton").removeClass("refreshButtonBusy").addClass("refreshButtonIdle");
    }
    else {
        $(".refreshButton").removeClass("refreshButtonIdle").addClass("refreshButtonBusy");
    }
}

var curToken = -1;
var tokenPoolSize = 10;
function applyToken() {
    var res;
    if (curToken == -1) {
        res = 0;
    }
    res = (++curToken) % tokenPoolSize;
    curToken = res;
    updateRefreshButton(false);
    return res;
}
function verifyCurToken(token) {
    return curToken == token;
}
function clearToken(token) {
    if (curToken == token) {
        curToken = -1;
        updateRefreshButton(true);
    }
}

var viewPath = [];
function naviToHere(key, type) {
    viewPath.push({ KEY: key, TYPE: type });
    if (viewPath.length >= 2) {
        $('#naviBack').show();
    }
    else {
        $('#naviBack').hide();
    }
}
function naviBack() {
    hideNetError();
    viewPath.pop();
    var pre = viewPath.pop();
    if (pre == undefined) {
        return;
    }
    switch (pre.TYPE) {
        case "navi":
            showNavi(pre.KEY);
            break;
        case "albumList":
            showAlbumList(pre.KEY);
            break;
        case "hp":
            showHP();
            break;
    }
}
function refreshCurPage() {
    hideNetError();
    var cur = viewPath.pop();
    if (cur) {
        switch (cur.TYPE) {
            case "navi":
                showNavi(cur.KEY);
                break;
            case "albumList":
                showAlbumList(cur.KEY);
                break;
            case "hp":
                showHP();
                break;
            case "album":
                showAlbum(cur.KEY);
                break;
        }
    }
    else {
        showHP();
    }
}

function showHP() {
    var dispatcher = function (hpJson) {
        var hp = eval('(' + hpJson + ')');
        //$('#main').html(hp.type);
        switch (hp.type) {
            case "Navi":
                resovleNavigateGroupAndRender(hpJson, $('#main'));
                break;
            case "AlbumList":
                resolveAlbumListAndRender(hpJson, $('#main'));
                break;
            case "Album":
                resolveAlbumAndRender(hpJson, $('#main'));
                break;
        }
        naviToHere("", "hp");
    }
   
    var postData = window.external.GetReadyResInfo();
    var hpJson;

    var token = applyToken();

    var hpURL = "http://bdservice.cloudapp.net/wdapi/hp";
    jQuery.support.cors = true;
    $.ajax({
        url: hpURL,
        type: 'POST',
        data: postData,
        success: function (data) {
            if (verifyCurToken(token) == false) {
                clearToken(token);
                return;
            }
            hpJson = data;
            window.external.RegistHPData(hpJson);
            dispatcher(hpJson);
            clearToken(token);
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        showNetError();
        clearToken(token);
    });
}
function showNavi(key) {
    var token = applyToken();
    var postData = window.external.GetReadyResInfo();
    postData = postData + "targetKey:" + key + ";";
    var json;
    var url = "http://bdservice.cloudapp.net/wdapi/hp";
    jQuery.support.cors = true;
    $.ajax({
        url: url,
        type: 'POST',
        data: postData,
        success: function (data) {
            if (verifyCurToken(token) == false) {
                clearToken(token);
                return;
            }
            json = data;
            resovleNavigateGroupAndRender(json, $('#main'));
            naviToHere(key, "navi");
            clearToken(token);
        }
    }).fail(function() {
        showNetError();
        clearToken(token);
    });
}
function showAlbumList(key) {
    var token = applyToken();
    var postData = window.external.GetReadyResInfo();
    postData = postData + "targetKey:" + key + ";";
    var json;
    var url = "http://bdservice.cloudapp.net/wdapi/albumList";
    jQuery.support.cors = true;
    $.ajax({
        url: url,
        type: 'POST',
        data: postData,
        success: function (data) {
            if (verifyCurToken(token) == false) {
                clearToken(token);
                return;
            }
            json = data;
            window.external.RegistNewAlbumList(json);
            resolveAlbumListAndRender(json, $('#main'));
            naviToHere(key, "albumList");
            clearToken(token);
        }
    }).fail(function () {
        showNetError();
        clearToken(token);
    });
}
function showAlbum(key) {
    var token = applyToken();
    var json;
    var url = "http://bdservice.cloudapp.net/wdapi/album";
    var postData = window.external.GetReadyResInfo();
    postData = postData + "targetKey:" + key + ";";
    jQuery.support.cors = true;
    $.ajax({
        url: url,
        type: 'POST',
        data: postData,
        success: function (data) {
            if (verifyCurToken(token) == false) {
                clearToken(token);
                return;
            }
            json = data;
            window.external.RegistNewAlbum(json);
            resolveAlbumAndRender(json, $('#main'));
            naviToHere(key, "album");
            clearToken(token);
        }
    }).fail(function () {
        showNetError();
        clearToken(token);
    });
}
//Used by wdAlbumTransit.html only
function showAlbumFromMain() {
    var key = window.external.GetCurAlbumKey();
    var isHisExist = window.external.IsAlbumExist(key);
    var json;
    if (isHisExist == true) {
        json = window.external.GetAlbumJson(key);
        resolveAlbumAndRender(json, $('#main'));
    }
    else {
        var url = "http://bdservice.cloudapp.net/wdapi/album";
        var postData = window.external.GetReadyResInfo();
        postData = postData + "targetKey:" + key + ";";
        jQuery.support.cors = true;
        $.ajax({
            url: url,
            type: 'POST',
            data: postData,
            success: function (data) {
                json = data;
                window.external.RegistNewAlbum(json);
                resolveAlbumAndRender(json, $('#main'));
            }
        });
    }
}

function showNetError() {
    $('#netErrorMessage').show();
}
function hideNetError() {
    $('#netErrorMessage').hide();
}

function fixPNG(myImage) {
    var arVersion = navigator.appVersion.split("MSIE");
    var version = parseFloat(arVersion[1]);
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
        var imgID = (myImage.id) ? "id='" + myImage.id + "' " : "";
        var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : "";
        var imgTitle = (myImage.title) ? "title='" + myImage.title + "' " : "title='" + myImage.alt + "' ";
        var imgStyle = "display:inline-block;" + myImage.style.cssText;
        var strNewHTML = "<span " + imgID + imgClass + imgTitle

      + " style=\"" + "width:" + myImage.width

      + "px; height:" + myImage.height

      + "px;" + imgStyle + ";"

      + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"

      + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>";
        myImage.outerHTML = strNewHTML;
    }
}