
var javaEnabled = navigator.javaEnabled();
var appletLoaded = false;
var appletShown = false;

var smsMaxMessages = 1;
var smsFreeTest = 0;
var smsRate = '-';

var keypadToOrig = false;
var actbuttonTempDisabled = false;


function PhoneBox(id, valnamePrefix, defaultValname) {
	if (arguments.length>0) this.init(id, valnamePrefix, defaultValname);
}

PhoneBox.prototype = new SuggestBox();

PhoneBox.prototype.init = function(id, valnamePrefix, defaultValname) {
	SuggestBox.prototype.init.call(this,id);
	this.valnamePrefix = valnamePrefix;
	this.defaultValname = defaultValname;
	this.matchAnywhere = true;
	this.clearOnFocus = false;
	this.countryCode = '1';
	this.valueForValname = false;
}

PhoneBox.prototype.setData = function(values) {
	this.rawData = values;
	var dvalues = [];

	for(var i=0; i < values.length; i++) {
		var v = values[i];
		var s = v.dest;

		if (s.length < 4 || s.charAt(3)!=':') {
			s = '+' + s;
		}

		if (v.name) {
			s += ' - ' + v.name;
			if (v.type) {
				if (v.type == 'ph') {
					s += ' (h)';
				}
				else if (v.type == 'pw') {
					s += ' (w)';
				}
				else if (v.type == 'pm') {
					s += ' (m)';
				}
			}
		}
		dvalues[dvalues.length] = s;
	}
	SuggestBox.prototype.setData.call(this,dvalues);
}

PhoneBox.prototype.getPhoneValue = function() {
	var v = this.getValue();
	if (v.length > 5) {
		if (v.charAt(3) == ':') {
			return v;
		}
	}
// Remove everything but letters and digits
	v = v.replace(/\W|_/g,'');
// Get all digits from the start of the string
	v = /\d+/.exec(v);
	return v;
}

PhoneBox.prototype.onmouseup = function(e, event) {
	if (document.all) {e.selStart = getSelectionStart(e);}
	SuggestBox.prototype.onmouseup.call(this, e, event);
}

PhoneBox.prototype.onkeyup = function(e, event) {
	if (this.valueForValname && this.valueForValname != e.value) {
		this.valueForValname = false;
		this.setValname(this.defaultValname);
	}
	SuggestBox.prototype.onkeyup.call(this, e, event);
}

PhoneBox.prototype.setValue = function(val,skipNotify) {
	if (val.length>0) {
		if (val.charAt(0)=='+') {
			val = val.substring(1);
		}
	}
	var valname;
	var pos = val.indexOf(' - ');
	if (pos > 0) {
		valname = val.substring(pos+3);
		val = val.substring(0,pos);
		valname = this.valnamePrefix + valname;
		this.valueForValname = val;
	}
	else {
		valname = this.defaultValname;
		this.valueForValname = false;
	}
	this.setValname(valname);

	SuggestBox.prototype.setValue.call(this,val,skipNotify);
}

PhoneBox.prototype.setValname = function(valname) {
	$(this.id + 'name').innerHTML = valname;
}

PhoneBox.prototype.observedChanged = function(widget,value) {
	// Corresponding phone country box has changed
	// Set the value of this phonebox but do not notify the observers
	//alert("Phone observing "+widget.id+" value="+value);
	this.setValue(value,false);
}

PhoneBox.prototype.populateDropDown = function(str) {
	if (str.length > 0) {
		str = '+' + str;
	}
	SuggestBox.prototype.populateDropDown.call(this,str);
}

function CountryBox(id,imgpath,imgext,w,h) {
	if (arguments.length>0) this.init(id,imgpath,imgext,w,h);
}

CountryBox.prototype = new SuggestBox();

CountryBox.prototype.init = function(id,imgpath,imgext,w,h) {
	SuggestBox.prototype.init.call(this,id);
	this.imagePath=imgpath;
	this.imageExt=imgext;
	this.imageWidth=w;
	this.imageHeight=h;
	this.showAllItems = true;
	this.allowEmptySearch = true;
}

CountryBox.prototype.setData = function(values) {
	SuggestBox.prototype.setData.call(this,values);

// Hash by phonecode
	this.hash = new Array();
	for(var i=0;i<values.length;i++) {
		this.hash[values[i][2]] = i;
	}
}

