var http_call;
var call_isWorking = false;
var callLoop = false;
var pollwindow;
var operator_id = 0;
function getHTTPObject()
{
	if (window.XMLHttpRequest)// code for Mozilla, etc.
  	{
  		xmlhttp=new XMLHttpRequest()
		exp = 'mz' ;
  	}
	else if (window.ActiveXObject)// code for IE
  	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  		exp = 'ie' ;
  	}
	return xmlhttp;
}

function appenValueInBox(textid, appendval)
{
	if(document.getElementById(textid))
	{
		curValue = document.getElementById(textid).value ;
		
		if(appendval == "back")
		{
			stt = curValue.substring(0, (curValue.length)-1) ;
			document.getElementById(textid).value = stt ;
		}
		else if(appendval == "reset")
		{
			stt = '' ;
			document.getElementById(textid).value = stt ;
		}
		else
		{
			document.getElementById(textid).value = curValue+appendval;
		}
	}
	//document.getElementById(textid).focus();
}
function endCall()
{
	document.getElementById('actionRow').style.display = '';
	document.getElementById('callboxarea').style.display = '';
	document.getElementById('digitalcallboxarea').style.display = '';
	document.getElementById('msgRow').style.display = 'none';
	document.getElementById('standByRow').style.display = 'none';
}
function open_CallBox(OperatorId)
{

	document.getElementById('iOperatorIdVerify').value =  OperatorId ;
	
	msg = "";
	
	msg += '<div class="dial-pad-popup"><div class="dialpad-heading"><a href="javascript:hidePopupBox(\'hc_popup_box\');" title="close"><img src="images/close-pop.png" style="float:right"></a>Dial Pad</div><div class="dialpad-msg">Enter your phone number and click "call"<br><br><font color="#17A40E">Example: 5552228888</font></div><div class="dial-area"><div class="textbox-of-number" id="callboxarea"><input type="text" name="phonenumber" id="phonenumber" maxlength=18 onkeydown="if(event.keyCode==13){callphone(document.getElementById(\'phonenumber\'), document.getElementById(\'iOperatorIdVerify\').value);return false;}" /></div><div class="digital-area" id="digitalcallboxarea">';
	msg += '<ul><li class="one"><a href="#" onclick="appenValueInBox(\'phonenumber\', this.innerHTML);return false;" >1</a></li><li class="two"><a href="#" onclick="appenValueInBox(\'phonenumber\', this.innerHTML);return false;">2</a></li><li class="three" ><a href="#" onclick="appenValueInBox(\'phonenumber\', this.innerHTML);return false;" >3</a></li><li class="four"><a href="#" onclick="appenValueInBox(\'phonenumber\', this.innerHTML);return false;" >4</a></li><li class="five"><a href="#" onclick="appenValueInBox(\'phonenumber\', this.innerHTML);return false;" >5</a></li><li class="six"><a href="#" onclick="appenValueInBox(\'phonenumber\', this.innerHTML);return false;" >6</a></li><li class="seven"><a href="#" onclick="appenValueInBox(\'phonenumber\', this.innerHTML);return false;" >7</a></li><li class="eight"><a href="#" onclick="appenValueInBox(\'phonenumber\', this.innerHTML);return false;" >8</a></li><li class="nine"><a href="#" onclick="appenValueInBox(\'phonenumber\', this.innerHTML);return false;">9</a></li><li class="star"><a href="#" onclick="appenValueInBox(\'phonenumber\', \'*\');return false;" >star</a></li><li class="zero"><a href="#" onclick="appenValueInBox(\'phonenumber\', \'0\');return false;" >zero</a></li><li class="hash"><a href="#" onclick="appenValueInBox(\'phonenumber\', \'#\');return false;" >hash</a></li></ul>';
	msg += '</div><div class="button-area" id="actionRow"><input type="reset" class="btn-reset-dial-pad" value="" onclick="appenValueInBox(\'phonenumber\', \'reset\');return false;" /><input type="button" class="btn-call" value="" onclick="callphone(document.getElementById(\'phonenumber\'), document.getElementById(\'iOperatorIdVerify\').value);return false;" /><input type="button" class="btn-back-dial-pad" value="" onclick="appenValueInBox(\'phonenumber\', \'back\');return false;" /></div>';
	msg += '<div id="msgRow" style="display:none;padding:125px 0 10px 0;"></div>';
	msg += '<div id="standByRow" style="margin-top:45px;margin-bottom:70px;display:none;"><input type="image" src="images/btn-close-box.png" onclick="hidePopupBox(\'hc_popup_box\');return false;" /></div>';
	msg += '</div></div>';

	title = "Alert";
	showdeadcenterdiv(338, 350, 'hc_popup_box', title, msg); 
}

