var FLIGHT_CLICK = 0;
var FLIGHT_HOVER = 1;
var FLIGHT_MOUSEOUT = 2;


function sortFlights(menu_element) {
	var key = menu_element.options[menu_element.selectedIndex].value;
	sortFlightsBy(key);
}

function useMobileLogo() {
	document.getElementById("logo").src = "images/logo/mobile_logo.png";
	
}

function addNBest(nbestList){
	//alert(nbestList);
	var newList = new Array();
	
	var formatted = "";
	
	for (i=0;i<nbestList.length;i++){
		var different = true;
		formatted = formatNbest(nbestList[i]);
		
		for (j=0;j<newList.length;j++){
			if (newList[j]==formatted){
				different = false;
				break;
			}
		}
		if ((different) && (formatted.length>1)){
			newList.push(formatted);
		}
	}
	
	
	for (i=0;i<newList.length;i++){
		if (document.getElementById("dropdown").options[i] != null){
			document.getElementById("dropdown").options[i].text = newList[i];
		}
		else{
			document.getElementById("dropdown").add(new Option(newList[i], i), null);
		}
	}
}

function formatNbest(string){
	firstUseful = string.search(/<(\d+)>/);
	beforeThat = string.lastIndexOf(" ", firstUseful);
	
	if (beforeThat!=-1){
		string = string.substr(beforeThat);
	}
	
	string = string.replace(/<(\d+)>/g,"");
	string = string.replace("_"," ");
	string = string.replace(/<background>/g,"");
	string = string.replace(/<noise>/g,"");
	string = string.replace(/<laugh>/g,"");

	return string.substring(0,1).toUpperCase() + string.substring(1,string.length);
}

function sortFlightsBy(key) {
	if (key && key!="") {
		if (currentlyExpanded != -1){
			mobileRemoveInfo(currentlyExpanded);
		}
		var xmlDoc = newXMLDocument("update");
	    var root = xmlDoc.firstChild;
	    root.setAttribute("sort_by", key);
	    
	    //var string = (new XMLSerializer()).serializeToString(xmlDoc);
	    var string = xmlToString(xmlDoc);
	    postXML(string,true); // send message to server side
	}
}

function hideHelpBox() {
	var helpBoxE = document.getElementById("helpBox");
	helpBoxE.style.visibility = "hidden";
	helpBoxE.style.display = "none";
}

function showHelpBox() {
	var helpBoxE = document.getElementById("helpBox");
	helpBoxE.style.visibility = "visible";
	helpBoxE.style.display = "inline";
}

function hideTaskBox() {
	var taskBoxE = document.getElementById("taskBox");
	taskBoxE.style.visibility = "hidden";
	taskBoxE.style.display = "none";
}

function showTaskBox() {
	var taskBoxE = document.getElementById("taskBox");
	taskBoxE.style.visibility = "visible";
	taskBoxE.style.display = "inline";
}


function sendPassCode() {
	var passCodeBoxE = document.getElementById("passCodeBox");
	if (passCodeBoxE != null) {
		var xmlDoc = newXMLDocument("update");
		var root = xmlDoc.firstChild;
		root.setAttribute("passCode", passCodeBoxE.value);
		//var string = (new XMLSerializer()).serializeToString(xmlDoc);
	    var string = xmlToString(xmlDoc);
	    postXML(string,true); // send message to server side
	}
}

function formFieldRecord() {
	var audioApplet = document.getElementById("AudioApplet");
	audioApplet.stopPlaying(); //alexgru
	audioApplet.startListening(); //alexgru
	
}

function linkFieldClick(elementName) {
	//alert('hello!!!');
	if (elementName.substring(0,5) == "link_") {
		
		//var elementId = element.id.substring(5);
		root.setAttribute("select_form_field", elementName.substring(5));
		root.setAttribute("button_click", "1");
	} 
}