// Value is the phonecode for the country
CountryBox.prototype.setValue = function(val,skipNotify) {
	SuggestBox.prototype.setValue.call(this,val,skipNotify);

//alert("Country.setValue val="+val);
	var ccode = this.values[this.hash[val]][0];
	var cname = this.values[this.hash[val]][1];

//alert("Country.setValue ccode="+ccode);

	var imgsrc = this.imagePath + ccode + this.imageExt;
	var e = $(this.id);
	e.src = imgsrc;
	e.title = cname + ' - Click to change country code';
}

CountryBox.prototype.observedChanged = function(widget,p) {
// Corresponding phone box has changed
// We got the phone number from the box
	//alert("Country observing "+widget.id+" value="+p);

// Clean up the number and get up to 4 first digits
	var pos = p.indexOf('+');
	if (pos>=0) {
		p = p.substr(pos+1);
	}

	if (p.length>4) {
		p = p.substr(0,4);
	}

// Try to match against known country phone codes
	while(p.length>0) {
		if (this.hash[p]>=0) {
			this.setValue(p,true);
			break;
		}
		p = p.substr(0,p.length-1);
	}
}

CountryBox.prototype.populateDropDown = function(str) {

	var nn = this.id;

	str = str.toLowerCase();

	var e = $(nn + '-dropdown');

	var pelem = "widgets['" + nn + "']";

	var html = '<div style="width: 100%;">';

	for(var i=0, counter=0;i<this.values.length && (str.length || this.allowEmptySearch);i++) {
	// Country info
		var info = this.values[i];

	// Country code
		var cc = info[0];
	// Country name
		var cname = info[1];
	// Country phone code
		var cphone = info[2];


		var pos = cname.toLowerCase().indexOf(str);

		if (this.showAllItems || pos==0 || (pos>0 && this.matchAnywhere) ) {
			if (pos == 0 && cname.length == str.length) {
				fullMatch = true;
			}

			var line = '';

			if (pos < 0 || !this.markMatched) {
				line = cname;
			}
			else {
				line = markSubstring(cname,pos,str.length);
			}

			var imgsrc = this.imagePath + cc + this.imageExt;
			var imgsize = 'width="'+this.imageWidth+'" height="'+this.imageHeight+'"';
//			line = '<img src="' + imgsrc + '" ' + imgsize + ' />&nbsp;' + line + ' (+' + cphone + ')';
			line = '&nbsp;' + line + ' (+' + cphone + ')';

			var val = cphone; 

			html += this.makeItemHtml(nn + '-item-' + counter, val, line, pelem);
			counter ++;
		}
	}

	html += '</div>';

	this.numItems = counter;
	e.innerHTML = html;

	this.showDropDown(true);

// Select the first item
	if (html) {
		this.itemOver($(nn+'-item-0'));
	}
	else {
		this.selectedItem = null;
	}
}



function ContactsBox(id) {
	if (arguments.length>0) this.init(id);
}

ContactsBox.prototype = new SuggestBox();

ContactsBox.prototype.init = function(id) {
	SuggestBox.prototype.init.call(this,id);
	this.matchAnywhere = true;
	this.allowEmptySearch = true;
	this.incUpdates = false;
	this.showNumbers = true;
}

ContactsBox.prototype.showDropDown = function(visible) {
//	SuggestBox.prototype.showDropDown(nn,visible);
//	e = $('tips');
//	e.style.display = visible ? 'none':'';
}

ContactsBox.prototype.itemClicked = function() {
	if (this.selectedItem) {
	// TODO: uses global variable?
//		alert(this.selectedItem.title);
//		destBox.setValue(this.selectedItem.title);
		this.notifyObservers(this.selectedItem.title);

	// When user selects a contact, give focus to the call button
		//$('callbutton').focus();
	}
}

ContactsBox.prototype.keyItemOver = function(itemId) {
	var item = $(itemId);
	if (item) {
		this.itemOver(item);

		if (item.parentNode && item.parentNode.scrollIntoView) {
			item.parentNode.scrollIntoView(false);
		}
	}
}

ContactsBox.prototype.makeItemHtml = function(id,val,line,pelem) {
	return '<div class="suggest-item" id="' + id + '" ' + 
		'title="' + val + '" ' + 
		'onmouseover="' + pelem + '.itemOver(this)" ' +
		'onmouseout="' + pelem + '.itemOver(null)" ' +
		'onmousedown="' + pelem + '.itemClicked()">' + line + '</div>';
}



