
$(document).ready(
function () 
{
	//ban drag of <img> and select of header
	$('img').bind('dragstart', function(){return false;});
    $('#header').bind('selectstart', function(){ return false;});

	window.external.GetRadios();
	window.external.GetAlbums();
	
	window.external.GetList();
	window.external.GetBookmark();
	window.external.GetDownload();
	window.external.InitItems();
});


//to detect whether a function exists
function funExists(funName)
{ 
	try
	{  
		if (typeof eval(funName)=="undefined"){return false;} 
		if (typeof eval(funName)=="function"){return true;}
	}
	catch(e)
	{
		return false;
	} 
} 


function cancelBubble()
{
	window.event.cancelBubble=true;
}


//------------------------------------------------------------------------------
//获取元素的纵坐标 
function getTop(e)
{ 
	var offset=e.offsetTop; 
	if (e.offsetParent!=null) offset+=getTop(e.offsetParent); 
	return offset; 
} 
//获取元素的横坐标 
function getLeft(e)
{ 
	var offset=e.offsetLeft; 
	if (e.offsetParent!=null) offset+=getLeft(e.offsetParent); 
	return offset; 
} 

//获取所有class==n的元素
function getElementsByClassName(n) 
{ 
	var classElements = [],allElements = document.getElementsByTagName('*'); 
	for (var i=0; i< allElements.length; i++ ) 
	{ 
		if (allElements[i].className == n ) 
		{ 
			classElements[classElements.length] = allElements[i]; //某类集合
		} 
	} 
	return classElements; 
}

//内存回收
window.setInterval(
function gc(){ if (document.all) CollectGarbage(); }, 
60000
); 

//----------------------------------------------------
function GetRadios_Fail()
{
	$('.radio_panel').css('display','none');
	$('#radios_fail').css('display','block');
	
	show_radio_msg('加载电台列表失败！');
}
function show_radio_msg(msg)
{
	$('#radio_msg').stop().html(msg).css({'display':'block','opacity':0})
	.animate({'opacity':1},100,
	function()
	{
		$('#radio_msg').animate({'opacity':1},600,function()
		{
			$('#radio_msg').animate({'opacity':0},300,function(){ $('#radio_msg').css({'display':'none'});} );	
		})
	})
}
function rf_btn_onclick()
{
	$('.radio_panel').css('display','none');
	$('#radios_loading').css('display','block');
	window.external.GetRadios();
}


function GetRadios_Succeed(radios)
{
	$('.radio_panel').css('display','none');
	$('#radios_loading').css('display','none');
	
	$('#radios').html(radios);
	setTimeout(function ()
	{
		$('#radios').css('display','block');
	},10);
}

//----------------------------------------------------
function GetAlbums_Fail()
{
	$('.album_panel').css('display','none');
	$('#albums_fail').css('display','block');
	
	show_album_msg('加载电台列表失败！');
}
function show_album_msg(msg)
{
	$('#album_msg').stop().html(msg).css({'display':'block','opacity':0})
	.animate({'opacity':1},100,
	function()
	{
		$('#album_msg').animate({'opacity':1},600,function()
		{
			$('#album_msg').animate({'opacity':0},300,function(){ $('#album_msg').css({'display':'none'});} );	
		})
	})
}
function af_btn_onclick()
{
	$('.album_panel').css('display','none');
	$('#albums_loading').css('display','block');
	window.external.GetAlbums();
}


function GetAlbums_Succeed(albums)
{
	$('.album_panel').css('display','none');
	$('#albums_loading').css('display','none');
	
	$('#albums').html(albums);
	setTimeout(function ()
	{
		$('#albums').css('display','block');
	},10);
}

//----------------------------------------------------
function GetList_Succeed(items)
{
	$('#list').html(items);
}

//----------------------------------------------------
function GetBookmark_Succeed(items)
{
	$('#bookmark').html(items);
}

//----------------------------------------------------
function GetDownload_Succeed(items)
{
	$('#download').html(items);
}

//----------------------------------------------------
function GetItemIdsInLists()
{
	var itemIds = '';
	$('.list_item').each(function(index, element) {
        itemIds += $(element).find('.li_id').html()+'\r\n'
    });
	
	$('.bookmark_item').each(function(index, element) {
        itemIds += $(element).find('.bi_id').html()+'\r\n'
    });
	
	$('.download_item').each(function(index, element) {
        itemIds += $(element).find('.di_id').html()+'\r\n'
    });
	
	return itemIds;
}

//----------------------------------------------------
//header 
function header_onmousedown()
{
	window.external.OnHeaderMouseDown();
}

//------------------------------------------------------------
//min
function min_onclick()
{
    window.external.OnMin();
}

//------------------------------------------------------------------------------
//close
function close_onclick()
{
    window.external.OnClose();
}