function formFieldClick(element) {
	var xmlDoc = newXMLDocument("update");
    var root = xmlDoc.firstChild;
    

	if (element.id.substring(0,6) == "field_") {
		var elementId = element.id.substring(6); //remove "field_" from element name
		root.setAttribute("button_click", "0");
	} else if (element.id.substring(0,10) == "fieldname_") {
		var elementId = element.id.substring(10); //remove "fieldname_" from element name
		root.setAttribute("button_click", "1");
	} else if (element.id.substring(0,7) == "button_") {
		var elementId = element.id.substring(7);
		root.setAttribute("button_click", "1");
	} 
	else if (element.id.substring(0,10) == "topbutton_") {
		var elementId = element.id.substring(10);
		root.setAttribute("button_click", "1");
		
		
		
		// Change color here. Need check if color is already changed.
		if (getColored() == elementId){
			document.getElementById("toplink_" + elementId).style.color = "blue";
			setColored("");
		}
		else{
			document.getElementById("toplink_" + elementId).style.color = "red";
			setColored(elementId);
		}
		
	}
	root.setAttribute("select_form_field", elementId);
	
	for (var i=0; i<attributeNames.length; i++) {
		var fieldName = "fieldname_" + attributeNames[i];
		var button = "button_" + attributeNames[i];
		var buttonElement = document.getElementById(button);
		
		if (attributeNames[i] == elementId) {
			document.getElementById(fieldName).className = "formFieldLabelSelected";
			
			buttonElement.src = 'images/flightbrowser_icons/Microphone-Normal-Red-128x128.png';
			buttonElement.onmouseover = function() {this.src="images/flightbrowser_icons/Microphone-Normal-Red-128x128.png";};
			buttonElement.onmouseout  = function() {this.src="images/flightbrowser_icons/Microphone-Normal-Red-128x128.png";};
			buttonElement.onmousedown = function() {this.src="images/flightbrowser_icons/Microphone-Normal-Red-128x128.png";};
			buttonElement.onmouseup   = function() {this.src="images/flightbrowser_icons/Microphone-Normal-Red-128x128.png";};
			//document.getElementById(button).onmouseout = 'this.src=images/flightbrowser_icons/Microphone-Normal-Red-128x128.png';
			//document.getElementById(button).onmousedown = 'this.src=images/flightbrowser_icons/Microphone-Normal-Red-128x128.png';
			//document.getElementById(button).onmouseup = 'this.src=images/flightbrowser_icons/Microphone-Normal-Red-128x128.png';
		} else {
			document.getElementById(fieldName).className = "formFieldLabelUnselected";
			
			document.getElementById(button).src = 'images/flightbrowser_icons/Microphone-Normal-128x128.png';
			buttonElement.onmouseover = function() {this.src="images/flightbrowser_icons/Microphone-Pressed-128x128.png";};
			buttonElement.onmouseout  = function() {this.src="images/flightbrowser_icons/Microphone-Normal-128x128.png";};
			buttonElement.onmousedown = function() {this.src="images/flightbrowser_icons/Microphone-Normal-Red-128x128.png";};
			buttonElement.onmouseup   = function() {this.src="images/flightbrowser_icons/Microphone-Pressed-128x128.png";};
			//document.getElementById(button).onmouseover = 'this.src=images/flightbrowser_icons/Microphone-Pressed-128x128.png';
			//document.getElementById(button).onmouseout = 'this.src=images/flightbrowser_icons/Microphone-Normal-128x128.png';
			//document.getElementById(button).onmousedown = 'this.src=images/flightbrowser_icons/Microphone-Normal-Red-128x128.png';
			//document.getElementById(button).onmouseup = 'this.src=images/flightbrowser_icons/Microphone-Pressed-128x128.png';
		}
	}	
    
    //var string = (new XMLSerializer()).serializeToString(xmlDoc);
    var string = xmlToString(xmlDoc);
    postXML(string,true); // send message to server side         
    
    //now start recording -- alexgru, non-galaxy interface
    formFieldRecord();
}