ContactsBox.prototype.populateDropDown = function(str) {

	var nn = this.id;

	str = str.toLowerCase();

	var e = $(nn + '-dropdown');

	var pelem = "widgets['" + nn + "']";

	var html = '<table class="tabledialog" width="100%"><tbody>';

	for(var i=0, counter=0, rows=0, ilen = this.values.length; i < ilen && (str.length || this.allowEmptySearch); i++) {

	// Contact info
		var cc = this.values[i];

	// Contact details
		var cname = cc.name;
		var cemail = cc.email;
		var phones = [];
		var ims = [];

		var matchFound = str.length == 0;

	// Phones
		if (cc.phones) {
			var arr = cc.phones.split(',');
			for(var j=0, jlen=arr.length; j < jlen; j++) {
				var td = arr[j].split(':');
				if (td && td.length==2) {
					var spos = td[1].toLowerCase().indexOf(str);
					if (!matchFound) {matchFound = spos >=0;}
					phones[phones.length] = {type: td[0], dest: td[1], spos: spos};
				}
			}
		}

	// IMs
		if (cc.ims) {
			var arr = cc.ims.split(',');
			for(var j=0, jlen=arr.length; j < jlen; j++) {
				var td = arr[j].split(':');
				if (td && td.length==2) {
					var spos = td[1].toLowerCase().indexOf(str);
					if (!matchFound) {matchFound = spos >=0;}
					ims[ims.length] = {type: td[0], dest: td[1], spos: spos};
				}
			}
		}

	// Show the contacts name
		var pname = cname.toLowerCase().indexOf(str);

		var line = '';

		if (this.showAllItems || pname>=0 || matchFound) {

			var className = (rows&1) == 0 ? 'odd' : 'even';
			rows++;


			if (this.showNumbers) {

			html +=  
				'<tr class="' + className + '"><td width="118">' + 
				'<a href="contacts.html#' + cc.uniq + '">' + 
				markSubstring(cname,pname,str.length) + 
				'</a>' +
				'</td>';

			// Phones
			html += '<td width="117">';
			for(var j=0, jlen=phones.length; j < jlen; j++) {
				var t = phones[j];
				line = '+' + markSubstring(t.dest, t.spos, str.length);
				var tlabel = ' (' + t.type.substr(1) + ')';
				html += this.makeItemHtml(nn + '-item-' + counter, '+'+t.dest+' - '+cname+tlabel, line + tlabel, pelem);
				counter++;
			}

			// IMs
			html += '<td width="117">';
			for(var j=0, jlen=ims.length; j < jlen; j++) {
				var t = ims[j];
				line = markSubstring(t.dest, t.spos, str.length);
				var tlabel = ' (' + t.type + ')';
				html += this.makeItemHtml(nn + '-item-' + counter, t.type + ':' + t.dest + ' - ' + cname, line + tlabel, pelem);
				counter++;
			}

			}
			else {
				line = markSubstring(cname,pname,str.length);
				html +=  
					'<tr class="' + className + '"><td>' + 
					this.makeItemHtml(nn + '-item-' + counter, cc.uniq, line, pelem) + 
					'</td>';
				counter++;
			}


			html += '</tr>';
		}
	}

	html += '</tbody></table>';

	this.numItems = counter;
	e.innerHTML = html;

	this.showDropDown(true);

// Select the first item
	if (html) {
		this.itemOver($(nn+'-item-0'));
	}
}


function AsyncComm() {
	this.timerId = 0;
}

AsyncComm.prototype.observedChanged = function(widget,value) {
	if (this.timerId) {
		clearTimeout(this.timerId);
	}
	this.timerId = setTimeout('sendAsyncGetRate()',500);
}

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';


	if (result.error) {
		setStatusLine("Error: "+result.error);
		//setStatusLine('');
	}
	else {
	// 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.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' : 'N/A';
				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) {
			destBox.setData(result.destHistory);
		}

	// New status
		if (result.status) {
			setStatusLine(result.status);
			clearStatusLine(4000);
		}

	// Webphone call token
		if (result.webcalluri) {
			var ap = getWebphoneApplet('webphone');
			if (ap) {
				if (!ap.isInCall()) {
					ap.doCall(result.webcalluri);
					checkWebphoneState(true);
				}
			}
		}
	}

	$('callback_rate').innerHTML = callback_rate;
	$('callback_maxdur').innerHTML = callback_maxdur;
	mainTabs[1].state = callback_state;
	$('local_rate').innerHTML = local_rate;
	$('local_maxdur').innerHTML = local_maxdur;
	mainTabs[2].state = local_state;
	//$('sms_rate').innerHTML = sms_rate;
	//$('sms_maxdur').innerHTML = sms_maxdur;
	_updateSmsCharCount();
	mainTabs[3].state = sms_state;

	actbuttonUpdate();
}

