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


$(document).ready(
function () {
$(document).bind('keydown',keyDown)
.bind('keyup',keyUp)
.bind('keypress',keyPress)
;
}
);
function keyDown()
{
}

function keyUp()
{
}
function keyPress()
{
}


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

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

//------------------------------------------------------------------------------
//BtnClose
function BtnClose_onclick()
{
    window.external.OnClose();
}

var currentIframe='';
function showIframe(ifrmID)
{
	var main=document.getElementById("main");

	var ifrms=main.childNodes;

	for (var i=0;i<ifrms.length;i++)
	{
		var item = ifrms.item(i);
		if (item.id==ifrmID)
		{
			item.style.display='block';
			currentIframe=item.id;
			$(item).focus();//make sure the keyboard event can be send to current iframe
		}
		else if (item.id!=undefined)
		{
			item.style.display='none';
		}
	}	
}

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

//QuestionPoolsPage
function setBestResult(bestRestult)
{
	showIframe("QuestionPoolsPage");
	document.frames["QuestionPoolsPage"].window.setBestResult(bestRestult);
}

function setRecentResult(recentRestult)
{
	showIframe("QuestionPoolsPage");
	document.frames["QuestionPoolsPage"].window.setRecentResult(recentRestult);
}

function setQuestionPoolList(questionPoolList)
{
	showIframe("QuestionPoolsPage");
	document.frames["QuestionPoolsPage"].window.setQuestionPoolList(questionPoolList);
}

function NoRemainQuota() 
{
	showIframe("QuestionPoolsPage");
	document.frames["QuestionPoolsPage"].window.NoRemainQuota();
}

function FailGetRankData()
{
	showIframe("QuestionPoolsPage");
	document.frames["QuestionPoolsPage"].window.FailGetRankData();
}

function FailGetNewQuestions()
{
    showIframe("QuestionPoolsPage");
    document.frames["QuestionPoolsPage"].window.FailGetNewQuestions();
}

//QuestionPage
function setQuestions(currentQuestionPoolName, currentQuestionPoolType, currentQuestionPoolAlias, questions)
{
	showIframe("QuestionPage");
	document.frames["QuestionPage"].window.setQuestions(currentQuestionPoolName, currentQuestionPoolAlias, questions);
}

//ResultPage
function setRankScore(rankScore)
{
	showIframe("ResultPage");
	document.frames["ResultPage"].window.setRankScore(rankScore);
}

function setRankJudgement(rankJudge)
{
	showIframe("ResultPage");
	document.frames["ResultPage"].window.setRankJudgement(rankJudge);
}

function showRankText(winPercent)
{
	showIframe("ResultPage");
	var totalQuestions=0;
	totalQuestions=$("#questions .question",document.frames["QuestionPage"].document).length;
	var rightQuestions=0;
	$(".question-choices .selected",document.frames["QuestionPage"].document).each(function(i, ch) {
        if ($(ch).find('.question-choice-answer').html()=='right')
		{
			rightQuestions++;
		}
    });

	var clockCount=0;
	clockCount=document.frames["QuestionPage"].clockCounter;
	var minutes=parseInt(clockCount/60);
	var seconds=parseInt(clockCount%60);
	var percent=winPercent;
	var rankText='本次挑战'+totalQuestions+'题，答对'+rightQuestions+'题，用时'+minutes+'分'+seconds+'秒，击败了全国'+percent+'%的挑战者！';
	
	document.frames["ResultPage"].window.setRankText(rankText);
}

