
var hashTimer = null;
var currentHash = null;
var defaultHash = "";
var currentContactId = 0;
var isLoggedIn = false;
var profileMobile = '';
var jsonContacts = '';

var hashWithoutLogin = {
	startMenu: 1, 
	help: 1,
	helpItem: 1,
	login: 1,
	register: 1,
	registerDone: 1,
};

var xhrs = [];

/**
* Destination types and labels
*/

var destTypes = {
	phone: [
		{value: 'pm', label: 'Mobile'},
		{value: 'ph', label: 'Home'},
		{value: 'pw', label: 'Work'}
	],
	phoneLabels: {
		pm: 'Mobile',
		ph: 'Home',
		pw: 'Work',
		def: 'Phone'
	},
	im: [
		{value: 'gtk', label: 'GTalk'},
		{value: 'sip', label: 'SIP'},
		{value: 'sky', label: 'Skype'}
	],
	imLabels: {
		gtk: 'GTalk',
		sip: 'SIP',
		sky: 'Skype',
		def: 'VoIP'
	}
};


/**
* Support for contact editing
*/
var nextIdx = {
	phone : 0,
	im: 0
};

var counts = {
	phone : 0,
	im: 0
};



function $(id) {
	return document.getElementById(id);
}

function ddd() { console.log.apply(console, arguments); }

function doClassName(e,cn,add) {
	var t = e.className;
	var pos = t.indexOf(cn);
	if (pos>=0) {
		if (pos == 0) {
		}
	}

	if (add) {
		if (pos < 0) {
			t += ' ' + cn;
		}
	}
	else {
		t = t.replace(cn,'');
	}
	e.className = t;
}

function gup(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var r = regex.exec( window.location.href );
  if(r == null) return "";
  else return r[1];
}


function emptyCallback() {
}

function getXHR() {
	if (xhrs.length > 0) {
		return xhrs.pop();
	}
	else {
//		ddd('create xhr');
		if (window.XMLHttpRequest) {
			return new XMLHttpRequest();
		}
		else if (window.ActiveXObject) {
			return new ActiveXObject("Msxml2.XMLHTTP");
		}
	}
	return null;
}

function releaseXHR(xhr) {
	xhr.onreadystatechange = emptyCallback;
	xhrs.push(xhr);
}

function apiCall(m, params, cb) {
	var url = 'api/shop/' + m + '.json';

	url += '?plat=iph'; // &cookies=p';

	if (params) {
		url += '&' + params;
	}

//	if (m=='get_profile' || m=='login') {
		var l = getLocalValue('login', null);
		var p = getLocalValue('password', null);
		if (l && p) {
			var stamp = parseInt( (new Date().getTime()) / 1000 );
			var hash = hex_md5( hex_md5(p) + stamp );
			url += '&auth=' + encodeURIComponent('hash|' + l + '|' + hash + '|' + stamp)
		}
//	}

	sendAsyncRequest(url, cb);
}


function sendAsyncRequest(url, cb) {

	var m = 'get';
	var q = null;

	if (0) {
		m = 'post';
		var pos = url.indexOf('?');
		if (pos > 0) {
			q = url.substring(pos+1);
			url = url.substring(0, pos);
		}
		else {
			q = '';
		}
	}

	var xhr = getXHR();

	xhr.open(m, url, true);

	if (m == 'post') {
		var len = q && q.length > 0 ? q.length : 0;
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//xhr.setRequestHeader('Content-Length', len);
	}

	xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				var response = xhr.responseText;
//alert(response);
				var result = response ? eval('('+response+')'):'';

				if (result.error) {
					setStatusLine("Error: "+result.error);
					clearStatusLine(1000);
				}
				else {
					cb(result);
				}
				releaseXHR(xhr);
			}
		};
	xhr.send(q);
}



function body_onload() {

	if (window.navigator.standalone) {
		$('body').setAttribute('standalone', 'true');
	}

	updateOrientation();

	if (location.hash == '#register') {
		setLocalValue('login', null);
		setLocalValue('password', null);
	}

	if (!hashTimer) {
		hashTimer = setInterval(checkHash,200);
	}

	if (haveLoginPassword()) {
//alert('have login');
		sendGetProfile();
	}
	else {
		defaultHash = "#startMenu";
		if (location.hash != '#register') {
			//defaultHash = "#startMenu";
			location.href = "#startMenu";
		}
	}
}


