var AFL = Object();
var callername = 'webuser';
var callerid='';
var exten = '';
//var webapp = 'http://192.168.2.1/afl/virtu/';


var loadingTimeoutID = null;
var firstLoaded=0;
var debugText = ' .... ';
var browser = navigator.userAgent.toLowerCase();
var isSafari = (browser.indexOf("safari") > -1);
var isIE = (navigator.appName == "Microsoft Internet Explorer");
var isNS = (navigator.appName == "Netscape");

var isRinging = false;
var isAnswered = false;
var statusTimer = null;




AFL.Params = new Object();

AFL.initialise = function(debug, dialno, callername, callerid, domain, webapp)
{
	//if (isIE)
    //	document.writeln ('<bgsound id="btn_sound" loop=1 src="#">');
	//else if (isNS)
   	//	document.writeln ('<embed type="audio/x-wav" name="btn_sound" id="btn_sound" src="#" loop="false" autostart="false" hidden="true">');

	AFL.Params = {	'image_dir' : '/assets/images/voip/',
					'btnDial'	: $('VoipBtnDial'),
					'btnHangUp'	: $('VoipBtnHangUp'),
					'cnctStatus': $('VoipConnectionStatus'),
					'btn1'		: $('BtnDialPad1'),
					'btn2'		: $('BtnDialPad2'),
					'btn3'		: $('BtnDialPad3'),
					'btn4'		: $('BtnDialPad4'),
					'btn5'		: $('BtnDialPad5'),
					'btn6'		: $('BtnDialPad6'),
					'btn7'		: $('BtnDialPad7'),
					'btn8'		: $('BtnDialPad8'),
					'btn9'		: $('BtnDialPad9'),
					'btn0'		: $('BtnDialPad0'),
					'btnStar'	: $('BtnDialPadStar'),
					'btnHash'	: $('BtnDialPadHash'),
					'debugText'	: $('debugText')
					//'btn_sound' : $('btn_sound')
					};
	AFL.Params.debugLevel = debug;
	AFL.LogVoipClick(1);
	makeApplet(debug, dialno, callername, callerid, domain, webapp);
}

AFL.playsound = function(sourcefile)
{
    AFL.Params.btn_sound.src = sourcefile;
}

AFL.LogVoipClick = function(click)
{
    var getObj = {
		url: '/ajax/voip/',
		clickType: click,
		onLoading: function( obj ){},
		onSuccess: function( obj ){}
	};

	advAJAX.get( getObj );
}
AFL.btnDial_onclick = function()
{
	AFL.Params.btnDial.src= AFL.Params.image_dir + 'call-now-clicked.gif';
	dial();
}
AFL.btnHangUp_onclick = function()
{
	AFL.Params.btnHangUp.src = AFL.Params.image_dir + 'hang-up-clicked.gif';
	AFL.btnDial_offclick();
	hangup();
	return true;
}
AFL.btnHangUp_offclick = function()
{
	AFL.Params.btnHangUp.src = AFL.Params.image_dir + 'hang-up.gif';
}
AFL.btnDial_offclick = function()
{
	AFL.Params.btnDial.src = AFL.Params.image_dir + 'call-now.gif';
}
AFL.statusConnected = function()
{
	AFL.Params.cnctStatus.src = AFL.Params.image_dir + 'connected.gif';
}
AFL.statusDisconnected = function()
{
	AFL.Params.cnctStatus.src = AFL.Params.image_dir + 'disconnected.gif';
}
AFL.mapBtn = function(d)
{
	var aBtn = new Object();
	switch (d) {
		case 1:	aBtn.element = AFL.Params.btn1; aBtn.name = 'one'; break;
		case 2:	aBtn.element = AFL.Params.btn2; aBtn.name = 'two'; break;
		case 3:	aBtn.element = AFL.Params.btn3; aBtn.name = 'three'; break;
		case 4:	aBtn.element = AFL.Params.btn4; aBtn.name = 'four'; break;
		case 5:	aBtn.element = AFL.Params.btn5; aBtn.name = 'five'; break;
		case 6:	aBtn.element = AFL.Params.btn6; aBtn.name = 'six'; break;
		case 7:	aBtn.element = AFL.Params.btn7; aBtn.name = 'seven'; break;
		case 8:	aBtn.element = AFL.Params.btn8; aBtn.name = 'eight'; break;
		case 9:	aBtn.element = AFL.Params.btn9; aBtn.name = 'nine'; break;
		case 0:	aBtn.element = AFL.Params.btn0; aBtn.name = 'zero'; break;
		case '*':	aBtn.element = AFL.Params.btnStar; aBtn.name = 'star'; break;
		case '#':	aBtn.element = AFL.Params.btnHash; aBtn.name = 'hash'; break;
	}
	return aBtn;
}

