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

//detect and response to keyboard event
$(document).ready(
function () {
$(document).bind('keydown',window.event,keyDown)
.bind('keyup',window.event,keyUp)
.bind('keypress',window.event,keyPress)
;
$(window.parent.document).bind('keydown',window.parent.event,keyDown)
.bind('keyup',window.parent.event,keyUp)
.bind('keypress',window.parent.event,keyPress)
;
}
);
function keyDown(evt)
{
}
function keyUp(evt)
{
	//only should be triggered when current page is QuestionPage
	if (window.parent.window.currentIframe!='QuestionPage_PronChallenge')
	{
		return;
	}
	
	var keyCode = evt.keyCode;

	if ((keyCode >= 37 && keyCode <= 40) || (keyCode==33||keyCode==34))//left, up, right, down || page up, page down
	{
		trySwitchQuestion(keyCode);
		return;
	}
	
	if (keyCode == 27 || keyCode == 8)//ESC,Backspace
	{
		GiveUpChallenge_onclick(); //give up and go back to QuestionPoolsPage
		return;
	}

}
function keyPress(evt)
{
}


function trySwitchQuestion(keyCode)
{
	if (keyCode==37||keyCode==38||keyCode==33)
	{
		PrevQuestion_onclick()
		return;
	}
	if (keyCode==39||keyCode==40||keyCode==34)
	{
		NextQuestion_onclick()
		return;
	}
}

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


function goToPage(pageNum)
{
	if ($('#recorder_mask').is(':visible')){return;}
	
	if (!isNaN(pageNum))
	{
		$('#questions .question').removeClass('current');
		$('#questions #question-'+pageNum.toString()).addClass('current');
		
		$('#nav-page-tabs .page-tab').removeClass('selected');
		$('#nav-page-tabs #page-tab-'+pageNum.toString()).addClass('selected');
		
		if ($('#nav-page-tabs #page-tab-'+pageNum.toString()).hasClass('done'))
		{
			$('#question_buttons #question_recorder').html('重新录音');
		}
		else
		{
			$('#question_buttons #question_recorder').html('录音');
		}
	}
}

function pageTab_onclick(obj)
{   
	var pageNum = parseInt(obj.id.substring(9));

	if (!isNaN(pageNum))
	{
		goToPage(pageNum);
	}
}

function PrevQuestion_onclick()
{
	var pageNum = parseInt($('.question.current').attr('id').substring(9));
	if (!isNaN(pageNum) && pageNum>1)
	{
		goToPage(pageNum-1);
	}
}

function NextQuestion_onclick()
{
	var pageNum = parseInt($('.question.current').attr('id').substring(9));
	if (!isNaN(pageNum) && pageNum<$('#questions .question').length)
	{
		goToPage(pageNum+1);
	}
}


function RedoChallenge_onclick() 
{
	if ($('#recorder_mask').is(':visible')){return;}
	
    getCurrentQuestions_PC();
}

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

function GiveUpChallenge_onclick()
{
	if ($('#recorder_mask').is(':visible')){return;}
	
	window.external.AddChallengeQuota(1);
	
	$('#ShareRanking',parent.frames['ResultPage'].document).show();
    parent.showIframe('QuestionPoolsPage');
    parent.frames['QuestionPoolsPage'].window.location.reload();
}

/**************************************************************/

function QuestionAudio_onclick(obj)
{
	var url = '';
	if ($(obj).parent().hasClass('question-pron'))
	{
		var guid=$(obj).parent().parent().find('.question-id').html();
		url = 'https://wordchallenge.blob.core.windows.net/oralenglish/'+guid+'.mp3';
	}
	
	StartPlayQuestionAudio(url);
}

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


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

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

function QuestionResultAudio_StartRecordFailed_PC()
{
	$('#recorder_mask').hide();
	changeRecorderStatus('recorderror');
	
	ShowWarning('开启录音失败，请确定您的音频输入设备正常！')
}

function QuestionResultAudio_StopRecordFailed_PC()
{
	$('#recorder_mask').hide();
	changeRecorderStatus('recorderror');
	
	ShowWarning('停止录音失败，请确定您的音频输入设备正常！')
}

function hideRecorderMask()
{
	//$('#questions .question.current .question-result').html('').hide();
	$('#recorder_mask').hide();
	changeRecorderStatus('unrecorded');
	
	window.external.StopRecord();//stop recorder and reset recorder
}

function showRecorderMask()
{
	//$('#questions .question.current .question-result').html('').hide();
	$('#recorder_mask').show();
	changeRecorderStatus('unrecorded');
	
	window.external.StartRecord();//start recorder and record
	setTimeout(function () { if (curRecorderStatus != 'recorderror') { changeRecorderStatus('recording'); } }, 1000);

	window.external.AddToLog('WC_StartRecord');
}

function stopRecorder()
{
	$('#recorder_mask').show();
	changeRecorderStatus('recorded');
	
	window.external.StopRecord();//stop recorder
	window.external.GetEvaResult($('#questions .question.current .question-id').html());//get evaluation result
}