function updateOrientation() {
	var o = window.orientation;
	var cn = 'portrait';

	if (o==90 || o==-90) {
		cn='landscape';
	}

	$('body').className = cn;

// Resize the phone number if needed
	var tmp = $('destphone').value;
	if (tmp) {
		setDestPhone(tmp);
	}
	
	window.scrollTo(0,1);
	//$('tab_account').scrollIntoView(true);
}

function checkHash() {
	if (currentHash != location.hash) {
//alert('checkHash cur=\'' + currentHash + '\' loc=' + location.hash);
		showByHash(location.hash);
	}
}

function showByHash(hash) {
//alert('showByHash=\'' + hash + '\' loc=' + location.hash);
	currentHash = hash;
	if (!hash) {
		hash = defaultHash;
	}
	else if (!isLoggedIn) {
		var t = hash.substring(1);
		var pos = t.indexOf('(');
		if (pos > 0) {
			t = t.substr(0, pos);
		}
//alert('check=\'' + t + '\'');
		if (!hashWithoutLogin[t]) {
			//alert('no login assign default='+defaultHash);
			hash = defaultHash;
		}
	}
	else if (hash != 'morePopup') {
		hideMorePopup();
	}
	//alert("showByHash "+hash);
	if (hash.length>1) {
		hash = hash.substr(1);
		var fname = 'show' + hash.substr(0,1).toUpperCase() + hash.substr(1);
		if (fname.charAt(fname.length-1)!=')') {fname += '()';}
		eval(fname);
	}
}

function keypad(c) {
	var e = $('destphone');
	var t = e.value;
	setDestPhone(t + c);

}

function keypad_bspace() {
	var e = $('destphone');
	var t = e.value;
	if (t.length>0) {
		setDestPhone(t.substr(0,t.length-1));
	}
}

function keypad_clear() {
	setDestPhone('');
}

function destphoneUpdated() {
	setDestPhone($('destphone').value, false, true);
}

function getDestPhone() {
	return $('destphone').value;
}

function setDestPhone(p, nodelay, noChangeCheck) {

	p = '' + p;

	if (p.length > 4) {
		if (p.charAt(0) == '+') {
			p = p.substr(1);
		}

		// Is this an IM destination?
		if (p.length >= 4 && p.charAt(3) == ':') {
		}
		// This is a phone number
		else {
		// Clean up the number
			p = p.match(/\d+/);
			if (!p) p='';
			else p = '' + p;
			if (p.length > 3) {
				if (p.charAt(0) == '0') {
					if (p.charAt(1) == '0') {
						p = p.substr(2);
					}
					else if (p.charAt(1) == '1' && p.charAt(2) == '1') {
						p = p.substr(3);
					}
				}
			}

			p = '+' + p;
			if (p.length > 18) {p = p.substr(0,18);}
		}
	}

	var e = $('destphone');
//	e.style.fontSize = '100%';

	var old = e.value;

	e.value = p;
//	if (e.clientWidth > e.parentNode.clientWidth - 60) {
//		e.style.fontSize = '60%';
//	}
	
	if (old != p || noChangeCheck==true) {
		destChanged(nodelay);
	}
}

function getMyPhone() {
	var myphone = getLocalValue('myphone', null);
	if (!myphone || myphone.length < 8) {
		if (isLoggedIn && profileMobile) {
			myphone = profileMobile;
		}
	}
	return myphone;
}

function saveMyPhone(p) {
	setLocalValue('myphone',p);
}

function getOrigPhone() {
	return getMyPhone();
}

function setLocalValue(name, value) {
	if (value == null) {
		localStorage.removeItem(name);
	}
	else {
		localStorage[name] = value;
	}
}

function getLocalValue(name, defaultValue) {
	if (!localStorage[name]) {
		return defaultValue;
	}
	else {
		return localStorage[name] ? localStorage[name] : defaultValue;
	}
}

function haveLoginPassword() {
	var l = getLocalValue('login', null);
	var p = getLocalValue('password', null);

	return (l && p );
}