function sendAsyncGetRate() {
	var origPhone = encodeURIComponent(origBox.getPhoneValue());
	var destPhone = encodeURIComponent(destBox.getPhoneValue());
	sendAsyncRequest('index.php?d=async&a=get_rates&orig='+origPhone+'&dest='+destPhone, handleRateResponse);
}

function sendAsyncTriggerCallback() {
	var origPhone = encodeURIComponent(origBox.getPhoneValue());
	var destPhone = encodeURIComponent(destBox.getPhoneValue());
	sendAsyncRequest('index.php?d=async&a=callback&orig='+origPhone+'&dest='+destPhone, handleRateResponse);
}

function sendAsyncWebphoneCall() {
	var destPhone = encodeURIComponent(destBox.getPhoneValue());
	sendAsyncRequest('index.php?d=async&a=webphone_call&dest='+destPhone, handleRateResponse);
}

function sendAsyncSendSMS() {
	var origPhone = encodeURIComponent(origBox.getPhoneValue());
	var destPhone = encodeURIComponent(destBox.getPhoneValue());
	var txt = encodeURIComponent($('smsta').value);
	sendAsyncRequest('index.php?d=async&a=send_sms&orig='+origPhone+'&dest='+destPhone+'&msgtext='+txt, handleRateResponse);
}


function clearContactsSearch() {
	$('contacts').value='';
	contactsBox.populateDropDown('');
}


function doTab(id, visible) {
// Hide all other tabs
	if (visible) {
		for(var i=1;i<=3;i++) {
			if (i!=id) doTab(i,false);
		}
	}

// Tab name
	var tabName = mainTabs[id].name;

// Show/hide rates
	$(tabName+'_rate').style.display=visible?'':'none';
	$(tabName+'_maxdur').style.display=visible?'':'none';

// Show/hide tips
	e = $(tabName+'_tips');
	if (e) e.style.display=visible?'':'none';

	if (visible) {
	// Set the page title
		$('pagetitle').innerHTML = mainTabs[id].getTitle();
	// Update call button
		actbuttonUpdate();
	// Update the receiver of keypad events
		if (id!=1) keypadToOrig = false;
	}


// Tab 1 (Callback)
	if (id==1) {
	// Show/hide 'callfrom' textfield
		var e = $('callfrom');
		e.style.display=visible?'':'none';

	// Show/hide 'keypad'
		e = $('keypad');
		e.style.visibility=visible?'visible':'hidden';
	}
// Tab 2 (Webphone)
	else if (id==2) {
		doApplet('webphone',visible);

	// Show/hide 'keypad'
		e = $('keypad');
		e.style.visibility=visible?'visible':'hidden';
	}
// Tab 3 (SMS)
	else if (id==3) {
	// Show/hide smsfrom text
		var e = $('smsfrom');
		e.style.display=visible?'':'none';

	// Show/hide 'smstext' textearea
		e = $('smstext');
		e.style.display=visible?'':'none';

	// Show char/msg count
		updateSmsCharCount()
	}
}




function getSelectionStart(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', o.value.length)
		if (r.text == '') return o.value.length
		return o.value.lastIndexOf(r.text)
	} else return o.selectionStart
}
 
function getSelectionEnd(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveStart('character', -o.value.length)
		return r.text.length
	} else return o.selectionEnd
}

function setSelectionRange(o, start, end) {
	if (o.setSelectionRange) {
		o.focus();
		o.setSelectionRange(start, end);
	}
	else if (o.createTextRange) {
		var range = o.createTextRange();
		range.collapse(true);
		range.moveEnd('character', end);
		range.moveStart('character', start);
		range.select();
	}
}

