/*===================================================================================
This file provides methods that allow entering 
alpha-numeric characters using standard phone DTMF keypad

Many thanks to http://www.codingforums.com/showthread.php?t=37148.

The following controls should be present on the page:

FilterControl - this is a server intput control which contains the string entered.
				it should not be visible on the phone
<input id="FilterControl" type="text" runat="server" style="LEFT:0px;COLOR:red;POSITION:absolute;TOP:470px"> 

filterDiv - this is the div which contains the string entered plus, possibly, a "_"
			symbol which is meant to indicate current cursor position.
			This value must be synchronised with FilterControl on each postback.
<div class="PK1Large" id="key1_1" style="LEFT:47px; WIDTH:400px"><div class="BlackDiv" id="filterDiv" runat="server"></div></div>

CurrentSearchMode - since the same phone button is used to enable input system, 
					initiate the search and then clear the search, a button state
					indicator is needed. CurrentSearchMode can be 
					0=Search, 1=Waiting for input, 2=Clear Search
<input id="CurrentSearchMode" type="text" runat="server" style="LEFT:300px;WIDTH:30px;COLOR:red;POSITION:absolute;TOP:21px" name="CurrentSearchMode"> 

SearchImage - this image displays a label for multi-state Search button.
<div class="PK1Large" id="key1"><a id="SCREENKEY1" onclick="OnSearchKeyPress()"></a><img runat="server" id="SearchImage" src="Images/search.gif" onclick="OnSearchKeyPress()"></div>
pageDescription2 - this image displays instructions image corresponding to 
					the current state of the Search button
<asp:imagebutton id="pageDescription2" runat="server" imageurl="Images/instruction1.gif"></asp:imagebutton>

SearchButton - this is an asp button control. Should be invisible on the phone.
				needed for doing postbacks from client side (by calling __doPostBack('SearchButton','')). 
				This is needed because a single control can't do both javascropt onclick 
				and postback. Thus SearchImage does client-side work, while SearchButton 
				performs server-side search.
<asp:button id="SearchButton" style="LEFT: 165px; POSITION: absolute; TOP: 20px" runat="server" text="Search" width="130" visible="True" enabled="false"></asp:button>

Anchors 1-9, *, #
===================================================================================*/
var search_images; // the array of 4 images for search button
var instruction_images; // the array of 4 images for instruction
var keys = []; //hash array that will hold the characters that correspond to a DTMF key
var modes = ['abc','ABC','123']; //write message mode: abc=lowercase letter, ABC=uppercase letter, 123=number
var modeIndex = 0; //default is lowercase ('abc')
var appendChar = true; //flag that tells if the character is appended or not
var keyDown = false; //flag that tells if the key is held down or not
var prevKey = null; //flag that remembers the previous key pressed
var timer; //the timer for function call delay
var delay = 2000; //2 seconds delay
var maxSmsLen = 160; //maximum length of SMS message
var poundPressed = false;
var isInputMode = false; // this indicates if the app is currently in the input mode
function addKey(num, arrChar){
	keys[num] = new Object();
	keys[num].ctr = 0;
	keys[num].chars = arrChar;
}
function EnterInputMode(add_capital_letters)
{
    //alert("enter");
	// Enter the "input" mode, i.e. a DTMF click shouldn't dial, but rather 
	// input corresponding letters to the FilterControl edit box.
	
	isInputMode = true; // the app is now in the input mode
	
	if(parent.TelML){
		for( var i = 0; i <= 11; ++i )
		{
			var ButtonObj = TelML.Buttons.Item( i );
			// clear auto event for all DTMF keys, set all DTMFs to be browser clicks
			ButtonObj.SetAutoEvent( 0, null );
		}
	}
	//add corresponding characters for each key
	//change characters as needed (lowercase characters only)
	if(!add_capital_letters){
		addKey('1', ['\'','.',',','1','?','!','@','-','_','(',')',':',';','&','/','~','\\','%','*','#','+','<','=','>','"']);
		addKey('2', ['a','b','c','2']);
		addKey('3', ['d','e','f','3']);
		addKey('4', ['g','h','i','4']);
		addKey('5', ['j','k','l','5']);
		addKey('6', ['m','n','o','6']);
		addKey('7', ['p','q','r','s','7']);
		addKey('8', ['t','u','v','8']);
		addKey('9', ['w','x','y','z','9']);
		addKey('0', [' ','0']);
	}else{
		addKey('1', ['\'','.',',','1','?','!','@','-','_','(',')',':',';','&','/','~','\\','%','*','#','+','<','=','>','"']);
		addKey('2', ['a','b','c','2','A','B','C']);
		addKey('3', ['d','e','f','3','D','E','F']);
		addKey('4', ['g','h','i','4','G','H','I']);
		addKey('5', ['j','k','l','5','J','K','L']);
		addKey('6', ['m','n','o','6','M','N','O']);
		addKey('7', ['p','q','r','s','7','P','Q','R','S']);
		addKey('8', ['t','u','v','8','T','U','V']);
		addKey('9', ['w','x','y','z','9','W','X','Y','Z']);
		addKey('0', [' ','0']);
	}
	
	//alert(document.getElementById("filterDiv").innerHTML +"\n"+ (document.getElementById("filterDiv").innerHTML==""));
	if(document.getElementById("filterDiv").innerHTML==""){
		document.getElementById("filterDiv").style.visibility = "visible";
		document.getElementById("filterDiv").innerHTML = "_";
	}
	
	// exit input mode if idle with empty filter for 60 seconds
	clearTimeout(timer);
	timer = setTimeout(
		function(){
			var curr_search_mode = document.getElementById("CurrentSearchMode").value;
			if(curr_search_mode == "1"){
				// Reset to idle state.
				ResetToIdleState();
			}
		}
		, 60*1000); 
}
function ExitInputMode(){
	//alert("exit");
	// Exit the "input" mode, i.e. DTMF keys should be back to normal
	
	isInputMode = false; // the app is no longer in the input mode
	
	if(parent.TelML){
		for( var i = 0; i <= 11; ++i )
		{
			var ButtonObj = TelML.Buttons.Item( i );
			// set all DTMFs to be phone keypresses
			ButtonObj.SetAutoEvent( 3, i );
		}
	}
}
function ResetToIdleState(){
	document.getElementById("CurrentSearchMode").value = "0";
	document.getElementById("SearchImage").src = search_images[0];//"images/search.gif";
	document.getElementById("pageDescription2").src = instruction_images[0];//"images/instruction1.gif";
	document.getElementById("SearchButton").value = "Search";

	document.getElementById("FilterControl").value = "";
	document.getElementById("filterDiv").innerHTML = "";
	document.getElementById("filterDiv").style.visibility = "hidden";

	ExitInputMode();
}
function DTMFPress(key){
	// This is the dial keypad key press
	// key may be 0-9 * or #
	// Need to distinguish if this is the "input char" press versus "dial digit" press
	// the global var isInputMode indicates if the app is in the input mode
	if(!isInputMode){
	    // do nothing
	    return;
	}
	
	document.getElementById("SearchImage").src = search_images[2];//"images/search-now.gif";
	document.getElementById("pageDescription2").src = instruction_images[2];//"images/instruction3.gif";
	document.getElementById("SearchButton").value = "Search Now";
	
	clearTimeout(timer); // clear the timer
	
	var input_ctrl = document.getElementById("FilterControl"); // edit box which passes entered value to the server
	var input_div = document.getElementById("filterDiv"); //a div which displays entered value next to Search button
	//document.getElementById("filterDiv").innerHTML = "Loen";
	//document.getElementById("FilterControl").value = "Loen";
	
	keyDown = true;
	if (prevKey != null && prevKey != key) { // if key is different from previous key pressed
		appendChar = true; // the character will be apended
	}
	if (keys[key].ctr > keys[key].chars.length-1 || appendChar) {
		keys[key].ctr = 0; //go back to first item in keypad
	}
	var ch = getChar(key);
	if (appendChar) { 
		//append character
		str = input_ctrl.value + ch;
		if(ch != " ")
			str_with_cursor =  input_ctrl.value + "<span style=\"text-decoration:underline\">" + ch + "</span>";
		else
			str_with_cursor =  input_ctrl.value + "_";
	}else{
		//replace character
		str = (input_ctrl.value.length==0) ? ch : input_ctrl.value.substring(0, input_ctrl.value.length-1) + ch;
		if(ch != " ")
			str_with_cursor = str.substring(0, str.length-1) + "<span style=\"text-decoration:underline\">" + ch + "</span>";
		else
			str_with_cursor = str.substring(0, str.length-1) + "_";
	}
	
	input_ctrl.value = str;
	input_div.innerHTML = str_with_cursor.replace(/ /g,"&nbsp;");
	
	keys[key].ctr++; // increase the marker for the current key
	prevKey = key; // save current key
	
	//reset flags and timer
	appendChar = false;
	poundPressed = false;
	//clearTimeout(timer);
}