//------------------------------------------------
//tabs
function switch_tab(idx)
{
	$('.tab').removeClass('tab_s');
	$('#tab_'+idx).addClass('tab_s');
	$('.cnt').removeClass('cnt_s');
	$('#cnt_'+idx).addClass('cnt_s');
}

function switch_tab2(idx)
{
	$('.tab2').removeClass('tab2_s');
	$('#tab2_'+idx).addClass('tab2_s');
	$('.cnt2').removeClass('cnt2_s');
	$('#cnt2_'+idx).addClass('cnt2_s');
}

//------------------------------------------------
//radios
function radio_onclick(obj)
{
	$('.radio_panel').css('display','none');
	$('#radio_info').css('display','block');
	
	window.external.GetRadioInfo($(obj).find('.radio_id').html(),'');
}
function GetRadioInfo_Fail()
{
	return;
}
function GetRadioInfo_SetRadio(id,title,image)
{
	$('#radio_info .ri_id').html(id);
	$('#radio_info .ri_title').html('<span class="ri_back lnkbtn" onclick="ri_back_onclick();">电台</span> &gt; <span>'+title+'</span>');
	$('#radio_info .ri_img').html('<img src="'+image+'"/>');
}
function GetRadioInfo_SetLoading(html)
{
	$('#radio_info #ri_list').html(html);
	$('#ri_play_all').css('display','none');
}
function GetRadioInfo_SetRadioItems(html)
{
	$('#radio_info #ri_list').html(html);
	$('#ri_play_all').css('display','block');
}

function rim_icon_onclick(obj)
{
	window.external.GetRadioInfo($(obj).parent().parent().find('.radio_id').html(),'ri_play_all_onclick');
}

function ri_back_onclick()
{
	$('.radio_panel').css('display','none');
	$('#radios').css('display','block');
}

function ri_play_all_onclick()
{
	if($('.ri_list_item').length == 0)
	{
		return;
	}
	
	$first = $('.ri_list_item').first();

	play_item($first.find('.rli_id').html(),$first.find('.rli_txt').html(),'list')
	
	$('.ri_list_item').each(function(i, item) 
	{
		add_list($(item).find('.rli_id').html(),$(item).find('.rli_txt').html())
	});
}


function rli_txt_onclick(obj)
{
	play_item($(obj).parent().find('.rli_id').html(),$(obj).parent().find('.rli_txt').html(),'list');
}

function rli_play_onclick(obj)
{
	play_item($(obj).parent().find('.rli_id').html(),$(obj).parent().find('.rli_txt').html(),'list');
}

function rli_bookmark_onclick(obj)
{
	add_bookmark($(obj).parent().find('.rli_id').html(),$(obj).parent().find('.rli_txt').html());
}

function rli_download_onclick(obj)
{
	add_download($(obj).parent().find('.rli_id').html(),$(obj).parent().find('.rli_txt').html());
}

var current_share_obj = null; 
function rli_share_onclick(obj)
{
	current_share_obj = obj;
	cancelBubble();

	$('.popup_box').css('display','none');
	$('#li_share').css({'left':$(obj).offset().left-120,'top':$(obj).offset().top-6}).css('display','block');
	$('#ls_btns').stop().css('left','120px').animate({'left':'0px'},200);
	
	$(document).bind('click',function()
	{
		$('#li_share').css('display','none');
		$('#ls_btns').css('left','120px');
		$(document).unbind('click');
	});
}

function lsb_share_onclick(category)
{
	var title = ''; 
	if(current_share_obj != null)
	{
	    $(current_share_obj).parent().find('.rli_txt').length == 0?title = $(current_share_obj).parent().find('.ali_txt').html().ToHtmlDecode():title = $(current_share_obj).parent().find('.rli_txt').html().ToHtmlDecode();
	}
	if(title == '' && $('#item #item_id').html().Trim().length != 0)
	{
	    title = $('#item #item_txt').html().ToHtmlDecode();
	}
	
	var txt = '';
	if(title != '')
	{
		txt='我正在使用必应词典的必应电台收听：'+title+'。必应电台真的很赞，小伙伴们赶快一起学起来！';
	}
	else 
	{
		txt = '我正在使用必应词典的必应电台收听英文。必应电台真的很赞，小伙伴们赶快一起学起来！'
	}
	
	var url='';
	switch(category)
	{
		case 'share_tsina':
			url='http://service.weibo.com/share/share.php?' + 'url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&appkey=2546683754&ralateUid=3167273451' + '&title=' + encodeURIComponent(txt);
			break;
		case 'share_renren':
		    url = 'http://widget.renren.com/dialog/share?resourceUrl=' + encodeURIComponent('https://cn.bing.com/dict/') + '&form=BDVB05&title=%e5%bf%85%e5%ba%94%e8%af%8d%e5%85%b8&description=' + encodeURIComponent(txt);
			break;
		case 'share_qzone':
		    url = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&form=BDVB05&title=%e5%bf%85%e5%ba%94%e8%af%8d%e5%85%b8&summary=' + encodeURIComponent(txt);
			break;
		case 'share_tqq':
		    url = 'http://share.v.t.qq.com/index.php?c=share&a=index&url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&form=BDVB05&title=' + encodeURIComponent(txt);
			break;
		default:
		    url = 'http://service.weibo.com/share/share.php?' + 'url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&appkey=2546683754&ralateUid=3167273451' + '&title=' + encodeURIComponent(txt);
			break;
	}

	window.open(url,'_blank','width=640, height=480, top=320, left=180, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no');
}