function showHardQuestions()
{
	showIframe("ResultPage");
	var hardQuestions='';
	var oddEvenCounter=0;
	$("#questions .question-choices .selected",document.frames["QuestionPage"].document).each(function(i, ch) {

        if ($(ch).find('.question-choice-answer').html()=='wrong')//if it is a question user's got wrong answer 
		{
			var headword=""; 
			var questionTxt="";
			var rightChoice="";
			var wordToAdd="";
			headword=$(ch).parent().parent().find('.question-headword').html();
			questionTxt=$(ch).parent().parent().find('.question-text').html();
			questionTxt=questionTxt.length<=45?questionTxt:questionTxt.substring(0,42)+'...';
			wordToAdd=$(ch).parent().parent().find('.word-to-add').html();
			
			$(ch).siblings().each(function(j, ch2) {
                if ($(ch2).find('.question-choice-answer').html().indexOf('right')!=-1)
				{
					rightChoice = $(ch2).find('.question-choice-text').html();
					rightChoice=(questionTxt.length+rightChoice.length)<=60?rightChoice:rightChoice.substring(0,12)+'...';
				}
            });
			oddEvenCounter++;
			var oddEvenLine=oddEvenCounter%2==1?"odd-line":"even-line";

			var bDisplayAddToNWL = wordToAdd.length>0 || 
			!(
			(headword.indexOf('完形填空')!=-1)
			|| (headword.indexOf('完型填空') != -1)
            || (headword.indexOf('空格') != -1)
			|| (headword.indexOf('空格处通常填什么')!=-1)
			|| (headword.indexOf('下列哪个词最符合以下描述') != -1)
            || (headword.indexOf('这通常比喻什么') != -1)
            || (headword.indexOf('这是什么意思') != -1)
			);
			
			hardQuestions+=""+
"<div class=\"list-item "+oddEvenLine+"\" " +
"onmouseover=\"$(this).addClass('hovered');\"" +
"onmouseout=\"$(this).removeClass('hovered');\"" +
">" +
    "<div class=\"list-item-left\">" +
        "<div class=\"list-item-up\">" +
            "<div class=\"list-item-title\">" +
				"<div class=\"word-to-add\">"+wordToAdd+"</div>" +
                "<div class=\"question-index\">"+(i+1).toString()+"</div>" +
                "<div class=\"question-headword question-headword-normal\" title=\"点击查词\" " +
                "onmouseover=\"$(this).removeClass('question-headword-normal').removeClass('press_co').removeClass('hover_co').addClass('hover_co');\"" +
                "onmouseout=\"$(this).removeClass('question-headword-normal').removeClass('press_co').removeClass('hover_co').addClass('question-headword-normal');\"" +
                "onmousedown=\"$(this).removeClass('question-headword-normal').removeClass('press_co').removeClass('hover_co').addClass('press_co');\"" +
                "onmouseup=\"$(this).removeClass('question-headword-normal').removeClass('press_co').removeClass('hover_co').addClass('hover_co');\"" +
                "onclick=\"HeadWord_onclick(this);\"" +
				">" +
                headword +
                "</div>" +       
            "</div>" +
        "</div>" +       
        "<div class=\"list-item-down\">" +
            "<div class=\"question-text\">" +
            questionTxt +
            "</div>" +
            "<div class=\"question-choice-text\">" +
            rightChoice +
            "</div>" +
        "</div>" +
    "</div>" +
    "<div class=\"list-item-right\">" +	
        "<div class=\"AddToNWL AddToNWL_Pending normal_ba\"  title=\"加入生词本\"" + (bDisplayAddToNWL ? "style=\"display:block;\"" : "style=\"display:none;\"") +
        "onmouseover=\"this.title=='加入生词本'?this.className='AddToNWL AddToNWL_Pending hover_ba':this.className='AddToNWL AddToNWL_Added hover_ba';\"" +
        "onmouseout=\"this.title=='加入生词本'?this.className='AddToNWL AddToNWL_Pending normal_ba':this.className='AddToNWL AddToNWL_Added';\"" +
        "onmousedown=\"this.title=='加入生词本'?this.className='AddToNWL AddToNWL_Pending press_ba':this.className='AddToNWL AddToNWL_Added press_ba';\"" +
        "onclick=\"AddToNWL_onclick(this);\""+
        ">" +
        "</div>" +
    "</div>" +    
"</div>" +
"";
		}
    });

	if (hardQuestions=='')
	{
		hardQuestions+=""+
"<div class=\"list-no-item " +
"onmouseover=\"$(this).addClass('hovered');\"" +
"onmouseout=\"$(this).removeClass('hovered');\"" +
">" +
"恭喜您这次挑战全部回答正确！" +
"</div>" +
"";
	}
	
	document.frames["ResultPage"].window.setHardQuestions(hardQuestions);
}


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