var iStopRecorderTimer = null;
var curRecorderStatus = 'unrecorded';
function changeRecorderStatus(status)
{
	window.external.StopPlayQuestionResultAudio();
	StopPlayQuestionAudio();
	
	curRecorderStatus = status;
	switch (status)
	{
	case 'unrecorded':
		$('#recorder_mask #RecorderCnt_image').attr('class','RecorderCntImage_UnRecorded');
		$('#recorder_mask #RecorderCnt_submitting').show();
		$('#recorder_mask #RecorderCnt_text').html('正在进行初始化，请稍候...');
		$('#recorder_mask #RecorderCnt_btn').show().hide();
		
		if (iStopRecorderTimer != null)
		{
			clearTimeout(iStopRecorderTimer);
			iStopRecorderTimer = null;
		}
		break;
		
	case 'recorded':
		$('#recorder_mask #RecorderCnt_image').attr('class','RecorderCntImage_Recorded')
		$('#recorder_mask #RecorderCnt_submitting').show();
		$('#recorder_mask #RecorderCnt_text').html('已经完成录音，正在提交...');
		$('#recorder_mask #RecorderCnt_btn').show().hide();
		
		if (iStopRecorderTimer != null)
		{
			clearTimeout(iStopRecorderTimer);
			iStopRecorderTimer = null;
		}
		break;
	
	case 'recording':
		$('#recorder_mask #RecorderCnt_image').attr('class','RecorderCntImage_Recording')
		$('#recorder_mask #RecorderCnt_submitting').hide();
		$('#recorder_mask #RecorderCnt_text').html('正在录音，请您朗读...');
		$('#recorder_mask #RecorderCnt_btn').show().hide().html('结束录音').unbind()
		.click(function()
		{
		    stopRecorder();
		})
		.delay(500).show(function(){});
		
		iStopRecorderTimer = setTimeout(function(){if (curRecorderStatus == 'recording'){stopRecorder();}},10000);
		break;
		
	case 'recorderror':
		$('#recorder_mask #RecorderCnt_image').attr('class','RecorderCntImage_RecordError')
		$('#recorder_mask #RecorderCnt_submitting').hide();
		$('#recorder_mask #RecorderCnt_text').html('录音失败！');
		$('#recorder_mask #RecorderCnt_btn').show().html('重新录音').unbind()
		.click(function()
		{
			showRecorderMask();
		});
		
		if (iStopRecorderTimer != null)
		{
			clearTimeout(iStopRecorderTimer);
			iStopRecorderTimer = null;
		}
		break;
	}
	
	return;
}

function QuestionScore_onclick(obj)
{
	$(obj).animate({ fontSize: "30px" },500).animate({ fontSize: "16px" },500);
}


function setQuestions_PC(currentQuestionPoolName, currentQuestionPoolAlias, questions)
{
	//replace the questions
    $('#question-pool-name').html('').html(currentQuestionPoolName);
    $('#question-pool-alias').html('').html(currentQuestionPoolAlias);
    $('#questions').html('').html(questions);
	$('#question_buttons #question_submit').hide();
	
	//generate page tabs
	var pageTabs='';
	for (var i=1;i<=$('#questions .question').length;i++)
	{
		pageTabs+=
		"<div id=\"page-tab-"+i+"\" class=\"page-tab\" title=\"第"+i+"页\"\
		onmouseover=\"$(this).addClass('hovered');\"\
		onmouseout=\"$(this).removeClass('hovered');\"\
		onclick=\"pageTab_onclick(this);\"\
		>\
			<div class=\"page-tab-inner-box\"></div>\
		</div>\
		";
    }
    $('#nav-page-tabs').html('').html(pageTabs);
	$('#nav-page-tabs #page-tab-1').click();

}