//------------------------------------------------
//albums
function album_onclick(obj)
{
	$('#albums').css('display','none');
	$('#album_info').css('display','block');
	
	window.external.GetAlbumInfo($(obj).find('.album_id').html(),'');
}
function GetAlbumInfo_Fail()
{
	return;
}
function GetAlbumInfo_SetAlbum(id,title,image)
{
	$('#album_info .ai_id').html(id);
	$('#album_info .ai_title').html('<span class="ai_back lnkbtn" onclick="ai_back_onclick();">听力宝库</span> &gt; <span>' + title + '</span>');
	$('#album_info .ai_img').html('<img src="'+image+'"/>');
}
function GetAlbumInfo_SetLoading(html)
{
	$('#album_info #ai_list').html(html);
	$('#ai_play_all').css('display','none');
}
function GetAlbumInfo_SetAlbumItems(html)
{
	$('#album_info #ai_list').html(html);
	$('#ai_play_all').css('display','block');
}




function aim_icon_onclick(obj)
{
	window.external.GetAlbumInfo($(obj).parent().parent().find('.album_id').html(),'ai_play_all_onclick');
}

function ai_back_onclick()
{
	$('#album_info').css('display','none');
	$('#albums').css('display','block');
}

function ai_play_all_onclick()
{
	if($('.ai_list_item').length == 0)
	{
		return;
	}
	
	$first = $('.ai_list_item').first();

	play_item($first.find('.ali_id').html(),$first.find('.ali_txt').html(),'list')
	
	$('.ai_list_item').each(function(i, item) 
	{
		add_list($(item).find('.ali_id').html(),$(item).find('.ali_txt').html())
	});
}

function ali_txt_onclick(obj)
{
	play_item($(obj).parent().find('.ali_id').html(),$(obj).parent().find('.ali_txt').html(),'list');
}

function ali_play_onclick(obj)
{
	play_item($(obj).parent().find('.ali_id').html(),$(obj).parent().find('.ali_txt').html(),'list');
}

function ali_bookmark_onclick(obj)
{
	add_bookmark($(obj).parent().find('.ali_id').html(),$(obj).parent().find('.ali_txt').html());
}

function ali_download_onclick(obj)
{
	add_download($(obj).parent().find('.ali_id').html(),$(obj).parent().find('.ali_txt').html());
}

function ali_share_onclick(obj)
{
	current_share_obj = obj;
	cancelBubble();
		
	$('.popup_box').css('display','none');
	$('#li_share').css({'left':$(obj).offset().left-120,'top':$(obj).offset().top-6}).css('display','block');
	$('#ls_btns').stop().css('left','120px').animate({'left':'0px'},200);
	
	$(document).bind('click',function()
	{
		$('#li_share').css('display','none');
		$('#ls_btns').css('left','120px');
		$(document).unbind('click');
	});
}

//------------------------------------------------

function dictation_submit_onclick()
{
	var dictation = $('#textarea').val().Trim();
	var origin = $('#original_txt').html().ToHtmlDecode().Trim();
	
	if(dictation=='')
	{
		show_dictation_msg('听写内容为空！');
		return;
	}
	if(origin=='')
	{
		show_dictation_msg('原文内容为空！');
		return;
	}
	
	window.external.DictationSubmit(dictation,origin);
}

function DictationSubmit_Complete(result)
{
	$('#dictation').css('display','none');
	$('#comparation').css('display','block');
	$('#comparation_area').html(result);
}


function show_dictation_msg(msg)
{
	$('#dictation_msg').stop().html(msg).css({'display':'block','opacity':0})
	.animate({'opacity':1},100,
	function()
	{
		$('#dictation_msg').animate({'opacity':1},600,function()
		{
			$('#dictation_msg').animate({'opacity':0},300,function(){ $('#dictation_msg').css({'display':'none'});} );	
		})
	})
}

function comparation_go_back_onclick()
{
	$('#comparation').css('display','none');
	$('#dictation').css('display','block');
}

//------------------------------------------------
//item