function keypad(key) {

// Webphone?
	if (activeMainTab==2)  {
			var ap = getWebphoneApplet('webphone');
			if (ap) {
				if (ap.isInCall()) {
					ap.dtmf(key);
					return;
				}
			}
	}

	var b = keypadToOrig && activeMainTab == 1 ? origBox : destBox;

	var v = b.getValue();
	var elem = $(b.id);
	elem.focus();
	var s = getSelectionStart(elem);
	var e = getSelectionEnd(elem);
	if (document.all) {
		if (s==0 && e==0) {
			s = elem.selStart || elem.selStart=='0' ? elem.selStart : v.length; 
			e = s;
		}
	}
	v = v.substring(0,s) + key + v.substring(e);
	s++;
	b.setValue(v);
	setSelectionRange(elem,s,s);
}

function keypad_backspace() {
	var b = keypadToOrig && activeMainTab == 1 ? origBox : destBox;
	var v = b.getValue();
	if (v.length <= 0) {
		return;
	}

	var elem = $(b.id);
	elem.focus();
	var s = getSelectionStart(elem);
	var e = getSelectionEnd(elem);
	if (document.all) {
		if (s==0 && e==0) {
			s = elem.selStart || elem.selStart=='0' ? elem.selStart : v.length; 
			e = s;
		}
	}
	if (s < e) {
		v = v.substring(0,s) + v.substring(e);
	}
	else if (s > 0) {
		v = v.substring(0,s-1) + v.substring(s);
		s --;
	}
	else {
		return;
	}

	b.setValue(v);
	setSelectionRange(elem,s,s);
}

function keypad_plus() {
	var b = keypadToOrig && activeMainTab == 1 ? origBox : destBox;
	b.setValue(''); 
}

function keypad_clear() {
	var b = keypadToOrig && activeMainTab == 1 ? origBox : destBox;
	var c = keypadToOrig && activeMainTab == 1 ? origCountryBox : destCountryBox;
	b.setValue(c.getValue()); 
}


function setStatusLine(s) {
	var e = $('statusline');
	e.innerHTML = s;
}

function clearStatusLine(delay) {
	setTimeout('setStatusLine("&nbsp;")',delay);
}



function doApplet(div,visible) {

//alert("do applet "+visible);
// IFRAME id
	var iframe = div + 'ifr';

	var d = $(div);

// Applet visible, hide it
	if (!visible && appletShown && appletLoaded) {
		appletShown=false;

		d.className='';

		var i = $(iframe);
		i.style.width="0px";
		i.style.height="0px";
/*
		var idoc = i.contentWindow || i.contentDocument;
		if (idoc.document) {
			idoc = idoc.document;
		}
		var ap = idoc.getElementById('dialer');
		ap.setSize(0,0);
*/
	}
// Applet not visible, show it
	else if (visible && !appletShown) {
		d.className='frombox';

	// Applet already loaded, just make it visible
		if (appletLoaded) {
			var i = $(iframe);
			i.style.width=appletWidth+"px";
			i.style.height=appletHeight+"px";

			var idoc = i.contentWindow || i.contentDocument;
			if (idoc.document) {
				idoc = idoc.document;
			}
			var ap = idoc.getElementById('dialer');
//alert(ap);
			try {
				if (ap && ap.isActive()) {
					ap.setSize(appletWidth,appletHeight);
				}
			}
			catch(e) {}
		}
	// Load the applet via an iframe
		else {
			d.innerHTML = '<ifra' + 'me id="'+iframe+'" frameborder="0" ' + 
				'marginwidth="0" margenheight="0" scrolling="no" ' + 
				'src="?d=wphone" allowtransparency="true" ' +
				'width="'+appletWidth+'" height="'+appletHeight+'" class="bg_webphone"' +
				'</ifr' + 'ame>';
			appletLoaded = true;
		}
		appletShown=true;
	}
}

function getWebphoneApplet(div) {

// iframe containing the applet document
	var iframe = div + 'ifr';
	var i = $(iframe);
	if (!i) return null;

// document that contains the applet
	var idoc = i.contentWindow || i.contentDocument;
	if (idoc.document) {
		idoc = idoc.document;
	}

// The applet
// TODO: what if the applet cannot be loaded?
	var ap = idoc.getElementById('dialer');

	return ap;
}

function actbuttonUpdate() {
	var state = actbuttonGetState();
	var bvalue = mainTabs[activeMainTab].buttonLabel;
	var bclass = 'button_pink' + (state=='d' ? ' disabled' : '');
	var btn = $('actbutton');
	if (btn.className != bclass) {btn.className = bclass;}
	if (btn.value != bvalue) {btn.value = bvalue;}
}

function actbuttonGetState() {
	return actbuttonTempDisabled ? 'd' : mainTabs[activeMainTab].state;
}

