
//-----------------------------------------------
//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')
	{
		return;
	}
	
	var keyCode = evt.keyCode;

	if (!(evt.altKey||evt.ctrlKey||evt.shiftKey)&&(keyCode >= 65 && keyCode <= 70))//a A ~ f F
	{
		trySelectChoice(keyCode);
		return;
	}
	
	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 trySelectChoice(keyCode)
{
	var realKey=String.fromCharCode(keyCode).toLowerCase();//a ~ f

	$('#questions .question.current .question-choices').find('.question-choice').each(function(i, choice) {
		if ($(choice).find('.question-choice-index').html().toLowerCase()==realKey)
		{
			questionChoice_onclick(choice);
			return;
		}
	});
}
function trySwitchQuestion(keyCode)
{
	if (keyCode==37||keyCode==38||keyCode==33)
	{
	    PrevQuestion_onclick();
		return;
	}
	if (keyCode==39||keyCode==40||keyCode==34)
	{
	    NextQuestion_onclick();
		return;
	}
}

//----------------------------------------------------
//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 goToPage(pageNum)
{
	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');
	}
}

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

	if (!isNaN(pageNum))
	{
		goToPage(pageNum);
	}
}
function QuestionFeedback_onclick(obj)
{
	if ($(obj).hasClass('normal_ba'))
	{
		$(obj).removeClass('normal_ba').addClass('FeedBack_D');
		$(obj).attr('title','已经反馈');
		window.external.SendFeedback($(obj).parent().find('.question-id').html());

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

function QuestionBingSearch_onclick(obj)
{
	var query='';
	query=$(obj).parent().find('.word-to-search').html();
	if (!query||query=='')
	{
		query=$(obj).parent().find('.question-headword').html();
	}
	window.open('http://cn.bing.com/search?mkt=zh-CN&setLang=zh&form=BDCN21&q=' + encodeURIComponent(query).substring(0, 1800));

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


function playAudio_onclick(obj)
{
    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 url = 'http://media.engkoo.com:8129/en-us/'+$(obj).parent().find('.question-media-signature').html()+'.mp3';
    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;
        }
    }

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

function questionChoice_onclick(obj)
{
	$('.question.current .question-choice').removeClass('selected');
	$(obj).addClass('selected');
	
	//tell c# the answer you selected
	window.external.SetQuestionAnswer($('.question.current .question-id').html(),$(obj).find('.question-choice-id').html());
	
	//go to next page if there are any after current page
	var pageNum = parseInt($('.question.current').attr('id').substring(9));
	if (!isNaN(pageNum))
	{
		$('#nav-page-tabs #page-tab-'+pageNum.toString()).addClass('done');
		if ( pageNum<$('#questions .question').length)
		{
			goToPage(pageNum+1);
		}
	}
	
	//make the SubmitResult btn clickable if all questions done
	if ($('#nav-page-tabs .page-tab').length==$('#nav-page-tabs .done').length)
	{
		$('#right-lower #SubmitResult').attr('class','normal_ba');
	}
	
}

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() 
{
    getCurrentQuestions();
}

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

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


function setQuestions(currentQuestionPoolName, currentQuestionPoolAlias, questions)
{
	
	//replace the questions
    $('#question-pool-name').html('').html(currentQuestionPoolName);
    $('#question-pool-alias').html('').html(currentQuestionPoolAlias);
    $('#questions').html('').html(questions);
	
	//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();
	//diable the SubmitResult btn at start
	if ($('#nav-page-tabs .page-tab').length!=$('#nav-page-tabs .done').length)
	{
		$('#right-lower #SubmitResult').attr('class','SubmitResult_D');
	}
	//start clock
	resetClcok();
	startClock();
}


var clockId=0;
var clockCounter=0;
var clockCounterUpperBound=60*60;
var clockTipInterval=1000;

function startClock()
{
	if (clockId!=0)
	{
		window.clearInterval(clockId);
		clockId=0;
	}
	clockCounter=0;
	clockTipInterval=1000;
	clockId=window.setInterval(clockTip,clockTipInterval);
	updateClockOnUI();
}

function stopClock()
{
	if (clockId!=0)
	{
		window.clearInterval(clockId);
		clockId=0;
	}
	updateClockOnUI();
}

function resetClcok()
{
	if (clockId!=0)
	{
		window.clearInterval(clockId);
		clockId=0;
	}
	clockCounter=0;
	clockTipInterval=1000;
	updateClockOnUI();
}

function clockTip()
{
	clockCounter++;
	if (clockCounter>=clockCounterUpperBound)
	{
		stopClock();
	}
	updateClockOnUI();
}

function updateClockOnUI()
{
	var currentClockCounter=clockCounter;
	var minutes=parseInt(currentClockCounter/60);
	var seconds=parseInt(currentClockCounter%60);
	var displayString = (minutes<10?'0'+minutes:minutes)+':'+(seconds<10?'0'+seconds:seconds);
	$('#clock-value').html(displayString);
}


function SubmitResult_onclick() 
{
	//make sure that all the questions are done
	if ($('#nav-page-tabs .page-tab').length!=$('#nav-page-tabs .done').length)
	{
		return;
	}
	
	//get timeUsed
	stopClock();
	var timeUsed=clockCounter;
	if (timeUsed<20){timeUsed=20;}
	if (timeUsed>500){timeUsed=500;}
	
	//get totalQuestions and rightQuestions  
	var totalQuestions=$('#questions .question').length;
	if (totalQuestions==0){return false;}
	var rightQuestions=0;

	$('#questions .question').each(function(i, question) 
	{
		var questionFailed=false;
		$(question).find('.question-choices .selected').each(function(j, selectedChoice) 
		{
			if ($(selectedChoice).find('.question-choice-answer').html().toLowerCase().indexOf('wrong')!=-1)
			{
				questionFailed=true;
				return false;
			}
		});
		
		if (questionFailed==false)
		{
			rightQuestions++;
		}
	});

	//get rawScore and 
	var rawScore = (rightQuestions/totalQuestions)*20;
	var finalScore = parseInt( rawScore*(rawScore*4+500-timeUsed)/50 );
	var questionPoolName = $('#question-pool-name').html();
	var questionPoolAlias = $('#question-pool-alias').html();
	//submit the result
	
	window.external.SubmitResult(questionPoolName, questionPoolAlias, finalScore, timeUsed);
}

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