var iSaveListTimer = null;
function add_list(item_id,item_title)
{
	if($('#list_item_'+item_id).length != 0)
	{
		return;
	}
	
	$('#list').append('\
<div class="list_item" id="list_item_'+item_id+'">\
	<div class="li_id">'+item_id+'</div>\
	<div class="li_txt" \
	title="'+item_title+'"\
	onclick="li_txt_onclick(this);"\
	>\
	'+item_title+'\
	</div>\
	<div class="li_bookmark" title="收藏" onclick="li_bookmark_onclick(this);"></div>\
	<div class="li_download" title="下载" onclick="li_download_onclick(this);"></div>\
	<div class="li_delete" title="删除" onclick="li_delete_onclick(this);"></div>\
</div>');

	//save
	if (iSaveListTimer != null)
	{
		clearTimeout(iSaveListTimer);
		iSaveListTimer = null;
	}
	iSaveListTimer = setTimeout(function()
	{
		window.external.SaveList($('#list').html());
	},100);
}

function remove_list(item_id)
{
	while($('#list_item_'+item_id).length > 0)
	{
		$('#list_item_'+item_id).remove();
	}
	show_list_msg('已经将条目移除出"播放列表"');
	
	//save
	if (iSaveListTimer != null)
	{
		clearTimeout(iSaveListTimer);
		iSaveListTimer = null;
	}
	iSaveListTimer = setTimeout(function()
	{
		window.external.SaveList($('#list').html());
	},100);
}

var iSaveBookmarkTimer = null;
function add_bookmark(item_id,item_title,silent)
{
	//add bookmark item into the bookmark list
	if($('#bookmark_item_'+item_id).length != 0)
	{
		if(silent != 'silent')
		{
			show_list_msg('条目已经存在于"我的收藏"');
		}
		return;
	}
	
	$('#bookmark').append('\
<div class="bookmark_item" id="bookmark_item_'+item_id+'">\
	<div class="bi_id">'+item_id+'</div>\
	<div class="bi_txt" \
	title="'+item_title+'"\
	onclick="bi_txt_onclick(this);"\
	>\
	'+item_title+'\
	</div>\
	<div class="bi_download" title="下载" onclick="bi_download_onclick(this);"></div>\
	<div class="bi_delete" title="删除" onclick="bi_delete_onclick(this);"></div>\
</div>');
	
	if($('#item_id').html() == item_id)
	{
		$('#ib_bookmark').addClass('ib_bookmarked').attr('title','取消收藏');
	}
	show_list_msg('已经将条目添加至"我的收藏"');

	//save
	if (iSaveBookmarkTimer != null)
	{
		clearTimeout(iSaveBookmarkTimer);
		iSaveBookmarkTimer = null;
	}
	iSaveBookmarkTimer = setTimeout(function()
	{
		window.external.SaveBookmark($('#bookmark').html());
	},100);
}

function remove_bookmark(item_id)
{
	//remove bookmark item from the bookmark list
	while($('#bookmark_item_'+item_id).length > 0)
	{
		$('#bookmark_item_'+item_id).remove();
	}
	if($('#item_id').html() == item_id)
	{
		$('#ib_bookmark').removeClass('ib_bookmarked').attr('title','收藏');
	}
	show_list_msg('已经将条目移除出"我的收藏"');
	
	//save
	if (iSaveBookmarkTimer != null)
	{
		clearTimeout(iSaveBookmarkTimer);
		iSaveBookmarkTimer = null;
	}
	iSaveBookmarkTimer = setTimeout(function()
	{
		window.external.SaveBookmark($('#bookmark').html());
	},100);
}

var iSaveDownloadTimer = null;
function add_download(item_id,item_title,silent)
{
	if($('#download_item_'+item_id).length != 0)
	{
		if(silent != 'silent')
		{
			show_list_msg('条目已经存在于"我的下载"');
		}
		return;
	}
	
	$('#download').append('\
<div class="download_item" id="download_item_'+item_id+'">\
	<div class="di_id">'+item_id+'</div>\
	<div class="di_txt" \
	title="'+item_title+'"\
	onclick="di_txt_onclick(this);"\
	>\
	'+item_title+'\
	</div>\
	<div class="di_delete" title="删除" onclick="di_delete_onclick(this);"></div>\
</div>');

	show_list_msg('已经将条目添加至"我的下载"');
	
	//save the mp3 file
	window.external.AddItem(item_id);
	
	//save
	if (iSaveDownloadTimer != null)
	{
		clearTimeout(iSaveDownloadTimer);
		iSaveDownloadTimer = null;
	}
	iSaveDownloadTimer = setTimeout(function()
	{
		window.external.SaveDownload($('#download').html());
	},100);
}
function remove_download(item_id)
{
	//remove bookmark item from the bookmark list
	while($('#download_item_'+item_id).length > 0)
	{
		$('#download_item_'+item_id).remove();
	}
	show_list_msg('已经将条目移除出"我的下载"');
	
	//delete the mp3 file
	window.external.RemoveItem(item_id);
	
	//save
	if (iSaveDownloadTimer != null)
	{
		clearTimeout(iSaveDownloadTimer);
		iSaveDownloadTimer = null;
	}
	iSaveDownloadTimer = setTimeout(function()
	{
		window.external.SaveDownload($('#download').html());
	},100);
}