function showStartMenu() {
	showDialer();
	$('menuContainer').style.display='block';
	$('startMenu').style.display='block';
	$('loginMenu').style.display='none';
}

function showLogin() {
	showStartMenu();

	$('startMenu').style.display='none';
	$('loginMenu').style.display='block';

	populateField('login', getLocalValue('login',''), '' );
	populateField('password', '', '');
}

function showRegisterDone() {
	showSingle('body','registerDone');
}

function showHelp() {
	// Populate help topics if necessary
	var e = $('helpItemList');
	if (!e.innerHTML) {
		var html = '';
		for(var i=0; i<Voxofon.faqs.length; i++) {
			var h = Voxofon.faqs[i];
			html += "<li><a href=\"#helpItem(" + i + ")\">"+h.title+"</a>";
		}
		e.innerHTML = html;
	}
	showSingle('body','help');
}

function showHelpItem(i) {
	var h = Voxofon.faqs[i];
	$('helpItemTitle').innerHTML = h.title;
	$('helpItemText').innerHTML = h.text;
	showSingle('body','helpItem');
}



function loginMenu_login() {
	sendLogin();
}

function showMorePopup() {
	if (!checkNumbers()) return;
	$('morePopup').style.display = 'block';
}

function hideMorePopup() {
	$('morePopup').style.display = 'none';
}


function doCallback() {
	if (checkNumbers()) {
		setStatusLine("Starting the call...");
		sendCallback();
	}
}

function doCallthrough() {
	if (checkNumbers()) {
		setStatusLine("Starting the call...");
		sendCallthrough();
	}
}

function doSendSMS() {
	if (checkNumbers() && checkTextMessage()) {
		setStatusLine("Sending message...");
		sendSendSMS();
	}
}


function checkNumbers() {
	var p = getOrigPhone();
	if (!p || p.length < 8) {
		setStatusLine("Invalid 'call from' number");
		clearStatusLine(1000);
		location.href="#options";
		return false;
	}

	p = getDestPhone();
	if (!p || p.length < 8) {
		setStatusLine("Invalid destination number");
		clearStatusLine(1000);
		return false;
	}

	return true;
}

function checkTextMessage() {
	var t = $('smsta').value;
	var dt = $('smsta').defaultValue;
	if (t == dt || t.length==0) {
		setStatusLine('Empty message');
		clearStatusLine(1000);
		return false;
	}
	return true;
}

function smstaChanged(e) {
	var len = e.value.length;
	var isUnicode = false;
	if (e.value == e.defaultValue) {
		len = 0;
	}
	else {
		var s = e.value;
		for(var i=0; i < len; i++) {
			if (s.charCodeAt(i) > 127) {
				isUnicode = true;
				break;
			}
		}
	}
	var oneSmsChars = isUnicode ? 70 : 160;
	var nextSmsChars = isUnicode ? 67 : 153;
	var maxChars = oneSmsChars + (smsMaxMessages-1) * nextSmsChars;
	var smsCount = 1;

	if (len > oneSmsChars) {
		if (len >= maxChars) {
			e.value = e.value.substring(0,maxChars);
			len = maxChars;
			smsCount = smsMaxMessages;
		}
		else {
			smsCount = 2 + parseInt( (len - oneSmsChars - 1) / nextSmsChars);
		}
	}

	$('smsCharsCount').innerHTML = len + '/' + maxChars + (isUnicode ? ' - Unicode' : '');
	$('smsTotalPrice').innerHTML = (smsCount != 1 ? smsCount + 'x' : '') + smsRate;
}

function populateProfile(p) {
	$('pBalance').innerText = p.credit;

	var ff = ['email','mobile'];

	var html='';

	for(var i = 0; i < ff.length; i++) {
		var f = ff[i];
		if (p[f] != undefined && p[f]) {
			var v = (i > 0 ? '+' : '<a href="mailto:' + p[f] + '">') + p[f] + (i > 0 ? '' : '</a>');
			html += "<li><div class=\"label\">"+ f +"</div>" + v + "</li>";
		}
	}
	$('pDetails').innerHTML = html;

	profileMobile = p.mobile ? p.mobile : '';
}

