
//-----------------------------------------------
//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 QuestionReviewPage
	if (window.parent.window.currentIframe!='QuestionReviewPage')
	{
		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
	{
		ContinueChallenge_onclick(); //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 ShareQuestion_onclick(obj)
{
	window.external.AddChallengeQuota(1);
	
	var headWord=$(obj).parent().find('.question-headword').html();
	//remove \" and trim white space at front and end
	headWord=headWord.replace(/\"/g,'').replace(/(^\s*)|(\s*$)/g, ''); 
	
	var text=$(obj).parent().find('.question-text').html();
	var choices='';
	$(obj).parent().find('.question-choices').find('.question-choice').each(function(index, choice) {
		var choiceIndex=$(choice).find('.question-choice-index').html();
        choices += choiceIndex;
		choices += '.';
		var choiceTxt = $(choice).find('.question-choice-text').html();
		
		choices += choiceTxt;

		choices += ' \n';
    });
	
	var postProcessLen2=80;
	while ((choices).length >= 80 || encodeURIComponent(choices).length > 720)
	{
		postProcessLen2-=3;
		choices = choices.length >= postProcessLen2 ? choices.substring(0,postProcessLen2)+'...\n':choices;//length limitation for all choices
	}
	
	var postProcessLen=100;
	while ((headWord+text+choices).length>=100||encodeURIComponent(headWord+text+choices).length>=900)
	{
		postProcessLen -= 3;
		var textLength = postProcessLen - (headWord.length + choices.length) - 3 > 0 ? postProcessLen - (headWord.length + choices.length) - 3 : 0;
		text = text.substring(0, textLength)+'...';
	}

	var content='';
	content += '这道题有点意思，你会做吗？ \n'
	content += (headWord=='')?(''):(headWord+' \n');
	content += text + ' \n';
	content += choices;
	content += '嗨~我正在使用 @必应词典 的扩展应用-- #我爱说英语# 跟我一起来挑战英语吧~';
	content = content.replace(/\"/g,'\"');
	window.open('http://service.weibo.com/share/share.php?' + 'url=' + encodeURIComponent('http://dict.bing.msn.cn/') + '&appkey=2546683754&ralateUid=3167273451' + '&title=' + encodeURIComponent(content), '_blank', 'width=640, height=480, top=320, left=180, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no');
}

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('OE_QuestionBingSearch');
}


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('OE_QuestionFeedback');
	}	
}


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('OE_PlayAudio');
}

function questionChoice_onclick(obj)
{

}


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()
{
	$('#ShareRanking',parent.frames['ResultPage'].document).hide();
    getCurrentQuestions();
}

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

function Back_onclick()
{
    window.parent.showIframe("ResultPage");
}

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

function setReviewQuestions(questions)//
{
	//identify right choices and wrong choices
	$('#questions').html(questions);
	$('#questions .question-choices .question-choice-answer').each(function(i, choiceAnswer) {
        if ($(choiceAnswer).html()=='right')
		{
			$(choiceAnswer).parent().removeClass('wrong-choice').addClass('right-choice');
		}
    });
	
	$('#questions .question-choices .selected').each(function(i, selectedChoice) {
        if ($(selectedChoice).find('.question-choice-answer').html()!='right')
		{
			$(selectedChoice).removeClass('right-choice').addClass('wrong-choice');
		}
    });
	
	//generate page nav
	var pageTabs='';

	$('#questions .question').each(function(i, ques) 
	{
		var rightWrong='';
		if ($(ques).find('.selected').length==0||$(ques).find('.selected').find('.question-choice-answer').html()!='right')
		{
			rightWrong=' answer-wrong';
		}
		else 
		{
			rightWrong=' answer-right';
		}
		
		pageTabs+=
		"<div id=\"page-tab-"+(i+1)+"\" class=\"page-tab\" title=\"第"+(i+1)+"页\"\
		onmouseover=\"$(this).addClass('hovered');\"\
		onmouseout=\"$(this).removeClass('hovered');\"\
		onclick=\"pageTab_onclick(this);\"\
		>\
			<div class=\"page-tab-inner-box"+rightWrong+"\"></div>\
		</div>\
		";
	});
	
	$('#nav-page-tabs').html(pageTabs);
	$('#nav-page-tabs #page-tab-1').click();
}


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

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




