/*===================================================================================
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 resources and controls should be present on the page:
|script src="Resources/app-datastore.js" type="text/javascript"||/script| -
			the encodeHtml() method is defined there

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:460px" /> 

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" 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>
InstructionImage - this image displays instructions image corresponding to 
					the current state of the Search button
<asp:imagebutton id="InstructionImage" 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" runat="server" text="Search" 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, char_timer; //the timers for function call delays
var timer_delay; //delay for maximum allowed idle time before resetting to idle state. Usually 60 seconds. Set to -1 to NOT deploy this timer.
var char_timer_delay = 1; //1 second delay for accepting the current char
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
var isDemoVersion = false; // this should be set to true ONLY on the DEMO page!
var span_tag_add = ""; // this is not empty ONLY on the Demo page and ONLY in Firefox!
var star_click_counter; // three consecutive *-clicks will erase the whole input string.
function addKey(num, arrChar){
	keys[num] = new Object();
	keys[num].ctr = 0;
	keys[num].chars = arrChar;
}
function EnterInputMode(add_capital_letters)
{
	// 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
	star_click_counter = 0; // no star clicks yet
	
	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']);
	}
	
	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
	StopTimer(timer);
	if(timer_delay != -1) // if the delay value is valid
		timer = setTimeout(
			function(){
				var curr_search_mode = document.getElementById("CurrentSearchMode").value;
				if(curr_search_mode == "1"){
					// Reset to idle state.
					ResetToIdleState();
				}
			}
			, timer_delay*1000);
}
function StopTimer(t){
	if(typeof(t)!="undefined")
		clearTimeout(t); // if timer was already defined before - clear it
}
function ExitInputMode(){
	// Exit the "input" mode, i.e. DTMF keys should be back to normal
	
	isInputMode = false; // the app is no longer in the input mode
	
	StopTimer(char_timer);
	star_click_counter = 0; // clear the star clicks counter
	
	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(){
	StopTimer(char_timer);
	star_click_counter = 0; // clear the star clicks counter
	
	document.getElementById("CurrentSearchMode").value = "0";
	document.getElementById("SearchImage").src = search_images[0];
	document.getElementById("InstructionImage").src = instruction_images[0];
	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){
		if(isDemoVersion){ // this should run ONLY on the DEMO page
			// Mock-up dialing the number
			TelephonyDivShow();
			TelephonyDivShowSound();
			document.getElementById("TextDisplay").innerHTML += key;
			document.getElementById("SK74").innerHTML = ""; //"Phonebook";
			document.getElementById("SK75").innerHTML = ""; //"";
			document.getElementById("SK76").innerHTML = ""; //"";
			document.getElementById("SK77").innerHTML = "Redial"; //"Redial";
			document.getElementById("SK78").innerHTML = ""; //"Music On";
			document.getElementById("SK79").innerHTML = "Hang-up"; //"Messaging";
		}
	    return;
	}
	
	StopTimer(char_timer);
	star_click_counter = 0; // clear the star clicks counter
	
	document.getElementById("SearchImage").src = search_images[2];
	document.getElementById("InstructionImage").src = instruction_images[2];
	document.getElementById("SearchButton").value = "Search Now";
	
	StopTimer(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
	
	keyDown = true;
	if (prevKey != null && prevKey != key) { // if key is different from previous key pressed
		appendChar = true; // the character will be appended
	}
	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(window.parent.isDemoVersion) // this is for Demo page and for Firefox ONLY!
		span_tag_add = (!window.parent.bOK)?"font-family:Verdana;font-weight:bold;font-size:10px;":"";
	if (appendChar) { 
		//append character
		str = input_ctrl.value + ch;
		if(ch != " ")
			str_with_cursor = encodeHtml(input_ctrl.value) + "<span style=\""+span_tag_add+"text-decoration:underline\">" + encodeHtml(ch) + "</span>";
		else
			str_with_cursor = encodeHtml(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 = encodeHtml(str.substring(0, str.length-1)) + "<span style=\""+span_tag_add+"text-decoration:underline\">" + encodeHtml(ch) + "</span>";
		else
			str_with_cursor = encodeHtml(str.substring(0, str.length-1)) + "_";
	}
	
	input_ctrl.value = str;
	input_div.innerHTML = str_with_cursor;
	
	keys[key].ctr++; // increase the marker for the current key
	prevKey = key; // save current key
	
	//reset flags and timer
	appendChar = false;
	poundPressed = false;
	
	// insert this char after a one-second delay
	char_timer = setTimeout("moveCursorRight();", char_timer_delay*1000);
}
function eraseChar(){
    if(!isInputMode){
	    // do nothing
	    return;
	}
	
	StopTimer(char_timer);
	star_click_counter++; // this is the star click
	
	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(star_click_counter == 3){
		input_ctrl.value = ""; //erase everything
		star_click_counter = 0;
	}
	
	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) ? "_" : encodeHtml(str.substring(0, str.length-1)) + "<span style=\""+span_tag_add+"text-decoration:underline\">" + encodeHtml(ch) + "</span>";
	}else
		str_with_cursor = (str.length==0) ? "_" : encodeHtml(str) + "_";
	input_ctrl.value = str;
	input_div.innerHTML = str_with_cursor;

	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;
	}
	
	StopTimer(char_timer);
	star_click_counter = 0; // clear the star clicks counter
	
//=== 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 = encodeHtml(input_ctrl.value) + "_";
	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
//===============================================================================================
}
function getChar(key){
	var ch = keys[key].chars[keys[key].ctr];
	return ch;
}