var theList;
var pageSize = 48;
var pageCount;
var theNavA;
var theArea;
var thePage;
var theRadio;
var isLogin;
var showLoginWindow;
var playtimes = 0;
if (self == parent) {
    isLogin = 1;
    showLoginWindow = function() {
        alert('请先登录');
    };
} else {
    isLogin = parent.J.isLogin;
    showLoginWindow = function(s) {
        parent.showLoginWindow(s || "请先登录再进行操作:");
    };
}
function $id(s) {
    return document.getElementById(s);
}
var playerErr = 0;
var player = function() {
    var v0 = +getCookie('volume') || 50;
    var isie = navigator.appName == 'Microsoft Internet Explorer';
    var mp2 = $id('mp2');
    mp2.innerHTML = playerHTML(false, null);
    var wmp = $id('player' + (isie ? 'object': 'embed'));
    var bar = $id('mpvolbar');
    var val = $id('mpvolval');
    var blk = $id('mpvolblk');
    var bt_play = $id('mpplay');
    var bt_stop = $id('mpstop');
    var mpinfo = $id('mpinfo');
    var mpinfo2 = $id('mpinfo2');
    var timer = setTimeout(updateInfo, 300);
    var x0;
    var uped;
    var w_bar = bar.offsetWidth;
    var w_blk = blk.offsetWidth;
    bt_play.onclick = function() {
        play();
        return false;
    };
    bt_stop.onclick = function() {
        stop();
        return false;
    };
    blk.onmousedown = slideStart;
    setClick();
    try {
        setVol(v0);
    } catch(e) {
        playerErr = 1;
        $('#wmpts').show().find('a').attr('href', wmpdlurl);
    }
    function playerHTML(autoStart, url) {
        var s = '<object id=playerobject classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="788" height="64">';
        if (url) s += '<param value="' + url + '" name="URL">';
        s += '<param value="' + (autoStart || false) + '" name="AutoStart">';
        s += '<param value="9999" name="PlayCount">';
        s += '<param name=EnableContextMenu value=false>';
        s += '<param name=enableErrorDialogs value=false>';
        if (!isie) s += '<embed id="playerembed" type="application/x-mplayer2" pluginspage="http://microsoft.com/windows/mediaplayer/en/download/"' + (url ? ' src="' + url + '"': '') + ' width="788" height="64">';
        s += '</object>';
        return s;
    }
    function setVol(n) {
        if (n < 0) n = 0;
        if (n > 100) n = 100;
        wmp.settings.volume = n;
        val.style.width = ~~ ((w_blk * 100 + n * (w_bar - w_blk)) / w_bar) + '%';
    }
    function move(e) {
        setVol(v0 + ~~ (((e || window.event).clientX - x0) * 100 / (w_bar - w_blk)));
    }
    function setClick() {
        bar.onclick = click;
    }
    function up() {
        if (uped) return;
        uped = true;
        if (blk.setCapture) {
            blk.onmousemove = null;
            blk.onmouseup = null;
            blk.onlosecapture = null;
            blk.releaseCapture();
        } else {
            document.removeEventListener('mousemove', move, true);
            document.removeEventListener('mouseup', up, true);
        }
        setVol(v0 = wmp.settings.volume);
        setCookie('volume', v0, 30);
        setTimeout(setClick, 1);
    }
    function click(e) {
        if (!e) e = window.event;
        var x = e.offsetX || e.layerX;
        wmp.settings.volume = ~~ ((x - w_blk / 2) * 100 / (w_bar - w_blk));
        setVol(v0 = wmp.settings.volume);
        setCookie('volume', v0, 30);
    }
    function slideStart(e) {
        if (!e) e = window.event;
        x0 = e.clientX;
        uped = false;
        bar.onclick = null;
        if (blk.setCapture) {
            blk.onmousemove = move;
            blk.onmouseup = up;
            blk.onlosecapture = up;
            blk.setCapture();
        } else {
            document.addEventListener('mousemove', move, true);
            document.addEventListener('mouseup', up, true);
        }
        if (e.preventDefault) {
            e.preventDefault();
            e.stopPropagation();
        } else {
            e.returnValue = false;
            e.cancelBubble = true;

        }
    }
    function updateInfo() {
        try {
            var n = wmp.playState,
            s;
            switch (n) {
            case 3:
                s = '正在播放: ' + theRadio.name;
                break;
            default:
                s = wmp.status;
            }
            switch (n) {
            case 0:
            case 1:
            case 2:
            case 10:
                btn_play();
                break;
            case 3:
            default:
                btn_stop();
                break;
            }
            timer = setTimeout(updateInfo, 300);
        } catch(e) {
            s = e + '';
        }
        showInfo(s);
    }
    function showInfo(s) {
        if (!s) s = '爱上广播，爱上1616！';
        if ('innerText' in mpinfo) mpinfo.innerText = s;
        else mpinfo.textContent = s;
    }
    function play(s) {
        if (! (s || wmp.url || wmp.src)) {
            Ts.show('请选择要播放的广播', 'alert');
            return;
        }
        if (s) {
            if (isie) wmp.url = s;
            else {
                mp2.innerHTML = playerHTML(true, s);
                wmp = $id('playerembed');
                setVol(v0);
            }
        }
        wmp.controls.play();
        clearTimeout(timer);
        updateInfo();
    }
    function stop() {
        wmp.controls.stop();
        clearTimeout(timer);
        updateInfo();
    }
    function btn_play() {
        bt_play.style.display = 'block';
        bt_stop.style.display = 'none';
    }
    function btn_stop() {
        bt_play.style.display = 'none';
        bt_stop.style.display = 'block';
    }
    return {
        play: play,
        stop: stop
    };
} ();
var busy = false;
function unBusy() {
    busy = false;
}
function CB(f) {
    return f ?
    function(r) {
        busy = false;
        f(r);
    }: unBusy;
}
function ajaxPost(url, s, cb) {
    if (busy) return;
    busy = true;
    $.post(url, s, CB(cb));
}
function ajaxGet(url, cb) {
    if (busy) return;
    busy = true;
    $.get(url, CB(cb));
}
function htmlEncode(s) {
    return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function emptyFunc() {}
function getCookie(name) {
    var re = new RegExp('(?:^| )' + name + '=([^;]*)');
    var a = document.cookie.match(re);
    if (!a) return '';
    return unescape(a[1]);
}
function setCookie(name, value, days) {
    var d = new Date;
    d.setDate(d.getDate() + days);
    document.cookie = name + '=' + escape(value) + '; expires=' + d.toGMTString();
}
function inArr(a, v) {
    for (var i = a.length; i--;) if (v == a[i]) return i;
    return - 1;
}
function addToHis(id) {
    ajaxPost('index.php?a=count', 'id=' + id);
    if (!isLogin) {
        var a = getCookie('his');
        a = a ? a.split(',') : [];
        var n = inArr(a, id);
        if (n != -1) a.splice(n, 1);
        if (a.length < pageSize + 3) {
            a.unshift(id);
        }
        setCookie('his', a.join(), 30);
    }
}
function play(i) {
    if (theRadio) blurit(theRadio.id);
    if (!isLogin && ++playtimes > 5) {
        showLoginWindow('登录后,可以收藏自己喜欢的电台哦!');
        playtimes = 0;
        return false;
    }
    theRadio = theList[i];
    focusit(theRadio.id);
    addToHis(theRadio.id);
    player.play(theRadio.address, theRadio.name);
    $('#mpinfo2').text(theRadio.frequency);
    return false;
}
function json_decode(s) {
    return eval('0,' + s);
}
var i_del;
function cbAddToFav(r) {
    Ts.show(r == 'true' ? '添加成功': r == 'false' ? '添加失败': r, r == 'true' ? 'valid': 'alert');
}
function addToFav2(id) {
    if (!isLogin) {
        showLoginWindow();
        return;
    }
    if (id) ajaxPost('index.php?a=fav', 'id=' + id, cbAddToFav);
    else Ts.show('当前没广播', 'alert');
}
function addToFav(i) {
    addToFav2(theList[i].id);
}
function delFromFav(i) {
    ajaxPost('index.php?a=fav', 'ids=' + theList[i_del = i].id, cbDelFromFav);
}

function cbDelFromFav(r) {
    Ts.show( + r ? '删除成功': '出错啦：' + r, +r ? 'valid': 'alert');
    if ( + r) {
        var t = $id('rd' + i_del);
        t.parentNode.removeChild(t);
    }
}
function focusit(id) {
    var a = $('#it' + id);
    if (a.length) {
        a.parents('li').addClass('radio_playing').addClass('on');
        var s = a.text(),
        t;
        if (theNavA.id == 'popular') {
            var p = s.indexOf('.');
            t = s.slice(0, p);
            s = s.slice(p + 1);
        }
        a.html('<img src="http://r.9533.com/iplatform/merge/radio/img/laba.gif"' + (t ? ' alt=' + t: '') + '>' + htmlEncode(s));
    }
}
function blurit(id) {
    var a = $('#it' + id);
    if (a.length) {
        a.parents('li').removeClass('radio_playing').removeClass('on');
        var s = a.text(),
        t;
        if (theNavA.id == 'popular') {
            t = a.find('img').attr('alt');
        }
        a.text((t ? t + '.': '') + s);
    }
}
var Ts = function() {
    var div;
    var t = 0,
    th = 0;
    function show(s, c) {
        clearTimeout(th);
        clearInterval(t);
        div.innerHTML = s;
        div.className = c;
        div.style.opacity = 1;
        div.style.filter = 'alpha(opacity=100)';
        div.style.display = 'block';
        th = setTimeout(hide, 1000);
    }
    var n = 100,
    v = 10,
    a = 2;
    function _hide() {
        n -= v;
        if (n <= 0) {
            clearInterval(t);
            div.style.display = 'none';
            return;
        }
        div.style.opacity = n / 100;
        div.style.filter = 'alpha(opacity=' + n + ')';
        v += a;
    }
    function hide() {
        n = 100;
        v = 1;
        t = setInterval(_hide, 50);
    }
    function init() {
        if (!div) div = $id('ts');
    }
    return {
        show: show,
        hide: hide,
        init: init
    };
} ();
Ts.init();
function cbGetList(r) {
    $('#Lnav').find('dd.on').removeClass('on');
    $(theNavA.parentNode).addClass('on');
    var tid = theNavA.id;
    r = json_decode(r);
    var a = theList = r.list;
    var f = tid == 'myfav' ?
    function(i) {
        return '<a class="add" href="#" onclick="delFromFav(' + i + ');this.blur();return false;">删除</a>';
    }: function(i) {
        return '<a class="add" href="#" onclick="addToFav(' + i + ');this.blur();return false;">收藏</a>';
    };
    var cls = '';
    if (tid == 'region') cls = 'h2';
    else if (tid == 'myfav' || tid == 'playhis') cls = 'h3';
    var num, useNum = tid == 'popular';
    if (useNum) num = (thePage - 1) * (pageSize + (tid == 'region' ? -6 : tid == 'myfav' || tid == 'playhis' ? 3 : 0));
    var s = '<ul>';
    for (var i = 0; i < a.length; i++) {
        s += '<li id=rd' + i + '><dl><dt><a id=it' + a[i].id + ' href="#" onclick="return play(' + i + ');">' + (useNum ? ++num + '.': '') + htmlEncode(a[i].name) + '</a></dt><dd>';
        s += '<a class=play href="#" onclick="this.blur();return play(' + i + ');">播放</a> ';
        s += f(i);
        s += '</dd></dl></li>';
    }
    $('#radio_list').html(s + '</ul>')[0].className = cls;
    var re_ch = /^[\u0100-\uffff]+/;
    function setNum(a, n) {
        a.text(re_ch.exec(a.text())[0] + (n ? '(' + n + ')': ''));
    }
    if (a = r.catNum) {
        var t;
        for (i in a) {
            switch (i) {
            case 'total':
                t = $('#popular');
                a[i] = Math.min(100, a[i]);
                break;
            case 'areaTotal':
                t = $('#region');
                break;
            default:
                if ( + i) t = $('#cat' + i);
            }
            if (t) {
                setNum(t, +a[i]);
                t = null;
            }
        }
    }
    if (a = r.area) {
        theArea = r.areaIndex;
        s = '<div>';
        for (i in a) {
            s += '<a href="#" onclick="getArea(' + i + ');return false;"' + (theArea == i ? ' class=on': '') + '>' + a[i] + '</a>';
        }
        $('#region_list').html(s + '</div>').show();
    } else $('#region_list').empty().hide();
    var nb = $('#nobody').hide();
    if (tid == 'myfav' || tid == 'playhis') {
        $('#app_pages').hide();
        if (tid == 'myfav' && !theList.length) nb.html('目前没有任何收藏，<a href=# onclick="return nofav();" style="color:#008de7">请选择要收藏的广播</a>').show();
    } else {
        var ps = pageSize;
        if (tid == 'region') ps -= 6;
        var rc;
        switch (tid) {
        case 'popular':
            rc = Math.min(100, +r.catNum.total);
            break;
        case 'region':
            rc = +r.curNum;
            break;
        default:
            rc = +r.catNum[tid.slice(3)];
        }
        var pc = pageCount = Math.ceil(rc / ps);
        var sel = $id('changePage');
        sel.options.length = 0;
        for (i = 1; i <= pc; i++) sel.options.add(new Option('第' + i + '页', i));
        sel.selectedIndex = thePage - 1;
        $('#app_pages').show().find('span').text(thePage + '/' + pc);
    }
    if (theRadio) focusit(theRadio.id);
}
function getArea(n) {
    theArea = n;
    ajaxGet('index.php?type=area&s=0&l=' + (pageSize - 6) + '&v=' + n, cbGetList);
}
function pageTo(n) {
    if (1 <= n && n <= pageCount) {
        thePage = n;
        var s = '';
        var ps = pageSize;
        var tid = theNavA.id;
        switch (tid) {
        case 'popular':
            break;
        case 'region':
            s = 'type=area&v=' + theArea;
            ps -= 6;
            break;
        case 'myfav':
            s = 'a=fav&r=' + ( + new Date);
            ps += 3;
            break;
        case 'playhis':
            if (isLogin) s = 'a=his&s=0&l=' + (ps + 3);
            else s = 'a=ids&ids=' + (getCookie('his') || '');
            s += '&r=' + ( + new Date);
            break;
        default:
            s = 'type=cat&v=' + tid.slice(3);
        }
        if (tid != 'playhis') s += '&s=' + ((n - 1) * ps) + '&l=' + ps;
        ajaxGet('index.php?' + s, cbGetList);
    }
}
function getArea(n) {
    theArea = n;
    pageTo(pageCount = thePage = 1);
}
function pageFirst() {
    pageTo(1);
    return false;
}
function pagePrev() {
    pageTo(thePage - 1);
    return false;
}
function pageNext() {
    pageTo(thePage + 1);
    return false;
}
function pageLast() {
    pageTo(pageCount);
    return false;
}
$('#to-tab').find('a').each(function() {
    var a = [$('#app_radio_main')[0], $('#app_music_main')[0]];
    var t = $('#to-tab').find('a');
    var b = false;
    function Go(i) {
        return function() {
            if (i == 1) {
                try {
                    player.stop();
                } catch(e) {}
                if (!b) {
                    b = true;
                    $id('douban').src = "http://douban.fm/partner/smallplayer";
                    $id('weibo').src = "http://v.t.sina.com.cn/widget/widget_topic_mblog.php?tags=%E8%B1%86%E7%93%A3%E7%94%B5%E5%8F%B0&height=500&width=778";
                }
            }
            setCookie('tab', i, 30);
            t[1 - i].className = '';
            $(a[1 - i]).addClass('hide');
            t[i].className = 'app_bt_sc';
            $(a[i]).removeClass('hide');
        };
    }
    return function(i) {
        $(this).click(Go(i));
    };
} ()).eq(getCookie('tab') || 0).click();
function navClick() {
    if (busy) return false;
    theNavA = this;
    if (!isLogin) {
        switch (this.id) {
        case 'myfav':
            showLoginWindow();
            return false;
        }
    }
    theArea = '';
    pageTo(pageCount = thePage = 1);
    return false;
}
$('#Lnav a').click(navClick);
function getPopular() {
    navClick.call($('#Lnav a')[0]);
}
function nofav() {
    getPopular();
    return false;
}
$('#radio_list li').live('mouseover',
function() {
    var a = $(this);
    if (!a.find('img').length) a.addClass('on');
}).live('mouseout',
function() {
    var a = $(this);
    if (!a.find('img').length) a.removeClass('on');
});
void
function(a) {
    var fs = [pageFirst, pagePrev, pageNext, pageLast];
    for (var i = 0; i < 4; i++) a[i].onclick = fs[i];
} ($('#app_pages').find('a'));
$('#changePage').change(function() {
    pageTo( + this.value);
    this.blur();
});
$('#add2').click(function() {
    addToFav2(theRadio && theRadio.id);
});
function init() {
    getPopular();
}
init();
if (self == parent) {} else {
    parent.J.add('radio', {},
    window);
}