function populateContacts(cc) {
	jsonContacts = cc;

	var html='';

	for(var i=0;i<jsonContacts.length;i++) {
		var c = jsonContacts[i];
		html += "<li><a href=\"#contact(" + i + ")\">"+c.name+"</a>";
	}

	$('contactList').innerHTML = html;
}


function populateRecentCalls(pp) {
	var html='';

	for(var i=0;i<pp.length;i++) {
		var v = pp[i];
		var s = v.dest;

		if (v.name) {
			s = v.name;
			if (v.type) {
				s += ' (' + getShortDestLabel(v.type) + ')';
			}
		}
		else {
			if (s.length < 4 || s.charAt(3)!=':') {
				s = '+' + s;
			}
		}

		html += "<li><a href=\"#dialer('" + v.dest + "')\">"+s+"</a>";
	}

	$('recentCalls').innerHTML = html;
}


function showDialer(p) {
	showSingle('body','tabScreen');
	if (p) {
		setDestPhone(p,true);
	}
}

function showContacts() {
	showSingle('body','contacts');
}


function showContact(id) {
	showSingle('body','contact_details');

	if (arguments.length==0) id = currentContactId;
	else currentContactId = id;

	var c = jsonContacts[id];

	// Contact name
	$('contactName').innerText=c.name;

	var html='';

	// Contact email
	if (c.email) {
			var href = "mailto:" + c.email;
			html += '<li><a href="' + href+ '"><div class="label">email</div>' + c.email + '</a></li>';
	}

	// Contact phones
	if (c.phones) {
		var arr = c.phones.split(',');
		for(var j=0, jlen=arr.length; j < jlen; j++) {
			var td = arr[j].split(':');
			if (td && td.length==2) {
				var t = td[0];
				var d = td[1];

				var href = "#dialer('" + d + "')";
				html += '<li><a href="' + href+ '"><div class="label">' + getDestLabel('phone', t) + '</div>+' + d + '</a></li>';
			}
		}
	}

	$('contactPhones').innerHTML = html;
	$('contactPhones').style.display = html ? '' : 'none';

	// Contact IMs
	html = '';
	if (c.ims) {
		var arr = c.ims.split(',');
		for(var j=0, jlen=arr.length; j < jlen; j++) {
			var td = arr[j].split(':');
			if (td && td.length==2) {
				var t = td[0];
				var d = td[1];

				var href = "#dialer('" + t + ':' + d + "')";
				
				html += '<li><a href="' + href+ '"><div class="label">' + getDestLabel('im', t) + '</div>' + d + '</a></li>';
			}
		}
	}

	$('contactIms').innerHTML = html;
	$('contactIms').style.display = html ? '' : 'none';
}


function getDestLabel(mode, type) {
	var o = destTypes[mode+'Labels'];
	return o[type] ? o[type] : o['def'];  
}

function getShortDestLabel(type) {
	if (type.length == 2) return type.substr(1);
	return type;
}


/**
* mode = im|phone
*/
function appendDestItem(mode, type, value) {
	var idx = nextIdx[mode];
	if (idx > 10) return;

	nextIdx[mode]++;
	counts[mode]++;

	var divId = mode+'d['+idx+']';
	var selectId = mode+'t['+idx+']';
	var inputId = mode+'v['+idx+']';

	var html = ''; 

	html += '<a class="removeDest" href="javascript:removeDestItem(\''+mode+'\','+idx+')">x</a>';

	html += '<div class="label"><select class="combobox" id="'+selectId+'">';
	for(var i=0, ilen = destTypes[mode].length; i < ilen; i++) {
		html += '<option value="' + destTypes[mode][i].value + '"';
		if (destTypes[mode][i].value == type) {
			html += ' selected';
		}
		html += '>' + destTypes[mode][i].label;
	}
	html += '</select></div>';

	if (!value) value = '';

	html += ' <input type="text" class="withLabel" id="'+inputId+'" value="'+value+'" onblur="validateDestInput(this)">';

//	html += '<a style="position: absolute" href="javascript:removeDestItem(\''+mode+'\','+idx+')">x</a>';

	var div = document.createElement('li');
	div.id = divId;
	div.className='dest-item';
	$(mode+'Container').insertBefore(div, $(mode+'Add'));
	div.innerHTML = html;
}

