var bot_id;
var bot_name;
var VLT_username;
//var wave_root_url='http://www.langkoo.com/botwave/';

//var wave_root_url='http://192.168.1.118:8080/vox';
//var default_wave_root_url='http://www.langkoo.com/botwave/default/';
var wave_root_url='/bot';

var cur_wave_file_name;
var cur_wave_file_url;
var wave_play_completed=1;
var history_child_length=10;
var b_sound_support=false;
var b_playsound_mode=false;
//var audio_player=new VOX.REPEAT.AudioDealEngine();
var bot_engine=new VOX.BOT.DataEngine();
var bot_response=[];
var dialogue_history;
var botreply_label;
var botreply;
var div_right_hint;
var right_hint;

var basePath;

function init(wave_base_path,botid,botname,username)
{
	basePath = wave_base_path;
	bot_id=botid;
	bot_name=botname;
	//wave_root_url=wave_base_path;
	default_wave_root_url=wave_base_path+'default/';
	VLT_username=username;
	document.getElementById("sound_mode").checked=false;	
	sendToBot('Call me '+VLT_username, false, false, document.getElementById("sentence_mode").checked);
}
/**
 * Puts the cursor into the input field.
 */
function focusInput()
{
	var input = document.getElementById('user-input').focus();
}


/**
* 过滤用户输入的空格
*/
function trim(str){ //删除左右两端的空格 
  return str.replace(/(^\s*)|(\s*$)/g, ""); 
}

function submitText()
{
  var basePath = "http://"+window.location.host+"/"+window.location.href.replace(new RegExp("/+", 'g'), "/").split("/")[2];
	var userInput = document.getElementById('user-input').value;
	var boutFin = document.getElementById('bout_fin').value;
	
	//用户输入空格或没有输入信息 不做处理 20100330
	userInput=trim(userInput);
	if(userInput==null||userInput=="") return;

	// if bout finished
	if ("true" == boutFin) {
		
		// and the answer is 'yes'
		if ("yes" == userInput || "Yes" == userInput || "YES" == userInput) {
			window.location = basePath + "/user/mainPage.action";
			return;
		}

	}
	
	// sentence mode
	var sentence_mode = document.getElementById("sentence_mode").checked;
	

	if(b_sound_support){
		if(wave_play_completed==1){
			sendToBot(userInput, true, true, sentence_mode);
		}
	}else{
		sendToBot(userInput, true, true, sentence_mode);
	}
}

/**
 * Sends a non-empty message to the bot, and sets up
 * a callback (thanks to DWR) that will receive the
 * response and display it.
 */
function sendToBot(message,intercepted,displayUserinput, sentence_mode)
{
	
	if(typeof bot_engine=='undefined'){
		bot_engine=new VOX.BOT.DataEngine();
	}
	//alert('wave_play_completed before send to bot= '+wave_play_completed);
	if ( (message != null) && (message != '') && (message != ' '))//&& (!message.match(/^(\W)+$/)) 
	{
		if(!b_sound_support){
			bot_engine.getResponse(message,null,null,bot_id,intercepted,{
				success:function(a){
					bot_response=a;
					
					displayResponse(bot_response,displayUserinput);
				},
				failure:function(){
					//alert("获取机器人响应失败！");
				}
			},sentence_mode);
			//bot.getResponse(displayResponse, message, null);
		}else{
			cur_wave_file_name='_'+(new Date()).getTime()+'.wav';
			//cur_wave_file_url=wave_root_url+cur_wave_file_name;
			
			
			bot_engine.getResponse(message,cur_wave_file_name,null,bot_id,intercepted,{
				success:function(a){
					//20100326调转到学页是做判断用户是否安装了插件
          if (!checkActivexForConfirm(false)) return;
          
					//cur_wave_file_url = wave_root_url + "/getWave.action?TTS_inputText=" + a[12];
					cur_wave_file_url = getAbsolute()+getServName()+ "/getWave.action?TTS_inputText=" + a[12]; 
					bot_response=a;
					displayResponse(bot_response,displayUserinput);
				},
				failure:function(){
					//alert("获取机器人响应失败！");
				}
			},sentence_mode);
		}		
	}
}

/**
 * Displays a response sent from the bot, filling/changing
 * the appropriate boxes on the page, and leaves the cursor
 * in the input box.
 */