function formHighlightClear() {
	for (var i=0; i<attributeNames.length; i++) {
		var fieldName = "fieldname_" + attributeNames[i];
		var button = "button_" + attributeNames[i];
		document.getElementById(fieldName).className = "formFieldLabelUnselected";
		document.getElementById(button).src = 'images/flightbrowser_icons/Microphone-Normal-128x128.png';
		document.getElementById(button).onmouseover = 'this.src=images/flightbrowser_icons/Microphone-Pressed-128x128.png';
		document.getElementById(button).onmouseout = 'this.src=images/flightbrowser_icons/Microphone-Normal-128x128.png';
		document.getElementById(button).onmousedown = 'this.src=images/flightbrowser_icons/Microphone-Normal-Red-128x128.png';
		document.getElementById(button).onmouseup = 'this.src=images/flightbrowser_icons/Microphone-Pressed-128x128.png';
	}
}

function goBackRequest() {
	var xmlDoc = newXMLDocument("update");
    var root = xmlDoc.firstChild;
    
    root.setAttribute("go_back_request", "true");
    
    //var string = (new XMLSerializer()).serializeToString(xmlDoc);
    var string = xmlToString(xmlDoc);
    postXML(string,true); // send message to server side 
    if (_iPhone) {
  		document.getElementById("viewport").setAttribute('content','initial-scale=.7, maximum-scale=1.0, minimum-scale=0.8, user-scalable=1');
  		window.scrollTo(0, 0);
  	}
}

function startOverRequest() {
	var xmlDoc = newXMLDocument("update");
    var root = xmlDoc.firstChild;
    
    root.setAttribute("start_over_request", "true");
    
    //var string = (new XMLSerializer()).serializeToString(xmlDoc);
    var string = xmlToString(xmlDoc);
    postXML(string,true); // send message to server side
    
    
    if (_iPhone) {
  		document.getElementById("viewport").setAttribute('content','initial-scale=1, maximum-scale=1.0, minimum-scale=0.8, user-scalable=0');
  		window.scrollTo(0, 0);
  	}
}

function flightClick(flightIndex, segmentIndex, isDblClick) {
	//abortAudio();

	var xmlDoc = newXMLDocument("update");
    var root = xmlDoc.firstChild;
    
    root.setAttribute("flight_click_index", flightIndex);
    root.setAttribute("flight_click_segment_index", segmentIndex);
    root.setAttribute("flight_double_click", isDblClick);
    
    //var string = (new XMLSerializer()).serializeToString(xmlDoc);
    var string = xmlToString(xmlDoc);
    postXML(string,true); // send message to server side 
    
    
    if (_iPhone) {
    	mobileAddInfo(flightIndex,FLIGHT_CLICK);
    }
    else{
    	changeRowColor(flightIndex,FLIGHT_CLICK);
    }
}


function flightHover(flightIndex, segmentIndex, isHover) {
	if (isHover) {
		changeRowColor(flightIndex,FLIGHT_HOVER);
	} else {
		changeRowColor(flightIndex,FLIGHT_MOUSEOUT);
	}
}

var currentlyExpanded = -1;

function mobileAddInfo(flightIndex, eventType){
	if (document.getElementsByTagName){
		var table = document.getElementById('flightTableMobile');
		
		if(table) {
			var rows = table.getElementsByTagName("tr");
			if (eventType == FLIGHT_CLICK) {
				if ((currentlyExpanded-2) == flightIndex){
					mobileRemoveInfo(currentlyExpanded);
					
				}
				else{ 
					if (currentlyExpanded != -1){
						mobileRemoveInfo(currentlyExpanded);
						
					}
					for (i = 0; i < rows.length; i++){
						if (i == flightIndex + 1) {
							//var newrow = document.createElement("TR");
							var newrow = table.insertRow(flightIndex+2);
							var bgcolor;
							if (flightIndex % 2 == 0){
								bgcolor = "#B9CDFA";
							}
							else{
								bgcolor = "#ECD8C0";
							}
							newrow.style.backgroundColor = bgcolor;
							var newcell = newrow.insertCell(0);
							newcell.colSpan='5';
							currentlyExpanded = i+1;
							newcell.innerHTML = "<center><a href='javascript:mobileRemoveInfo("+currentlyExpanded+")'><img src='images/arrowup_smaller.png' style='border-style: none'/></a><hr></center>"
							newcell.innerHTML += getDetailedInfo(flightIndex);
						}
					}
					newcell.innerHTML += "<br><center><button type='button' class='bookButton' onclick='buttonBook(" + flightIndex + ")'>Add to Itinerary</button></center>";
					
					var currentHash = location.hash;
					window.location.hash="#row"+flightIndex;
					
				}
			}
		}
	}
}