function validateDestInput(input) {
	var mode = input.id.indexOf('phone') >=0 ? 'phone' : 'im';
	var ov = input.value;
	var v = ov;
	if (mode == 'phone') {

	// Remove everything but letters and digits
		v = v.replace(/\W|_/g,'');
	// Get all digits from the start of the string
		v = /\d+/.exec(v);

		if (!v) v='';
		else v = '' + v;


		if (v.length > 0 && v.charAt(0) != '+') {
			if (v.length > 3) {
				if (v.charAt(0)=='0') {
					if (v.charAt(1)=='0') {
						v = v.substr(2);
					}
					else if (v.charAt(1)=='1' && v.charAt(2)=='1') {
						v = v.substr(3);
					}
				}
			}
			v = '+' + v;
		}
	}
	else {
		var pos = v.indexOf(':');
		if (pos>=0) {
			v = v.substr(pos+1);
		}
	}

	if (v!=ov) {
		input.value = v;
	}
}

function removeDestItem(mode, idx) {
	if (counts[mode] == 0) return;

	if (counts[mode]==1) {
		var inputId = mode+'v['+idx+']';
		$(inputId).value = '';
		var selectId = mode+'t['+idx+']';
		$(selectId).selectedIndex = 0;
	}
	else {
		var divId = mode+'d['+idx+']';
		var e = $(divId);
		if (e) {
			e.parentElement.removeChild(e);
		}
		counts[mode]--;
	}
}

function setupDests(mode, dests) {

	var label = mode == 'phone' ? 'Add phone...' : 'Add IM or VoIP...';

	$(mode+'Container').innerHTML = '<li id="'+mode+'Add"><a href="javascript:appendDestItem(\''+mode+'\')">'+label+'</a></li>';

	if (dests) {
		var arr = dests.split(',');
		for(var i=0, ilen = arr.length; i < ilen; i++) {
			var td = arr[i].split(':');
			if (td && td.length==2) {
				var t = td[0];
				var d = td[1];
				if (mode == 'phone' && d) {
					d = '+' + d;
				}
				appendDestItem(mode,t,d);
			}
		}
	}

//	if (nextIdx[mode]==0) {
//		appendDestItem(mode);
//	}
}

function encodeDest(mode) {
	var s = '';

	for(var idx=0, ilen = nextIdx[mode]; idx < ilen; idx++) {

		var inputId = mode+'v['+idx+']';
		var input = $(inputId);
		var selectId = mode+'t['+idx+']';
		var select = $(selectId);
		
		if (input && select) {
			var t = select.options[select.selectedIndex].value;
			var d = input.value;

			if (mode=='phone') {
				if (d.charAt(0) == '+') {
					d = d.substr(1);
				}
			}

			if (d && d.length > 0) {
				if (s.length > 0) {s += ',';}
				s += t + ':' + d;
			}
		}
	}

	return s;
}



function showEditContact(id) {
	showSingle('body','contact_edit');

	nextIdx.phone = 0;
	nextIdx.im = 0;
	counts.phone = 0;
	counts.im = 0;

	if (arguments.length == 0) {
		id = currentContactId;
	}
	else {
		currentContactId = id;
	}

	var c; 

// New contact
	if (id < 0) {
		c = {uniq: -1, name:'', email:'', phones:'', ims:''};
	}
	else {
		c = jsonContacts[id];
	}

	$('deleteContact').style.display = id >= 0 ? '' : 'none';

	
// Populate contact fields
	populateField('ceName',c.name,'');
	populateField('ceEmail',c.email,'');

	setupDests('phone',c.phones);
	setupDests('im',c.ims);
}

function populateField(id,val,prefix) {
	var e = $(id); 
	e.value = val ? prefix + val : e.defaultValue; 
	doClassName(e,'empty',val ? false : true);
}

function showRecent() {
	showSingle('body','recent');
}

function showAccount() {
	var p = getMyPhone();
	if (!p) p = 'Not specified';
	$('pThisMobile').innerHTML = p;

	showSingle('body','account');
}

function showOptions() {
	var e = $('oThisMobile');
	var p = getMyPhone();
	if (!p) p = '+';
	e.value = p;
	showSingle('body','options');

	e.focus();
}