function callphone(phone_obj, operatorid)
{
	phone_obj.value = Trim(phone_obj.value) ;
	if(phone_obj.value == '')
	{
		alert('Enter Phone number');
		phone_obj.focus();
		return false;
	}
	if(phone_obj.value.length < 10)
	{
		alert('Please Enter Minimum 10 digits for Valid Phone Number');
		return false;
	}
	if(operatorid == '')
	{
		alert('Please Select Operator') ;
		return false ;
	}
	
	document.getElementById('callNo').value = phone_obj.value ;
	
	var url = site_url+"ajax_twilio.php?call_method=CallPhone&phone_number="+phone_obj.value+"&iOperatorId="+operatorid ;
	operator_id = operatorid;
	//alert(url);
	//return false;
	//alert(call_isWorking);
	
	if(!call_isWorking)
	{
		callLoop = false; // do not continue running call status
		http_call = getHTTPObject();
		call_isWorking = true;
		http_call.onreadystatechange=handleHttpResponse_callPhone;
  		http_call.open("GET", url, true);
		//http_call.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset= UTF-8");
	  	http_call.send(null);
	}
}
function handleHttpResponse_callPhone()
{
	if (http_call.readyState == 4)
	{
		call_isWorking = false;
		if (http_call.responseText.indexOf('invalid') == -1) 
		{
			//alert(http_call.responseText);
			var xmlDocument = http_call.responseXML;
			var iserror = xmlDocument.getElementsByTagName('iserror').item(0).firstChild.data;
			var latestbalance = xmlDocument.getElementsByTagName('latestbalance').item(0).firstChild.data;

			if(document.getElementById('webTopBalance'))
			{
				document.getElementById('webTopBalance').innerHTML = latestbalance;
			}

			if(iserror > 0)
			{
				errormsg = xmlDocument.getElementsByTagName('errormsg').item(0).firstChild.data;
				errorcode = xmlDocument.getElementsByTagName('errorcode').item(0).firstChild.data;
			}
			else
			{
				v_sid = xmlDocument.getElementsByTagName('sid').item(0).firstChild.data;
				v_phonenumber = xmlDocument.getElementsByTagName('phonenumber').item(0).firstChild.data;
				v_callafterseconds = xmlDocument.getElementsByTagName('callafterseconds').item(0).firstChild.data;
			}

			if(iserror > 0)
			{
				msgtext = errormsg;
				testfun(); // start continue running call status again
			}
			else
			{
				msgtext = 	'<table width="100%" cellspacing="1" cellpadding="1"><tr><td align="center" ><b>Connecting to you on '+v_phonenumber+' </b></td></tr><tr><td align="center" >&nbsp;</td></tr></table>';
				//alert(v_callafterseconds);
				// If button of operator is avaliable, make change of state.
				if(document.getElementById('action_'+operator_id))
					document.getElementById('action_'+operator_id).innerHTML = '<a href="#"><img src="'+website_image_url+'btn-on-a-call.png" name="btnonacall" value="On A Call!" onclick="return false;"  /></a>';
				setTimeout("isCallConnected('"+v_sid+"');", 1000*(parseInt(v_callafterseconds)+2)) ;
			}
			
			if(iserror > 0 && errorcode == 1)
			{
				// Check Opening of Pop Up For Deposit Process.
				//url = site_url+'customer-deposit.html';
				//pollwinnew(url, 650, 450);setTimeout("hidePopupBox('hc_popup_box');", 5000) ;
				
				url = main_site_url+'customer-payment-transaction-deposit-money.html';
				//alert(url);
				setTimeout("hidePopupBox('hc_popup_box');", 3000) ;
				setTimeout("window.location='"+url+"'", 3010) ;
			}
			else
			{
				setTimeout("hidePopupBox('hc_popup_box');", 10000) ;
			}
			//msgtext = 	'<table width="100%" cellspacing="1" cellpadding="1"><tr><td align="center" >MyPhoneSite got Call SID : <b>'+sid+'</b></td></tr><tr><td align="center" >&nbsp;</td></tr></table>';
			msg = "";
			
			msg += '<div class="dial-pad-popup"><div class="dialpad-heading"><a href="javascript:hidePopupBox(\'hc_popup_box\');" title="close"><img src="images/close-pop.png" style="float:right"></a>Alert</div>';
			msg += '<div style="padding:125px 0 10px 0;" id="msgRow" ><b>'+msgtext+'</b></div>';
			msg += '<div  style="margin-top:45px;margin-bottom:70px;" id="standByRow" ><input type="image" src="images/btn-close-box.png"  value="Close Box" onclick="hidePopupBox(\'hc_popup_box\');return false;" /></div>';
			msg += '</div>';

			title = "Alert";
			showdeadcenterdiv(338, 350, 'hc_popup_box', title, msg); // Below was original.
			
		}
	}
	else
	{
		document.getElementById('actionRow').style.display = 'none';
		document.getElementById('callboxarea').style.display = 'none';
		document.getElementById('digitalcallboxarea').style.display = 'none';
		document.getElementById('msgRow').style.display = '';
		document.getElementById('standByRow').style.display = '';
		document.getElementById('msgRow').innerHTML = '<b>Verifying...</b><br><br><img src="'+site_url+'images/dial_msg_loading.gif">' ;
	}
}
/* CALL PROCESS ENDS   */