function actbuttonSetState(state) {
	var old = mainTabs[activeMainTab].state;
	if (old!='d' && old!=state) {
		mainTabs[activeMainTab].state = state;
		actbuttonUpdate()
	}
}

function actbuttonSetLabel(id, bvalue) {
	if (bvalue != mainTabs[id].buttonLabel) {
		mainTabs[id].buttonLabel = bvalue;
		if (id == activeMainTab) {
			actbuttonUpdate()
		}
	}
}

function actbuttonTempDisable(flag) {
	actbuttonTempDisabled = flag;
	actbuttonUpdate();
	if (flag) {
		setTimeout("actbuttonTempDisable(false);",3000);
	}
}

function actbuttonOver(e,over) {
	actbuttonSetState(over ? 'o':'n');
}

function actbuttonDown(e,down) {
	actbuttonSetState(down ? 'a':'o');
}

function actbuttonClick(e) {
	if (actbuttonGetState() == 'd') return false;

//	alert("ActButtonA "+activeMainTab+" clicked!");

	switch(1 * activeMainTab) {
	// Web callback
		case 1:
			actbuttonTempDisable(true);
			setStatusLine("Starting the call...");
			sendAsyncTriggerCallback();
			break;
	// Web phone
		case 2:
			var ap = getWebphoneApplet('webphone');
			if (ap) {
				if (ap.isInCall()) {
					setStatusLine("Hanging up...");
					ap.doHangup();
				}
				else {
					setStatusLine("Starting the call...");
					sendAsyncWebphoneCall();
				}
			}
			else {
				setStatusLine("Could not find WebPhone");
			}
			break;
	// Send SMS
		case 3:
			actbuttonTempDisable(true);
			setStatusLine("Sending...");
			sendAsyncSendSMS();
			break;
	}
	//alert("ActButtonB "+activeMainTab+" clicked!");
}

// Called from the webphone applet/iframe
function webphoneInCall(flag) {
	setStatusLine("In Call: "+flag);
}

function checkWebphoneState(firstTime) {
	var repeat = firstTime;

	if (!firstTime) {
		var ap = getWebphoneApplet('webphone');
		if (ap) {
			repeat = ap.isInCall();
		}
	}

	var status = repeat ? "Calling..." : "Call ended";
	setStatusLine(status);

	actbuttonSetLabel(2, repeat ? 'hangup' : 'call');

	if (repeat) {
		setTimeout("checkWebphoneState(false)",500);
	}
	else {
		clearStatusLine(4000);
	}
}

function updateSmsCharCount() {
	if (activeMainTab!=3) return;
	setTimeout("_updateSmsCharCount()",100);
}

function _updateSmsCharCount() {

	var ta = $('smsta');
	var s = ta.value;
	var len = s.length;

	var oneSmsChars = 160;
	var smsCount = 1;
	var maxChars = 0;

	if (smsFreeTest) {oneSmsChars -= 24;}

	if (smsMaxMessages>0) {
		maxChars = smsMaxMessages==1 ? oneSmsChars : smsMaxMessages * 153;
	}

	if (len > oneSmsChars) {
		if (len >= maxChars) {
			ta.value = s.substring(0,maxChars);
			len = maxChars;
			smsCount = smsMaxMessages;
		}
		else {
			smsCount = parseInt(len / 153) + 1;
		}
	}

	$('sms_rate').innerHTML = (smsMaxMessages>1 ? smsCount + ' x ' : '') + smsRate;
	$('sms_maxdur').innerHTML = len + ' / ' + maxChars;
}

function main_window_onmousedown(event) {
	if (!event) event=window.event;
	var e = event.target ? event.target : event.srcElement;

	if (e && (!e.id || !widgets[e.id])) closeDropDowns();
}

function main_window_onload() {
// Show the contacts list
	if (contactsBox) {
		contactsBox.populateDropDown('');
	}

// Set default from/to phones
	var orig = origPhone ? origPhone : (origBox.values.length ? origBox.values[0]: defaultCountryCode); 
	origBox.setValue(orig);

	var dest = destPhone ? destPhone : (destBox.values.length ? destBox.values[0]: defaultCountryCode); 
	destBox.setValue(dest);

	var comm = new AsyncComm();
	origBox.addObserver(comm);
	destBox.addObserver(comm);

// Show initial Tab
	doTab(activeMainTab,true);

// Get the first rates
	sendAsyncGetRate();
}