function saveOptions() {
	var myphone = $('oThisMobile').value;
	if (myphone.length < 8) {
		setStatusLine("Invalid phone number");
		clearStatusLine(1000);
	}
	else {
		saveMyPhone(myphone);
		history.back();
	}
}

function showSendsms() {
	$('smsto').innerHTML = getDestPhone();

	var e = $('smsta');
	e.value = '';
	input_onblur(e);
	smstaChanged(e);

	showSingle('body','sendsms');

	e.focus();
}

function showRegister() {
//	location.href = registerURL + '&mobile=' + encodeURIComponent(getMyPhone());
	$('captchaContainer').innerHTML = '<img src="classes/libs/captcha/img.php?mode=n" width="60" height="22" />';
	showSingle('body','register');
}


function setStatusLine(s) {
	var display = s ? 'block' : 'none';
	var e = $('statusMsg');
	e.style.display = display;
	e.innerHTML = s;
}

function clearStatusLine(delay) {
	setTimeout('setStatusLine("")',delay);
}

function showSingle(parentId, childId) {
//	ddd('showSingle: ' + parentId + ' ' + childId);
	var p = $(parentId);
//	ddd('childNodes '+p.childNodes.length);
	for(var i=0; i < p.childNodes.length; i++) {
		var c = p.childNodes[i];
//		ddd('child: '+c);
		if (c.nodeType == 1) {
//			ddd('  elem: ' + c.id + ' class="' + c.className + '"');
			if (c.className.indexOf('screen')>=0) {
				c.style.display = c.id == childId ? 'block' : 'none';
			}
		}
	}
	//window.scrollTo(0,1);
}


function input_onfocus(e) {
	if (e.value==e.defaultValue) {
		if (e.id!='myphone') e.value='';
		if (e.id=='password' && e.type!='password') e.type='password';
		doClassName(e,'empty',false);
	}
	var h = $(e.id+'Help');
	if (h) h.style.display='block';
}

function input_onblur(e) {
	if (e.value=='' || e.value==e.defaultValue) {
		e.value=e.defaultValue;
		doClassName(e,'empty',true);
		if (e.id=='password') e.type='text';
	}
	var h = $(e.id+'Help');
	if (h) h.style.display='none';
}

function onchange_phone(e) {
	var p = e.value;
	p = p.replace(/\D*/g,'');
	if (!p) p='';
	else {
		if (p.indexOf('00')==0) {
			p = p.substr(2);
		}
		else if (p.indexOf('011')==0) {
			p = p.substr(3);
		}
	}
	if (p) {
		p = '+' + p;
	}
	e.value = p;
}




/**
* Communications
*/

function sendGetRate() {
	apiCall('get_rates', 'orig='+encodeURIComponent(getOrigPhone())+
		'&dest='+encodeURIComponent(getDestPhone()), handleRateResponse);
}

function sendCallback() {
	apiCall('callback', 'orig='+encodeURIComponent(getOrigPhone())+
	'&dest='+encodeURIComponent(getDestPhone()), handleRateResponse);
}

function sendCallthrough() {
	apiCall('callthrough', 'orig='+encodeURIComponent(getOrigPhone())+
	'&dest='+encodeURIComponent(getDestPhone()), handleRateResponse);
}


function sendSendSMS() {
	var txt = $('smsta').value;
	apiCall('send_sms', 'orig='+encodeURIComponent(getOrigPhone())+
		'&dest='+encodeURIComponent(getDestPhone())+
		'&msgtext='+encodeURIComponent(txt)
		, handleSendSMSResponse);
}




var smsMaxMessages = 1;
var smsFreeTest = 0;
var smsRate = '-';


var commTimerId = 0;

function destChanged(nodelay) {
	if (commTimerId) {
		clearTimeout(commTimerId);
	// Clear rates displayed on buttons
		$('callback_rate').innerHTML = '';
		$('sms_rate').innerHTML = '';
		$('local_rate').innerHTML = '';
		$('destname').innerHTML = '';
	}
	commTimerId = setTimeout('sendGetRate()', nodelay ? 0 : 1000);
}