function isCallConnected(sid)
{
	//alert(sid);
	
	var url = site_url+"ajax_twilio.php?call_method=CheckCall&sid="+sid ;
	
	//alert(url);
	//return false;
	//alert(call_isWorking);
	
	if(!call_isWorking)
	{
		http_call = getHTTPObject();
		call_isWorking = true;
		http_call.onreadystatechange=handleHttpResponse_checkCall;
  		http_call.open("GET", url, true);
		//http_call.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset= UTF-8");
	  	http_call.send(null);
	}
}
function handleHttpResponse_checkCall()
{
	if (http_call.readyState == 4)
	{
		call_isWorking = false;
		if (http_call.responseText.indexOf('invalid') == -1) 
		{
			//alert(http_call.responseText);
			var xmlDocument = http_call.responseXML;
			try
			{
				var iserror = xmlDocument.getElementsByTagName('iserror').item(0).firstChild.data;
				
				var latestbalance = xmlDocument.getElementsByTagName('latestbalance').item(0).firstChild.data;
				var callcontinue = xmlDocument.getElementsByTagName('callcontinue').item(0).firstChild.data;
				var callid = xmlDocument.getElementsByTagName('callid').item(0).firstChild.data;
				//alert(latestbalance) ;
				if(document.getElementById('webTopBalance'))
				{
					document.getElementById('webTopBalance').innerHTML = latestbalance;
				}
				
				if(callcontinue > 0)
				{
					var currentcharges = xmlDocument.getElementsByTagName('currentcharges').item(0).firstChild.data;
					var timestring = xmlDocument.getElementsByTagName('timestring').item(0).firstChild.data;

					if(document.getElementById('runningCallDetails'))
					{
						document.getElementById('runningCallDetails').innerHTML = 'Call :: Amount: '+currentcharges+'&nbsp;&nbsp;Duration: '+timestring+'<br><br>';
					}
				}
				else
				{
					if(document.getElementById('runningCallDetails'))
					{
						document.getElementById('runningCallDetails').innerHTML = '';
					}
				}

				if(iserror > 0)
				{
					errormsg = xmlDocument.getElementsByTagName('errormsg').item(0).firstChild.data;
					errorcode = xmlDocument.getElementsByTagName('errorcode').item(0).firstChild.data;
				}
				else
				{
					v_sid = xmlDocument.getElementsByTagName('sid').item(0).firstChild.data;
				}
				
				if(iserror > 0)
				{
					msgtext = errormsg;
					
					if(errorcode == 1)
					{
						// Open Pop Up For Deposit Process.
						
						url = main_site_url+'customer-deposit-cc.html';
						pollwinnew(url, 650, 450);

					}
					else if(errorcode == 2)
					{
						// If we want anything done when call is forcefully hanged up.
					}
				}
				
				if(iserror == 0 || (iserror > 0 && (errorcode == 1) )) //If Call is not hanged up or ended than call twilio again.
				{
					v_callafterseconds = xmlDocument.getElementsByTagName('callafterseconds').item(0).firstChild.data;

					setTimeout("isCallConnected('"+v_sid+"');", 1000*parseInt(v_callafterseconds)) ;
				}
				
				if(iserror > 0)
				{

					setTimeout("hidePopupBox('hc_popup_box');", 5000) ;
					//msgtext = 	'<table width="100%" cellspacing="1" cellpadding="1"><tr><td align="center" >MyPhoneSite got Call SID : <b>'+sid+'</b></td></tr><tr><td align="center" >&nbsp;</td></tr></table>';
					msg = "";
				
					msg += '<div class="dial-pad-popup"><div class="dialpad-heading"><a href="javascript:hidePopupBox(\'hc_popup_box\');" title="close"><img src="images/close-pop.png" style="float:right"></a>Alert</div>';
					msg += '<div style="padding:125px 0 10px 0;" id="msgRow" ><b>'+msgtext+'</b></div>';
					
					// Call is ended than open feed back link...
					if(errorcode == 5 || errorcode == 6) 
					{
						msg += '<div  style="margin-top:25px;margin-bottom:30px;"  >Click <a href="'+main_site_url+'customer-call-history.html/'+callid+'" >Here</a> to give feedback for this call.</div>';
					}
					
					msg += '<div  style="margin-top:45px;margin-bottom:70px;" id="standByRow" ><input type="image" src="images/btn-close-box.png"  value="Close Box" onclick="hidePopupBox(\'hc_popup_box\');return false;" /></div>';
					msg += '</div>';

					title = "Alert";
					showdeadcenterdiv(338, 350, 'hc_popup_box', title, msg); // Below was original.
					
					if(errorcode != 1)
					{
						testfun(); // start continue running call status again
					}
				}
			}
			catch (e)
			{
				
			}
			
		}
	}
	else
	{
		/*document.getElementById('actionRow').style.display = 'none';
		document.getElementById('callboxarea').style.display = 'none';
		document.getElementById('digitalcallboxarea').style.display = 'none';
		document.getElementById('msgRow').style.display = '';
		document.getElementById('standByRow').style.display = '';
		document.getElementById('msgRow').innerHTML = '<b>Verifying...</b><br><br><img src="'+site_url+'images/dial_msg_loading.gif">' ;*/
	}
}