function eraseChar(){
    if(!isInputMode){
	    // do nothing
	    return;
	}
	
	var input_ctrl = document.getElementById("FilterControl"); // edit box which passes entered value to the server
	var input_div = document.getElementById("filterDiv"); //a div which displays entered value next to Search button
	
	//clearTimeout(timer);
	keyDown = true;
	
	// get the last char of initial string
	var ch = input_ctrl.value.substring(input_ctrl.value.length-1,input_ctrl.value.length);
	
	// delete last character
	str = input_ctrl.value.substring(0, input_ctrl.value.length-1);
	if(ch != " "){
		ch = str.substring(str.length-1,str.length);
		str_with_cursor = (str.length==0) ? "_" : str.substring(0, str.length-1) + "<span style=\"text-decoration:underline\">" + ch + "</span>";
	}else
		str_with_cursor = (str.length==0) ? "_" : str + "_";
	input_ctrl.value = str;
	input_div.innerHTML = str_with_cursor.replace(/ /g,"&nbsp;");

	if (prevKey != null) { // if prevkey is not empty
		if(keys[prevKey])
			keys[prevKey].ctr = 0; //go back to first item in keypad
	}
	prevKey = '*'; // save current key: need this so that the next char, no matter which one, is appended.
}
function moveCursorRight(){
    if(!isInputMode){
	    // do nothing
	    return;
	}
//=== Use 0 to insert spaces, # to insert char; use ## to initiate search ========================================
	var input_ctrl = document.getElementById("FilterControl"); // edit box which passes entered value to the server
	var input_div = document.getElementById("filterDiv"); //a div which displays entered value next to Search button
	
	if(poundPressed){
		DoTheSearch();
		return;
	}
	
	input_div.innerHTML = input_ctrl.value.replace(/ /g,"&nbsp;") + "_";
	if(prevKey != null){
		if(keys[prevKey])
			keys[prevKey].ctr = 0;
	}
	
	prevKey = null; // clear prevoius key
	appendChar = true; // the next char should be appended
	poundPressed = true; // if pound is pressed for the second time, space will be added
//===============================================================================================
/*=== Use # to insert spaces; use ### to initiate search ========================================
	var input_ctrl = document.getElementById("FilterControl"); // edit box which passes entered value to the server
	var input_div = document.getElementById("filterDiv"); //a div which displays entered value next to Search button
	
	if(poundPressed){
		input_ctrl.value += " "; 
	}
	input_div.innerHTML = input_ctrl.value.replace(/ /g,"&nbsp;") + "_";
	if(prevKey != null){
		keys[prevKey].ctr = 0;
	}
	prevKey = null; // clear prevoius key
	appendChar = true; // the next char should be appended
	poundPressed = true; // if pound is pressed for the second time, space will be added
	
	var ch = input_ctrl.value.substring(input_ctrl.value.length-2,input_ctrl.value.length);
	
	if(ch == "  "){
		input_ctrl.value = input_ctrl.value.substring(0, input_ctrl.value.length-2);
		
		//__doPostBack('SCREENKEY1',''); // simulate Search button click 
		__doPostBack('SearchButton',''); // simulate Search button click 
	}
=================================================================================================*/			
}
function getChar(key){
	var ch = keys[key].chars[keys[key].ctr];
	return ch;
}