function buttonBook(flightIndex){
	mobileRemoveInfo(currentlyExpanded);

	var xmlDoc = newXMLDocument("update");
    var root = xmlDoc.firstChild;
    root.setAttribute("flight_click_index", flightIndex);
	root.setAttribute("flight_double_click", 'true');
	var string = xmlToString(xmlDoc);
    postXML(string,true); // send message to server side 
}

function mobileRemoveInfo(infoIndex){
	var table = document.getElementById('flightTableMobile');
	
	table.deleteRow(infoIndex);
	currentlyExpanded=-1;
}



function changeRowColor(flightIndex,eventType) {
	if(document.getElementsByTagName){  
		if (!_iPhone){
		  	var table = document.getElementById('flightTable'); 
		  	if (table) { 
		  		var rows = table.getElementsByTagName("tr");
		  		if (eventType == FLIGHT_CLICK) { 
				  	for (i = 0; i < rows.length; i++){
				  		if (flightIndex == null) {
							rows[i].className = "flightTableUnselected";	  			          
				    	} else if (i == flightIndex + 1){
				      		rows[i].className = "flightTableSelected";
				    	} else {
				      		rows[i].className = "flightTableUnselected";
				    	}      
				 	}
				} else if (eventType == FLIGHT_HOVER) {
					for (i = 0; i < rows.length; i++){
				  		if (flightIndex == null) {
							rows[i].className = "flightTableUnselected";
						} else if (rows[i].className == "flightTableSelected") {
							continue;	  			          
				    	} else if (i == flightIndex + 1) {
				      		rows[i].className = "flightTableHover";
				    	} else {
				      		rows[i].className = "flightTableUnselected";
				    	}      
				 	}
			 	} else { // (eventType == FLIGHT_MOUSEOUT) {
			 		for (i = 0; i < rows.length; i++){
				  		if (flightIndex == null) {
							rows[i].className = "flightTableUnselected";
						} else if (rows[i].className == "flightTableSelected") {
							continue;		  			          
				    	} else if (i == flightIndex + 1) {
				      		rows[i].className = "flightTableUnselected";
				    	}   
				 	}
			 	}
		 	}
	  	}
	}
}

function sendPartialNL(element) {
	//abortAudio();
	var focusAttribute = element.id.substring(5);       // remove "form_" from element name
	var elementId = "field_" + element.id.substring(5); // append "field_" to focus attribute
													    
    var nlString = document.getElementById(elementId).value;
    userIsTyping = false;													    
	sendNLFocusAttribute(nlString, focusAttribute);
}

function sendNLFocusAttribute(nlString, focusAttribute, isCorrection) {
	if(!isCorrection) {
		isCorrection = false;
	}
	
	if(nlString == null) {
		var inputArea = document.getElementById("inputNL");
		nlString = inputArea.value;
		inputArea.value = "";
	}
	
	if(nlString == null || nlString == "") {
		return false;
	}
	
		
	var xmlDoc=newXMLDocument("update");
	var root = xmlDoc.firstChild;
	root.setAttribute("inputNL", nlString);
	root.setAttribute("focusAttribute", focusAttribute);
	root.setAttribute("isCorrection", isCorrection ? 'true' : 'false');
	postXML(xmlDoc);	
	
	if(_galaxyHandlers && _galaxyHandlers.typedInputSentHandler) _galaxyHandlers.typedInputSentHandler();
}