//ResultPage
function setRankScore_PC(rankScore)
{
	showIframe("ResultPage_PronChallenge");
	document.frames["ResultPage_PronChallenge"].window.setRankScore_PC(rankScore);
}

function setRankJudgement_PC(rankJudge)
{
	showIframe("ResultPage_PronChallenge");
	document.frames["ResultPage_PronChallenge"].window.setRankJudgement_PC(rankJudge);
}

function showRankText_PC(meanScore, winPercent)
{
	showIframe("ResultPage_PronChallenge");
	var totalQuestions=$("#questions .question",document.frames["QuestionPage_PronChallenge"].document).length;
	var rankText='本次挑战完成'+totalQuestions+'题，平均得分'+meanScore+'分，击败全国'+winPercent+'%的挑战者！';
	
	document.frames["ResultPage_PronChallenge"].window.setRankText_PC(rankText);
}

function showHardQuestions_PC()
{
	showIframe("ResultPage_PronChallenge");
	var hardQuestions='';
	var oddEvenCounter=0;
	$("#questions .question",document.frames["QuestionPage_PronChallenge"].document).each(function(i, question) 
	{
		var oddEvenLine = i%2==0?"odd-line":"even-line";
		var questIndex = i+1;
		var questText = $(question).find('.question-text').html();
		var questStdPronId = $(question).find('.question-id').html();
		var questMyPronId = $(question).find('.question-result-id').html();
		var questMyScore = $(question).find('.question-score-content').html();
		
		var questMyHardestWordScore = 101;
		var questMyHardestWord = '';
		$(question).find('.question-result-text .word').each(function(j, word) 
		{
			if (parseInt($(word).attr('title'))<questMyHardestWordScore)
			{
				questMyHardestWordScore = parseInt($(word).attr('title'));
				questMyHardestWord = $(word).html();
			}  
        });
		
		
		hardQuestions+=""+
"<div class=\"list-item "+oddEvenLine+"\" "+
"onmouseover=\"$(this).addClass('hovered');\" "+
"onmouseout=\"$(this).removeClass('hovered');\" "+
"> "+
    "<div class=\"list-item-up\"> "+
        "<div class=\"question-index\">"+questIndex+"</div> "+
        "<div class=\"question-text\">"+questText+"</div> "+
    "</div> "+
    "<div class=\"list-item-down normal_co\"> "+
        "<div class=\"question-std-pron\"> "+
            "<div class=\"question-std-pron-id\">"+questStdPronId+"</div> "+
            "<div class=\"question-std-pron-title\">标准发音：</div> "+
            "<div class=\"question-std-pron-icon playAudio_N\" "+
            "onmouseover=\"this.className = 'question-std-pron-icon playAudio_H';\" "+
            "onmousedown=\"this.className = 'question-std-pron-icon playAudio_P';\" "+
            "onmouseup=\"this.className = 'question-std-pron-icon playAudio_H';\" "+
            "onmouseout=\"this.className = 'question-std-pron-icon playAudio_N';\" "+
            "onclick=\"PlayStardardPron(this);\" "+
            "> "+
            "</div> "+
        "</div> "+    
        "<div class=\"question-my-pron\"> "+
            "<div class=\"question-my-pron-id\">"+questMyPronId+"</div> "+
            "<div class=\"question-my-pron-title\"> "+
            "我的发音："+
            "</div> "+
            "<div class=\"question-my-pron-icon playAudio_N\" "+
            "onmouseover=\"this.className = 'question-my-pron-icon playAudio_H';\" "+
            "onmousedown=\"this.className = 'question-my-pron-icon playAudio_P';\" "+
            "onmouseup=\"this.className = 'question-my-pron-icon playAudio_H';\" "+
            "onmouseout=\"this.className = 'question-my-pron-icon playAudio_N';\" "+
            "onclick=\"PlayMyPron(this);\" "+
            "> "+
            "</div> "+
        "</div> "+
        "<div class=\"question-my-score\"> "+
            "<div class=\"question-my-score-title\"> "+
            "本题得分："+
            "</div> "+
            "<div class=\"question-my-score-content\">"+questMyScore+
            "</div> "+
        "</div> "+     
        "<div class=\"question-hardest-word\"> "+
            "<div class=\"question-hardest-word-title\"> "+
            "最难读单词："+
            "</div> "+
            "<div class=\"question-hardest-word-content\">"+questMyHardestWord+
            "</div> "+
            "<div class=\"question-hardest-word-nwl\"> "+
                "<div class=\"qhw-nwl addToNewWordList_Pending_N\"  title=\"加入生词本\" "+
				"onmouseover=\"this.title=='加入生词本'?this.className = 'qhw-nwl addToNewWordList_Pending_H':this.className = 'qhw-nwl addToNewWordList_Added_H';\" "+
				"onmousedown=\"this.title=='加入生词本'?this.className = 'qhw-nwl addToNewWordList_Pending_P':this.className = 'qhw-nwl addToNewWordList_Added_P';\" "+
				"onmouseup=\"this.title=='加入生词本'?this.className = 'qhw-nwl addToNewWordList_Pending_H':this.className = 'qhw-nwl addToNewWordList_Added_H';\" "+
				"onmouseout=\"this.title=='加入生词本'?this.className = 'qhw-nwl addToNewWordList_Pending_N':this.className = 'qhw-nwl addToNewWordList_Added_N';\" "+
				"onclick=\"AddToNWL_onclick(this);\" "+
				"> "+
                "</div> "+
            "</div> "+
        "</div> "+
    "</div> "+
"</div> "+
"";
		
    });	
	document.frames["ResultPage_PronChallenge"].window.setHardQuestions_PC(hardQuestions);
}


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