var displayResponse = function(a_response,displayUserinput)
{

	// need change words color
	if (a_response[13] != "") {
		var divId = a_response[13] + "Div";
		document.getElementById(divId).innerHTML = "<font color='blue'>" + a_response[13] + "</font>";
	}
	
	// refresh new words
	if (a_response[14] != "") {
		var divWord = document.getElementById("divWord");
		var words = a_response[14].split(",");
		var str = "";
		for (var i = 0;i < words.length;++i)
			str += "<div id='" + words[i] + "Div'>" + words[i] + "</div>";
		divWord.innerHTML = str;

	}

	// change bg color
	if (a_response[15] != "") {
		var strs = a_response[15].split(";");
		var bgColor = strs[0];
		var borderColor = strs[1];
		document.getElementById("coco").style.backgroundColor = bgColor;
		document.getElementById("coco").style.border = "3px " + borderColor + " solid";
	}

	//by CSI.1111
	if (a_response[16] != "") {
		var retStrs = a_response[16].split(" ");
		var amountOfSentetnces = retStrs[0];
		var highestScore = retStrs[1];
		var flag = retStrs[2];
		
		//if (amountOfSentetnces % 20 == 0 && amountOfSentetnces != 0) {
		//if (amountOfSentetnces >= 20) {
			//var reminderSpan = $("reminderSpan");
			//reminderSpan.style.display = "inline";
			//reminderSpan.innerText = "您已经达到" + 20 + "句，今天任务已经完成";
		//}
		document.getElementById("bout").innerHTML = "<font color='red'>"+amountOfSentetnces + "</font>/20";
		document.getElementById("boutHighestScore").innerText = highestScore;
		if (flag == "true")
			document.getElementById("conguratulations").style.display = "inline";
		else
			document.getElementById("conguratulations").style.display = "none";
			
		retStrs = undefined;
	}


	//if(a_response[9]=='0'){
	//	alert("会话过期，请您重新登录！");
	//	window.location.reload();
	//}	
	//prompt("",a_response[0]+"$"+a_response[1]+"$"+a_response[2]+"$"+a_response[3]);
	
	
	var bout_fin = a_response[11];
	if (null == bout_fin || "" == bout_fin)
		bout_fin = "false";
	document.getElementById('bout_fin').value = bout_fin;
	
	// Grab the dialogue_history box.
	dialogue_history = document.getElementById('dialogue-history');
	div_right_hint = document.getElementById('right_hint');
	right_hint = a_response[10];

	if(displayUserinput){
		// Get the input.
		var input_element=document.getElementById('user-input');
		var input = a_response[5];
		
		// Create a paragraph that will display the user input in the dialogue history.
		var userinput_label = document.createElement('div');
		var userinput = document.createElement('div');
		userinput_label.className="userlabel"
		userinput.className='usersaid';
		userinput_label.innerHTML=VLT_username+"<font color='black'> Said:</font>";
		userinput.innerHTML='&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+input;
		dialogue_history.appendChild(userinput_label);
		dialogue_history.appendChild(userinput);
		
		input_element.value='';
		var range=input_element.createTextRange(); 
		range.collapse(true); 
		range.moveStart('character',0); 
		range.select();
	}

	// Blank out the user input.
	/*
	 * TODO:
	 * Need some way to notify the field that it has changed
	 * (so onchange will work right if the same value is
	 * typed again).
	 */

	//if b_sound_support && b_playsound_mode condition is fufilled, the bot replay will delay to display
	botreply_label = document.createElement('div');
	botreply = document.createElement('div');
	botreply_label.className='botlabel';
	botreply.className='botreply';
	botreply_label.innerHTML=bot_name+"<font color='black'> Said:</font>";
	botreply.innerHTML='&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+a_response[0];
	if(!(b_sound_support && b_playsound_mode)){
		dialogue_history.appendChild(botreply_label);
		dialogue_history.appendChild(botreply);
		div_right_hint.innerHTML=right_hint;
	}
	
	dialogue_history.doScroll("pagedown");
	dialogue_history.doScroll("pagedown");
	dialogue_history.doScroll("pagedown");
	
	//display statistics
	var amount_of_sentences = document.getElementById('amount_of_sentences');
	amount_of_sentences.innerHTML = a_response[1];
	var average_sentence_length = document.getElementById('average_sentence_length');
	average_sentence_length.innerHTML = a_response[2];
	var amount_of_vocabulary = document.getElementById('amount_of_vocabulary');
	amount_of_vocabulary.innerHTML = a_response[3];
	var word_frequency = document.getElementById('word_frequency');
	word_frequency.innerHTML = a_response[4];
	var user_score = document.getElementById('user_score');
	user_score.innerHTML = a_response[6];
	var user_score = document.getElementById('user_total_score');
	user_score.innerHTML = a_response[8];
	
	if(b_sound_support){
		
		wave_play_completed=0;
/*		if(!checkActivexInstall()){
			return;
		}*/
		
		if(!_vox_engine_obj){
			vox_engine_init();
		}
		document.getElementById("cocoPic").src = basePath + "/images/CocoSaiding.jpg";
		if(a_response[7]!=null && a_response[7]!=0){
			cur_wave_file_name='1'+'.wav';
			cur_wave_file_url=default_wave_root_url+cur_wave_file_name;
			//alert("cur_wave_file_url == " + cur_wave_file_url);
			try{
				//changeNewImg();
				vox_engine_event_playstop=playSoundCallback;
				vox_engine_init();

				var play_result=vox_engine_playSpecUrl(cur_wave_file_url);
				if(play_result!=0){
					playSoundCallback();
				}
			}catch(e){
			}
		}else{
			try{
				//changeNewImg();
				vox_engine_event_playstop=playSoundCallback;
				var wavUrl = "";

				var play_result = vox_engine_playSpecUrl(cur_wave_file_url);

				if(play_result != 0){
					playSoundCallback();
				}
				/**
				new Ajax.Request(
					cur_wave_file_url,{
						onComplete: function (request){
										//alert(request.responseText);
										wavUrl = request.responseText;
										var play_result = vox_engine_playSpecUrl(wavUrl);
										if(play_result != 0){
											playSoundCallback();
										}
									}
					}
				);
				*/
			}catch(e){
				
			}
		}
	}
	
	//oAudio.src = cur_wave_file_url;
	//oAudio.beginElement();
	
	// Scroll to the bottom (so the history will be visible).
	//window.scrollTo(0, 1000000);
	
	// Put the cursor back in the input field.
	focusInput();
	
}