function show_list_msg(msg)
{
	$('#list_msg').stop().html(msg).css({'display':'block','opacity':0})
	.animate({'opacity':1},100,
	function()
	{
		$('#list_msg').animate({'opacity':1},600,function()
		{
			$('#list_msg').animate({'opacity':0},300,function(){ $('#list_msg').css({'display':'none'});} );	
		})
	})	
}

function ib_bookmark_onclick(obj)
{
	if($('#item #item_id').html().Trim().length == 0)
	{
		return;
	}
	
	if(!$(obj).hasClass('ib_bookmarked'))
	{
		add_bookmark($('#item #item_id').html(),$('#item #item_title').html());
	}
	else
	{
		remove_bookmark($('#item #item_id').html());	
	}
}

function ib_download_onclick()
{
	if($('#item #item_id').html().Trim().length == 0)
	{
		return;
	}
	
	add_download($('#item #item_id').html(),$('#item #item_title').html());
}

function ib_share_onclick()
{
	cancelBubble();
		
	$('.popup_box').css('display','none');
	$('#item #item_share').css('display','block');
	$('#item #is_btns').stop().css('left','120px').animate({'left':'0px'},200);
	
	$(document).bind('click',function()
	{
		$('#item #item_share').css('display','none');
		$('#item #is_btns').css('left','120px');
		$(document).unbind('click');
	});
}

function isb_share_onclick(category)
{
	var txt='我正在使用必应词典的必应电台收听：'+$('#item #item_title').html().ToHtmlDecode()+'。必应电台真的很赞，小伙伴们赶快一起学起来！';
	if($('#item #item_id').html().Trim().length == 0)
	{
		txt = '我正在使用必应词典的必应电台收听英文。必应电台真的很赞，小伙伴们赶快一起学起来！'
	}
	
	var url='';
	switch(category)
	{
		case 'share_tsina':
		    url = 'http://service.weibo.com/share/share.php?' + 'url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&appkey=2546683754&ralateUid=3167273451' + '&title=' + encodeURIComponent(txt);
			break;
		case 'share_renren':
		    url = 'http://widget.renren.com/dialog/share?resourceUrl=' + encodeURIComponent('https://cn.bing.com/dict/') + '&form=BDVB05&title=%e5%bf%85%e5%ba%94%e8%af%8d%e5%85%b8&description=' + encodeURIComponent(txt);
			break;
		case 'share_qzone':
		    url = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&form=BDVB05&title=%e5%bf%85%e5%ba%94%e8%af%8d%e5%85%b8&summary=' + encodeURIComponent(txt);
			break;
		case 'share_tqq':
		    url = 'http://share.v.t.qq.com/index.php?c=share&a=index&url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&form=BDVB05&title=' + encodeURIComponent(txt);
			break;
		default:
		    url = 'http://service.weibo.com/share/share.php?' + 'url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&appkey=2546683754&ralateUid=3167273451' + '&title=' + encodeURIComponent(txt);
			break;
	}

	window.open(url,'_blank','width=640, height=480, top=320, left=180, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no');
}

//------------------------------------------------
//play_prog
function set_item_time(cur_time,total_time)
{
	$('#item #item_time').html(cur_time+' | '+total_time);
}

function set_play_prog(prog)
{
	$('#play_prog #pp_current').css({'width':prog+'px'});
	$('#play_prog #pp_drag').css({'left':prog+'px'});
}

var play_prog_mousedown = false;
function play_prog_onmousedown(obj)
{
	if($('#item #item_id').html().Trim().length == 0)
	{
		return;
	}
	
	play_prog_mousedown = true;
	var play_prog_left = getLeft(document.getElementById('play_prog'));
	var play_prog_width = $('#play_prog').width() - 10;
	
	$(document).bind('mouseup',function ()
	{
		play_prog_mousedown = false;
		$(document).unbind('mousemove');
		$(document).unbind('mouseup');
		
		var x = event.clientX;
		var x2 = x - play_prog_left - 6;
		if(x2 < 0)
		{
			x2 = 0;
		}
		else if(x2 > play_prog_width)
		{
			x2 = play_prog_width;
		}
		window.external.SetPlayProg(x2*1.0/play_prog_width); //0~1
	});

	$(document).bind('mousemove',function ()
	{
		var x = event.clientX;
		var x2 = x - play_prog_left - 6;
		if(x2 < 0)
		{
			x2 = 0;
		}
		else if(x2 > play_prog_width)
		{
			x2 = play_prog_width;
		}

		set_play_prog(x2);
	});
	$(document).mousemove();
}

