// the base url
var c2call_testrun = 0;
var c2call_url_base = 'http://www.vbill.com.au';
//var c2call_url_base = 'http://192.168.0.20:4025';
var local_url = 'c2call/c2call.aspx';
var c2call_already_done_call_me = false;
var c2call_email = "";
var c2call_sp_email = "";
var c2call_bar_mobile = "";
var c2call_bar_int = "";


function c2call_createRequestObject() { 
   var req; 
   if(window.XMLHttpRequest){ 
      // Firefox, Safari, Opera... 
      req = new XMLHttpRequest(); 
   } else if(window.ActiveXObject) { 
      // Internet Explorer 5+ 
      req = new ActiveXObject("Microsoft.XMLHTTP"); 
   } else { 
      // There is an error creating the object, 
      // just as an old browser is being used. 
      alert('Problem creating the XMLHttpRequest object'); 
   } 
   return req; 
}

// Make the XMLHttpRequest object 
var c2call_http = c2call_createRequestObject(); 
var g_csid = '';
function c2call_runAction(csid){
	// get the details for this service
	var c2call_url_path = '/click2call/get_details.php';
	g_csid = csid;
	var params = 'test=' + c2call_testrun + '&url_base=' + c2call_url_base + '&url_path=' + c2call_url_path + '&csid=' + csid;
	c2call_http.open("POST", local_url, true);
	if(c2call_testrun){
	  alert(params);
	}
	//Send the proper header information along with the request
	c2call_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	c2call_http.setRequestHeader("Content-length", params.length);
	c2call_http.setRequestHeader("Connection", "close");
	c2call_http.onreadystatechange = c2call_handleRunAction;
	c2call_http.send(params);
	return false;
}

function c2call_handleRunAction(){
	if (c2call_http.readyState == 4) {
		// Split the comma delimited response into an array
		var c2call_res = c2call_http.responseText.split(",");
		if(c2call_testrun){
			alert(c2call_res);
		}
		// check if we found the service detail
		if(c2call_res[0] == 0){
			document.getElementById('c2call_callMeSubmit').value = 'Invalid Account';
			document.getElementById('c2call_numtocall').disabled = true;
			document.getElementById('c2call_savenum').disabled = true;
		}else{
		//	timeStatus
			if(c2call_res[1] == 'ok'){
				c2call_showCookieDetail();
			}else{
			  //alert("stuf");
				document.getElementById('c2call_callMeSubmit').value = c2call_res[1];
				document.getElementById('c2call_numtocall').disabled = true;
				document.getElementById('c2call_savenum').disabled = true;
			}
			// set the vars
			//c2call_ext_num = c2call_res[2];
			c2call_email = c2call_res[3];
			c2call_sp_email = c2call_res[4];
			c2call_bar_mobile = c2call_res[5];
			c2call_bar_int = c2call_res[6];
		}
	}
}

function c2call_callMeNow(){
  //alert("doing call me now");
	var c2call_pageUrl = location.href;
	var c2call_numtocall = document.getElementById('c2call_numtocall').value;
  var c2call_savenum = 'n';
	var c2call_callStart = new Date()
	

	if(document.getElementById('c2call_savenum').checked){
		c2call_createCookie('c2call_callMeCookie',c2call_numtocall,30);
	}else{
		c2call_eraseCookie('c2call_callMeCookie');
	}
	var c2call_url_path = '/click2call/dial_go.php';
	//var params = 'test=' + c2call_testrun + '&url_base=' + c2call_url_base + '&url_path=' + c2call_url_path + '&date=' + Date() + '&ext=' + c2call_ext_num + '&email=' + c2call_email + '&sp_email=' + c2call_sp_email + '&csnum=' + c2call_numtocall + '&callStart=' + c2call_callStart.getTime() + '&pageUrl=' + c2call_pageUrl + '&csid=' + g_csid;
	var params = 'test=' + c2call_testrun + '&url_base=' + c2call_url_base + '&url_path=' + c2call_url_path + '&date=' + Date() + '&email=' + c2call_email + '&sp_email=' + c2call_sp_email + '&csnum=' + c2call_numtocall + '&callStart=' + c2call_callStart.getTime() + '&pageUrl=' + c2call_pageUrl + '&csid=' + g_csid;
	c2call_http.open("POST", local_url, true);
	c2call_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	c2call_http.setRequestHeader("Content-length", params.length);
	c2call_http.setRequestHeader("Connection", "close");
	c2call_http.onreadystatechange = c2call_handleHttpResponse;
	c2call_http.send(params);
	document.getElementById('c2call_callMeSubmit').disabled = true;
	document.getElementById('c2call_callMeSubmit').value = 'Initiating ...';
	return false;
}