AFL.keyPad_onclick = function(d)
{
	var aBtn = AFL.mapBtn(d);
	aBtn.element.src = AFL.Params.image_dir + aBtn.name +'-clicked.jpg';
	//AFL.playsound('/assets/sounds/callnow.wav');
	dtmf(d);
}
AFL.keyPad_offclick = function(d)
{
	var aBtn = AFL.mapBtn(d);
	aBtn.element.src = AFL.Params.image_dir + aBtn.name +'.gif';
}
AFL.displayDebugText = function(dText)
{
	if(AFL.Params.debugLevel)
		AFL.Params.debugText.innerHTML = dText;
}



function initVars(){}

function pageLoaded(evt)
{

	AFL.displayDebugText("PageLoaded");
  	pushtofront();
  	if (firstLoaded == 0)
  	{
    	window.onunload=hangup;
  	}

  	// in case the script doesn't make it to 'ringing' in
  	// 20 sec (= 20000 msec)
    var msec = 20 * 1000;
    loadingTimeoutID = window.setInterval(loadingFailed, msec);
    statusTimer = window.setInterval(phoneStatusPoll, 1000);
}

function dial()
{
	AFL.displayDebugText("dialing...");
	var phone = getPhoneFromHere();
	if (phone)
	{
		phone.dial(exten);
	}
	AFL.LogVoipClick(2);
/*
	statusjson = phone.getCallStatus();
	phoneStatus = eval("(" + statusjson + ")");
	var x = '';
	for(var i in phoneStatus)
		x += "\n" + i + ':'+phoneStatus[i];
	alert(x);
*/

}

function dtmf(d)
{
	AFL.displayDebugText("dtmf - "+d);

	var phone = getPhoneFromHere();
	if (phone)
	{
		phone.sendDTMF(d);
	}
}

function phoneStatusPoll()
{
	var phone = getPhoneFromHere();

	if (phone)
	{
		statusjson = phone.getCallStatus();
		phoneStatus = eval("(" + statusjson + ")");

		phoneStatus.status="Loaded....";

		window.clearInterval(loadingTimeoutID);
		loadingTimeoutID = null;

	  	// peer should be set up straight away, unless error
		if (phoneStatus.peer == true)
		{
		  // applet uses autostart, so call should happen soon
		  if (phoneStatus.call == true)
		  {
		      if (phoneStatus.ringing == true)
		      {
		          ringing();
		      }
		      else if (phoneStatus.answered == true)
		      {
		          answered();
		      }
		  }
		  else
		  {
		      hungUp();
		  }
		}
		else
		{
	      AFL.displayDebugText('Ohh we got some serious problems people.')
	    }
	}
	else
	{
		phoneStatus = new Object();
		phoneStatus.status="Loading....";
	}


}

function phonefromherestatus(what, error, statusjson)
{
	phoneErrormess = error;
	phoneStatus = eval("(" + statusjson + ")");

	if (what == 1)
		hungUp();
	else if (what == 2)
		answered();
	else if (what == 3)
		if (phoneStatus.ringing == true)
			ringing();
		else
			isRinging = false;

	AFL.displayDebugText(debugText);
}

function phonefromhereGotDtmf(digit) { }
function phonefromhereGotText(text) { }

function ringing()
{
	if (isRinging == false)
	{
		isRinging = true;
		connectedSomehow(": ringing", "Ringing ...");
	}
	AFL.displayDebugText('Ringing....');
}

function answered()
{
      // alert('answered');
	if (isAnswered == false)
	{
		isAnswered = true;
		connectedSomehow('Unexpectantly answered');
		AFL.statusConnected();
		AFL.LogVoipClick(3);
	}
	else
	{
		AFL.displayDebugText('Answered');
	}
}