var lastEditedTextField = "";
var userIsTyping = false;

function formFieldTypedInput(element,evnt) {

	/* can't get this to work
	alert(evnt);
  	
  	if (window.event) {// IE
  		keynum = evnt.keyCode;
  	} else { // Netscape/Firefox/Opera
  		keynum = evnt.which;
  	}

	alert(keynum);
	*/
	
	var appendMobile = "";
	if (_iPhone){
		appendMobile = "Mobile";
	}

	if (element.id != lastEditedTextField) {
		element.value = "";
		element.className = "formFieldOld"+appendMobile;
		userIsTyping = true;
	}
	
	lastEditedTextField = element.id;
	userIsTyping = true;
} 

function autoEnroll() {
	sendNL("new user");
	clearTables();
}

function clearTables() {
	document.getElementById("flightDisplay").innerHTML = "";
}

function clearItinerary() {
	document.getElementById("itineraryDisplay").innerHTML = "";
}

function clearTopNav() {
	updateForm("source", "*CLEAR*", DISPLAY_NEW);
	updateForm("destination", "*CLEAR*", DISPLAY_NEW);
	updateForm("date", "*CLEAR*", DISPLAY_NEW);
	updateForm("time", "*CLEAR*", DISPLAY_NEW);
	updateForm("airline", "*CLEAR*", DISPLAY_NEW);
	
	var headElem = document.getElementById("headerText");
	headElem.style.textAlign='left';
	
	document.getElementById("headerText").innerHTML = "<center>Started Over. Please speak to begin.</center><br><br>" +
		
		"<p id='headerText'><font size=4><strong>FlightBrowser</strong> is a conversational research prototype which lets you speak to obtain flight schedule information.<br>" + 
		"<br><ul id='instructions'><li>Hold the 'Hold to Talk' button, then speak<br> into your device's microphone.</li>" +
		"<br><li>If the recognition is wrong, check the<br> drop-down menu to see if the<br> right information is there</li>" + 
		"<br><li>Click a highlighted word and then the 'Hold<br> to Talk' button to re-record only<br> a portion of your sentence.</li>" +
		"<br><li>You can say 'Go back' or 'Start over'<br> if the system gets confused.</li></font></p>";
	
	
	
}

function clearNBest() {
	select = document.getElementById("dropdown");
	select.style.display = 'none';
	select.style.visibility = 'hidden';
	for (var i=select.options.length-1; i>=0; i--){
		select.remove(i);
	}
	
}

//function returnFlightNBest(NBestString) {
//	clearNBest();
//	select = document.getElementById("dropdown")
//	select.add(new Option(NBestString, 0), null);
//	select.selectedIndex=0;
//	//sendNLFocusAttribute(select.options[0].text)
//}

function sendBrowserInfo() {
	var xmlDoc=newXMLDocument("update");
	var root = xmlDoc.firstChild;
	root.setAttribute("browserInfo", "1");
	root.setAttribute("appName", navigator.appName);
	root.setAttribute("appVersion", navigator.appVersion);
	root.setAttribute("platform", navigator.platform);
	root.setAttribute("resolution", screen.width+"x"+screen.height);
	postXML(xmlDoc);
}

function xmlToString(xmlDoc) {
	try { // Works in firefox
		return (new XMLSerializer()).serializeToString(xmlDoc);
	} catch (e) {
		try { // This should work in Internet Explorer
			return xmlDoc.xml;
		} catch (e) {
			alert("XMLSerializer not supported in this browser");
		}
	}
}

function clickItineraryHeader(header) {
	var id = header.id.substring(15);
	var itinInfoE = document.getElementById("itineraryInfo"+id);
	
	if (itinInfoE.style.visibility == "hidden") {
		itinInfoE.style.visibility = "visible";
		itinInfoE.style.display = "inline";
	} else {
		itinInfoE.style.visibility = "hidden";
		itinInfoE.style.display = "none";
	}
}