function c2call_handleHttpResponse() {
	if (c2call_http.readyState == 4 && c2call_http.status == 200 && c2call_already_done_call_me == false) {
    c2call_already_done_call_me = true;
		var results = c2call_http.responseText.split(",");
    //	echo $code.','.$message.','.$unique_id.','.$callStart.','.$error;
		if(c2call_testrun){
			alert(results);
		}
		if(results && results[1] != 'DENIED'){
      //alert("results[2]" +results[2] + ", results[3]" + results[3]); 
      //alert("running create timer");
			c2call_createTimer(results[2],results[3]);
		}else{
			document.getElementById('c2call_callMeSubmit').value = 'Access Denied - Invalid A Number';
		}
		if(results[0] == '3' || results[0] == '4'){
		  document.getElementById('c2call_callMeSubmit').value = 'Access Denied - Too many attempts';
		}
	}
}

function getSipStatus(sipID,keyStr,c2call_callStart) {
  //alert("getSipStatus: " + sipID + " " + keyStr + " " + c2call_callStart);
	var keyStr = keyStr;
	var c2call_url_path = '/click2call/dial_status.php';
	var params = 'test=' + c2call_testrun + '&url_base=' + c2call_url_base + '&url_path=' + c2call_url_path + '&keyStr=' + keyStr + '&sipID=' + sipID + '&callStart=' + c2call_callStart;
	c2call_http.open("POST", local_url, true);
	//Send the proper header information along with the request
	c2call_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	c2call_http.setRequestHeader("Content-length", params.length);
	c2call_http.setRequestHeader("Connection", "close");
	c2call_http.onreadystatechange = c2call_handleGetSipStatusResponse;
	c2call_http.send(params);
}

function c2call_handleGetSipStatusResponse() {
	if (c2call_http.readyState == 4) {
		// Split the comma delimited response into an array
		var res = c2call_http.responseText.split(",");
		//var results = c2call_http.responseText;
		if(c2call_testrun){
			alert(res);
		}
		var timeNow = new Date();
		var difference = (timeNow.getTime() - res[4]) / 1000;

    //echo $keyStr.','.$code.','.$message.','.$unique_id.','.$callStart.','.$error;
    //        0             1           2               3
    
		if(res[2] == 'START'){
			document.getElementById('c2call_callMeSubmit').value = 'Calling ...';
			// if this has been running for 50 sec cancel it
			if(difference > 55){
				document.getElementById('c2call_callMeSubmit').value = 'No operator available ...';
				c2call_clockStop();
			}
		}
		if(res[2] == 'MIDDLE'){
			document.getElementById('c2call_callMeSubmit').value = 'Connected ...';
		}
		if(res[2] == 'END'){
			document.getElementById('c2call_callMeSubmit').value = 'Hung Up';
			c2call_clockStop();
      c2call_already_done_call_me = false;
			setTimeout("location.reload()",3000);
		}
	}
}