function FailGetOralEnglishEvaluation_PC()
{
	//$('#questions .question.current .question-result').html('').hide();
	$('#recorder_mask').hide();
	changeRecorderStatus('unrecorded');
	
	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 SetEvaluationResult_PC(questionId, resultJson)
{
    if (!$('#recorder_mask').is(':visible')){return;} //has already canceled submitting
    if ($('#questions .question.current .question-id').html() != questionId){return;} //the evaluation result is not for current question 
	
	var resultObj = eval('('+resultJson.replace(/\n/g,'')+')');
	var questionText = $('#questions .question.current .question-text').html();
	var startInd = 0;
	$(resultObj.Words).each(function(i, word) 
	{
		var tmpInd =  questionText.toUpperCase().indexOf(word["WordText"],startInd);
		if (tmpInd >= startInd)
        {
			word["WordStartIndex"] = tmpInd;
		}
		else 
		{
			word["WordStartIndex"] = startInd;
		}
		startInd = word["WordEndIndex"] = word["WordStartIndex"] + word["WordText"].length;
    });
	
	//compose the result text
	var resultText = '';
	resultText += '<div class=\"unword\">'+questionText.substring(0,resultObj.Words[0]["WordStartIndex"]).ToHtmlEncode()+'</div>';
	
	$(resultObj.Words).each(function(i, word) 
	{
		var fScore = parseFloat(word["WordScore"]);

		var evaClass = 'qr-quality-bad';
		if (fScore<25)
		{
			evaClass = 'qr-quality-bad';
		}
		else if (fScore<50)
		{
			evaClass = 'qr-quality-fair';
		}
		else if (fScore<75)
		{
			evaClass = 'qr-quality-good';
		}
		else if (fScore<=100)
		{
			evaClass = 'qr-quality-excellent';
		}
		
		resultText += '<div class=\"word wordid_'+word["WordId"]+' '+evaClass+'\" title=\"'+Math.round(word["WordScore"])+'\">'+questionText.substring(word["WordStartIndex"],word["WordEndIndex"]).ToHtmlEncode()+'</div>';
		
		if (i < resultObj.Words.length - 1)
		{
			resultText +='<div class=\"unword\">'+questionText.substring(word["WordEndIndex"],resultObj.Words[i+1]["WordStartIndex"]).ToHtmlEncode()+'</div>';
		}
    });
	
	resultText += '<div class=\"unword\">'+questionText.substring(resultObj.Words[resultObj.Words.length-1]["WordEndIndex"],questionText.length).ToHtmlEncode()+'</div>';
	
	
	var quesiontResult = ""+
	"<div class=\"question-result-id\">"+
	resultObj["ResultAudioId"]+
    "</div>"+
	"<div class=\"question-result-title\">"+
"朗读结果："+
"</div>"+                                   
"<div class=\"question-result-text\">"+
    resultText+  
"</div>"+                                                                        
"<div class=\"question-result-legend\">"+
    "<div class=\"qrl-legend excellent\">"+
        "<div class=\"qrl-legend-title\">优秀</div>"+
    "</div>"+
    "<div class=\"qrl-legend good\">"+
        "<div class=\"qrl-legend-title\">良好</div>"+
    "</div>"+                
    "<div class=\"qrl-legend fair\">"+
        "<div class=\"qrl-legend-title\">一般</div>"+
    "</div>"+                      
    "<div class=\"qrl-legend bad\">"+
        "<div class=\"qrl-legend-title\">较差</div>"+
    "</div>"+
"</div>"+           
"<div class=\"question-result-pron\">"+
    "<div class=\"question-audio QuestionAudio_N\" title=\"点击朗读句子\" "+ 
    "onmouseover=\"$(this).attr('class','question-audio QuestionAudio_H');\" "+
    "onmouseout=\"$(this).attr('class','question-audio QuestionAudio_N');\" "+
    "onmouseup=\"$(this).attr('class','question-audio QuestionAudio_H');\" "+
    "onmousedown=\"$(this).attr('class','question-audio QuestionAudio_P');\" "+
    "onclick=\"QuestionResultAudio_onclick(this);\""+
    ">"+
    "</div>"+
"</div>"+                    
"<div class=\"question-result-score\">"+
    "<div class=\"question-score-title\">"+
    "本题得分："+
    "</div>"+
    "<div class=\"question-score-content\" "+
    "onclick = \"QuestionScore_onclick(this);\" "+
    ">"+
    Math.round(resultObj["PronunciationScore"])+
    "</div>"+
"</div>"+
"";

	$('#questions .question.current .question-result').html(quesiontResult).show();
	$('#questions .question.current .question-score-content').click()
	$('#recorder_mask').hide();
	changeRecorderStatus('unrecorded');
	
	//go to thsi page to update some infos
	var pageNum = parseInt($('.question.current').attr('id').substring(9));
	if (!isNaN(pageNum))
	{
		$('#nav-page-tabs #page-tab-'+pageNum.toString()).addClass('done');	
		goToPage(pageNum);
	}
	
	//make the SubmitResult btn clickable if all questions done
	if ($('#nav-page-tabs .page-tab').length==$('#nav-page-tabs .done').length)
	{
		$('#question_buttons #question_submit').show();
	}
}


function submitResult()
{
	//make sure that all the questions are done
	if ($('#nav-page-tabs .page-tab').length!=$('#nav-page-tabs .done').length)
	{
		return;
	}

    //get totalQuestions and totalScore  
	var totalQuestions=$('#questions .question').length;
	if (totalQuestions==0){return false;}
	var totalScore = 0;
	$('#questions .question').each(function(i, question) 
	{
	    totalScore += parseInt($(question).find('.question-result-score .question-score-content').html());
	});
	
	var meanScore = (totalScore/totalQuestions);	
	var questionPoolName = $('#question-pool-name').html();
	var questionPoolAlias = $('#question-pool-alias').html();
	//submit the result	
	window.external.SubmitResult_PC(questionPoolName, questionPoolAlias, meanScore);
}

/********skin********/
function UpdateSkinForPage(model, color, image)
{
    $("link#_NewSkinColor").attr("href", "").attr("href", "../../../../../skin/Color/" + color + ".css");
}