function handleRateResponse(result) {
	var callback_rate = '';
	var callback_maxdur = '';
	var callback_state = 'd';
	var local_rate = '';
	var local_maxdur = '';
	var local_state = 'd';
	var sms_state = 'd';


	// Callback rate and max duration
		if (!isNaN(result.callback_rate)) {
			if (result.callback_rate==0) {
				callback_rate = result.callback_maxdur ? 'FREE call' : 'not free';
			}
			else {
				callback_rate = parseInt(result.callback_rate*1000)/10;
				callback_rate += ' c/min';
			}
			callback_state = result.callback_maxdur>0 ? 'n' : 'd';
			callback_maxdur = result.callback_maxdur + " min" + (result.callback_maxdur!=1?'s':'');
		}

	// Local rate and max duration
		if (!isNaN(result.local_rate)) {
			if (result.direct_call) {
				local_rate = 'direct call';
			}
			else if (!result.local_did) {
				result.local_maxdur = 0;
				local_rate = 'not available';
			}
			else {
				if (result.local_rate==0) {
					local_rate = result.local_maxdur ? 'FREE call' : 'not free';
				}
				else {
					local_rate = parseInt(result.local_rate*1000)/10;
					local_rate += ' c/min';
				}
			}
			local_state = result.local_maxdur>0 ? 'n' : 'd';
			local_maxdur = result.local_maxdur + " min" + (result.local_maxdur!=1?'s':'');
		}

	// SMS rate and max messages
		if (!isNaN(result.sms_rate)) {
			if (result.sms_rate==0) {
				//smsRate = result.sms_maxdur ? 'FREE msg' : 'not free';
				//smsFreeTest = 1;
				smsRate = 'n/a';
			}
			else {
				smsRate = parseInt(result.sms_rate*1000)/10;
				smsRate += ' c';
			}

			sms_state = result.sms_maxdur>0 ? 'n' : 'd';
			smsMaxMessages = result.sms_maxdur;
		}
	// New origination history
//		if (result.origHistory) {
//			origBox.setData(result.origHistory);
//		}
	// New destination history
		if (result.destHistory) {
			populateRecentCalls(result.destHistory);
		}

		$('morePopupSendSMS').style.display = smsMaxMessages > 0 ? 'block' : 'none';

		if (result.credit) {
			$('pBalance').innerHTML = result.credit;
		}

		if (result.dest_name) {
			$('destname').innerHTML = result.dest_name;
		}

	// New status
		if (result.status) {
			setStatusLine(result.status);
			clearStatusLine(4000);
		}


	$('callback_rate').innerHTML = callback_rate;
//	$('callback_maxdur').innerHTML = callback_maxdur;
//	actbuttonStates[1] = callback_state;
	$('local_rate').innerHTML = local_rate;
//	$('local_maxdur').innerHTML = local_maxdur;
//	actbuttonStates[2] = local_state;
	$('sms_rate').innerHTML = smsRate;
	//$('sms_maxdur').innerHTML = sms_maxdur;
//	_updateSmsCharCount();
//	actbuttonStates[3] = sms_state;

//	actbuttonUpdateImage();

	// Call local access number
		if (result.call_local_did) {
			window.location.href="tel:" + result.call_local_did;
		}
}



function sendUpdateContact() {

	var uniq = (currentContactId >= 0 && currentContactId < jsonContacts.length) ? jsonContacts[currentContactId].uniq : -1;

	setStatusLine("Saving contact...");

	var params = 'uniq='+uniq;
	var e = $('ceName');
	params += '&name=' + (e.value!=e.defaultValue ? encodeURIComponent(e.value) : '');
	e = $('ceEmail');
	params += '&email=' + (e.value!=e.defaultValue ? encodeURIComponent(e.value) : '');
	params += "&phones=" + encodeURIComponent(encodeDest('phone'));
	params += "&ims=" + encodeURIComponent(encodeDest('im'));

	apiCall('update_contact', params, handleContactsResponse);
}

function sendDeleteContact() {
	if (currentContactId < 0 || currentContactId >= jsonContacts.length) return;

	var uniq = jsonContacts[currentContactId].uniq;
	setStatusLine("Deleting contact...");
	var params = 'uniq='+uniq;
	apiCall('delete_contact', params, handleContactsResponse);
}