function showdeadcenterdiv(Xwidth,Yheight,divid, divtitle, divdata) { 
	// First, determine how much the visitor has scrolled 
	var scrolledX, scrolledY, pageHeight; 
	if( self.pageYoffset ) { 
		scrolledX = self.pageXoffset; 
		scrolledY = self.pageYoffset; 
		pageHeight = self.pageYoffset; 
	} else if( document.documentElement && document.documentElement.scrollTop ) { 
		scrolledX = document.documentElement.scrollLeft; 
		scrolledY = document.documentElement.scrollTop; 
		pageHeight = document.body.offsetHeight;
	} else if( document.body ) { 

		scrolledX = document.body.scrollLeft; 
		scrolledY = document.body.scrollTop; 
		pageHeight = document.body.offsetHeight;
	} 

// Next, determine the coordinates of the center of browser's window 
	
	var centerX, centerY; 
	if( self.innerHeight ) { 
		centerX = self.innerWidth; 
		centerY = self.innerHeight; 
	} else if( document.documentElement && document.documentElement.clientHeight ) { 
		centerX = document.documentElement.clientWidth; 
		centerY = document.documentElement.clientHeight; 
	} else if( document.body ) { 
		centerX = document.body.clientWidth; 
		centerY = document.body.clientHeight; 
	} 

	// Xwidth is the width of the div, Yheight is the height of the 
	// div passed as arguments to the function: 
	var leftoffset = scrolledX + (centerX - Xwidth) / 2; 
	var topoffset = scrolledY + (centerY - Yheight) / 2; 
	// The initial width and height of the div can be set in the 
	// style sheet with display:none; divid is passed as an argument to // the function 
	var o=document.getElementById(divid); 
	var r=o.style; 
	r.position='absolute'; 
	r.top = topoffset + 'px'; 
	r.left = leftoffset + 'px'; 
	r.display = "block"; 
	
	var opar = document.getElementById(divid+'_parent');
	if(opar){
		opar.style.width = centerX+'px';
		opar.style.height = pageHeight+'px';
		opar.style.display = "block"; 
	}

	//divtitle = '<div class="popup-title">'+divtitle+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#"  title="Close" onclick="hidePopupBox(\'hc_popup_box\');" >Close</a></div>' ;
	//alert(divtitle) ;
	//divdata = divtitle + divdata ;
	//alert(divdata) ;
	document.getElementById(divid).innerHTML = divdata;
} 

function hidePopupBox(divObj)
{
	if(document.getElementById(divObj))
		document.getElementById(divObj).style.display='none';
	if(document.getElementById(divObj+"_parent"))
		document.getElementById(divObj+"_parent").style.display='none';
}
function Trim(s) 
{
  // Remove leading spaces and carriage returns

  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns

  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function pollwinnew(url,w, h)
{
	if(typeof(pollwindow)=="undefined")
	{
	pollwindow=window.open(url,'pollwindowdeposit','top=0,left=0,status=no,toolbars=no,scrollbars=yes,width='+w+',height='+h+',maximize=no,resizable');
	}
	try{
		pollwindow.focus();
	}catch(e)
	{
		pollwindow=window.open(url,'pollwindowdeposit','top=0,left=0,status=no,toolbars=no,scrollbars=yes,width='+w+',height='+h+',maximize=no,resizable');
		pollwindow.focus();
	}
}

function continueCallTest()
{//alert(callLoop)
	if(callLoop){
		isCallConnected('');
		setTimeout("continueCallTest();", 1000*60) ; // Call after 1 minute
	}
}

function testfun()
{
	//alert('in here');
	callLoop = true;
	continueCallTest();
}
document.onload = testfun();
