
var hashTimer = null;
var currentHash = null;
var defaultHash = "";
var currentContactId = 0;
var isLoggedIn = false;
var profileMobile = '';
var jsonContacts = '';

var xhrs = new Array();

/**
* 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: 'gzm', label: 'Gizmo5'},
		{value: 'gtk', label: 'GTalk'},
		{value: 'sip', label: 'SIP'},
		{value: 'sky', label: 'Skype'}
	],
	imLabels: {
		gzm: 'Gizmo5',
		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 sendAsyncRequest(url, cb) {
	url += '&plat=iph';

	var xhr = getXHR();
	xhr.open('get', url);
	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(null);
}



function body_onload() {
	updateOrientation();

	if (!hashTimer) {
		hashTimer = setInterval(checkHash,200);
	}
	
	if (!$('tabs')) return; 

	showTabs(isLoggedIn);

	sendGetProfile();
}

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) {
		showByHash(location.hash);
	}
}

function showByHash(hash) {
	currentHash = hash;
	if (!hash) hash = defaultHash;

	//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 = $('myphone').value;
	if (myphone.length < 8) myphone = getCookie('cmyphone','+1');
	if (!myphone || myphone.length < 8) {
		if (isLoggedIn && profileMobile) {
			myphone = profileMobile;
			saveMyPhone(myphone);
		}
	}
	return myphone;
}

function saveMyPhone(p) {
	$('myphone').value = p;
	setCookie('cmyphone',p,365);
}

function getOrigPhone() {
	return getMyPhone();
}

function setCookie(name, value, days) {
	var expire = new Date();
	if (!days) days=1;
	expire.setTime(expire.getTime() + 3600000*24*days);
	document.cookie = name + "=" + escape(value) + ";expires="+expire.toGMTString();
}

function getCookie(name, defaultValue) {
	if (document.cookie.length > 0) {
		var pos1 = document.cookie.indexOf(name + "=");
  	if (pos1 != -1) { 
    	pos1 += name.length+1; 
    	var pos2 = document.cookie.indexOf(";", pos1);
			if (pos2 == -1) pos2 = document.cookie.length;
			return unescape(document.cookie.substring(pos1,pos2));
		}
	}
	return defaultValue;
}


function showTabs(loggedIn) {
	var test = loggedIn ? 'none' : 'block';
	var acc = loggedIn ? 'block' : 'none';
	
	$('tab_register').style.display = test;
	$('tab_login').style.display = test;
	$('tab_recent').style.display = acc;
	$('tab_contacts').style.display = acc;
	$('tab_keypad').style.display = test;
	$('tab_account').style.display = acc;
	$('tab_options').style.display = 'block';
}

function showStartMenu() {
	showDialer();
	$('menuContainer').style.display='block';
	$('startMenu').style.display='block';
	$('optionsMenu').style.display='none';
	$('loginMenu').style.display='none';
}

function showOptions() {
	showStartMenu();

	$('startMenu').style.display='none';
	$('optionsMenu').style.display='block';

	$('myphone').value = getMyPhone();
	$('myphone').focus();
}

function showLogin() {
	showStartMenu();

	$('startMenu').style.display='none';
	$('loginMenu').style.display='block';
}

function optionsMenu_continue() {
	var myphone = $('myphone').value;
	if (myphone.length < 8) {
		setStatusLine("Invalid phone number");
		clearStatusLine(1000);
	}
	else {
		saveMyPhone(myphone);

		$('optionsMenu').style.display='none';
		$('menuContainer').style.display='none';

		setStatusLine("Enter destination phone number");
		clearStatusLine(1000);
		location.href="#dialer";
	}
}

function loginMenu_login() {
	setCookie('clogin',$('login').value,365);
	sendLogin();
}

function doCallback() {
	if (checkNumbers()) {
		setStatusLine("Starting the call...");
		sendCallback();
	}
}

function doCallthrough() {
	if (checkNumbers()) {
		setStatusLine("Starting the call...");
		sendCallthrough();
	}
}

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 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() {
	showSingle('body','account');
}

function showRegister() {
	location.href = registerURL + '&mobile=' + encodeURIComponent(getMyPhone());
}


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() {
	sendAsyncRequest('?d=async&a=get_rates&orig='+encodeURIComponent(getOrigPhone())+
		'&dest='+encodeURIComponent(getDestPhone()), handleRateResponse);
}

function sendCallback() {
	sendAsyncRequest('?d=async&a=callback&orig='+encodeURIComponent(getOrigPhone())+
	'&dest='+encodeURIComponent(getDestPhone()), handleRateResponse);
}

function sendCallthrough() {
	sendAsyncRequest('?d=async&a=callthrough&orig='+encodeURIComponent(getOrigPhone())+
	'&dest='+encodeURIComponent(getDestPhone()), handleRateResponse);
}

/*
function sendAsyncSendSMS() {
	var origPhone = origBox.getPhoneValue();
	var destPhone = destBox.getPhoneValue();
	var txt = $('smsta').value;
	sendAsyncRequest('?d=async&a=send_sms&orig='+origPhone+'&dest='+destPhone+'&msgtext='+txt);
}
*/



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 = '';
		$('local_rate').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;
			}
			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);
		}

		if (result.credit) {
			$('pBalance').innerText = result.credit;
		}

	// 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 = sms_rate;
	//$('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 sendEditContact() {

	var uniq = (currentContactId >= 0 && currentContactId < jsonContacts.length) ? jsonContacts[currentContactId].uniq : -1;

	setStatusLine("Saving contact...");

	var url = '?d=async2&a=update_contact&uniq='+uniq;
	var e = $('ceName');
	url += '&name=' + (e.value!=e.defaultValue ? encodeURIComponent(e.value) : '');
	e = $('ceEmail');
	url += '&email=' + (e.value!=e.defaultValue ? encodeURIComponent(e.value) : '');
	url += "&phones=" + encodeURIComponent(encodeDest('phone'));
	url += "&ims=" + encodeURIComponent(encodeDest('im'));

	sendAsyncRequest(url, handleContactsResponse);
}

function sendDeleteContact() {
	if (currentContactId < 0 || currentContactId >= jsonContacts.length) return;

	var uniq = jsonContacts[currentContactId].uniq;
	setStatusLine("Deleting contact...");
	var url = '?d=async2&a=delete_contact&uniq='+uniq;
	sendAsyncRequest(url, 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 login = e1.value;
	var password = e2.value;

	var hash = hex_md5(hex_md5(password) + serverSeed);

	var url = '?d=async2&a=login&login='+login+'&hash='+hash;
	sendAsyncRequest(url, handleLoginResponse);
}

function sendGetProfile() {
	var url = '?d=async2&a=get_profile';
	sendAsyncRequest(url, handleLoginResponse);
}

function sendLogout() {
	var url = '?d=async2&a=logout';
	sendAsyncRequest(url, handleLoginResponse);

	populateProfile('');
	populateContacts('');
	populateRecentCalls('');
	isLoggedIn = false;
	showTabs(isLoggedIn);
	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;
		showTabs(isLoggedIn);
		defaultHash="#dialer";
		location.href="#dialer";
	}

	if (!result.profile) {
		defaultHash = "#startMenu";
		var login = gup('login');
		populateField('login', login ? login : getCookie('clogin',''), '');
		if (login) {
			location.href="#login";
		}
		else {
			location.href="#startMenu";
			showStartMenu();
		}
	}
}