
//-----------------------------------------------
//ban drag of <img>
$(document).ready(
function()
{
	$('img').bind('dragstart',function(){return false;});
}
);

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


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

//------------------------------------------------------------
//BtnMin
function BtnMin_onclick()
{
    window.external.OnMin();
}

//------------------------------------------------------------------------------
//BtnClose
function BtnClose_onclick()
{
    window.external.OnClose();//dont try to close window,only hide it.
}


//获取元素的纵坐标 
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
); 


/*
* Timer类
* @author: kmlxk@yahoo.com.cn
* @created: 2011-2-12 18:51
* 方法: 
* 构造函数: Timer(间隔, 回调函数)
* 清除: clear()
* 使用示例: var timer = new Timer(200, function(t) {alert('nana'); t.clear();} );    
*/
function Timer(interval,functor) 
{
	this.id = 'timer_'+Math.ceil(Math.random()*900000000+100000000);
	eval(this.id+' = this;');
	this.tid = setInterval(this.id+'.callback()',interval)
	this.functor = functor;
	this.callback = function(){
		this.functor(this);
	}
	this.clear = function(){
		clearInterval(this.tid);
	}
}

function ShareRanking_onclick()
{
	var rankJudge=$('#rank-judgement').html();
	var questionPoolAlias=$('#question-pool-alias',parent.frames['QuestionPage_PronChallenge'].document).html();
	var promoteTxt = '嗨~我正在使用 @必应词典 的扩展应用-- #我爱说英语#';
	var rankTxt=$('#rank-text').html();
	var questionPool='（'+questionPoolAlias+'）';
	
	var scorePercent=parseInt($('#rank-score-content').html().replace('%',''));
	var picUrl='';
	if (scorePercent >= 90)
	{
	    picUrl = encodeURIComponent('http://dict.bing.msn.cn/images/20131227/badge1.png');
	}
	else if (scorePercent >= 80)
	{
	    picUrl = encodeURIComponent('http://dict.bing.msn.cn/images/20131227/badge2.png');
	}
	else if (scorePercent >= 60)
	{
	    picUrl = encodeURIComponent('http://dict.bing.msn.cn/images/20131227/badge3.png');
	}
	else if (scorePercent >= 40)
	{
	    picUrl = encodeURIComponent('http://dict.bing.msn.cn/images/20131227/badge4.png');
	}
	else if (scorePercent >= 20)
	{
	    picUrl = encodeURIComponent('http://dict.bing.msn.cn/images/20131227/badge5.png');
	}
	else
	{
	    picUrl = encodeURIComponent('http://dict.bing.msn.cn/images/20131227/badge6.png');
	}

	window.open('http://service.weibo.com/share/share.php?' + 'url=' + encodeURIComponent('https://cn.bing.com/dict/') + '&pic=' + picUrl + '&appkey=2546683754&ralateUid=3167273451' + '&title=' + encodeURIComponent(rankJudge + ' \n' + promoteTxt + ' \n' + rankTxt + questionPool), '_blank', 'width=640, height=480, top=320, left=180, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no');
	window.external.AddChallengeQuota(1);
}

function AddToNWL_onclick(obj)
{
	var headWord=$(obj).parent().parent().find('.question-hardest-word-content').html();
	
	if (obj.title=="加入生词本")
	{
		window.external.AddToNWL(headWord,"","");
	}
	else
	{
		window.external.DeleteInNWL(headWord);
	}
	
	//update the icon and title of btn
	if (!window.external.IsInNWL(headWord))
	{
		obj.title="加入生词本";
		obj.className="qhw-nwl addToNewWordList_Pending_N"; 
	}
	else
	{
		obj.title="移出生词本";
		obj.className="qhw-nwl addToNewWordList_Added_N"; 
	}
	updateNWLStatus();
}

function updateNWLStatus()
{
	$('#lower-panel .list-items').children().each(function(i, item) 
	{
		var headWord='';
		headWord=$(item).find('.question-hardest-word-content').html();
		
        if (window.external.IsInNWL( headWord ))
		{
			$(item).find('.qhw-nwl').attr('title','移出生词本');
			$(item).find('.qhw-nwl').attr('class','qhw-nwl addToNewWordList_Added_N');
		}
		else
		{
			$(item).find('.qhw-nwl').attr('title','加入生词本');
			$(item).find('.qhw-nwl').attr('class','qhw-nwl addToNewWordList_Pending_N'); 
		}
    });
}

function OpenNWL_onclick()
{
    window.external.OpenPlugin('NewWordList','-toDefault');
}

function CheckAnswer_onclick()
{
    parent.showReviewQuestions_PC();
}

function RedoChallenge_onclick() 
{
	$('#ShareRanking',parent.frames['ResultPage_PronChallenge'].document).hide();
    getCurrentQuestions();
}

function getCurrentQuestions() 
{
    window.external.getCurrentQuestions_PC();
}