function sendLogin() {
	var e1 = $('login');
	var e2 = $('password');

	if (!e1.value || e1.value == e1.defaultValue ||
			!e2.value || e2.value == e2.defaultValue) {

		setStatusLine('Incorrect login or password');
		clearStatusLine(2000);
		return;
	}

	setStatusLine("Logging in... ");

	var l = e1.value;
	var p = e2.value;

// Save Login and Password in local storage
	setLocalValue('login', l);
	setLocalValue('password', p);

	apiCall('login', '', handleLoginResponse);
}

function sendGetProfile() {
	apiCall('get_profile', '', handleLoginResponse);
}

function sendLogout() {
//	apiCall('logout', '', handleLoginResponse);

	setLocalValue('login', null);
	setLocalValue('password', null);

	populateProfile('');
	populateContacts('');
	populateRecentCalls('');
	isLoggedIn = false;
	defaultHash = "#startMenu";
	location.href="#startMenu";
}



function handleContactsResponse(result) {
	clearStatusLine(0);
	if (result.contacts) {
		populateContacts(result.contacts);
		//location.href="#contacts";
		history.back();
	}
}


function handleLoginResponse(result) {
 
	if (result.contacts) {
		populateContacts(result.contacts);
	}

	if (result.destHistory) {
		populateRecentCalls(result.destHistory);
	}

	if (result.profile) {
		populateProfile(result.profile);
	}

// New status
	if (result.status) {
		setStatusLine(result.status);
		clearStatusLine(2000);
	}
	else {
		clearStatusLine(0);
	}

//	if (result.ok) {
	if (result.profile) {
		isLoggedIn = true;
		defaultHash="#dialer";
		location.href="#dialer";
	}

	if (!result.profile) {
		defaultHash = "#startMenu";
		var login = gup('login');
		populateField('login', login ? login : getLocalValue('login',''), '');
		populateField('password', '', '');
		if (login) {
			location.href="#login";
		}
		else {
			location.href="#startMenu";
			showStartMenu();
		}
	}
}

function handleSendSMSResponse(result) {
 
	if (result.destHistory) {
		populateRecentCalls(result.destHistory);
	}

	if (result.profile) {
		populateProfile(result.profile);
	}

// New status
	if (result.status) {
		setStatusLine(result.status);
		clearStatusLine(2000);
	}
	else {
		clearStatusLine(0);
	}

//	if (result.ok) {
	if (result.call_id) {
		location.href="#dialer";
	}
}


function fval(id) {
	var e = $(id);
	return e.value!=e.defaultValue ? e.value : '';
}

function register() {
	var s = '';
	var e = fval('newemail');
	if (!e || e.indexOf('@') < 0 || e.indexOf('.') < 0) {
		s += 'Email is not valid<br>';
	}
	var m = fval('newphone');
	if (!m || m.length < 6) {
		s += 'Mobile number is not valid<br>';
	}
	var p1 = fval('newpassword');
	if (!p1) {
		s += 'Password is empty<br>';
	}
	var p2 = fval('newpassword2');
	if (p1 != p2) {
		s += 'Passwords do not match<br>';
	}
	var c = fval('captchaphone');
	if (!c) {
		s += 'Visual code is empty<br>';
	}

	if (s) {
		setStatusLine(s);
		clearStatusLine(4000);
	}
	else {
		$('doneemail').innerHTML = e;

		setStatusLine("Creating account...");

		var url = registerApiURL + '&a=register&email='+e+'&mobile='+m+'&password='+p1+'&captcha='+c+'&plat=iph';
		sendAsyncRequest(url, handleRegisterResponse);
	}
}

function handleRegisterResponse(result) {
 
// New status
	if (result.status) {
		setStatusLine(result.status);
		clearStatusLine(2000);
	}
	else {
		clearStatusLine(0);
	}

	if (result.ok) {
		var m = fval('newphone');
		setLocalValue('myphone', m);
		setLocalValue('login', m);

		$('newemail').value = '';
		$('newpassword').value = '';
		$('newpassword2').value = '';
		$('captchaphone').value = '';

		showRegisterDone();
	}
}



