// This variable is used to store the text display div ID.
// This div displays information about all telephony events happening on the phone.
var TextDisplayID = "TextDisplay";
// This variable stores the model number so only one call is made to get it.
var ModelNumber = "";
// This variable stores whether we need to do double-clicks.
var NeedsDoubleClick = false;
// ATTENTION! the following variables do not need explicit declarations:
// var TelML, TelMLEvent; The reason is that TelML object does not exist 
// on the phone and DO exist in the Simulator app. Declaring the variables 
// overwrites the valid TelML object. Thus Telephony script would fail 
// to run in the Simulator.

function HandleTelephonyNotIdle(){
	TelephonyDivShow();
}
function HandleTelephonyIdle(){
	TelephonyDivHide();
}
//=== ParseExtension function. Parses an extension from a telephony URI, such as tel:ext=1234. =====
function ParseExtension()
{
	if(parent.TelML){
		var DirectoryNumber = TelML.Lines.Item( 0 ).GetDirectoryNumber();
		var Result = DirectoryNumber;
		var ExtFlag = "ext=";
		var ExtIndex = DirectoryNumber.indexOf( ExtFlag );
		if( ExtIndex != -1 )
			Result = DirectoryNumber.substring( ExtIndex + ExtFlag.length );
		return Result;
	}else
		return "2007";
}
//=== NATIVE TELEPHONY HANDLERS FOR PHONEBOOK APP ======================================================
// See also User_Controls/TelephonyDiv.ascx
function IsTelephonyDivVisible(){
	var tel_div = F.document.getElementById("TelephonyDiv");
	return (tel_div.style.left == "0" || tel_div.style.left == "0px");
}
var native_key_labels = ["", "", "", "", "", "", "                    "]; // this is where we accumulate the results of multiple OnButtonInformation events
var first_time;
var tel_timer=null;
var tel_timeout_ms = 100; //the timeout after which all the accumulated key labels will be oushed to the innerHTML of the corresponding elements in the TelephonyDiv "pop-up" window.
function TelephonyDivShow1(){
	// Shows the TelephonyDiv (sets its left position to 0)
	var tel_div = F.document.getElementById("TelephonyDiv");
	if(tel_div.style.left == "3000" || tel_div.style.left == "3000px" || tel_div.style.left == ""){ // "hidden"
		tel_div.style.left = "0px";
		var ButtonObj1, telSK;
		F.document.getElementById("SK74").innerHTML = "Phonebook";
		F.document.getElementById("SK75").innerHTML = "";
		F.document.getElementById("SK76").innerHTML = "";
		F.document.getElementById("SK77").innerHTML = "Redial";
		F.document.getElementById("SK78").innerHTML = "Music On";
		F.document.getElementById("SK79").innerHTML = "Messaging";
		for(var i=74; i<=79; i++){
			//ButtonObj1 = TelML.Buttons.Item( i );
			//if(ButtonObj1 != null){
			//    ButtonObj1.SetAutoEvent( 3, i );
			//    telSK = document.getElementById("SK" + i.toString());
			//    telSK.innerHTML = ButtonObj1.GetLabel();
			//    native_key_labels[i-74] = ButtonObj1.GetLabel(); // initialization
			//}
		}
	}else{
		// do nothing so that the native phone app running in the background 
		// could pick up the button press and do what it's supposed to do.
	}
}
function TelephonyDivHide(){
	// hide telephony "pop-up" window
	var tel_div = F.document.getElementById("TelephonyDiv");
	tel_div.style.left = "3000px";
	F.document.getElementById("TextDisplay").innerHTML = "";
	for(var i=74; i<=79; i++){
		//var ButtonObj2 = TelML.Buttons.Item( i );
		//if(ButtonObj2 != null)
		//	ButtonObj2.SetAutoEvent( 0, null );
	}
}
function TelephonyDivToggle(){
	document.getElementById("Lamp").style.visibility = "hidden";
	// Toggles the TelephonyDiv (sets its left position to 0 or 3000)
	var tel_div = F.document.getElementById("TelephonyDiv");
	if(tel_div.style.left == "0" || tel_div.style.left == "0px"){ 
		// hide telephony "pop-up" window
		TelephonyDivHide();
	}else{
		// show telephony "pop-up" window
		TelephonyDivShow1(); 
	}
}
function TelephonyDivOffHookToggle(){
	var phone_img = document.getElementById("P");
	phone_img.src = (phone_img.src.indexOf("Demo_Images/5340-phone.gif") != -1) ? 
		"Demo_Images/5340-phone-off.gif" : "Demo_Images/5340-phone.gif";
		
	if(simulate_answer){
		F.document.getElementById("SK74").innerHTML = ""; //"Phonebook";
		F.document.getElementById("SK75").innerHTML = ""; //"";
		F.document.getElementById("SK76").innerHTML = ""; //"";
		F.document.getElementById("SK77").innerHTML = "Trans/Conf"; //"Redial";
		F.document.getElementById("SK78").innerHTML = ""; //"Music On";
		F.document.getElementById("SK79").innerHTML = "Hang-up"; //"Messaging";
		document.getElementById("Lamp").style.visibility = "hidden";
		simulate_answer = false;
		return;
	}
	document.getElementById("Lamp").style.visibility = "hidden";
	document.getElementById("Sound").style.visibility = 
		(document.getElementById("Sound").style.visibility == "hidden" || document.getElementById("Sound").style.visibility == "")?
		"visible" : "hidden";
	
	// Synchronize with "sound"
	// Toggles the TelephonyDiv (sets its left position to 0 or 3000)
	var tel_div = document.getElementById("Sound");
	if(tel_div.style.visibility == "hidden"){ 
		// hide telephony "pop-up" window
		TelephonyDivHide();
	}else{
		// show telephony "pop-up" window
		TelephonyDivShow1(); 
	}
	
	F.document.getElementById("SK74").innerHTML = ""; //"Phonebook";
	F.document.getElementById("SK75").innerHTML = ""; //"";
	F.document.getElementById("SK76").innerHTML = ""; //"";
	F.document.getElementById("SK77").innerHTML = "Redial"; //"Redial";
	F.document.getElementById("SK78").innerHTML = ""; //"Music On";
	F.document.getElementById("SK79").innerHTML = "Hang-up"; //"Messaging";
}
function TelephonyDivShowSound(){
	document.getElementById("Sound").style.visibility = "visible";
}
function TelephonyDivShowLamp(){
	document.getElementById("Lamp").style.visibility = "visible";
}
function TelephonyDivOnHook(){
	var result = true;
	// Synchronize with "sound"
	// Toggles the TelephonyDiv (sets its left position to 0 or 3000)
	var tel_div = document.getElementById("Sound");
	if(tel_div.style.visibility == "visible"){ 
		// hide telephony "pop-up" window
		TelephonyDivHide();
		result = false;
	}else{
		// show telephony "pop-up" window
		//TelephonyDivShow1(); 
	}
	document.getElementById("Lamp").style.visibility = "hidden";
	document.getElementById("Sound").style.visibility = "hidden";
	document.getElementById("P").src = "Demo_Images/5340-phone.gif";
	
	F.document.getElementById("SK74").innerHTML = ""; //"Phonebook";
	F.document.getElementById("SK75").innerHTML = ""; //"";
	F.document.getElementById("SK76").innerHTML = ""; //"";
	F.document.getElementById("SK77").innerHTML = "Redial"; //"Redial";
	F.document.getElementById("SK78").innerHTML = ""; //"Music On";
	F.document.getElementById("SK79").innerHTML = "Hang-up"; //"Messaging";
	//alert(result);
	return result;
}
var simulate_answer = false;
function TelephonyDivIncoming(sim_answ){
	// simulate incomming call
	if(document.getElementById("P").src.indexOf("Demo_Images/5340-phone.gif")!=-1){
		simulate_answer = sim_answ;
		
		TelephonyDivShow1();
		F.document.getElementById("TextDisplay").innerHTML = "1907 NICHOLAS COHEN";
		F.document.getElementById("SK74").innerHTML = ""; //"Phonebook";
		F.document.getElementById("SK75").innerHTML = ""; //"";
		F.document.getElementById("SK76").innerHTML = ""; //"";
		F.document.getElementById("SK77").innerHTML = ""; //"Redial";
		F.document.getElementById("SK78").innerHTML = ""; //"Music On";
		F.document.getElementById("SK79").innerHTML = ""; //"Messaging";
		
		TelephonyDivShowSound();
		TelephonyDivShowLamp();
	}else{
		alert("You have to hang up first :)");
	}
}
function SubscribeToNativeTelephonyUpdates()
{
	//TelMLEvent.OnDisplayChanged = HandlePhonebookDisplayChange;
	//TelMLEvent.OnButtonInformation = UpdateNativeTelephonyKeys;		
}
function UnSubscribeToNativeTelephonyUpdates()
{
	//TelMLEvent.OnDisplayChanged = "";
	//TelMLEvent.OnButtonInformation = "";		
}
function HandlePhonebookDisplayChange()
{
	//clearTimeout(tel_timer);
	//tel_timer = null;
	//var TextToDisplay = new String( TelML.TextDisplay.Item( 0 ).substring( 0, 20 ) );
	//if( native_key_labels[6] != TextToDisplay ){
	//	native_key_labels[6] = TextToDisplay.toString();
	//	tel_timer = setTimeout("SetTelephonyKeyLabels()",tel_timeout_ms);
	//}
}
function UpdateNativeTelephonyKeys()
{
	// I am interested in the following SKs:
	// 74 = SK1 = SCREENKEY1	"SK1" is the return value of GetTelephonyKeyName()
	// 75 = SK2 = SCREENKEY12	"SCREENKEY1" is the return value of GetKeyName()
	// 76 = SK3 = SCREENKEY2	the Buttons.Item() can access the button either by index or by 
	// 77 = SK4 = SCREENKEY13	the rerurn value of GetTelephonyKeyName().
	// 78 = SK5 = SCREENKEY3	I'll use index, which works presumably faster.
	// 79 = SK6 = SCREENKEY14
	// What I need to do here is:
	// Set the auto event of these SKs to the default "Phone Keypress" - was done in TelephonyDivShow().
	// Get the labels of the SKs and put them into corresponding anchors in the TelephonyDiv
	// ButtonIndex - this is the evern parameter
	//clearTimeout(tel_timer);
	//tel_timer = null;
	//var ButtonObj3 = TelML.Buttons.Item( TelMLEvent.ButtonIndex );
	//native_key_labels[TelMLEvent.ButtonIndex - 74] = ButtonObj3.GetLabel().replace(/</,"&lt;");
	//tel_timer = setTimeout("SetTelephonyKeyLabels()",tel_timeout_ms);
}
function SetTelephonyKeyLabels()
{
	tel_timer = null;
	var DisplayObj = document.getElementById( TextDisplayID );
	DisplayObj.innerHTML = native_key_labels[6];
	for(var i=74; i<=79; i++){
		var telSK = document.getElementById( "SK" + i.toString());
		if(telSK != null)
			telSK.innerHTML = native_key_labels[i-74];
	}
	// var inner_html = document.getElementById( "TelephonyDiv" ).innerHTML; -- THIS GIVES FATAL ERROR ON THE PHONE
}
//=== Apps Link mode script. See also SetAppsLinkMode on top. =======================================
//=== TelMLEvent.OnButtonPress event handler for Apps Link mode applications only ===================
function HandleAppsLinkKeyPress()
{
	var ButtonObj4 = TelML.Buttons.Item( TelMLEvent.ButtonIndex );
	var ButtonName = ButtonObj4.GetKeyName();
	InjectClick( ButtonName );
}
//=== InjectClick function ==========================================================================
// Used for double-click simulation
var ClickTimer = null;
var ClickObjectName = "";
function InjectClick( ObjectName )
{
	if (NeedsDoubleClick)
	{
		var ObjectName2 = "";
		if (ObjectName.substr(0,9) == "SCREENKEY")
		{
			var KeyNum = parseInt(ObjectName.substr(9));
			if (KeyNum >= 1 && KeyNum <= 11)
			{
				ObjectName2 = "SCREENKEY" + (KeyNum + 11);
				if (document.getElementById(ObjectName2) == null)
					ObjectName2 = "";
			}
		}
		if (ClickTimer != null)
		{
			clearTimeout(ClickTimer);
			ClickTimer = null;
			if (ClickObjectName == ObjectName && ObjectName2 != "")
			{
				InjectSingleClick(ObjectName2);	// Do double-click action for this button and return
				return;
			}
			InjectSingleClick(ClickObjectName);	// 2 different buttons clicked fast, do 1st one 1st
		}
		if (ObjectName2 != "")
		{
			// There is a double-click action, set a timer for the single-click action and return
			ClickObjectName = ObjectName;
			ClickTimer = setTimeout('ClickTimer = null;InjectSingleClick(\'' + ObjectName + '\')', 350);
			return;
		}
	}
	InjectSingleClick(ObjectName);	// Just do it!
}
//=== InjectSingleClick function ==========================================================================
function InjectSingleClick( ObjectName )
{
	var PageObject = document.getElementById( ObjectName );
	var Result = false;
	if( PageObject ){
		var LocationPage = PageObject.href;
		if( LocationPage != "" && LocationPage != undefined )
			document.location = LocationPage;
		else
			PageObject.fireEvent( "onclick" );
		Result = true;
	}
	return Result;
}
//=== Dial function =================================================================================
function Dial( Number )
{
	for (var i = 0; i < Number.length; i++)
	{
		var digit = Number.charAt(i);
		if (digit >= '0' && digit <= '9' || digit == '*' || digit == '#')
		{
			var ButtonObj = TelML.Buttons.Item(digit);
			ButtonObj.Press();
			for (var j = 0; j < 1000; j++); // short delay
		}
		else if (digit == ',')
		{
			// 2 second pause.
			var waitUntil = (new Date()).getTime() + 2000;
			while (true)
			{
				for (var j = 0; j < 10000; j++); // delay between checking
				if ((new Date()).getTime() >= waitUntil)
					break;
			}
		}
	}
}
//=== Date and Time script ==========================================================================
var ClockInterval = 60000; // 1 minute interval
//=== Displays current date in DateDisplay div, if such a div exists on the page ====================
function displayTime()
{
	var TimerDIV = document.getElementById( "TimeDisplay" );
	var CurrentTime = new Date();
	if( TimerDIV )
	{
		var Minutes = new String( CurrentTime.getMinutes() );

		if( Minutes.length < 2 )
			Minutes = "0" + Minutes;

		TimerDIV.innerHTML =
			CurrentTime.getHours() + ":" +
			Minutes;
	}
}
//=== Displays current time in TimeDisplay div, if such a div exists on the page ====================
function displayDate()
{
	var DateDIV = document.getElementById( "DateDisplay" );
	var CurrentTime = new Date();
	var num_month = ( CurrentTime.getMonth() + 1 );
	var abbrev_month="";
	switch(num_month){
		case 1:  abbrev_month="JAN"; break;
		case 2:  abbrev_month="FEB"; break;
		case 3:  abbrev_month="MAR"; break;
		case 4:  abbrev_month="APR"; break;
		case 5:  abbrev_month="MAY"; break;
		case 6:  abbrev_month="JUN"; break;
		case 7:  abbrev_month="JUL"; break;
		case 8:  abbrev_month="AUG"; break;
		case 9:  abbrev_month="SEP"; break;
		case 10: abbrev_month="OCT"; break;
		case 11: abbrev_month="NOV"; break;
		case 12: abbrev_month="DEC"; break;
	}
	if( DateDIV )
	{
		DateDIV.innerHTML =
			CurrentTime.getDate() + "-" +
			abbrev_month + "-" +
			CurrentTime.getFullYear();
	}
}
/*=== runClock function. Displays time in TimeDisplay div. 
	Displays date in DateDisplay div. Sets the timer to 
	update those divs every ClockInterval milliseconds.
	This function should be called on every(!) page which
	has TimeDisplay and DateDisplay divs as follows.
	In GUI replacement application page:
	<body onLoad="runClock();SetGUIReplacementMode();">...</body>
	In Apps Link mode application page: 
	<body onLoad="runClock();SetAppsLinkMode();">...</body> =======================================*/
function runClock()
{
	// Initially display the time, otherwise it won't show up
	// until ClockInterval milliseconds.
	displayTime();
	displayDate();
	setInterval( 'displayTime();displayDate();', ClockInterval );
}
function SetInnerHTMLSafely(element_name, inner_html)
{
	if(document.getElementById(element_name))
		if(inner_html != "")
			document.getElementById(element_name).innerHTML = inner_html;
}