function changeSound(){
	b_sound_support = document.getElementById("sound").checked;
	if(!b_sound_support){
		document.getElementById("sound_mode").checked=false;
		changePlaySoundMode();
		document.getElementById("sound_mode").disabled=true;
	}else{
		document.getElementById("sound_mode").disabled=false;
	}
}

function changePlaySoundMode(){
	//b_sound_support=document.getElementById("sound_mode").checked;
	b_playsound_mode = document.getElementById("sound_mode").checked;
}
var b_sentence_mode=false;
function changeSentenceMode(){
	b_sentence_mode = document.getElementById("sentence_mode").checked;
	if(b_sentence_mode){
		document.getElementById("sentence_mode_info").style.visibility ="visible";
	}else{
		document.getElementById("sentence_mode_info").style.visibility ="hidden";
	}
}
/**
 * added by liuchen
 * playSound function callback, remember if the wave file play completed
 * 
 */
function playSoundCallback(){

	vox_engine_event_playstop=null;
	wave_play_completed=1;
	if(b_sound_support && b_playsound_mode){
		
		dialogue_history.appendChild(botreply_label);
		dialogue_history.appendChild(botreply);		
		div_right_hint.innerHTML=right_hint;
		
		dialogue_history.doScroll("pagedown");
		dialogue_history.doScroll("pagedown");
		dialogue_history.doScroll("pagedown");
	}
	//changeOldImg();
	//alert('wave_play_completed after paly= '+wave_play_completed);
	
	// change face
	document.getElementById("cocoPic").src = basePath + "/images/girl.gif";
	
}
function changeNewImg(){
	var oldImgPath=document.getElementById("robotImg").src;
	var newImgPath=oldImgPath.replace("bot.gif","mouth.gif");
	document.getElementById("robotImg").src=newImgPath;
}
function changeOldImg(){
	var oldImgPath=document.getElementById("robotImg").src;
	var newImgPath=oldImgPath.replace("mouth.gif","bot.gif");
	document.getElementById("robotImg").src=newImgPath;
}