//QuestionReviewPage
function showReviewQuestions()
{
	showIframe("QuestionReviewPage");

	var currentQuestionPoolName = $('#question-pool-name', document.frames["QuestionPage"].document).html();
	var currentQuestionPoolAlias = $('#question-pool-alias', document.frames["QuestionPage"].document).html();
	var clockCount=$('#clock-value',document.frames["QuestionPage"].document).html();
	var questions=$('#questions',document.frames["QuestionPage"].document).html();
		
	$('#question-pool-name', document.frames["QuestionReviewPage"].document).html(currentQuestionPoolName);
	$('#question-pool-alias', document.frames["QuestionReviewPage"].document).html(currentQuestionPoolAlias);
	$('#clock-value',document.frames["QuestionReviewPage"].document).html(clockCount);
	document.frames["QuestionReviewPage"].window.setReviewQuestions(questions);
}

function showReviewQuestions_PC()
{
	showIframe("QuestionReviewPage_PronChallenge");

	var currentQuestionPoolName = $('#question-pool-name', document.frames["QuestionPage_PronChallenge"].document).html();
	var currentQuestionPoolAlias = $('#question-pool-alias', document.frames["QuestionPage_PronChallenge"].document).html();
	var questions=$('#questions',document.frames["QuestionPage_PronChallenge"].document).html();
		
	$('#question-pool-name', document.frames["QuestionReviewPage_PronChallenge"].document).html(currentQuestionPoolName);
	$('#question-pool-alias', document.frames["QuestionReviewPage_PronChallenge"].document).html(currentQuestionPoolAlias);
	document.frames["QuestionReviewPage_PronChallenge"].window.setReviewQuestions_PC(questions);
}

function F5_onkeydown()
{
    if (currentIframe == 'QuestionPage' || currentIframe == 'QuestionReviewPage' || currentIframe == 'ResultPage'
	|| currentIframe == 'QuestionPage_PronChallenge' || currentIframe == 'QuestionReviewPage_PronChallenge'|| currentIframe == 'ResultPage_PronChallenge'
    )
	{
		document.frames[currentIframe].window.RedoChallenge_onclick();
	}
}