//------------------------------------------------
//player
var current_list = 'list';
function prev_onclick(obj)
{	
	var currentId = $('#item_id').html(); 
	var $node = $('#'+current_list+' #'+current_list+'_item_'+currentId).prev().first();
	if($node.length == 0)
	{		
		$node = $('#'+current_list).children().last();
	}

	play_item($node.find('.'+current_list.substring(0,1)+'i_id').html(),$node.find('.'+current_list.substring(0,1)+'i_txt').html(),current_list);
}

function next_onclick(obj)
{
	var currentId = $('#item_id').html(); 
	var $node = $('#'+current_list+' #'+current_list+'_item_'+currentId).next().last();
	if($node.length == 0)
	{		
		$node = $('#'+current_list).children().first();
	}

	play_item($node.find('.'+current_list.substring(0,1)+'i_id').html(),$node.find('.'+current_list.substring(0,1)+'i_txt').html(),current_list);
}

var playpause_disabled = true;
function playpause_onclick(obj)
{
	if(playpause_disabled)
	{
		return;
	}
	
	if($(obj).hasClass('play'))
	{
		$(obj).attr({'class':'pause','title':'暂停[F5]'});
		window.external.Resume();
	}
	else
	{
		$(obj).attr({'class':'play','title':'播放[F5]'});
		window.external.Pause();
	}
}

//------------------------------------------------
//volume
var cur_vol=0;//0~100
function vol_btn_onclick(obj)
{
	if($(obj).hasClass('vol_btn_enable'))
	{
		$(obj).attr({'class':'vol_btn_disable'});
		cur_vol = parseInt($('#vol_prog #vp_drag').css('left')) * 2;
		set_vol(0);
	}
	else
	{
		$(obj).attr({'class':'vol_btn_enable'});
		set_vol(cur_vol);
	}
}

function set_vol(vol)
{
	if(vol<0){vol=0;}
	else if(vol>100){vol=100;}

	$('#vol_prog #vp_current').css({'width':vol*0.5+'px'});
	$('#vol_prog #vp_drag').css({'left':vol*0.5+'px'});
	window.external.SetVol(vol);
}

function vol_prog_onmousedown(obj)
{
	var vol_prog_left = getLeft(document.getElementById('vol_prog'));
	
	if($('#vol_btn').hasClass('vol_btn_disable'))
	{
		$('#vol_btn').attr({'class':'vol_btn_enable'});
	}
	
	$(document).bind('mouseup',function ()
	{
		$(document).unbind('mousemove');
		$(document).unbind('mouseup');
	});

	$(document).bind('mousemove',function ()
	{
		var x = event.clientX;
		var x2 = x - vol_prog_left - 6;
		if(x2 < 0)
		{
			x2 = 0;
		}
		else if(x2 > 50)
		{
			x2 = 50;
		}
	
		set_vol(x2*2.0);
	});
	$(document).mousemove();
}

//------------------------------------------------
//list_btns
function loop_mode_onclick(obj)
{
	if($(obj).hasClass('loop_list'))
	{
		$(obj).attr({'class':'loop_single','title':'单曲循环'});
	}
	else if($(obj).hasClass('loop_single'))
	{
		$(obj).attr({'class':'loop_sequence','title':'顺序播放'});
	}
	else if($(obj).hasClass('loop_sequence'))
	{
		$(obj).attr({'class':'loop_random','title':'随机播放'});
	}
	else if($(obj).hasClass('loop_random'))
	{
		$(obj).attr({'class':'loop_list','title':'列表循环'});
	}
}

//---------------------------------------------------
//app_btns

function ab_share_onclick()
{
	cancelBubble();
	
	$('.popup_box').css('display','none');
	$('#app_share').css('display','block');
	$('#as_btns').stop().css('left','120px').animate({'left':'0px'},200);
	
	$(document).bind('click',function()
	{
		$('#app_share').css('display','none');
		$('#as_btns').css('left','120px');
		$(document).unbind('click');
	});
}

function ab_feedback_onclick()
{
	window.open('http://bing.msn.cn/dict/feedback/web/?p=pc&v=bingradiov2');
}