function c2call_numbersonly(e,obj){
	var unicode = e.charCode? e.charCode : e.keyCode
	var special = false;
	if (unicode != 8){ //if the key isn't the backspace key (which we should allow)
		if (unicode < 48 || unicode > 57) //if not a number
		return false //disable key press
	}else{
		c2call_disableSubmit();
	}
  
	// if international isn't barred
	if(c2call_bar_int == 'n'){
	  
	  // single number section
  	  if(obj.value.length == 1 && obj.value.substring(0,1) == '8' && unicode != 8){
      	special = true;
      }
      // part 1 uk
      if(obj.value.length == 1 && obj.value.substring(0,1) == '4' && unicode != 8){
      	special = true;
      }
      // usa
  	  if(obj.value.length == 1 && obj.value.substring(0,2) == '1' && unicode != 8){
      	special = true;
      }
      // part 1 france
      if(obj.value.length == 1 && obj.value.substring(0,2) == '3' && unicode != 8){
      	special = true;
      }
      // part 1 nz
      if(obj.value.length == 1 && obj.value.substring(0,2) == '6' && unicode != 8){
      	special = true;
      }
      
    // double number section
      // uk
      if(obj.value.length > 1 && obj.value.substring(0,2) == '44' && unicode != 8){
    	  special = true;
      }
      // south korea
      if(obj.value.length > 1 && obj.value.substring(0,2) == '82' && unicode != 8){
      	special = true;
      }
      // japan
      if(obj.value.length > 1 && obj.value.substring(0,2) == '81' && unicode != 8){
      	special = true;
      }
      // france
      if(obj.value.length > 1 && obj.value.substring(0,2) == '33' && unicode != 8){
      	special = true;
      }
      // china
      if(obj.value.length > 1 && obj.value.substring(0,2) == '86' && unicode != 8){
      	special = true;
      }
      // nz
      if(obj.value.length > 1 && obj.value.substring(0,2) == '64' && unicode != 8){
      	special = true;
      }
      // singapore
      if(obj.value.length > 1 && obj.value.substring(0,2) == '65' && unicode != 8){
      	special = true;
      }
      // spain
      if(obj.value.length > 1 && obj.value.substring(0,2) == '34' && unicode != 8){
      	special = true;
      }
      // italy
      if(obj.value.length > 1 && obj.value.substring(0,2) == '39' && unicode != 8){
      	special = true;
      }
      
      // taiwan
      if(obj.value.length > 1 && obj.value.substring(0,2) == '88' && unicode != 8){
      	special = true;
      }
      // hong kong
      if(obj.value.length > 1 && obj.value.substring(0,2) == '85' && unicode != 8){
      	special = true;
      }
      
    // taiwan
    if(obj.value.length > 1 && obj.value.substring(0,2) == '886' && unicode != 8){
    	special = true;
    }
	}
	
	if(!special){
  	if(obj.value.length >= 1 && (obj.value.substring(0,1) > 1) && unicode != 8){
  		alert('Please include the area code!');
  		document.getElementById('c2call_numtocall').value = '';
  		return false;
  	}

  	if(obj.value.length > 1 && (obj.value.substring(0,2) > 18) && unicode != 8){
  	 	alert('Sorry, that number is invalid!');
  		document.getElementById('c2call_numtocall').value = '';
  		return false;
  	}
	
  	if(c2call_bar_mobile == 'y'){
  		if(obj.value.length > 1 && (obj.value.substring(0,2) == 04) && unicode != 8){
  			alert('Sorry, mobile numbers are not allowed!\n\nPlease enter a fixed line number.');
  			document.getElementById('c2call_numtocall').value = '';
  			return false;
  		}
  	}
  
	}
	if (obj.value.length <= 9 && unicode != 8){
		var keyCode = (document.layers) ? keyStroke.which : e.keyCode;
		var keyString = String.fromCharCode(keyCode).toLowerCase();
		c2call_enableSubmit();
	}
	
	if (obj.value.length < 9){
		c2call_disableSubmit();
	}
}
function c2call_updateCountry(obj){
  document.getElementById('c2call_numtocall').value = obj.value;
}

function c2call_checkString(obj){
	var pasteData = window.clipboardData.getData("Text"); 
	if (pasteData.length == 10 && pasteData.substring(0,1) < 2 && (pasteData / 1) == pasteData){
		c2call_enableSubmit();
	}else{
		c2call_disableSubmit();
	}
}

function c2call_clearNumField(){
	document.getElementById('c2call_numtocall').value = '';	
}

function c2call_checkBackSpace(e,obj){
	if ((e.keyCode == 8)){
		c2call_disableSubmit();
	}
}

function c2call_enableSubmit(){
	document.getElementById('c2call_callMeSubmit').disabled = false;
	document.getElementById('c2call_callMeSubmit').value = 'Call Me >>>';
}

function c2call_disableSubmit(){
	document.getElementById('c2call_callMeSubmit').disabled = true;
	document.getElementById('c2call_callMeSubmit').value = 'Waiting ..';
}

function c2call_createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function c2call_readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function c2call_eraseCookie(name) {
	c2call_createCookie(name,"",-1);
}

function c2call_showCookieDetail(){
	if(c2call_readCookie('c2call_callMeCookie')){
		document.getElementById('c2call_numtocall').value = c2call_readCookie('c2call_callMeCookie')
		document.getElementById('c2call_savenum').checked = true;
		c2call_enableSubmit();
	}
}

var t_secs
var t_timerID = null
var t_timerRunning = false
var t_delay = 4000

function c2call_createTimer(sipID,callStart){
	// Set the length of the timer, in seconds
    t_secs = 10
    c2call_clockStop()
    c2call_runTheTimer(sipID,callStart)
}

function c2call_clockStop(){
    if(t_timerRunning)
        clearTimeout(t_timerID)
    t_timerRunning = false
}

function c2call_runTheTimer(sipID,callStart){
  //alert("sipID" +sipID + ", callStart" + callStart);
	if (t_secs==0){
        c2call_clockStop()
		c2call_createTimer(sipID,callStart)
    }else{
        self.status = t_secs
        t_secs = t_secs - 1
        t_timerRunning = true
        t_timerID = self.setTimeout("c2call_runTheTimer('" + sipID + "','" + callStart + "')", t_delay)
		getSipStatus(sipID,c2call_randomPassword(50),callStart)
    }
}  

function c2call_randomPassword(length){
	chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	pass = "";
	for(x=0;x<length;x++){
		i = Math.floor(Math.random() * 62);
		pass += chars.charAt(i);
	}
	return pass;
}