function Enter_onkeydown()
{
	if (currentIframe=='QuestionPoolsPage')
	{
		$('#question-pool-list-items .list-item.hovered',document.frames[currentIframe].document).click();
		return;
	}
	else if (currentIframe=='QuestionPage')
	{
		document.frames[currentIframe].window.SubmitResult_onclick();
		return;
	}
	else if (currentIframe=='QuestionPage_PronChallenge')
	{
		document.frames[currentIframe].window.submitResult();
		return;
	}
}

///////////////////////////////////////////////////////////////////////////////////
//PronChallenge functions
function setQuestions_PC(currentQuestionPoolName, currentQuestionPoolType, currentQuestionPoolAlias,questions)
{
	showIframe("QuestionPage_PronChallenge");
	document.frames["QuestionPage_PronChallenge"].window.setQuestions_PC(currentQuestionPoolName, currentQuestionPoolAlias, questions);
}

function FailGetOralEnglishEvaluation_PC()
{
	document.frames["QuestionPage_PronChallenge"].window.FailGetOralEnglishEvaluation_PC();
}

function SetEvaluationResult_PC(questionId, resultJson)
{
    document.frames["QuestionPage_PronChallenge"].window.SetEvaluationResult_PC(questionId, resultJson);
}

function QuestionResultAudio_StartRecordFailed_PC()
{
	if (currentIframe == 'QuestionPage_PronChallenge')
	{
		document.frames[currentIframe].window.QuestionResultAudio_StartRecordFailed_PC();
	}
}

function QuestionResultAudio_StopRecordFailed_PC()
{
	if (currentIframe == 'QuestionPage_PronChallenge')
	{
		document.frames[currentIframe].window.QuestionResultAudio_StopRecordFailed_PC();
	}
}

function QuestionResultAudio_StartPlaybackFailed_PC()
{
	if (currentIframe == 'QuestionPage_PronChallenge'||currentIframe == 'QuestionReviewPage_PronChallenge'||currentIframe == 'ResultPage_PronChallenge')
	{
		document.frames[currentIframe].window.QuestionResultAudio_StartPlaybackFailed_PC();
	}
}

function QuestionResultAudio_StopPlaybackFailed_PC()
{
	if (currentIframe == 'QuestionPage_PronChallenge'||currentIframe == 'QuestionReviewPage_PronChallenge'||currentIframe == 'ResultPage_PronChallenge')
	{
		document.frames[currentIframe].window.QuestionResultAudio_StopPlaybackFailed_PC();
	}
}

/********skin********/
function UpdateSkinForAll()
{
    setTimeout('window.external.UpdateSkin()', 0);
}

var CurSkinModel = "DefaultModel";
var CurSkinColor = "Blue.css";
var CurSkinImage = "";
function GetCurrentSkinModel()
{
    return CurSkinModel;
}

function GetCurrentSkinColor()
{
    return CurSkinColor;
}

function GetCurrentSkinImage()
{
    return CurSkinImage;
}

function UpdateSkinForPage(model, color, image)
{
    CurSkinModel = model;
    CurSkinColor = color;
    CurSkinImage = image;
    $("link#_NewSkinColor").attr("href", "").attr("href", "../../../../../skin/Color/" + color + ".css");
    $("link#_NewSkinImage").attr("href", "").attr("href", "../../../../../skin/Image/" + image + "/BgImg.css");
	
	window.frames["QuestionPoolsPage"].window.UpdateSkinForPage(model, color, image);
    window.frames["QuestionPage"].window.UpdateSkinForPage(model, color, image);
    window.frames["QuestionReviewPage"].window.UpdateSkinForPage(model, color, image);
    window.frames["ResultPage"].window.UpdateSkinForPage(model, color, image);
    window.frames["QuestionPage_PronChallenge"].window.UpdateSkinForPage(model, color, image);
	window.frames["QuestionReviewPage_PronChallenge"].window.UpdateSkinForPage(model, color, image);
    window.frames["ResultPage_PronChallenge"].window.UpdateSkinForPage(model, color, image);
}