function asb_share_onclick(category)
{
	var txt='我正在使用必应词典的必应电台收听：'+$('#item #item_title').html().ToHtmlDecode()+'。必应电台真的很赞，小伙伴们赶快一起学起来！';
	if($('#item #item_id').html().Trim().length == 0)
	{
		txt = '我正在使用必应词典的必应电台收听英文。必应电台真的很赞，小伙伴们赶快一起学起来！'
	}
	
	var url='';
	switch(category)
	{
		case 'share_tsina':
		    url = 'http://service.weibo.com/share/share.php?' + 'url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&appkey=2546683754&ralateUid=3167273451' + '&title=' + encodeURIComponent(txt);
			break;
		case 'share_renren':
		    url = 'http://widget.renren.com/dialog/share?resourceUrl=' + encodeURIComponent('https://cn.bing.com/dict/') + '&form=BDVB05&title=%e5%bf%85%e5%ba%94%e8%af%8d%e5%85%b8&description=' + encodeURIComponent(txt);
			break;
		case 'share_qzone':
		    url = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&form=BDVB05&title=%e5%bf%85%e5%ba%94%e8%af%8d%e5%85%b8&summary=' + encodeURIComponent(txt);
			break;
		case 'share_tqq':
		    url = 'http://share.v.t.qq.com/index.php?c=share&a=index&url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&form=BDVB05&title=' + encodeURIComponent(txt);
			break;
		default:
		    url = 'http://service.weibo.com/share/share.php?' + 'url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&appkey=2546683754&ralateUid=3167273451' + '&title=' + encodeURIComponent(txt);
			break;
	}

	window.open(url,'_blank','width=640, height=480, top=320, left=180, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no');
}


//---------------------------------------------------------

function list_delete_all_onclick()
{
	$('#list').html('');
	window.external.SaveList($('#list').html());
}

function bookmark_delete_all_onclick()
{
	$('#bookmark').html('');
	window.external.SaveBookmark($('#bookmark').html());
	$('#item_btns .ib_bookmark').removeClass('ib_bookmarked');
}

function download_delete_all_onclick()
{
	$('#download').html('');
	window.external.SaveDownload($('#download').html());
	window.external.RemoveAllItems();
}

function li_txt_onclick(obj)
{
	play_item($(obj).parent().find('.li_id').html(),$(obj).parent().find('.li_txt').html(),'list');
}

function li_bookmark_onclick(obj)
{
	add_bookmark($(obj).parent().find('.li_id').html(),$(obj).parent().find('.li_txt').html());
}

function li_download_onclick(obj)
{
	add_download($(obj).parent().find('.li_id').html(),$(obj).parent().find('.li_txt').html());
}

function li_delete_onclick(obj)
{
	remove_list($(obj).parent().find('.li_id').html());
}

function bi_txt_onclick(obj)
{
	play_item($(obj).parent().find('.bi_id').html(),$(obj).parent().find('.bi_txt').html(),'bookmark');
}

function bi_download_onclick(obj)
{
	add_download($(obj).parent().find('.bi_id').html(),$(obj).parent().find('.bi_txt').html());
}

function bi_delete_onclick(obj)
{
	remove_bookmark($(obj).parent().find('.bi_id').html());
}

function di_txt_onclick(obj)
{
	play_item($(obj).parent().find('.di_id').html(),$(obj).parent().find('.di_txt').html(),'download');
}

function di_delete_onclick(obj)
{
	remove_download($(obj).parent().find('.di_id').html());
}