function ContinueChallenge_onclick() 
{
	$('#ShareRanking',parent.frames['ResultPage_PronChallenge'].document).show();
    parent.showIframe('QuestionPoolsPage');
    parent.frames['QuestionPoolsPage'].window.location.reload();
}

function setRankScore_PC(rankScore)
{
	$('#rank-score-content').html(rankScore+'%');
}

function setRankJudgement_PC(rankJudge)
{
	$('#rank-judgement').html(rankJudge);
}

function setRankText_PC(rankText)
{
	$('#rank-text').html(rankText);
}

function setHardQuestions_PC(hardQuestions)
{
	$('#lower-panel .list-items').html('').html(hardQuestions).scrollTop(0);
	
	updateNWLStatus();
}


function HeadWord_onclick(obj)
{
    window.external.SearchDict($(obj).html());
    window.external.AddToLog('OE_SearchHeadWord');
}

//-------------------------------------------------------
function QuestionResultAudio_StartPlaybackFailed_PC()
{
	ShowWarning('开启播放失败，请确定您的音频输出设备正常！')
}

function QuestionResultAudio_StopPlaybackFailed_PC()
{
	ShowWarning('停止播放失败，请确定您的音频输出设备正常！')
}

function ShowWarning(text)
{
	$('#warning1').html(text)
	.css({'opacity':0,'display':'block'})
	.animate({'opacity':1},500)
	.delay(1000).animate({'opacity':0},500,function(){ $('#warning').css('display','none');} );
}

function PlayStardardPron(obj)
{
	var id = $(obj).parent().find('.question-std-pron-id').html();
	var url = 'http://wordchallenge.blob.core.windows.net/oralenglish/'+id+'.mp3';
	StartPlayQuestionAudio(url);
}

function PlayMyPron(obj)
{
	StopPlayQuestionAudio();

	var id = $(obj).parent().find('.question-my-pron-id').html();
	window.external.StartPlayQuestionResultAudio(id);	
}

function StartPlayQuestionAudio(url)
{
	//prevent the question audio and result audio being played together
	window.external.StopPlayQuestionResultAudio();
	
	var audioPlayer = document.getElementById("_aplayer");
    if (audioPlayer == undefined || audioPlayer == null)
    {
        var a = document.createElement("div");
        a.style.display = "none";
        a.innerHTML = "\
<object \
id='_aplayer' \
style='width:0px;height:0px;' \
classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' \
width='0' \
height='0' \
type='application/x-shockwave-flash'>\
<param name='allowScriptAccess' value='sameDomain'/>\
<param name='movie' value='../Common/EhcPlayer.swf'/>\
<param name='quality' value='high'/>\
</object>\
		";

        document.body.appendChild(a);
    }
    var audioPlayer = document.getElementById("_aplayer");
    try
    {
        audioPlayer.SetVariable("hash", url);
        audioPlayer.GotoFrame(2); //Stop potentially any playing sounds
        audioPlayer.GotoFrame(1);
    }
    catch (e)
    {
        if (audioPlayer.Settings)
        {
            audioPlayer.Settings.PlayCount = 1; //Call Settings.PlayCount especially to draw an exception if this is not present
            audioPlayer.URL = url;
        }
    }
}

function StopPlayQuestionAudio()
{
	var audioPlayer = document.getElementById("_aplayer");
    if (audioPlayer == undefined || audioPlayer == null)
    {
        var a = document.createElement("div");
        a.style.display = "none";
        a.innerHTML = "\
<object \
id='_aplayer' \
style='width:0px;height:0px;' \
classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' \
width='0' \
height='0' \
type='application/x-shockwave-flash'>\
<param name='allowScriptAccess' value='sameDomain'/>\
<param name='movie' value='../Common/EhcPlayer.swf'/>\
<param name='quality' value='high'/>\
</object>\
		";

        document.body.appendChild(a);
    }
    var audioPlayer = document.getElementById("_aplayer");
    try
    {
        audioPlayer.SetVariable("hash", '');
        audioPlayer.GotoFrame(2); //Stop potentially any playing sounds
        audioPlayer.GotoFrame(1);
    }
    catch (e)
    {
        if (audioPlayer.Settings)
        {
            audioPlayer.Settings.PlayCount = 1; //Call Settings.PlayCount especially to draw an exception if this is not present
            audioPlayer.URL = '';
        }
    }
}

function QuestionResultAudio_onclick(obj)
{
	StopPlayQuestionAudio();
	
	var url = '';
	if ($(obj).parent().hasClass('question-result-pron'))
	{
		var AudioId=$(obj).parent().parent().find('.question-result-id').html().toString();
		window.external.StartPlayQuestionResultAudio(AudioId);
	}
}
/********skin********/
function UpdateSkinForPage(model, color, image)
{
    $("link#_NewSkinColor").attr("href", "").attr("href", "../../../../../skin/Color/" + color + ".css");
}