function hangup(evt)
{
	AFL.displayDebugText('Hanging up....');
	var phone = getPhoneFromHere();
	if (phone)
	{
		phone.hangup();
		AFL.statusDisconnected();
		AFL.displayDebugText('Phone hung up');
	}
}

function hungUp(causecode)
{
	disconnectedSomehow("Unexpected hang up");
	AFL.statusDisconnected();
}


 function loadingFailed()
{
	AFL.displayDebugText("loadingFailed!");

	window.clearInterval(loadingTimeoutID);
	loadingTimeoutID = null;
}

function leavingPage(evt)
{
	var retval;
	retval = "If you leave this page, you call will be disconnected.";
	return retval;
}

function connectedSomehow(addToDebug)
{
	// sometimes ringing, answered are skipped,
	//this is called by both ringing and answered.
	AFL.displayDebugText(addToDebug);
}

function disconnectedSomehow(addToDebug)
{
	 if (isAnswered == true || isRinging == true)
	 {
	     isAnswered = false;
	     isRinging = false;

	     var w = window.top;
	     window.onbeforeunload=null;
	     window.onunload=null;

     }
     AFL.displayDebugText(addToDebug);
}
function pushtofront()
{
	var w = window.top;
	if(w)
	{
		w.focus();
	}
	else
	{
		window.focus();
	}
}

function pushtoback()
{
	// printWindowSize();
	var w = window.top;
	if (w)
		w.blur();
	else
		window.blur();
}


function printEvent(evt)
{
	if (!evt)
		evt = window.event;
	if (evt)
		alert(evt.type);
}

// NAME
//      $RCSfile: makeApplet.js,v $
// DESCRIPTION
//
//      To use the object include the js in the HTML header:
//        <script src="script/makeApplet.js" type="text/javascript"></script>
//
//      And call the function from the HTML body (I recommend making it the last
//      before closing the body):
//        <script type="text/javascript">makeApplet();</script>
//
// DELTA
//      $Revision: 1.1 $
// CREATED
//      $Date: 2008/01/16 13:12:44 $
// AUTHOR
//      Ray Tran <birgit@westhawk.co.uk>
// COPYRIGHT
//      Westhawk Ltd
// TO DO
//

function makeApplet(debug, dialno, callername, callerid, domain, webapp)
{
	exten = dialno;
	AFL.displayDebugText('Initialising: ' +callername + ', '  + dialno);
	var archive = domain + '/assets/java/pfh.jar'
	var authuri = domain + '/' + webapp + '/auth.php';

  document.write('<applet');
  document.write('   code="com.phonefromhere.softphone.Phonefromhere"');
  document.write('   archive="' + archive + '" ');
  document.write('   id="phonefromhere" ');
  document.write('   name="phonefromhere" ');
  document.write('   height="1"');
  document.write('   width="1"');
  document.write('   hspace="0"');
  document.write('   vspace="0"');
  document.write('   align="middle"');
  document.write('   mayscript="true" >');
  document.write('      <param name="debug" value="' + debug + '"/>');
  document.write('      <param name="authuri" value="' + authuri + '"/>');
  document.write('      <param name="dialno" value ="' + dialno + '"/>');
  document.write('      <param name="autostart" value ="false"/>');
  document.write('      <param name="callerid" value ="' + callerid + '"/>');
  document.write('      <param name="callername" value ="' + callername + '"/>');
  document.write('      <param name="statusCallback" value="phonefromherestatus"/>');
  document.write('      <param name="dtmfCallback" value="phonefromhereGotDtmf"/>');
  document.write('      <param name="textCallback" value="phonefromhereGotText"/>');
  document.write('      <param name="doEncryption" value="true"/>');
  document.write('      <param name="doEC" value="true"/>');
  document.write('      <param name="technology" value="com.phonefromhere.softphone.iax.DigiumPhone"/>');
  document.write('      <param name="mayscript"/>');
  document.write('  </applet>');
}


//Helper methods
function getPhoneFromHere(){
  var phone = document.getElementById('phonefromhere');
  return phone;
}