var iPlayItemTimer = null;
function play_item(id, title, list)
{
	if(id == undefined)
	{
		return;
	}
	
	//add 
	current_list = list;
	switch(list)
	{
		case 'list':
			switch_tab2(1);
			add_list(id,title);
			break;
		case 'bookmark':
			switch_tab2(2);
			add_bookmark(id,title,'silent');
			break;
		case 'download':
			switch_tab2(3);
			add_download(id,title,'silent');
			break;
		default:
			switch_tab2(1);
			add_list(id,title);
			break;
	}
	
	//show new origin and clear dictation
	$('#original_txt').html(window.external.GetItemOriginTxt(id)/*.ToHtmlEncode()*/).scrollTop(0);
	$('#textarea').val('');
	
	//highlight the playing item
	$('.playing_item').removeClass('playing_item');
	var id2 = '#'+list+' #'+list+'_item_'+id;
	$(id2).addClass('playing_item');
	
	//auto scroll to make the playing item always visible in the list
	if ($(id2).position().top < 0)
	{
		$(id2).parent().scrollTop($(id2).parent().scrollTop() + $(id2).position().top);
	}
	if ($(id2).position().top + $(id2).outerHeight() > $(id2).parent().height())
	{
		$(id2).parent().scrollTop($(id2).parent().scrollTop() + $(id2).position().top + $(id2).outerHeight() - $(id2).parent().height());
	}

	//set the '#item',progress,current_list,etc
	$('#item_id').html(id);
	$('#item_title').html(title).attr('title',title.ToHtmlDecode().replace(/\"/g, ''));
	$('#item_img').html('<img src="'+window.external.GetItemImage(id)+'"/>');
	$('#bookmark_item_'+id).length>0?$('#ib_bookmark').addClass('ib_bookmarked').attr('title','取消收藏'):$('#ib_bookmark').removeClass('ib_bookmarked').attr('title','收藏')
	
	$('#playpause').attr({'class':'pause','title':'暂停[F5]'});
	playpause_disabled = true;
	PlayItem_UpdatePlayProg(0,0);

	//set a timer to make sure we will skip the invalid item that cannot be correctly played
	currentState = 0;// Undefined
	if (iPlayItemTimer != null)
	{
		clearTimeout(iPlayItemTimer);
		iPlayItemTimer = null;
	}
	iPlayItemTimer = setTimeout(function()
	{
		if(currentState == 10) // Ready
		{
			play_next_item();
		}
	},5000);
	//play
	window.external.PlayItem(id);
	window.external.AddToLog("FMRadio_PlayItem,CurrentId:" + id + ";CurrentTitle:" + title + ";CurrentList:" + list);
}

function play_next_item()
{
	var currentId = $('#item_id').html(); 
	var $node;
	
	if($('#loop_mode').hasClass('loop_single'))//单曲循环
	{
		$node = $('#'+current_list+' #'+current_list+'_item_'+currentId).last();
	}
	else if($('#loop_mode').hasClass('loop_list'))//列表循环
	{
		$node = $('#'+current_list+' #'+current_list+'_item_'+currentId).next().last();
		
		if($node.length == 0)
		{		
			$node = $('#'+current_list).children().first();
		}
	}
	else if($('#loop_mode').hasClass('loop_sequence'))//顺序播放
	{
		$node = $('#'+current_list+' #'+current_list+'_item_'+currentId).next().last();
	}
	else if($('#loop_mode').hasClass('loop_random'))//随机播放
	{
		var len = $('#'+current_list).children().length;
		var randIdx = Math.floor(Math.random()*len);
		$node = $($('#'+current_list).children()[randIdx]);
		
		if($node.length == 0)
		{	
			$node = $('#'+current_list).children().first();	
		}
	}
	
	if($node.length == 0)
	{	
		$('#playpause').attr({'class':'play','title':'播放[F5]'});
		window.external.Stop();
		return;
	}
	

	play_item($node.find('.'+current_list.substring(0,1)+'i_id').html(),$node.find('.'+current_list.substring(0,1)+'i_txt').html(),current_list);
}

var currentState = 0;// Undefined
var iPlayNextItemTimer = null;
function PlayItem_OnStateChange(newState)
{
	currentState = newState;
	switch(newState)
	{
	    case 0: // Undefined
	        break;
	    case 1: // Stopped
			if (iPlayNextItemTimer != null)
			{
				clearTimeout(iPlayNextItemTimer);
				iPlayNextItemTimer = null;
			}
			iPlayNextItemTimer = setTimeout(function()
			{
				play_next_item();
			},1000);
	        break;
	    case 2: // Paused
	        break;
	    case 3: // Playing
			playpause_disabled = false;
	        break;
	    case 4: // ScanForward
	        break;
	    case 5: // ScanReverse
	        break;
	    case 6: // Buffering
	        break;
	    case 7: // Waiting
	        break;
	    case 8: // MediaEnded
	        break;
	    case 9: // Transitioning
	        break;
	    case 10: // Ready
	        break;
	    case 11: // Reconnecting
	        break;
	    case 12: // Last
	        break;
	    default: // Unknown State
	        break;
	}
}

//used to update ui play progress from C#
function PlayItem_UpdatePlayProg(timeDone,timeTotal)
{
	
	if(timeDone<0||timeTotal<0||timeDone>timeTotal)
	{
		return;
	}
	
	if(!play_prog_mousedown)
	{
		var play_prog_width = $('#play_prog').width() - 10;	
		var x = timeTotal==0?0:timeDone/timeTotal*play_prog_width;
		set_play_prog(x);
	}
	
	var minDone=parseInt(timeDone/60);
	var secDone=parseInt(timeDone%60);
	var minTotal=parseInt(timeTotal/60);
	var secTotal=parseInt(timeTotal%60);
	
	var done = (minDone<=9?'0'+minDone:minDone)+':'+(secDone<=9?'0'+secDone:secDone);
	var total = (minTotal<=9?'0'+minTotal:minTotal)+':'+(secTotal<=9?'0'+secTotal:secTotal);
	$('#item_time').html(done+' | '+total);
}

//-----------------------------------------------------------------
//shortcuts supported by FMRadio
$(document).ready(function () 
{
	$(document).bind('keydown',window.event,function(evt)
	{
		switch(evt.keyCode)
		{
		case 116:
			OnKeyDown('F5');
			return false;
			break;
		case 33:
			OnKeyDown('PageUp');
			return false;
			break;
		case 34:
			OnKeyDown('PageDown');
			return false;
			break;	
		}
	});
});
function OnKeyDown(keycode)
{
	if(keycode=='F5')//F5
	{
		$('#playpause').click();
	}
	if(keycode=='PageUp')//PageUp
	{
		$('#prev').click();
	}
	if(keycode=='PageDown')//PageDown
	{
		$('#next').click();
	}
}
