# Surgeweb addressbook handling
# -----------------------------
# This file should pull out all the generic addressbook management, autocompletion and address picker functionality
# out of the normal surgeweb code into a reusable module ...
# -----------------------------
# Logical groupings:
# rcpt_picker: Address search and pick dialog. prereq: has address_book info
# rcpt_lister: Fancy address listing field
# -----------------------------

# *** Actual addressbook / contactlist implementation ***
# --- implementation: Addressbook searching, indexing, on demand search implementation ---
// Move from x_abk_*.js files
#var address_book;
#address_book.data=[];
#address_book.groups=[];

var abooks={};


function books_list(rb,wb)
{
	// Old storage
	sw.abooks_old=rb;
	sw.abooks_write=wb;
#	address_book.groups=[];
	
	// New storage
	abooks.read_books=rb;
	abooks.write_books=wb;
	abooks.groups_fake={};
	for(var i=0;i<rb.length;i++){
		var bk=abooks[rb[i]]={};
		bk.data=[];
		bk.realcount=0;
		bk.groups={};
		bk.options={};
		bk.name=rb[i];
#		bk.ac_order=[];
	}
}


# Append or update addressbook entry
function abook_entry(cid,c,late_add)
{
	var abk, item;
	// old storage
#	if(cid.length==0){
#		address_book.data.push(c);
#		if(late_add){
#// QQQ
#//			add_to_picker('User',address__book.data.length-1);
#//			address__book.ac_order.push(address__book.data.length-1);
#		}
#	}else{
#		address_book.data[cid]=c;
#	}

	// new storage
	if(cid.length==0){
		if(c.webmail) c.abook='User';
		if(!c.abook || !abooks[c.abook] ||!abooks[c.abook].data){
			// CQQQ catches webmail read only currently
			return
		}
		abk=abooks[c.abook];
		abk.data.push(c);
		item=abk.data.length-1;
		if(!c.isgroup) abk.realcount++;
		if(late_add && c.abook=='User'){
			add_to_picker('User',item);
			abk.ac_order.push(item);
		}
		if(late_add && c.groups){
			var arr=c.groups.split(',');
			for(var i=0;i<arr.length;i++){
				g=group_find(abk,arr[i]);
				if(!g) continue;
				if(g.isfake && !g.isfav) continue;
				g.contacts.push(item);
			}
		}
	}else{
		abooks[c.abook].data[cid]=c;
	}	
}
function abook_entry_group(g,contact_ids)
{
//	if(g.abook.length==0) return;
	
	// old storage
    g.is_group=true;
    g.contacts = contact_ids.split(',');
    if (g.contacts.length==1 && g.contacts[0]=='') 
    	g.contacts=[];

	// new storage
	if (g.isfake)
		abooks.groups_fake[g.name]=g;
	else
		abooks[g.abook].groups[g.name]=g;
}
function abook_ac_order(arr)
{
	// old storage
#	address__book.ac_order=arr;
	
	// new storage
	abooks['User'].ac_order=arr;	
	if(pref.ac_max) max_adr=pref.ac_max;
}

# access to contact descriptive strings
function c_name_string(c,noco)
{
	var co=(c.company?val(c.company.value):'');
	var first=(c.name?val(c.name.first):'');
	var last=(c.name?val(c.name.last):'');
	var email=(c.email?c.email[0].value:'');
	var srch=first+last+email+co;
	var txt='',hint='';
	
	if(c.file_by_co && co.length>0){
		if(noco){
			txt=first+' '+last; hint=co;
		}else{
			txt='<b>'+co+'</b>'; hint=first+' '+last;
		}
	}else if (last.length>0){
		txt=first+' <b>'+last+'</b>';
		hint=co;
	}else if (first.length>0){
		txt='<b>'+ first+'</b>';
		hint=co;
	}else if (c.email && email){
		txt='<b>'+email+'</b>';
		hint=co;
	}else {
		txt='$$st_ct_name_invalid$$';
	}
	return '<span src="'+srch+'" title="'+hint+'">'+txt+'</span>';
}
function c_name(c)
{
	var name;
	var first=(c.name?val(c.name.first):'');
	var last=(c.name?val(c.name.last):'');
	if (last.length>0){
		name=first+' '+last;
	}else{
		name=first;
	}
#	This is getting a bit messy but this covers most cases now (maybe tidy up at some stage)
	if((name.indexOf(',')!=-1 || name.indexOf(';')!=-1)&&(name.substring(0,1)!='"'))
		name='"'+name+'"';
	return name;
}
function c_name_co(c)
{
	var name = c_name(c);
	var co=(c.company?val(c.company.value):'');
	return (c.file_by_co || name=='') ? co : name;	
}
function c_email(c,i)
{
	if(!i) i=0;
	if(c.email && c.email[i] &&c.email[i].value)
		return c.email[i].value;
	return '';
}
function c_email_x(c,i)
{
	if(!i) i=0;
	if(!c.email || !c.email[i] || !c.email[i].value) return ''
	var txt=c.email[i].value;
	if(c.email.length>1 && c.email[i].type)
		txt+='&nbsp;<span class="g">('+c.email[i].type+')</span>';
	return txt;
}
function c_phone_x(c,i)
{
	if(!i) i=0;
	if(!c.phone || !c.phone[i] || !c.phone[i].value) return ''
	var txt=c.phone[i].value;
	if(c.phone.length>1 && c.phone[i].type)
		txt+='&nbsp;<span class="g">('+c.phone[i].type+')</span>';
	return txt;
}
function contact_string_full(c)
{
	var first=(c.name?val(c.name.first):'');
	var last=(c.name?val(c.name.last):'');
	var email=(c.email?val(c.email[0].value):'');
	if(first.length==0 && last.length==0)	
		return email;
	if(email.length==0)
		return first+' '+last;
	return first+''+last+' &lt;'+email+'&gt;';
}
function contact_string_short(c)
{
	var first=(c.name?val(c.name.first):'');
	var last=(c.name?val(c.name.last):'');
	var email=(c.email?val(c.email[0].value):'');
	if(first.length>0 || last.length>0)	
		return first+' '+last;
	if(email.length>0)	
		return email;			
	return '$$st_ct_name_invalid2$$';
}




function c_name_new(txt)
{
	return {'first':txt,'last':''}
}
function c_email_new(txt)
{
	return [{'type':'work','value':txt}]
}

function cp_mformat_address(c,i,type,fav)
{
	if(c.email && c.email.length>1){
		fav.push(cp_format_address(c,i,0,type,true));
		for(var n=1;n<c.email.length;n++){
			fav.push(cp_format_address(c,i,n,type,undefined,true));										
		}
		fav.push('</div>');
	}else{
		fav.push(cp_format_address(c,i,0,type));
	}
}


# *** implementation: cp_* (Contact Picker) ***
function cp_format_address(c,i,n_email,type,parent,child)
{
	return  '<div class="'+(parent?'xrow_subcontainer closed':'xrow_container')+(child?' hidden':'')+'"><div class="xrow" onclick="cp_select(this,event)" cp_abk="'+c.abook+'" cp_cid="'+i+'" cp_n="'+n_email+'">'\
			  +'<div class="xright">'
			  	+(c.shared?'<div class="cm_extra" title="$$st_ct_picker_shared$$">S</div>':'')
			  	+(c.webmail?'<div class="cm_extra" title="$$st_ct_picker_web$$">W</div>':'')+'</div>'
			  +'<div class="xcol1">'+(parent?'<img src="||www_base||shared/img/1pixel.gif" class="xtog" onclick="xrow_toggle(this,event)">':'&nbsp;')+'</div>'
			  +'<div class="xcol2"><input id="'+type+'_'+c.abook+'_'+i+'" type="checkbox"></div>'
			  +'<div class="xcol3">'+(child?'<span style="color:#999">':'')+c_name_string(c,true)+(child?'</span>':'')+'</div>'
			  +'<div class="xcol4">'+c_email(c,n_email)+'</div>'
		  	  +'</div>'+(parent?'':'</div>');
}
function cp_format_group(g)
{
	return '<div class="xrow_subcontainer closed" onclick="cp_select(this,event)" cp_abk="'+g.abook+'" grp_name="'+g.name+'">'+
		   '<div class="xrow">'+
			'<div class="xright">'
			  	+(g.shared?'<div class="cm_extra" title="$$st_ct_picker_shared$$">S</div>':'')
			  	+(g.webmail?'<div class="cm_extra" title="$$st_ct_picker_web$$">W</div>':'')+'</div>'+
			'<div class="xcol1"><img src="||www_base||shared/img/1pixel.gif" class="xtog" onclick="xrow_toggle(this,event)"></div>'+
			'<div class="xcol2"><input type="checkbox"></div>'+
			'<div class="xcol3"><b style="font-size:1.1em">'+g.name+'</b></div>'+
			'<div class="xcol4">'+g.contacts.length+' $$st_ct_contacts$$</div>'+
		   '</div>';
}
function cp_format_group_address(c,i,type)
{
	return 	'<div class="xrow_container hidden" >'+
			   '<div class="xrow" cp_abk="'+c.abook+'" cp_cid="'+i+'">'+
				 '<div class="xright"></div>'+
				 '<div class="xcol1">&nbsp;</div>'+
				 '<div class="xcol2">&nbsp;</div>'+
				 '<div class="xcol3">'+c_name_string(c)+'</div>'+
				 '<div class="xcol4">'+c_email(c)+'</div>'+
			   '</div>'+
			 '</div>';
}
function cp_format_abook(name)
{
	return '<div class="xrow_container shared_abook">'+name+'</div>'
}
function cp_format_abook2(name)
{
	return '<div class="xrow_container" style="color:green; border-top:1px solid black;">'+name+'</div>'
}
function cp_format_abook3(name)
{
	return '<li class="xrow_container shared_abook3">'+name+'</li>'
}

function cp_output_group(arr,g)
{
	if(g.contacts.length==0) return;
	arr.push(cp_format_group(g));

	for (j=0;j<g.contacts.length;j++){
		var c=abooks[g.abook].data[g.contacts[j]];
		if (!c) continue;
		arr.push(cp_format_group_address(c,g.contacts[j]));										
	}
	arr.push('</div>');
}


# Fill add real data 
function cp_init(ctl_id)
{
	var i,j,g;
	var arr=[],fav=[];
	for (i=0;i<abooks['User'].data.length;i++){
		var c=abooks['User'].data[i];
		if(c.isfav&&!c.isgroup) {
			cp_mformat_address(c,i,'cpf',fav);										
		}
		if(c.isgroup) continue;
		cp_mformat_address(c,i,'cpc',arr);
	}
	dge('ct_contacts_body').innerHTML=arr.join('');
	var txt=fav.join('');
	if (txt.length>0) dge('ct_favs_body').innerHTML=txt;	
	
	var arr=[];
	
	for (ii in abooks['User'].groups){
		g=abooks['User'].groups[ii];
		if(g.isfav) {continue;}
		cp_output_group(arr,g);
	}
	
	var rb=abooks.read_books;
	for(i=0;i<rb.length;i++){
		var abk=abooks[rb[i]];
		if (abk.name=="User") continue;
		var donesome=false;
		for (ii in abk.groups){
			g=abk.groups[ii];
			if(!donesome){
				arr.push('<div class="xrow_container shared_abook">$$st_ct_grp_dir$$ '+g.abook+'</div>');
				donesome=true;
			}
			cp_output_group(arr,g);
		}
	}
	
	dge('ct_groups_body').innerHTML=arr.join('');
	
	cp_fill_directory();
}

function add_to_picker(abook,i)
{
	if(abook!='User') return;	//QQQ added??
	
	var c=abooks[abook].data[i];

	var a=new_anchor('div',cp_format_address(c,i,0,'cpf'));
	dge('ct_favs_body').appendChild(a.firstChild);
	a.parentNode.removeChild(a);

	var a=new_anchor('div',cp_format_address(c,i,0,'cpc'));
	dge('ct_contacts_body').appendChild(a.firstChild);
	a.parentNode.removeChild(a);
}


function cp_show(ctl_id)
{
	var cp=dge('contacts_picker');
	var ctl=dge(ctl_id);

	if(sw.is_popup && !cp){
		cp=new_anchor('div',sw_win.dge('contacts_picker_anchor').innerHTML);
		cp=cp.firstChild;
	}
	if(!cp){	// or no data??
		set_status('$$st_stat_ct_notready$$',"warning");
		return;
	}
#	Unselect and reselect when switching fields
	if (cp.current_ctl!=ctl){
		if (cp.current_ctl){
			for(var li=cp.current_ctl.edit_li;li;li=li.previousSibling){
				if(li.mgr) cp_select_cb(li.mgr.cp_node,false);
			}				
		}		
		for(var li=ctl.edit_li;li;li=li.previousSibling){
			if(li.mgr) cp_select_cb(li.mgr.cp_node,true);
		}				
	}
	if (!cp.active_tab)
		cp_seltab('ct_favs');
	
	class_remove(cp,'hidden');	
#	pos_dropdown_by_ctl(cp,ctl)	
	menu_position(ctl,cp);
	cp.current_ctl=ctl;
}

function cp_select(el,e)
{
	cmgr_cp_select(e,el,el.selected!=true);
}
// Contact picker selection function designed to be called by cmgr to keep cp & cl in sync
function cp_select_cb(el,sel)
{
	if(sel){
		class_add(el,'selected');
		el.selected=true;
		xrow2sel(el).checked=true;
	}else{
		class_remove(el,'selected');
		el.selected=false;
		xrow2sel(el).checked=false;
	}
}




function xrow2sel(el)
{
	if(!el) return null;
	if (class_contains(el,'xrow_subcontainer'))
		return el.firstChild.firstChild.nextSibling.nextSibling.firstChild;
	else
		return el.firstChild.nextSibling.nextSibling.firstChild;
}

function cp_seltab(new_tab)
{
	var el=dge('contacts_picker');
	if (el.active_tab && el.active_tab.length>0){
		class_remove(dge(el.active_tab),'selected');
		class_add(dge(el.active_tab+'_body'),'hidden');
		var s=dge('cp_search');
		if (s.value!='' && s.value.indexOf('$$st_ct_search$$')==-1){
			s.value='';
			contact_search_do(s);
			s.value='$$st_ct_search$$';
		}
	}

	class_add(dge(new_tab),'selected');
	class_remove(dge(new_tab+'_body'),'hidden');
	el.active_tab=new_tab;
	
#	el=dge('cp_directories');
#	if(new_tab=='ct_dir')
#		class_remove(el,'hidden');
#	else
#		class_add(el,'hidden');
}

function cp_close(e)
{
#	dge('dlg_ovrl').style.display = 'none';
	var el=dge('contacts_picker');
	class_add(el,'hidden');
	stopEvent(e)
}

# *** implementation: cl_* (Contact Lister) ***
function cl_add_contact(c,n,location)
{
	if(!c){c=new Object;}
	if (!location) alert("location unknown");
	var node=new_anchor4('li','txt',location);
	if (c.group){
		var name=c_name(c);
		node.className=contact_colour(U,c,name);	// QQQLOCK
		node.innerHTML='<img src="||www_base||shared/img/1pixel.gif" class="rcpt_expand" onclick="cl_expand(this,event)" title="$$st_ct_picker_expand$$"><span>'+
					   '<b>'+name+'</b></span>'+
					   '<img src="||www_base||shared/img/1pixel.gif" class="rcpt_remove" onclick="cl_remove(this,event)" title="$$st_ct_picker_remove$$">';
		node.email=c_name(c);
	}else{
		var name=c_name(c);
		var email=c_email(c,n);
		
		contact_populate(c,email,name);
		if(pref.vault_lock){
			toggle_encrypt_vaultlock(!c.vaultsafe);
		}
		node.className=contact_colour(email,c,U);	// QQQLOCK
		cl_node_update(node,email,name);
		vcheck_add(node, c.vaultsafe);
	}
	return node;
}
function cl_node_update(node,email,name)
{
	var email2=email;
	if (name.length>0 && email.length>0 ){
		if(name==email){
			name='';
		}else{
			email2='&lt;'+email+'&gt;';
		}
	}
	node.innerHTML='<span oncontextmenu="cl_click(this,event)"><span>'+name+'</span>&nbsp;<span>'+email2+'</span></span><img src="||www_base||shared/img/1pixel.gif" class="rcpt_remove" onclick="cl_remove(this,event)" title="$$st_ct_picker_remove$$">';
	node.email=name+'<'+email+'>';
	node.name_only=name;
	node.email_only=email;
}

function cl_remove(el,e)
{
	var el=target(e);
	el=ancestor_by_tag(el,'li');
	cl_remove_el(el,e);
	cl_refresh_vaultlock();
}
#	If no manager do the removal ourselves else delegate to manager
function cl_remove_el(el,e)
{
	if (!el.mgr)
		cl_remove_cb(el);
	else
		cmgr_cl_remove(e,el);
}
function cl_remove_cb(el)
{
	var o=el.parentNode;
	o.removeChild(el);
	cl_setfocus(o);
}

function cl_refresh_vaultlock()
{
	if(!pref.vault_lock) return;
	vcheck_update_icon(dge('send_encrypt'));
}
var cx_contact;
function cl_click(el,e)
{
	var el=target(e);
	el=ancestor_by_tag(el,'li');
	cx_contact=el;
	var mnu = 'context_menu_contact';
	if(pref.vault_lock){
		valid = !class_contains(el,'rcpt_invalid');
		show_hide2(dge(mnu+'_lock'),valid);
		show_hide2(dge(mnu+'_unlock'),!valid);
	}
	do_menu_show(mnu,e,undefined,undefined,{cursor:true})
	stopEvent(e);
}
function cx_menu_contact(type,node)
{
	var eml = cx_contact.email_only; 
	var nm = cx_contact.name_only;
	switch (type){
		case 'remove': 
			cl_remove_el(cx_contact); 
			break;
		case 'send': 
			contact_click_send(eml,nm); 
			break;
		case 'add':
			contact_click_add(eml,nm); 
			break;
		case 'vaultunlock':
#			class_ra(cx_contact,'rcpt_invalid','rcpt_valid');
			contact_vault_update(cx_contact,type); 	
			break;			
		case 'vaultlock': 
#			class_ra(cx_contact,'rcpt_valid','rcpt_invalid')
			contact_vault_update(cx_contact,type);
			break;			
		case 'copy1':
			copy_popup(eml)
			break;
		case 'copy2':
			copy_popup(sw_format_address(nm, eml));
			break;
		case 'edit':
			edit_popup(node,cx_contact,sw_format_address(nm, eml));
			break;
	}
}

function cl_expand(el,e)
{
	var el=target(e);
	el=ancestor_by_tag(el,'li');
	cmgr_cl_expand(e,el);
}

function cmgr_cl_expand(e,clx)
{
	var cpx=clx.mgr.cp_node;		

	for (cpp=cpx.firstChild.nextSibling;cpp;cpp=cpp.nextSibling){
		var el=cpp.firstChild;
		var id=el.getAttribute('cp_cid');
		var abook=el.getAttribute('cp_abk');
		c=abooks[abook].data[id];
		var cp=dge('cpc_'+abook+'_'+id).parentNode.parentNode;
		if (cp.selected) continue;
		cl=cl_add_contact(c,el.getAttribute('cp_n'),clx);
		cp_select_cb(cp,true);
		var m=new Object;
		m.cp_node=cp;
		m.cl_node=cl;		
		cp.mgr = cl.mgr = m;		
	}
	vcheck_run();
	cpx.mgr=null;
	clx.mgr=null;
	cl_remove_cb(clx);
	cp_select_cb(cpx,false);	
}

function cl_onkeydown(ctl,e)
{	
	var el=target(e);
	el=ancestor_by_tag(el,'li');

	switch(e.keyCode){
		case 8:
			if(ctl.value=='' && el.previousSibling){
				cl_remove_el(el.previousSibling,e);
				cl_refresh_vaultlock();
			}
			break

		case 188: // COMMA
		case 186: // SEMICOLON
			if (e.shiftKey) break;			
			// drop through to tab
#		Enter
		case 13:
#		Tab
		case 9:
			if (ctl.value!='' && !autocomplete.active){
				var entries, c;
				var arr=split_to_addresses(ctl.value);
				for(var i=0;i<arr.length;i++){
					var node=cl_add_contact(text2contact(arr[i]),0,el);	//QQQLOCK
					if(sw.is_popup){
						c=sw_win.ac_lookup_string(arr[i], sw_win.abooks, autocomplete);
					}else{
						c=ac_lookup_string(arr[i], abooks, autocomplete);
					}
					node.className = contact_colour(U,c,U);
					ctl.value='';
				}
				vcheck_run();
				hcheck_trigger();
				stopEvent(e);
			}
			break;
		default:
	}
	resize_me(ctl,e);
}
function cl_onkeyup(ctl,e)
{	
	switch(e.keyCode){
		default:
	}
}
function cl_onpaste(ctl,e)
{	
#	alert("paste");
	setTimeout(function(){resize_me(ctl)},1);
}

function contact_colour(email,contact,group)
{
	if(pref.vault_lock){
		if(contact && contact.vaultsafe) return 'rcpt_valid';
		return 'rcpt_invalid';
	}else{
		if(contact==U) 	return 'rcpt_invalid';
		return 'rcpt_valid';
	}
}

function cl_update_contact(cx_contact,c2)
{
	cl_node_update(cx_contact,c_email(c2),c_name(c2));
}

# *** implementation: cmgr_* (Contact Manager) - syncronises contact picker and contact lister updates ***

function cp_to_groupname(cp)
{
	var abook=cp.getAttribute('cp_abk');
	var gid=cp.getAttribute('grp_name');
	if(abook=="User") return gid;
	return gid+' ('+abook+')';
}

# Add a selected contact
function cmgr_cp_select(e,cp,sel)
{
	if(sel){
		var m=new Object;
		var id=cp.getAttribute('cp_cid');
		if(id){
			c=abooks[cp.getAttribute('cp_abk')].data[id];
		}else{
			c=text2contact(cp_to_groupname(cp),true);
		}
		var o=cp;
		while(o.id!='contacts_picker') o=o.parentNode;
		var cl=cl_add_contact(c,cp.getAttribute('cp_n'),o.current_ctl.edit_li);
		m.cp_node=cp;
		m.cl_node=cl;		
		cp.mgr = cl.mgr = m;	
		vcheck_run();
	}else{
		var cl=cp.mgr.cl_node;		
		cp.mgr=null;
		cl.mgr=null;
		cl_remove_cb(cl);
	}
# 	Toggle selection on the picker
	cp_select_cb(cp,sel);	
}

# Remove a selected address
function cmgr_cl_remove(e,cl)
{
	var cp=cl.mgr.cp_node;		
	cp.mgr=null;
	cl.mgr=null;
	cl_remove_cb(cl);
	cp_select_cb(cp,false);	
}


function cl_outer_onclick(ctl,e)
{	
	cl_setfocus(ctl);
}

function cl_setfocus(el)
{	
	while(!el.edit_li) el=el.parentNode;
	el.edit_li.firstChild.focus();
}

function text2contact(txt,group)
{
	var x;
	var c=new Object;

	if(group){
		c.group=true;
		c.name=c_name_new(txt);
	}else{
#		parse address etc
		if (txt.indexOf('<')!=-1){
			if(txt.indexOf(' <')!=-1){
				x=txt.split(' <');
			}else{
				x=txt.split('<');
			}
			c.name = c_name_new(x[0]);
			var y=x[1].split('>');
			c.email = c_email_new(y[0]);
		}else{
			c.name=c_name_new(txt);
			c.email=c_email_new(txt);
		}
	}
	return c;
}
function contact_populate(c,email,name)
{
	if(!pref.vault_lock) return;
# 	bother we need real contact entry to generate extra info
	var real_c=abk_match_addresses(abooks,name,email);
	if(!real_c || real_c.length==0) return;
	c.vaultsafe = real_c[0].c.vaultsafe;
}

function measure_text(o,txt)
{
	if (txt == " " || txt == "") return 50;
	o.innerHTML=txt;
	return o.offsetWidth+25;
}

function resize_me(ctl,event){
	var x=measure_text(ctl.ruler,encode_lt_gt(ctl.value));
	ctl.style.width=px(x);
}






# *** implementation: Autocompletion dialog implementation ***
// Still part of x_abk_*.js files

# *** implementation: Stuff for moving out of generic module... ***




#*** OLD STUFF  **

#	init_autocomplete();
function x_ac_pageload(){
	var x;
	if(true){
		x=sw.active.field_to; 
		if (x) ac_register_ctl(x, "default source");	
		x=sw.active.field_cc; 
		if (x) ac_register_ctl(x, "default source");	
		x=sw.active.field_bcc; 
		if (x) ac_register_ctl(x, "default source");	
		autocomplete.selected=0;
	}
	if(sw.is_popup) abooks=sw_win.abooks;
	
}



function contact_search_clear(ctl,e)
{
	if(ctl.value.indexOf("Search") != -1){
		ctl.value="";
	}
}

function contact_search_do(ctl,e)
{
	setTimeout(function(){contact_search_real(ctl)},10);
}	
function contact_search_real(ctl)
{
	var match=ctl.value.toLowerCase();
	var cp=dge("contacts_picker");

#	if(cp.active_tab=='ct_dir'){
#		return seach_now_isbig(match)
#	}
	
	var tab=dge(cp.active_tab+'_body')
	class_add(tab,'hidden');
	for(row=tab.firstChild;row;row=row.nextSibling){
		if(class_contains(row,'shared_abook') || class_contains(row,'isbig')){
            class_remove(row,"hidden");
			if(!class_contains(row,'isbig')) continue;
			btn=row.getElementsByTagName('input')[0];
			if(match.length==0){
				btn.disabled=true;
				row_to_isbigresults(row).innerHTML='';
			}else{
				btn.disabled=false;
			}
            continue;
		}
		
		x=row.innerHTML.toLowerCase();
        if(x.indexOf(match)!=-1){
            class_remove(row,"hidden");
        }else{
	        class_add(row,"hidden");
        }
    }
   	class_remove(tab,'hidden');
}



# ***************************************
# ** Contacts management page ***
# ***************************************

function lang_group(g)
{
	if (g=='Favorites') return '$$st_ct_favs$$';
	if (g=='All Contacts') return '$$st_ct_all$$';
	if (g=='All Addresses') return '$$st_ct_all_addresses$$';
	if (g=='Last Import') return '$$st_ct_last_import$$';
	return g;
}

// Ok this function basically does what it needs to (still needs tidying) now lets look at the dynamic behaviour...
function contacts_init()
{
	var i;
	var arr=['<ul id="gtree" class="gtree ftree">'];

	if(abooks.read_books.length==1){
		contacts_output_abooks(arr,'User');
	}else{
		arr.push(cp_format_abook3('$$st_ct_personal$$'));
		contacts_output_abooks(arr,'User')
		arr.push(cp_format_abook3('$$st_ct_directories$$'));
		for(var i=0;i<abooks.read_books.length;i++){
			abook=abooks.read_books[i];
			if(abook=='User') continue;
			contacts_output_abooks(arr,abook,i)		
		}
 	 	arr.push('</ul>');
	}
	dge('cm_groups').innerHTML=arr.join('');
	dge('cm_details').innerHTML="$$st_ct_sel_detail$$";
	cm_reselect_group();
	dnd2_init();
}

function contacts_output_groupitem(arr,g,n,editable)
{
	var txt_color,icons_etc;
	var top_groups='', extra='',evt='';

	if(!g) return;
	if(!g.isfake && g.name==g.abook) return;
	
	if(g.webmail) extra='<div class="cm_extra" title="$$st_ct_info_webmail_tt$$">W</div>';
	if(!g.nodelete&&!g.shared) extra='<img src="||www_base||shared/img/1pixel.gif" class="delete_contact" title="$$st_ct_info_delgrp_tt$$" onclick="contact_delete_group(event)">';			
	
	if(g.ftree_node=='open'|| g.ftree_node=='closed') evt='onclick="return fld_expand(event)"';

	txt_color=(g.ftree_icon=='group_icon'?'color:#0066CC;':'');
	icons_etc='<div class="tree_icons folder_icons_top"><div class="tog" '+evt+'></div><div class="'+g.ftree_icon+'"></div></div>';
	if(g.isfake&&!g.isabook) top_groups=' tog_save';
	if(!n) n=0;
	if(g.contacts.length>0) n=g.contacts.length;
	if(g.isabook) n=abooks[g.abook].data.length;


	arr.push('<li class="cm_group '+g.ftree_node+top_groups+'" cm_abook="'+g.abook+'" cm_gid="'+g.name+'">');
	arr.push('<div class="full_cursor" style="padding-left:'+(g.level*16)+'px;">');
	arr.push('<span class="cm_right" style="">'+extra+'</span>'+icons_etc);
	arr.push('<div class="part_cursor _folder'+(g.level==-1?' top_lev_folder':'')+'" style="white-space:normal;'+txt_color+'">'+lang_group(g.name));
	arr.push('<span class="cm_count">'+(n>0?' ('+n+')':'')+'</span>');
	arr.push(editable?'<span style="color:#8b8"> $$st_ct_editable$$</span>':'');
	arr.push('</div></div>');
}
function contacts_output_abooks(arr,abook,item)
{
	var abk=abooks[abook],g;
	if(abook=="User"){
		contacts_output_groupitem(arr,abooks.groups_fake['Favorites'])
		contacts_output_groupitem(arr,abooks.groups_fake['All Contacts'],abk.realcount)
		arr.push('<ul>');
		for (i in abk.groups){
			g=abk.groups[i];
			if(g.linked) continue;		
			contacts_output_groupitem(arr,abk.groups[i]);
		}
		arr.push('</ul>');
	}else{
		if(item==1){
			var n=0
			for(var i=0;i<abooks.read_books.length;i++){
				bk=abooks.read_books[i];
				if(bk=='User') continue;
				n+=abooks[bk].realcount;
			}
			contacts_output_groupitem(arr,abooks.groups_fake["All Addresses"],n)
			arr.push('<ul>');
		}
		contacts_output_groupitem(arr,abooks.groups_fake[abk.name],U,in_array(abk.name,sw.abooks_write));
		arr.push('<ul>');
		for (i in abk.groups){
			contacts_output_groupitem(arr,abk.groups[i]);
		}
		arr.push('</ul>');
	}
}


function cm_groups_to_selected(outer,sel_name)
{
	var i,groups,gid,el,bak=null;
	if(!outer||!outer.childNodes.length>0) return null;
	groups=outer.getElementsByTagName('li');
	for(i=0;i<groups.length;i++){
		el=groups[i];
		gid=el.getAttribute('cm_gid');
		if(gid && gid==sel_name)
			return el;
		if(gid=='All Contacts')
			bak=el;
	}	
	return bak;
}


function cm_reselect_group()
{
	var el=cm_groups_to_selected(dge("cm_groups"),cm_cur_group);	
	dispatch_click(el);
}

function contacts_resize(h,w)
{
	if (sw.active.id!='contacts_panel') return;
	dbg("resizing contacts id="+sw.active.id+"h="+h+' w='+w);

# 	height of left panel	
	var o=dge('cm_contacts').parentNode;
	var s=o.style;
	s.height=px(h);
#	s.width=px(w*0.3);
	s.width=px(pref.sizer1*1.2);

#	s=dge('cm_details').style;
#	s.marginLeft=px(w*0.3);
#	s.marginLeft=px(pref.sizer1*1.2);
#	height of 2 right panels
	o=dge('cm_details').parentNode;
	o.style.height=px(h);
	var o=dge('contacts_info');
	o.style.height=px(h);
}
function cm_contact_string(c)
{
	return c_name_string(c);	
}

function cm_output_contact(arr,abk,cid,opt,gid)
{
	var c=abk.data[cid];
	if(!c || c.isgroup) return;
	var txt=cm_contact_string(c);
	var extra=''; 
#	if(c.isgroup && address__book.groups[id].name!='Favorites') return;
	if(c.webmail) extra='<div class="cm_extra" title="$$st_ct_info_webmail_tt$$">W</div>';
	else if(c.shared) extra='<div class="cm_extra" title="$$st_ct_info_shared_tt$$">S</div>';
	else if(opt.isfav&&c.autofav) extra='<div class="cm_extra" title="$$st_ct_info_fav_tt$$">A</div>';
	else if(gid=='All Contacts') extra='<img src="||www_base||shared/img/1pixel.gif" class="delete_contact" title="$$st_ct_cmd_del$$" onclick="contact_delete(this,\''+abk.name+'\',\''+cid+'\',event)" onmousedown="contact_delete_mousedown(event)">';			
	else extra='<img src="||www_base||shared/img/1pixel.gif" class="delete_contact" title="$$st_ct_info_nogrp_tt$$" onclick="contact_remove(event,\''+abk.name+'\')" cm_gid="'+gid+'">';			
	
	var extra2=(c.webmail || c.shared || c.isgroup)?'':' cm_draggable';
	arr.push('<div id="cm_list_'+cid+'" class="cm_contact'+extra2+'" cm_abk="'+abk.name+'" cm_cid="'+cid+'" title="'+contact_string_full(c)+'"><span class="cm_right">'+extra+'</span><span class="cm_left"><input type="checkbox" id="csel_'+cid+'"></span><div style="margin-top:3px;margin-right:20px;padding-left:5px;overflow:hidden;"><div style="height:20px;width:400px;">'+txt+'</div></div></div>');
}

function group_find(abk,gid)
{
	var el,g=xencode(gid);
	if(abk && abk.name!=gid) el=abk.groups[g];
	if(el){
#		dbg('GROUP: '+gid+' found in abk='+abk.name);
		return el;
	}
	if(!el) el=abooks.groups_fake[g];
#	if(el) dbg('GROUP: '+gid+' found in groups_fake');
#	else  dbg('GROUP: '+gid+' not found in ');
	return el;
}
function cm_select_group(o,e)
{
	var arr=[], abook,gid;
	var el=ancestor_by_class(target(e),'cm_group');
	if(!el) return;
	var pp=ancestor_by_class(el,'gtree');
	if(pp.current_sel)
		class_remove(pp.current_sel,'selected');	
	var real_el=el.firstChild
	class_add(real_el,'selected');
	pp.current_sel=real_el;
	
	abook=el.getAttribute('cm_abook');
	gid=el.getAttribute('cm_gid');
	cm_cur_group=gid;
	cm_cur_client_abook=abook;
	
	if(cur_keep_once){
		dbg('cur_keep_once was set')
		cur_keep_once=false;
	}else{
		dbg('cur_keep_once was reset')
		cm_cur_client_cid=undefined;	
		cm_cur_server_cid=undefined;
	}

#	Walk one or more addressbooks creating a single list of addresses for display
	var opt={}, contacts, abk;
	if(abook.length>0){
		abk=abooks[abook];
		var g=group_find(abk,gid);
		if(g.isfake && gid!="Favorites"){
#			List whole addressbook
			if(abook!='User')  arr.push('<div class="shared_abook4">'+abook+'</div>');
			if(g&&g.isbig){ 
				arr.push(isbig_search_link(abook,'cm'));
			}else{
				for(i=0;i<abk.data.length;i++){
					cm_output_contact(arr,abk,i,opt,gid);
				}
			}
		}else{
#			Just list one group
			if(abook!='User')  arr.push('<div class="shared_abook4">'+abook+' - '+g.name+'</div>');
			opt.isfav=g.name=='Favorites';
			cids=g.contacts;
			for(i=0;i<cids.length;i++){
				cm_output_contact(arr,abk,cids[i],opt,gid);
			}
		}
	}else{
#		List all in several addressbooks
		var rb=abooks.read_books;
		for(var i=0;i<rb.length;i++){
			var abook=rb[i]
			if(abook=='User') continue;
			abk=abooks[abook];
			var g=group_find(null,abook);
			if(abk.data.length>0 || (g&&g.isbig))  arr.push('<div class="shared_abook4">'+abook+'</div>');
			if(g&&g.isbig){ 
				arr.push(isbig_search_link(abook,'cm'));
			}else{
				for(j=0;j<abk.data.length;j++){
					cm_output_contact(arr,abk,j,opt,gid);
				}
			}
		}
	}
	
	if (arr.length==0) arr.push('<div style="padding:15px;color:#999;">$$st_ct_none_in_grp1$$<br><br>$$st_ct_none_in_grp2$$</div>');
	
#	dge('cm_contacts').innerHTML='<div class="position:relative;">'+arr.join('')+'<div>';
	var nodes=dge('cm_contacts');
	nodes.innerHTML=arr.join('');
	if(cm_new_atend){
		setTimeout(function(){nodes.parentNode.scrollTop=nodes.clientHeight;}, 0);
		cm_new_atend=false;
	}

	var o=dge('cm_details')
	o.innerHTML=dge('contacts_info').innerHTML;
	if(o.current_sel)
		class_remove(o.current_sel,'selected');	

	dbg('*** cm_cur_client_cid='+cm_cur_client_cid);
	var resel=dge('cm_list_'+cm_cur_client_cid);
#	Go out of our way to reselect any elements that were being edited (cur_keep_once)
	if(resel){
		class_add(resel,'selected');
		pp.current_sel=resel;
		cm_contact_show(cm_cur_client_abook,cm_cur_client_cid);
	}else if (cm_cur_server_cid){
		var c,cid;
		for(el=nodes.firstChild;el;el=el.nextSibling){
			cid=el.getAttribute('cm_cid')
			if(!cid)break;
			c=abooks[el.getAttribute('cm_abk')].data[cid]
			if(c&&c.svr_id==cm_cur_server_cid){
				class_add(el,'selected');
				pp.current_sel=el;
				break;
			}
			cid=undefined;
		}
		if(c&&cid) cm_contact_show('User',cid);
	}

#	if(!(dge("cm_abookshow_personal").checked || dge("cm_abookshow_shared").checked || dge("cm_abookshow_webmail").checked))
#	if(!(dge("cm_abookshow_webmail").checked||dge("cm_abookshow_webmail_groups").checked))
#		class_remove(o.firstChild.firstChild,'hidden');	
		
		
	var s=dge('cm_search');
	if (s.value!='' && s.value!='$$st_ct_srch_list$$'){ s.value='$$st_ct_srch_list$$';}
	cm_update_index();
}
var enCcxDelete=0, enCcxGroupNew=1, enCcxGroupAdd=2, enCcxVcard=3, enCcxHidden=4, enCcxExport=4;
function update_menu(txt,other)	// QQZ
{
	var el = dge(txt);
#	show_hide2(el.childNodes[enCcxHidden],false);
}


function cm_row2outer(el){return el.parentNode}

function contact_list_mouseup(e){return false;}
function contact_list_mousedown(e)
{
	if(!cx_menu(e)) return false;

#	Allow Ctl-Cmd to be used elsewhere by surgeweb without getting a context menu :-)
	if(e.metaKey) return false;
	
	var t=target(e);
	var tag=t.tagName.toLowerCase();
	var row=cl_find_row(sw.cl,t);
	var td=gs_find_td(sw.cl,t);
#	if(td==row.childNodes[1]){
#		return;
#	}

	gs_mousedown(sw.cl,e);

	update_menu('context_menu_contacts');
	do_menu_show('context_menu_contacts',e,U,U,{cursor:true});
	
	stop_def_action(e)
	return false;
}
function contact_delete_mousedown(e)
{
	gs_mousedown(sw.cl,e);
}
function contact_list_click(e)
{
	cm_select_contact(sw.cl,e);
}

function cl_show_soon(mid,nofocus,nostatus)
{
	cm_contact_show(cm_cur_client_abook,mid);
}	

function cm_select_contact(o,e)		// QQZ
{
	var el,id,abook,t;
	t=target(e);
	var tag=t.tagName.toLowerCase();

	var row=cl_find_row(sw.cl,t);
	el=ancestor_by_class(target(e),'cm_contact');
	dbg('target id='+t.id+' el='+el);
	if(!el) return;
	id=el.getAttribute('cm_cid');
	abook=el.getAttribute('cm_abk');

	cm_cur_client_cid=id;
	cm_cur_client_abook=abook;

	gs_list_click(sw.cl,e);

	if (tag=="input"){
#			no_msg_nopreview();
	} else {
		var valid_sel=cl_row_to_sel(row);
		mid=cl_sel_to_mid(valid_sel);
		var unselect;
		unselect=valid_sel.checked;
		if (!unselect){
#			msglist_select(mid,true);	
		}
#		preview_msg(mid,undefined,undefined,ctl_and_cmd_key(e));
	}
	cm_contact_show(abook,id);
}



function cm_contacts_refresh(save_source,do_import)
{
	var show=[];
	if(save_source){
#		show.push('pref_abook_personal='+dge('cm_abookshow_personal').checked);
#		show.push('pref_abook_shared='+dge('cm_abookshow_shared').checked);
		show.push('pref_abook_webmail='+dge('cm_abookshow_webmail').checked);
		show.push('pref_abook_webmail_groups='+dge('cm_abookshow_webmail_groups').checked);
		cm_cur_client_cid=undefined;
	}
	dge('cm_groups').innerHTML='$$st_ct_reloading$$';
	dge('cm_contacts').innerHTML='$$st_ct_reloading2$$';
	dge('cm_details').innerHTML=dge('contacts_info').innerHTML;
	abooks['User'].data=[];
	abooks['User'].groups=[];

	var data;
	data='cmd='+(save_source?'save_options,':'')+'show&page=~contacts.js';
	if (do_import) data+='&webmail_import=all';
	data+='&'+show.join('&');
	sndReqPost(data, function(chan){
		var success=actionReqJsStat(chan);			
		// TODO: Do success fail check
		if(save_source)cur_keep_once=true;
		cm_display_init();
	});		
}
function cm_display_init()
{
	contacts_init();
	cp_init();
}

function cm_contact_add2group(abook,cid,gid)
{
    var c=abooks[abook].data[cid];
    var group=group_find(abooks[abook],gid);
    var g_name=group.name;

	if(c.groups && c.groups.indexOf(g_name)!=-1) {
		alert($('$$st_dlg_is_ingroup$$',contact_string_short(c),g_name));
		return;
	}
	set_status($('$$st_stat_adding_togroup$$',g_name),"info");
	var updated=c.groups+(c.groups.length>0?',':'')+g_name;
	contact_group_save(cid,c,updated,function(){
				set_status($('$$st_stat_added_togroup$$',g_name),"success");
				group.contacts.push(cid);
			});
}

function contact_group_save(cid,c,groups,cb)
{
	var gs=xescape(encode_quotes(groups));
	fields=[];	
	fields.push('server_cid='+c.svr_id+'&client_cid='+cid+'&output=one');
	fields.push('contact_groups2='+(gs.length==0?'""':gs));
	fields.push('abook='+c.abook);

	var data;
	data='cmd=contact_update,show&page=~contacts.js';
	data+='&'+fields.join('&');
	sndReqPost(data, function(chan){			
		var success=actionReqJsStat(chan);			
		cb();
		cm_display_init();
	});
}

function contact_sel(xc,want_cid)	//QQCC
{
	var cs=[];
	var sel=gs_find_sel(sw.cl);
	if(xc && sel.length<2){
		cs.desc=contact_string_short(xc);
		cs.abook=xc.abook;
		cs.push(xc.svr_id);
	}else{
		var abook=cm_cur_client_abook;
		for(i=0;i<sel.length;i++){
			var c=abooks[abook].data[sel[i]]; 		
			if(want_cid){
				cs.push(sel[i]);
			}else{
				cs.push(c.svr_id);
			}
			if(i==0){
				cs.abook=c.abook;
			}else{
				if(cs.abook!=c.abook) {
					cs.warn='$$st_ct_all_not_same$$';
				}
			}
		}
		if(sel.length>1){
			cs.desc= sel.length+' contacts';
		}else{
			var c=abooks[abook].data[sel[0]]; 		
			cs.desc=contact_string_short(c);
		}
	}
	return cs;
}

#cx_contact_delete
function contact_delete(el,abook,id,e)
{
	var csel;
	if(el){
		if (id==U){
			el=ancestor_by_class(el,'cm_contact');
			id=el.getAttribute('cm_cid')
		}
		csel=contact_sel(abooks[abook].data[id]); 
	}else{
		csel=contact_sel(); 
	}
	if(csel.warn){
		x_alert(csel.warn);
		return;
	}
	
	x_confirm($('$$st_ct_dlg_rmv_all$$',csel.desc), function(n){
		if(!n)return;
		contact_delete_do(csel);
	});
	if(e){
		stopEvent(e);
		return false;
	}
}

function contact_remdel(e)
{
//	x_alert(cm_cur_client_abook+'|'+cm_cur_group);
	if(cm_cur_client_abook=='User' && cm_cur_group=='All Contacts'){
		contact_delete();
	}else{
		contact_remove(e,cm_cur_client_abook);
	}
}

# cf cm_contact_add2group
function contact_remove(e,abook)
{
	var t=target(e);
	var gid=t.getAttribute('cm_gid');
	var el=ancestor_by_class(t,'cm_contact');
	if(!el) return;
	cid=el.getAttribute('cm_cid')
	c=abooks[abook].data[cid];
    var group=group_find(abooks[abook],gid);

	x_custom_dlg('$$st_ct_dlg_rmv_del$$', '',
		function(n){
			if(!n)return;
			if(n==2) {
#				contact_remove_do(c,group,cid);
				contact_regroup(abook,contact_sel(c,true),'',gid)
			}
			if(n==1) contact_delete_do(contact_sel(c));
		},
		function(){
			btn_set(dge('dlg_ok'),'$$st_cmd_delete$$','ml2');
			btn_set(new_button('name',2,dge('dlg_ok')),'$$st_ct_grp_rmv$$');
			btn_set(dge('dlg_cancel'),U,'ml2');
		}
	);

	stopEvent(e);
	return false;
}

function contact_remove_do(c,group,cid)
{
    var g_name=group.name;
	set_status($('$$st_ct_dlg_rmv_grp$$',contact_string_short(c),g_name),"info");
	var tmp=c.groups.split(',');
	for(var i=0;i<tmp.length;i++){
		if (tmp[i]==g_name)
			tmp.splice(i,1);
	}
	contact_group_save(cid,c,tmp.join(','),function(){
			set_status($('$$st_ct_dlg_rmv_grp_ok$$',contact_string_short(c),g_name),"success");
			var tmp = group.contacts;
			for(var i=0;i<tmp.length;i++){
				if (tmp[i]==cid)
					tmp.splice(i,1);
			}
			cm_display_init();
		});
}
function contact_delete_do(csel)
{
	var fields=[];	
	fields.push('server_cid='+xescape(csel)+'');	
	var data;
	data='cmd=contact_delete,show&page=~contacts.js&abook='+csel.abook;
	data+='&'+fields.join('&');
	sndReqPost(data, function(chan){			
		cm_reset_abook(csel.abook,true)
		var success=actionReqJsStat(chan);			
		cm_display_init();
	});
}

# probably want to combine this with the first similar function 
function contact_search2_clear(ctl,e)
{
	if(ctl.value.indexOf("Quick search") != -1){
		ctl.value="";
	}
}
function contact_search2_reset(ctl,e)
{
	if(ctl.value==''){
		ctl.value="$$st_ct_srch_list$$";
	}
}
function contact_search3_clear(ctl,e)
{
	if(ctl.value.indexOf("$$st_ct_srch_list$$") != -1){
		ctl.value="";
	}
}
function contact_search2_do(ctl,e)
{
	setTimeout(function(){contact_search2_real(ctl)},10);
}
function contact_search2_real(ctl)
{
	var match=ctl.value.toLowerCase();
	var contacts=dge("cm_contacts");
	class_add(contacts,'hidden');
	if(contacts.current_sel)
		class_remove(contacts.current_sel,'selected');	
	for(row=contacts.firstChild;row;row=row.nextSibling){
		if(class_contains(row,'shared_abook') || class_contains(row,'isbig')){
            class_remove(row,"hidden");
			if(!class_contains(row,'isbig')) continue;
			btn=row.getElementsByTagName('input')[0];
			if(match.length==0){
				btn.disabled=true;
				row_to_isbigresults(row).innerHTML='';
			}else{
				btn.disabled=false;
			}
            continue;
		}		
		x=row.innerHTML.toLowerCase();
        if(x.indexOf(match) != -1 || !row.id){
            class_remove(row,"hidden");
        }else{
	        class_add(row,"hidden");
        }
    }
	cm_index_select(dge("cm_index").firstChild);
	dge("cm_details").innerHTML="";
	class_remove(contacts,'hidden');
}


function contact_new_group()
{
	var info='';
	if(abooks.write_books.length>1) info='<br><br><span style="color:#888">$$st_ct_dlg_group_add$$</span>';
	x_prompt('$$st_ct_newgroup$$ :'+info ,'$$st_ct_new_group_name$$',function(val){
		if(!val) return;
		var extra='&contact_name='+xescape(encode_quotes(val))+'&group=true';
		sndReq('cmd=contact_add,show&page=~contacts.js'+extra, function(chan){
			cm_reset_abook('User',true)
			var success=actionReqJsStat(chan);
			if(!success){
				set_status('$$st_ct_save_fail$$ ('+success_string+')','warning');
				cm_restore_abook('User');
			}else{
				set_status($('$$st_ct_group_added$$',val),'success');
				cm_display_init();
			}
		});
	});
}
# cf contact_delete
function contact_delete_group(e)
{
	var t=target(e);
	var el=ancestor_by_class(t,'cm_group');
	var abook=el.getAttribute('cm_abook');
	var name=el.getAttribute('cm_gid');
	var g=group_find(abooks[abook],name);
	
	x_custom_dlg('$$st_ct_dlg_group_del$$', '$$st_ct_dlg_group_del2$$',
		function(n){
			if(!n)return;
			contact_delete_group_do(g,name,n==2);
		},
		function(){
			btn_set(dge('dlg_ok'),'$$st_ct_delete_group$$',U,'');
			btn_set(new_button('name',2,dge('dlg_cancel')),'$$st_ct_delete_group_ct$$','ml2');
			btn_set(dge('dlg_cancel'),U,'ml2');
		}
	);

	stopEvent(e);
	return false;
}

function contact_delete_group_do(g,name,remove_all)
{
	var extra='&server_cid='+g.svr_id+'&contact_isgroup=true&contact_name='+xescape(encode_quotes(g.name))+(remove_all?'&remove_all=true':'');
	sndReq('cmd=contact_delete,show&page=~contacts.js'+extra, function(chan){
		cm_reset_abook(g.abook,true)
		var success=actionReqJsStat(chan);
		if(!success){
			set_status('$$st_ct_save_fail$$ ('+success_string+')','warning');
			cm_restore_abook(g.abook);
		}else{
			set_status($('$$st_ct_group_del_ok$$',name),'success');
			cm_display_init();
		}
	});
}

function do_contact_edit(abook,id)
{
	c=abooks[abook].data[id];
	cm_contact_edit(c,abook,id);
}


# Interface groupings that can be separately enabled, Separately enableable . Moslty a '1 to 1' mapping to database fields,
#  but in a few cases the mapping is '1 to n' or 'n to 1' to the database fields 
var CFD={
	'prefix':{hint:{'value':'Prefix'}, showdef:false, xblank:['name','prefix']},
	'name':{hint:{'first':'First Name','last':'Last Name'}, reload:true, showdef:true, blank:{first:'',last:''}},
	'phonetic':{hint:{'first':'Phonetic First Name','last':'Phonetic Last Name'}, blank:{first:'',last:''}},
	'suffix':{hint:{'value':'Suffix'}, xblank:['name','suffix']},
	'title':{hint:{'value':'Job Title'}, xblank:['company','title']},
	'department':{hint:{'value':'Department'}, xblank:['company','department']},
	'company':{hint:{'value':'Company'}, reload:true, showdef:true, blank:{value:''}},
	'file_by_co':{hint:{'value':'File by company'}, reload:true, plain:true, showdef:true, edit:'checkbox', blank:''},
	'vaultsafe':{hint:{'value':'Send without surgevault'}, reload:true, plain:true, showdef:true, edit:'checkbox', blank:''},

	'other_names':{ hint:{'value':'Other Name'}, multi:true, desc:'nickname,maiden name,middle name', blank:[{type:'other name',value:''}]},

	'phone':{hint:{'value':'Phone Number'}, showdef:true, multi:true, desc:'work,home,mobile,fax,pager', blank:[{type:'home',value:''},{type:'work',value:''}]},
	'email':{hint:{'value':'Email address'}, showdef:true, multi:true, desc:'work,home,other', blank:[{type:'home',value:''}], pref:extra_field_pref },
	'im':{hint:{'value':'Instant Messenger'}, multi:true, desc:'work,home,other', blank:[{type:'home',value:'',network:'msn'}], extra:extra_field_im},
	'url':{hint:{'value':'URL'}, multi:true, desc:'home page,blog,work', blank:[{type:'home page',value:''}] },

	'birthday':{hint:{'value':'Date'}, plain:true},
	'dates':{hint:{'value':'Date'},multi:true, desc:'anniversary',blank:[{type:'anniversary',value:''}] },
	'related_names':{hint:{'value':'Related Name'},multi:true, desc:'friend,father,mother,son,daughter',blank:[{type:'friend',value:''}] },

	'address':{hint:{'value':'Address'}, showdef:true, multi:true, edit:'textarea', desc:'work,home,other', blank:[{type:'home',value:''}] },
	'custom':{hint:{'value':'Custom'}, multi:true, desc:'custom', blank:[{type:'custom',value:''}]},
	'comment':{hint:{'value':'Comment'}, plain:true, showdef:true, edit:'textarea'},
	'groups':{hint:{'value':'Groups'}, plain:true, showdef:true, user_readonly:true, refresh_warn:true, blank:''}
};
var CFD_list=[	{address:'Address'},{birthday:'Birthday'},{comment:'Comment'},\
				{company:'Company'},{custom:'Custom Fields'},{dates:'Dates'},\
				{department:'Department'},{email:'Email'},{im:'Instant Messenger'},\
				{title:'Job Title'},{other_names:'Maiden Name'},{other_names:'Middle Name'},\
				{name:'Name'},{other_names:'Nickname'},{phone:'Phone'},\
				{phonetic:'Phonetic Names'},{prefix:'Prefix'},{address:'Address'},\
				{related_names:'Related Names'},{suffix:'Suffix'},{url:'URL'}];

var cal_translations = { 'Prefix':'$$st_ct_info_prefix$$', 'First Name':'$$st_ct_info_firstname$$',	
	'Last Name':'$$st_ct_info_lastname$$', 'Phonetic First Name':'$$st_ct_info_phfirst$$', 'Phonetic Last Name':'$$st_ct_info_phlast$$',
	'Suffix':'$$st_ct_info_suffix$$', 'Job Title':'$$st_ct_info_job$$', 'Department':'$$st_ct_info_dept$$',
	'Company':'$$st_ct_info_co$$', 'File by company':'$$st_ct_info_filebyco$$', 'Send without surgevault':'$$st_ct_info_novault$$',
	'Other Name':'$$st_ct_info_oname$$', 'Phone Number':'$$st_ct_info_phone$$', 'Email address':'$$st_ct_info_email$$',
	'Instant Messenger':'$$st_ct_info_im$$', 'URL':'$$st_ct_info_url$$', 'Birthday':'$$st_ct_info_birthday$$',
	'Date':'$$st_ct_info_date$$', 'Related Name':'$$st_ct_info_rname$$', 'Address':'$$st_ct_info_address$$',
	'Custom':'$$st_ct_info_custom$$', 'Comment':'$$st_ct_info_comment$$', 'Groups':'$$st_ct_info_groups$$',
	'Custom Fields':'$$st_ct_info_custom2$$', 'Dates':'$$st_ct_info_date2$$', 'Email':'$$st_ct_info_email2$$',
	'Maiden Name':'$$st_ct_info_mname$$', 'Middle Name':'$$st_ct_info_midname$$', 'Name':'$$st_ct_info_name$$',
	'Nickname':'$$st_ct_info_nname$$', 'Phone':'$$st_ct_info_phone2$$', 'Phonetic Names':'$$st_ct_info_phonetic$$',
	'Related Names':'$$st_ct_info_related$$',
	'work':'$$st_ct_class_work$$', 'home':'$$st_ct_class_home$$', 'other':'$$st_ct_class_other$$', 
	'mobile':'$$st_ct_class_mobile$$', 'fax':'$$st_ct_class_fax$$', 'pager':'$$st_ct_class_pager$$',
	'groups':'$$st_ct_class_groups$$', 'blog':'$$st_ct_class_blog$$', 'home page':'$$st_ct_class_homepg$$',
	'birthday':'$$st_ct_class_birthday$$', 'anniversary':'$$st_ct_class_anniv$$', 'comment':'$$st_ct_class_comment$$',
	'custom':'$$st_ct_class_custom$$',
	'friend':'$$st_ct_class_friend$$', 'father':'$$st_ct_class_father$$', 'mother':'$$st_ct_class_mother$$',
	'son':'$$st_ct_class_son$$', 'daughter':'$$st_ct_class_daughter$$'
	};

function ctx(item)
{
	var tx=cal_translations[item];
	if(tx) return tx;
	return item;
}

var explicitly_enabled=false,data_enabled=false;
function workout_fields_toshow(c,type)
{
	var cfd, k, kk;
	for (k in CFD){ 
		CFD[k].show=false;
	}
	for (k in CFD){
		cfd=CFD[k];
		if(cfd.showdef && type=='edit') {
			if(cfd.user_readonly&&!c.shared){
				cfd.show=false;
			}else{
				cfd.show=true;
			}
		}else if(cfd.showthis && type=='edit'){
			cfd.show=true;
		}else if(false){
			if(!c.shared){
				cfd.show=false;
			}else if (type=='edit'){
				cfd.show = true;
			}else if (c[k]){
				cfd.show = true;
			}
		}else if(true){
# also see hookup_fields
			if (cfd.xblank){
				kk=cfd.xblank[0];
				if(c[kk] && c[kk][cfd.xblank[1]])
					cfd.show=true;
			}else{
				for(kk in cfd.hint){
					if(c[k] && c[k][kk])	
						cfd.show=true;
					if(cfd.multi && c[k] && c[k][0] && c[k][0][kk])	
						cfd.show=true;
					if(cfd.plain && c[k])	
						cfd.show=true;
				}
			}
#			for (f in c){ 
#				if(CFD[k].showdef) CFD[k].show=true;
#			}
		}else{
			cfd.show=false;
		}		
	}

}


function contact_tr(arr,desc,edit,c1_extra)
{
	arr.push('<div class="tcell1"'+c1_extra+'>'+desc+'</div><div class="tcell2">'+edit+'</div>')	
}
var ctl_xevents=[' onchange="cctl_change(this,event)"', ' onfocus="cctl_focus(this)"', ' onblur="cctl_blur(this)"', ' onkeyup="cctl_keyup(this,event)"'];
var ctl_events = ctl_xevents.join('');
function new_field(c,field,cfd)
{
	if(!c) c=sw.curr_contact;
	if(c[field] && c[field].length>0){
		c[field].push(cloneObject(cfd['blank'][0]));
	}else{
		var o = cloneObject(cfd['blank'])
#		if(is_array(o)||!cfd['multi'])
			c[field]=o;
#		else
#			c[field]=[o];
	}
}
function new_field_create(field)
{
	var cfd=CFD[field];
	new_field(undefined,field,cfd);
	cm_contact_edit(sw.curr_contact,sw.curr_contact_abook,sw.curr_contact_id);
}
function field_remove(ctl,field,i)
{
	var c=sw.curr_contact;
	if(c[field].length>1)
		c[field].splice(i,1);
	else
		c[field][0]['value']='';
	cm_contact_edit(c,sw.curr_contact_abook,sw.curr_contact_id);
}
function confirm_exist(c,field)
{
	var cfd=CFD[field];
	if(cfd.xblank){
		var real_field=cfd.xblank[0];
		var xcfd=CFD[real_field];
		if(!c[real_field]){
			new_field(c,real_field,cfd);
		}
		if(!c[real_field][cfd.xblank[1]])
			c[real_field][cfd.xblank[1]]='';
		return;
	}
	if(!c[field]){
		new_field(c,field,cfd);
	}
}
function output_section(arr,c,field,edit,cfd)
{
	var donesome=false, output;
	if(!c[field] || c[field].length==0){
		if (!cfd['show']) return;
		new_field(c,field,cfd);
	}
	arr.push('<div id="cb_'+field+'" class="box">')
	for(i=0;i<c[field].length;i++){
		var xx=c[field][i];
		if (!edit && xx['value']=='') continue;
		if(!edit){
			if(field=='email'){ 
				output='<a href="#" onclick="do_contact_email2(\''+sw.curr_contact_abook+'\','+sw.curr_contact_id+',\''+val(xx,'value')+'\')" class="link_blue" >'+val(xx,'value')+'</a>';
			}else if(field=='url'){ 
				output='<a href="'+val(xx,'value')+'" target="_popup" class="link_blue" >'+val(xx,'value')+'</a>';
			}else if(cfd['edit']=='textarea'){ 
				output='<a href="http://maps.google.com/maps?q='+val(xx,'value').replace(/[\r\n ]+/g,'+')+'" title="Show map using Google Maps" class="link_black" target="_popup">'+val(xx,'value').replace(/[\r\n]+/g,'<br>')+'</a>';
			}else{ 
				output=val(xx,'value');
			}
#extra_field_pref
			contact_tr(arr,	'<span id="contact_'+field+'_'+i+'_type">'+ctx(val(xx,'type'))+'</span>',output+(cfd.extra?cfd.extra('show',xx):''))+'(aaa)'+(cfd.pref?cfd.pref('show',c,xx,i):'');
		}else{	
			var type_click=	' onmousedown="contact_type_menu(this,event)" onclick="return stopEvent(event)" field="'+field+'"';
			var type=	'<img class="xtype" src="||www_base||shared/img/1pixel.gif">';
			var btns=	'<a class="hidden" onclick="field_remove(this,\''+field+'\','+i+')"><img class="xclosetab" src="||www_base||shared/img/1pixel.gif" ></a>'+
						'<a class="hidden" onclick="new_field_create(\''+field+'\')""><img class="xaddtab" src="||www_base||shared/img/1pixel.gif" ></a>';
			if(cfd['edit']=='textarea'){
				contact_tr(arr,	'<span id="contact_'+field+'_'+i+'_type" unselectable="on"></span>'+type,
								(cfd.pref?cfd.pref('edit',c,xx,i):'')+'<span><textarea id="contact_'+field+'_'+i+'" rows=4 class="cm_edit" '+ctl_events+'>'+val(xx,'value')+'</textarea></span>'+btns,
								type_click);	
			}else{
				contact_tr(arr,	'<span id="contact_'+field+'_'+i+'_type" unselectable="on"></span>'+type+'',
								(cfd.pref?cfd.pref('edit',c,xx,i):'')+'<span><input type="text" id="contact_'+field+'_'+i+'"'+ctl_events+'>'+(cfd.extra?cfd.extra('edit'):'')+'</span>'+btns,
								type_click);
			}
			// Messes up dependencies in hookup_field
		}
		donesome=true;
	}
	if(donesome)
		arr.push('</div>')
	else
		arr.pop();
}
function output_field(arr,c,field,edit,cfd)
{
	if (!c[field] ||  c[field].length==0){
		if (!cfd['show']) return;
		c[field]='';
	}
	var xx=c[field];
	if (val(xx,'value')=='' && (!edit || (cfd['user_readonly']&&!c.shared))) return;
	arr.push('<div id="cb_'+field+'" class="box">');
	if(!edit){
		if(cfd['user_readonly'])
			contact_tr(arr,ctx(field),'<span id="contact_'+field+'" class="gray">'+val(xx,'value')+'</span>');
		else if(cfd['edit']=='textarea')
			contact_tr(arr,ctx(field),'<span id="contact_'+field+'">'+val(xx,'value').replace(/[\r\n]+/g,'<br>')+'</span>');	
		else
			contact_tr(arr,ctx(field),'<span id="contact_'+field+'">'+val(xx,'value')+'</span>');
	}else{
		if(cfd['user_readonly'] && !c.shared)
			contact_tr(arr,ctx(field),'<span id="contact_'+field+'" class="gray"><div style="padding-top:3px;min-height:20px">'+val(xx,'value')+'</div></span>');
		else if(cfd['edit']=='textarea')
			contact_tr(arr,ctx(field),'<textarea id="contact_'+field+'" rows=4 class="cm_edit" '+ctl_events+'>'+val(xx,'value')+'</textarea>');	
		else
			contact_tr(arr,ctx(field),'<input type=txt id="contact_'+field+'"'+ctl_events+'>');	
	}
	arr.push('</div>');
}

function output_myfields(arr,c,field,edit)
{
	var cfd=CFD[field];
#	if (!cfd) return;
	if (!cfd || !(cfd.show || cfd.showdef)) return;
	
	if(cfd['multi']){
		output_section(arr,c,field,edit,cfd);
	}else{
		output_field(arr,c,field,edit,cfd);
	}
}
function format_boxes()
{
	for (k in CFD){
		if(CFD.xblank) continue;
		format_box(k);
	}
}
function format_box(el)
{
	if(is_string(el)){
		el=dge('cb_'+el);
	}
	if(!el) return;
	panelise_round(el,enBoth);
	var outer=panel_correct(el);
	outer.style.width=px(450);
	class_add(outer,'grouping');
}

# Hookup editable fields to backing data object, set initial value of fields from data object,
# and cache any special divs we need for tweaking the interface
function hookup_fields(c)
{
	for (field in CFD){
		if (field=='file_by_co' || field=='vaultsafe') continue;
		var cfd=CFD[field];
		if(cfd.xblank){
			var real_field=cfd.xblank[0];
			var xcfd=CFD[real_field];
			if(c[real_field][cfd.xblank[1]]==undefined) continue;
			hookup_field(c[real_field],field,cfd,real_field);	
			continue;
		}
		if(c[field]==undefined) continue;
		if(is_array(c[field])){
#			Repeat for each instance of multi-instance fields
			for(i=0;i<c[field].length;i++){
				hookup_field(c[field][i],field,cfd);
			}
		}else{
			if(cfd.plain){
				hookup_field(c,field,cfd);	
			}else{
				hookup_field(c[field],field,cfd);	
			}
		}
	}
}
#Hookup one multivalue object / or string to its edit fields
function hookup_field(xvalue,field,cfd,real_field)
{
	var xid;

#	Get actual edit control
	for(var k in cfd['hint']){
		var hint=ctx(cfd['hint'][k]);
		var id=field;

		if(cfd.xblank){
			k=cfd.xblank[1];
			id=real_field;
		}
		if(k!='value')id+='_'+k;
		if(cfd['multi']) id+='_'+i;
		var o=dge('contact_'+id);
		if(!o) return;

		if(cfd.extra) cfd.extra('hookup',xvalue,o);

#	... and initialise it
		o.hint=hint;
		o.store=xvalue;
		o.store_type=cfd.plain?field:k;
		o.reload=cfd.reload;
	
#	Initialise controls for multiinstance values	
		if(cfd['multi']){
			o.div_del=abook_field2divdel(o);
			o.div_more=o.div_del.nextSibling;
		}
# 	Initialise the left hand type/descriptor field if required
		if(cfd['desc'] && !xid){
			var xid=field;
			if(cfd['multi']) xid+='_'+i;
			var t=dge('contact_'+xid+'_type');
			t.store=xvalue;
			t.store_type='type';
			o.div_type=t;
		}

#	Make sure ctl is in a valid state
		cctl_edit_start(o);
		cctl_value_init(o);
		if(xvalue[k]==''){
			cctl_edit_done(o);
		}
	}
}


function cm_contact_show(abook,id)
{
	var c=abooks[abook].data[id];
	if(!c.full){
		dge('cm_details').innerHTML='<div style="padding:20px;color:#666;">$$st_ct_reloading3$$</div>';
		sndReq('cmd=show&page=~contacts.js&output=one&server_cid='+xescape(c.svr_id)+'&client_cid='+id+'&abook='+xescape(c.abook), function(chan){
			var success;
			try{
				success=actionReqJsStat(chan);
			} catch (ex) {
				contact_error();
			}

			if(success){
				cm_contact_show(abook,id);
			}
		});
		return;
	}
	
	cm_cur_server_cid=c.svr_id;
	sw.curr_contact=c;
	sw.curr_contact_abook=abook;
	sw.curr_contact_id=id;

	dge('cm_details').innerHTML=cm_contact_show_html(abook,id,c,true);

	format_boxes();

}

function cm_contact_show_html(abook,id,c,extra)
{
	var arr=[];	
	var primary_fields=[];
	var img_url;
	var editable=contact_editable(c);
	var co_first=c.file_by_co;	
	var txt_sizing='font-size:20px;';

	workout_fields_toshow(c,'show');

	if(extra){
		if (c.shared) arr.push('<div class="cm_info cm_box">$$st_ct_read_shared$$ ('+c.abook+') - <i> '+(editable?'$$st_ct_read_shared_e$$':'$$st_ct_read_shared_r$$')+'</i></div>');

		if (c.webmail){
			arr.push('<div class="cm_warning cm_box" title="$$st_ct_read_web2_tt$$">$$st_ct_read_web2$$ <a href="#" onclick="webmail_import(\'all\')">$$st_ct_read_web_import$$</a></div>');
		}		
	}
	arr.push('<div style="padding:'+(c.shared?'0':'20px')+' 20px 20px 20px;">')
	if(c['invalid']==true){
		arr.push('<div class="cm_warning">$$st_ct_warn_missing$$</div>')
	}
	if(pref.devt_mode){
		arr.push('client_id='+id+' server_id='+val(c.svr_id)+'<br><br>')	
		arr.push('groups='+val(c.groups)+'<br>')	
	}
	arr.push('<div class="contact_show" style="padding:20px;">')

	if (c.file_by_co){
		output_primaryfield(c,primary_fields,'company',(c['company']?'<span  style="'+txt_sizing+'">'+val(c['company'].value)+'</span>':''));
		txt_sizing='';
	}	
	output_primaryfield(c,primary_fields,'phonetic',(c['phonetic']?'<span style="font-style:italic">('+val(c['phonetic'].first)+' '+val(c['phonetic'].last):'')+')</span>');
#	primary_fields.push((c['name']?'<span  style="'+txt_sizing+'">'+val(c['name'].prefix)+' '+val(c['name'].first)+' '+val(c['name'].last)+'</span> '+val(c['name'].suffix):'<i style="color:#888;'+txt_sizing+'">No name specified</i>'));
	primary_fields.push((c_name(c)!=''?'<span  style="'+txt_sizing+'">'+val(c['name'].prefix)+' '+val(c['name'].first)+' '+val(c['name'].last)+'</span> '+val(c['name'].suffix):'<span style="'+txt_sizing+'">'+c_email(c)+'</span>'));
	var tmp=[]
	output_primaryfield(c,tmp,'title',(c['company']?'<span>'+val(c['company'].title):'')+'</span>');
	output_primaryfield(c,tmp,'department',(c['company']?'<span>'+val(c['company'].department):'')+'</span>');
	if(tmp.length>0)
		primary_fields.push(tmp.join(' - '));
	if (!c.file_by_co)
		output_primaryfield(c,primary_fields,'company',(c['company']?'<span >'+val(c['company'].value)+'</span>':''));

	if(c.icon && c.icon.length>0)
		img_url='||cgi||?cmd=contact_icon&abook='+c.abook+'&icon='+c.icon+'&cid='+c.svr_id+'&sid='+sid;
	else
		img_url='||www_base||shared/img/no_picture.gif';
	if(pref.vault_lock && c.vaultsafe)
		primary_fields.push('<span class="vaultsafe">$$st_vaultlock_safe$$</span>');

	arr.push('<table><tr><td style="width:90px;">');
	arr.push('<div style="text-align:center;"><img id="contact_icon" src="'+img_url+'" height=64 width=64 style="border:1px solid #999;"></div>');
	arr.push('</td><td>');
	arr.push(primary_fields.join('<br>'));
	arr.push('</td></tr></table>');


	output_myfields(arr,c,'phone');
	output_myfields(arr,c,'email');
	output_myfields(arr,c,'im');
	output_myfields(arr,c,'url');
	output_myfields(arr,c,'other_names');
	output_myfields(arr,c,'birthday');
	output_myfields(arr,c,'dates');
	output_myfields(arr,c,'related_names');
	output_myfields(arr,c,'address');
	output_myfields(arr,c,'custom');
	output_myfields(arr,c,'comment');

	output_myfields(arr,c,'groups');

	if(extra){
		arr.push('<div style="width:450px">');
		arr.push(' <input style="float:left" type=button onclick="do_contact_email(\''+abook+'\','+id+')" value="$$st_ct_cmd_email$$">');
		if(editable) arr.push(' <input style="float:left;margin-left:7px;" type=button onclick="do_contact_edit(\''+abook+'\','+id+')" value=" '+(c.shared?'Edit Shared Contact':'$$st_ct_cmd_edit$$')+'">');
		if(!editable){
#			if (c.webmail) 
#				arr.push('<div class="cm_warning" style="margin-top:7px" title="Edit using webmail or import if you want to change them">Webmail contact information is read only. <a href="#" onclick="webmail_import('+id+')">Import this contact</a>, <a href="#" onclick="webmail_import(\'all\')">all webmail contacts</a></div>');
#			else	
#				arr.push('<div class="cm_warning" style="margin-top:7px" title="Contact your system administrator if you need edit permission">Not allowed to edit the shared contacts ('+c.abook+')</div>');
		}
		arr.push(' <input style="float:right" type=button onclick="cm_email_vcard(event,\''+abook+'\','+id+')" value="$$st_ct_cmd_vcfemail$$">');
		arr.push(' <input style="float:right;margin-right:7px;" type=button onclick="cm_contact_print(\''+abook+'\','+id+')" value="$$st_ct_cmd_vcfprint$$">');
		arr.push('</div>');
	}
	if(false){
		arr.push('<div style="margin-top:25px">$$st_ct_merge1$$ <a href="#">$$st_ct_merge2$$</a>?</div>');
	}

	arr.push('</div>')
	return arr.join('');
}
function cm_contact_edit(c,abook,id)
{
	var img_url,upload_txt;
	var heading,arr=[],new_contact;
	dge('cm_details').innerHTML='';
	if (!c) {
		c=new Object;
		heading='$$st_ct_new_contact$$';
		new_contact=true;
		c.svr_id='new';
		c.abook=abook_new;
		if (c.abook!='User') c.shared=true;
		if(abook_new==cm_cur_client_abook && cm_cur_group ){
			var abk=abooks[cm_cur_client_abook];
			var g=group_find(abk,cm_cur_group);
			if(g&&g.isfake&&!g.isfav) g=U;
			if(g) c.groups=cm_cur_group;
		}
		abook_new='User';
	}else{
		heading=contact_string_short(c);
	}
	sw.curr_contact=c;
	sw.curr_contact_abook=abook;
	sw.curr_contact_id=id;

	confirm_other_names(c)
	
	var cm_details=dge('cm_details');
#	Make sure the screen updates are "nice" on firefox
	class_add(cm_details,'hidden');
	scroll_top(cm_details);

	if (c.shared) arr.push('<div class="cm_warning" style="margin:7px 40px 0px 40px;text-align:center;">$$st_ct_shared_warn$$ ('+c.abook+')</div>');

	arr.push('<div style="padding:'+(c.shared?'0':'20px')+' 20px 20px 20px;">')
	if(pref.devt_mode){
		arr.push('client_id='+val(id)+' server_id='+val(c.svr_id)+'<br><br>')	
		arr.push('groups='+val(c.groups)+'<br>')	
	}
	arr.push('<div class="contact_edit" style="padding:20px;">')

	workout_fields_toshow(c,'edit');

	var primary_fields=[];
	var txt_sizing=' style="font-size:20px"';

	if (c.file_by_co){
		output_primaryfield(c,primary_fields,'company','<input id="contact_company"'+txt_sizing+ctl_events+'>',true);
		txt_sizing='';
	}	
	output_primaryfield(c,primary_fields,'prefix','<input id="contact_name_prefix"'+ctl_events+'>',true);
	output_primaryfield(c,primary_fields,'phonetic','<input id="contact_phonetic_first"'+ctl_events+'>&nbsp;<input id="contact_phonetic_last"'+ctl_events+'>',true);
	output_primaryfield(c,primary_fields,'name','<input id="contact_name_first"'+txt_sizing+ctl_events+'>&nbsp;<input id="contact_name_last"'+txt_sizing+ctl_events+'>',true);
	output_primaryfield(c,primary_fields,'suffix','<input id="contact_name_suffix"'+ctl_events+'>',true);
	var tmp=[]
	output_primaryfield(c,tmp,'title','<input id="contact_company_title"'+ctl_events+'>',true);
	output_primaryfield(c,tmp,'department','<input id="contact_company_department"'+ctl_events+'>',true);
	if(tmp.length>0)
		primary_fields.push(tmp.join('&nbsp;'));
	if (!c.file_by_co)
		output_primaryfield(c,primary_fields,'company','<input id="contact_company"'+ctl_events+'>',true);
	primary_fields.push('<input type="checkbox" id="contact_file_by_co"'+(c.file_by_co?' checked':'')+' onclick="toggle_file_by_co(this)"> $$st_ct_info_filebyco$$');
	if(pref.vault_lock){
		if(c.vaultwild){
			primary_fields.push('<span class="vaultsafe">$$st_vaultlock_safe$$</span>');
		}else{
			primary_fields.push('<input type="checkbox" id="contact_vaultsafe"'+(c.vaultsafe?' checked':'')+' onclick="toggle_vaultsafe(this)"> $$st_vaultlock_safe_edit$$');
		}
	}
	if(c.icon && c.icon.length>0){
		img_url='||cgi||?cmd=contact_icon&abook='+xescape(abook)+'&icon='+c.icon+'&cid='+c.svr_id+'&sid='+sid;
		upload_txt='$$st_ct_icon_change$$';
	}else{
		img_url='||www_base||shared/img/no_picture.gif';
		upload_txt='$$st_ct_icon_add$$';
	}

	arr.push('<table><tr><td style="width:90px;">');

	arr.push('<div style="text-align:center;"><img src="'+img_url+'" height=64 width=64 style="border:1px solid #999;"><br><a href="#" onclick="icon_upload(\''+abook+'\',\''+c.svr_id+'\')">'+upload_txt+'</a></div>');
	arr.push('</td><td>');
	arr.push(primary_fields.join('<br>'));
	arr.push('</td></tr></table>');

	output_myfields(arr,c,'phone',true);
	output_myfields(arr,c,'email',true);
	output_myfields(arr,c,'im',true);
	output_myfields(arr,c,'url',true);
	output_myfields(arr,c,'other_names',true);
	output_myfields(arr,c,'birthday',true);
	output_myfields(arr,c,'dates',true);
	output_myfields(arr,c,'related_names',true);
	output_myfields(arr,c,'address',true);
	output_myfields(arr,c,'custom',true);
	output_myfields(arr,c,'comment',true);
	output_myfields(arr,c,'groups',true);	

	arr.push('<input type="button" value="$$st_cmd_save$$" onclick="contact_edit_save(\''+abook+'\','+id+')">')
	if(!new_contact)
		arr.push(' <input type="button" value="$$st_cmd_delete$$" onclick="contact_delete(undefined,\''+abook+'\','+id+')">');
	arr.push(' <input type="button" value="$$st_cmd_cancel$$" onclick="contact_edit_cancel(\''+abook+'\','+id+')">')
	arr.push('&nbsp;&nbsp;');
	arr.push(' <input type="button" value="$$st_ct_menu_more$$" onclick="contact_fields_add(\''+abook+'\','+id+',event)">')

	arr.push('<input type=hidden id="contact_svr_id" value="'+val(c.svr_id)+'">');

# *** old stuff ***
	arr.push('<input type=hidden id="contact_name" value="'+c_name(c)+'">');
	arr.push('<input type=hidden id="contact_email" value="'+c_email(c)+'">');
	if(!c.shared)
		arr.push('<input type=hidden id="contact_groups2" value="'+val(c.groups)+'">');
# *** old stuff end ***

	arr.push('</div>')
	cm_details.innerHTML=arr.join('');
# 	Complete form fields initialisation
	hookup_fields(c);
	format_boxes();

	class_remove(cm_details,'hidden');
		
}

function confirm_other_names(c)
{
	var add=true;
	if(!contact_check_add) return;
	var field='other_names';
	
#	if(!c.other_names)
#		new_field(c,'other_names',cfd)

	var q=sw.curr_contact[field];
	for (var j=q.length-1;j>=0;j--){
		if(q[j].type==contact_check_add)
			add=false;
	}
	if(add){
		new_field(undefined,field,CFD[field]);
		q[q.length-1].type=contact_check_add;
	}

	contact_check_add=undefined;
}
function output_primaryfield(c,arr,type,txt,edit)
{
	if(!edit){
		if (CFD[type].show)
			arr.push(txt);			
		return;
	}
	if(CFD[type].show || type=='name' || type=='company'){
		arr.push(txt);
		confirm_exist(c,type);
	}
}
function contact_edit_save(abook,id)
{
#	// bit like contact_click & contact_group_save but have whole contacts object serialised
	var c=sw.curr_contact;
	var full=c.reload && keep_sorted;
	
	fields=[];	
	if(c.file_by_co && !c.company.value)
		c.file_by_co='';

	var server_cid=dge('contact_svr_id').value;
	fields.push('server_cid='+server_cid);
	fields.push('client_cid='+(full?'':val(id)));
	fields.push('output='+(full?'all':'one'));
	
	for (k in CFD){
		field=CFD[k];
		if (field.xblank) continue;
		if (!c[k] && c[k]!='') continue;
		var noblank = true;
#		//  (hack to keep company fields even though 'value' is used...)		
		if (k=='company') noblank = !c[k]['department'] && !c[k]['title'];
		fields.push('contact_'+k+'='+xescape(serialise(c[k],noblank,field.plain)));
	}

	fields.push('abook='+c.abook);
	
	var data;
	data='cmd=contact_update,show&page=~contacts.js';	// QQQCU
	data+='&'+fields.join('&');
	sndReqPost(data, function(chan){			

#		As we are getting all data back, remove original data for now.
#		//error check this response!!!
		if(full){
			cm_reset_abook(c.abook)
		}else if(server_cid=='new'){
			if(cm_cur_client_abook!=c.abook) cm_cur_group=c.abook;
			cm_cur_client_abook=c.abook;
			cm_cur_client_cid=abooks[c.abook].data.length;	// 
			cm_new_atend=true;
		}
		cur_keep_once=true;
		var success=actionReqJsStat(chan);			
		cm_display_init();
	});
}

function contact_edit_cancel(abook,id)
{
	if (!id) return cm_contacts_refresh(false);
	abooks[abook].data[id].full=false;
	cm_contact_show(abook,id);
}

#cf contact_fields_add
function contact_type_menu(ctl,e)
{
	var t=ancestor_by_att(target(e),'field')
	if (!t) return;
	var type_div=t.firstChild;
	var m=contact_fields_menu(t.getAttribute('field'));
	m.type_div=type_div;
	do_menu_show('ed_menu_'+'type',e,true,function(){remove_node(dge('ed_menu_'+'type'));},{right:true,xoffset:15,yoffset:dge('cm_details_scrolled').scrollTop-3});
}
function contact_fields_add(abook,id,e)
{
	var m=contact_fields_menu('contacts');
	do_menu_show('ed_menu_'+'contacts',e,true,function(){remove_node(dge('ed_menu_'+'contacts'));},{upwards:true,yoffset:dge('cm_details_scrolled').scrollTop});
}


function contact_fields_menu(id)
{
	var arr=[];
	var o=dge('ed_menu_'+id);
	var show;
	if (!o){
		var o=document.createElement("div");
		o.className = 'xmenu';
		if (id=='contacts'){
			o.onmouseup=contact_select_fields;
			for (var i=0;i<CFD_list.length;i++){
				for(k in CFD_list[i]){
					show=CFD[k]['show'];
					if(k=='other_names'){
						show=false;
						var q=sw.curr_contact.other_names;
						if(!q) continue;
						for (var j=q.length-1;j>=0;j--){
							if(q[j].type==CFD_list[i][k].toLowerCase())
								show=true;
						}
					}
					arr.push('<a href="#" class="fontname" style="'+(show?'color:#777;':'font-weight:bold;')+'padding:0 3px;" param="'+k+'">'+cal_translations[CFD_list[i][k]]+'</a>');
				}
			}
		}else{
			o.onmouseup=contact_select_type;
			var tmp=CFD[id].desc.split(',');
			for(var i=0;i<tmp.length;i++){
				arr.push('<a href="#" class="fontname" style="padding:0 15px 0 5px;" item="'+tmp[i]+'">'+ctx(tmp[i])+'</a>');
			}
#			arr.push('<a href="#" style="padding:0 15px 0 5px;" disabled>&nbsp;</a>');
#			arr.push('<a href="#" class="fontname" style="padding:0 15px 0 5px;">$$st_ct_custom$$</a>');
			id='type';
		}
		o.innerHTML='<div style="font-size:12px">'+arr.join('')+'</div>';
		o.id = 'ed_menu_'+id;

		o.onmouseout=function(e){ if(!e) e=window.event; menu_action_mouseout(e,o.id)}; 
		o.onmouseover=function(e){ if(!e) e=window.event; menu_action_mouseover(e,o.id)};
		o.onclick=function(e){ if(!e) e=window.event; stopEvent(e);};
		document.body.appendChild(o);
	}
	if (isIE) ignore_one_hide=true;		
	return o;
}
var contact_check_add;
function contact_select_fields(e)	// cf ed_click
{
	if(!e) e=window.event;
	var t=target(e);
	var field=t.getAttribute("param");
#	alert(t.getAttribute("param"))
	menu_delete('ed_menu_'+'contacts')
	CFD[field]['showthis']=true;
	if(field=='other_names') contact_check_add=t.innerHTML.toLowerCase();
	
	cm_contact_edit(sw.curr_contact,sw.curr_contact_abook,sw.curr_contact_id);
}
function contact_select_type(e)
{
	if(!e) e=window.event;
	var t=target(e);
	var pp=pparent(t);
	if(pp==U || pp.type_div==U) return;
	menu_delete('ed_menu_'+'type')
	var type_div=pp.type_div;
	var txt=t.getAttribute('item');
	if (txt=='$$st_ct_custom$$') return alert('$$st_ct_custom_soon$$')
	type_div.store[type_div.store_type]=txt;
	cm_contact_edit(sw.curr_contact,sw.curr_contact_abook,sw.curr_contact_id);
}


# Fancy control used on the contacts page
function cctl_focus(ctl){cctl_edit_start(ctl);}
function cctl_blur(ctl){cctl_edit_done(ctl);}
function cctl_change(ctl,e){ cctl_propagate_value(ctl); }
function cctl_keyup(ctl,e){ cctl_value_based_update(ctl); }

# Actual implementation functions
function cctl_value_init(ctl)
{
	if(ctl.div_type){
		var unenc=val(ctl.div_type.store[ctl.div_type.store_type])
		ctl.div_type.innerHTML=ctx(unenc);
	}
	ctl.value=val(ctl.store[ctl.store_type]);

	if (ctl.div_del && (ctl.valid && ctl.value.length>0 || abook_outer2prev(abook_field2outer(ctl))))
		class_remove(ctl.div_del,'hidden');

	if(ctl.value.length>0){
		if(ctl.div_more && !abook_outer2next(abook_field2outer(ctl)))
			class_remove(ctl.div_more,'hidden');
	}

	cctl_edit_done(ctl);
}
var refresh_warned;
function cctl_propagate_value(ctl)
{
	if (!ctl.store)return;

	ctl.store[ctl.store_type]=ctl.value;
	
	if(CFD[ctl.store_type] && CFD[ctl.store_type].refresh_warn && !refresh_warned){
		setTimeout(function(){
			refresh_warned=true;
			x_alert('$$st_ct_goups_modified$$')
		},0);
	}
	
	if(ctl.reload)
		sw.curr_contact.reload=true;
}
function cctl_edit_start(ctl)
{
	if(!ctl.valid){
		ctl.value='';
	}
	ctl.valid=true;
	class_remove(ctl,'invalid')
	class_add(ctl,'valid')
}
function cctl_edit_done(ctl)
{
	if(ctl.value.length==0){
		ctl.valid=false;
		ctl.value=ctl.hint;
		class_remove(ctl,'valid')
		class_add(ctl,'invalid')
	}
}
function cctl_value_based_update(ctl)
{
	if(!ctl.div_del) return;
	if(ctl.value.length>0){
		class_remove(ctl.div_del,'hidden');
		if(!abook_outer2next(abook_field2outer(ctl)))
			class_remove(ctl.div_more,'hidden');
	}else{
#		class_add(ctl.div_del,'hidden');
		class_add(ctl.div_more,'hidden');
	}
}

function toggle_file_by_co(ctl)
{
	sw.curr_contact.file_by_co=!sw.curr_contact.file_by_co;
	sw.curr_contact.reload=true;	
	cm_contact_edit(sw.curr_contact,sw.curr_contact_abook,sw.curr_contact_id);
}
function toggle_vaultsafe(ctl)
{
	sw.curr_contact.vaultsafe=!sw.curr_contact.vaultsafe;
}
# cf contact_search2_real
function cm_index_click(e)
{
	var id,hdr,count=0,abook;
	t=target(e);
	if(!class_contains(t,'cm_present')) return;
	var match=t.innerHTML;

	cm_index_select(t);

	var contacts=dge("cm_contacts");
	class_add(contacts,'hidden');
	if(contacts.current_sel)
		class_remove(contacts.current_sel,'selected');	

	for(row=contacts.firstChild;row;row=row.nextSibling){
		id=row.getAttribute('cm_cid');
		if(id==null){
			if(count>0 && hdr) class_remove(hdr,"hidden");
			hdr=row;
		}
		abook=row.getAttribute('cm_abk');
		if(!abook) continue;
		c=abooks[abook].data[id];        
        if(match=='all' || (c && c.index_letter == match)){
            class_remove(row,"hidden");
            count++;
        }else{
	        class_add(row,"hidden");
        }
    }
	if(count>0 && hdr) class_remove(hdr,"hidden");
	dge("cm_search").value="$$st_ct_srch_list$$";
	dge("cm_details").innerHTML="";
	class_remove(contacts,'hidden');
}

function cm_update_index()
{
	var type,id,abk;
	var o=new Object;
	var ab,last_abk;

	var oo=dge("cm_contacts").childNodes;
	for (var i=oo.length-1;i>=0;i--){

		id=oo[i].getAttribute('cm_cid');
		if(!id) continue;

		abk=oo[i].getAttribute('cm_abk');
		if(abk!=last_abk){
			ab=abooks[abk].data;
		}
		
		o[ab[id].index_letter]=true;
	}

	var idx=dge("cm_index").childNodes;
	for (var i=idx.length-1;i>=1;i--){
		type=idx[i].innerHTML;
		if(o[type])
			class_add(idx[i],"cm_present")
		else
			class_remove(idx[i],"cm_present")
	}
	class_add(idx[0],"cm_present");
	cm_index_select(idx[0]);
}


function cm_index_select(el)
{
	if(el.parentNode['sel_idx'])
		class_remove(el.parentNode['sel_idx'],"selected");
	class_add(el,"selected");
	el.parentNode['sel_idx']=el;
}
function contact_error()
{
	alert('$$st_ct_broken$$');
}

var keep_sorted=false;
var cm_cur_group, cm_cur_client_abook, cm_cur_client_cid, cm_cur_server_cid, cp_cur_tab, cur_keep_once, cm_new_atend;

var old_data, old_groups;
function cm_reset_abook(abook,svr_id_reset)
{
	old_data=abooks[abook].data;
	old_groups=abooks[abook].groups;
	abooks[abook].data=[];
	abooks[abook].groups=[];
	cm_cur_client_cid=undefined;
	if(svr_id_reset)
		cm_cur_server_cid=undefined;
}
function cm_restore_abook(abook)
{
	abooks[abook].data=old_data;
	abooks[abook].groups=old_groups;
}

function webmail_import(id)
{
	if (id=='all'){
		if(!confirm('$$st_ct_import_webwarn$$')) return;
		
		dge('cm_abookshow_webmail').checked=false;
		dge('cm_abookshow_webmail_groups').checked=false;
		cm_contacts_refresh(true,true);
		contacts_import(3);		
	}else{	
		webmail_import_one(id);
	}
}
# cf: contact_edit_save
function webmail_import_one(id)
{
	var c,cc,db,fields,email,i;

	fields=[];	
	db=abooks['User'].data;
	c=db[id];
	email=c_email(c).toLowerCase();
	for (i=0;i<db.length;i++){
		cc=db[i];
		if(c_email(cc).toLowerCase().indexOf(email)!=-1 && cc.webmail!=true){
			if(!confirm(email+' $$st_ct_import_warnsame$$'))
				return;
			else
				break;
		}
	}	
	
	fields.push('server_cid=new');
	fields.push('client_cid=');
	fields.push('output=one');
	
	for (k in CFD){
		field=CFD[k];
		if (field.xblank) continue;
		if (!c[k]) continue;
		fields.push('contact_'+k+'='+xescape(serialise(c[k],true,field.plain)));
	}
	fields.push('contact_groups2='+xescape(encode_quotes('Webmail import')));
	
	var data;
	data='cmd=contact_update,show&page=~contacts.js'+'&'+fields.join('&');
	sndReqPost(data, function(chan){			
		cm_cur_client_abook='User';
		cm_cur_client_cid=abooks['User'].data.length;
		cm_cur_group=1;
		cur_keep_once=true;
		var success=actionReqJsStat(chan);			
		cm_display_init();
	});
}
function contact_new_group2()
{
	var info='';
	if(abooks.write_books.length>1) info='<br><br><span style="color:#888">$$st_ct_dlg_group_add$$</span>';
	x_prompt('$$st_ct_newgroup$$ :'+info ,'$$st_ct_new_group_name$$',function(val){
		if(!val) return;
		contact_regroup(cm_cur_client_abook,contact_sel(U,true),cm_cur_client_abook,val);
	});
}
function contact_regroup(abk_src,csel_local,abk_dst,dst_grp)	//cf cm_contact_add2group contact_copy_one   
#							contact_remdel [ contact_delete | contact_remove ]
#											contact_remove_do | contact_delete_do YY
{
	var csel=contact_sel();
	var fields=[];	
	fields.push('server_cid='+xescape(csel)+'');
	fields.push('abook_src='+xescape(encode_quotes(abk_src)));
	fields.push('abook_dst='+xescape(encode_quotes(abk_dst)));
	if(dst_grp)
		fields.push('dst_group='+xescape(encode_quotes(dst_grp)));
	
//		contact_copy_one(abooks[abk_src].data[cid],abk_to,gid);
	
	
	var data;
	data='cmd=contact_regroup,show&page=~contacts.js&abook='+csel.abook;
	data+='&'+fields.join('&');
	sndReqPost(data, function(chan){			
		cm_reset_abook(csel.abook,true)
		var success=actionReqJsStat(chan);			
		cm_display_init();
	});
}
function contact_copy_one(c,dst_abk,dst_grp)
{
	var c,cc,db,fields,email,i;

	fields=[];	

	fields.push('server_cid=new');
	fields.push('client_cid=');
	fields.push('output=one');
	
	for (k in CFD){
		if(k=='groups') continue;
		field=CFD[k];
		if (field.xblank) continue;
		if (!c[k]) continue;
		fields.push('contact_'+k+'='+xescape(serialise(c[k],true,field.plain)));
	}
	fields.push('abook='+dst_abk);
	if(dst_grp)
		fields.push('contact_groups='+xescape(encode_quotes(dst_grp)));
	
	var data;
	data='cmd=contact_update,show&page=~contacts.js'+'&'+fields.join('&');
	sndReqPost(data, function(chan){			
		cm_cur_client_abook=dst_abk;
		cm_cur_client_cid=abooks[dst_abk].data.length;
		cm_cur_group=1;
		cur_keep_once=true;
		var success=actionReqJsStat(chan);			
		cm_display_init();
	});
}

function contact_editable(c)
{
	return !(c.shared || c.webmail) || group_editable(c);
}
function group_editable(g)
{
	return g.shared && sw.abooks_write && in_array(g.abook,sw.abooks_write);
}

function extra_field_im(type,xx,oo)
{
	var out=[], field='network';
	var networks={'msn':'MSN', 'google':'Google Talk', 'aim':'AIM', 'yahoo':'Yahoo', 'icq':'ICQ', 'jabber':'Jabber', 'skype':'Skype', 'dbabble':'DBabble', 'other':'$$st_ct_im_other$$'};
	if(type=='edit'){
		out.push('&nbsp;<select '+ctl_xevents[0]+'>');
		for(k in networks)
			out.push('<option value="'+k+'">'+networks[k]+'</option>');
		out.push('</select>');
		return out.join('');
	}else if(type=='show'){
		var v=networks[val(xx,field)];
		if (!v || v.length==0) return '';
		return ' <span style="color:#777">('+v+')</span>';
	}else if(type=='hookup'){
		var el=abook_field2extra(oo);
		el.store=xx;
		el.store_type=field;
	}
	return '';
}

function extra_field_pref(type,c,xx,i)
{
	return '';
	var txt=''
	if(type=='edit'){
		if (i==0){
			txt='<span style="float:right;color:#888">$$st_ct_preferred$$ <img class="star star_sel" src="||www_base||shared/img/1pixel.gif" ></span>';
		}else{
			txt='<span style="float:right"><img class="star" src="||www_base||shared/img/1pixel.gif" ></span>';
		}
	}else if(type=='show'){
		if (i==0){
			txt=' <span style="color:#888">$$st_ct_preferred$$</span>';
		}
	}
	return txt
}

function abook_field2extra(o) {return o.nextSibling.nextSibling};
function abook_field2divdel(o) {return o.parentNode.nextSibling};
function abook_field2outer(o) {return o.parentNode.parentNode};
function abook_outer2prev(o) {return o.previousSibling.previousSibling};
function abook_outer2next(o) {return o.nextSibling};


function cp_fill_directory()
{
	var arr=[],arr_big=[];
	var rb=abooks.read_books;
	for(j=0;j<rb.length;j++){
		var abk=abooks[rb[j]];
		if (abk.name=="User") continue;
		g=abooks.groups_fake[abk.name];
		len=abk.data.length;
		if(g&&g.isbig) {
			arr.push(isbig_search_link(abk.name,'cp'));
			continue;
		}		

		if (len==0) continue;
		arr.push('<div class="xrow_container shared_abook">$$st_ct_directory$$ '+abk.name+'</div>');
		for (i=0;i<abk.data.length;i++){
			var c=abk.data[i];
			arr.push(cp_format_address(c,i,0,'cpc'));
		}
		
	}
	dge('ct_dir_body').innerHTML=arr_big.join('')+arr.join('');
}

function row_to_isbigresults(el)
{
	return el.childNodes[1];
}

# contact search results MW:ABOOK
var contact_search={};
function seach_now_isbig(el,abook,type)
{
	var match=dge(type+'_search').value;
	var o=row_to_isbigresults(ancestor_by_class(el,'isbig'));
	o.innerHTML='<div style="text-align:center;">$$st_ct_searching$$</div>';
	abooks[abook].data=[];
	sndReq('cmd=contact_search,show&page=~contacts.js&abook='+xescape(abook)+'&match='+xescape(match), function(chan){
		var success=actionReqJsStat(chan);
		if(!success){
			set_status('$$st_ct_srchbig_fail$$','warning');
		}
		seach_done_cp(o,abook,type);
	});
}
function plain_entry(cid,a,late_add)
{
#	dbg('***:'+cid+':'+a.svr_id+':***')
	abooks[a.abook].data.push(a);
}
function seach_done_cp(o,abook,type)
{
	var abk=abooks[abook];
	var arr=[],opt={};

	for (i=0;i<abk.data.length;i++){
		var c=abk.data[i];
		if(type=='cp'){
			arr.push(cp_format_address(c,i,0,'cpc'));
		}else{
			cm_output_contact(arr,abk,i,opt);
		}
	}
	o.innerHTML=arr.join('');
}

function isbig_search_link(name,type)
{
	var arr=[];
	var txt1='$$st_ct_warn_nobrowse$$';
	var btn_style=(type=='cp'?'margin:5px 0 0 10px':'margin:auto');
	var btn='<input type=button disabled="disabled" value="$$st_ct_search_now$$" onclick="seach_now_isbig(this,\''+name+'\',\''+type+'\')" style="'+btn_style+'">';
	
	if(type=='cp'){
		arr.push('<div class="xrow_container shared_abook" style="border-bottom:none;">$$st_ct_directory$$ '+name+'</div>');
		arr.push('<div class="xrow_container isbig"><div style="padding:10px 20px;">');
		arr.push('<div style="float:right">'+btn+'</div>'+txt1+'</div>');
		arr.push('<div style="background:#eee;border-top:1px solid #aaa"></div></div>');
	}else{
		arr.push('<div class="isbig"><div style="padding:10px 20px;">'+txt1);
		arr.push('<div style="text-align:center">'+btn+'</div></div>');
		arr.push('<div style="background:#eee;border-top:1px solid #aaa"></div></div>');
	}	
	return arr.join('')
}
function cm_contact_print()
{
	if(!cm_cur_client_abook || !cm_cur_client_cid) {
		x_alert('$$st_ct_err_select$$');
		return;
	}
	var new_win=open_popup('cmd=show&page=print.htm&show=contact&sid='+sid);	
	if (new_win==null) return;	
	pending_popups[new_win]={'type':'print', 'extra':'format_boxes', 'cb':function(doc){
			return cm_contact_show_html(cm_cur_client_abook,cm_cur_client_cid,abooks[cm_cur_client_abook].data[cm_cur_client_cid],false);
		}};		
}
function cm_contact_printlist()
{
	var abk=abooks[cm_cur_client_abook];
	var g=group_find(abk,cm_cur_group);
	var i,xbad;
	var cids=g.contacts;
	if(!g.isfake && cids.length==0) {
		xbad=$('$$st_ct_noprint$$',cm_cur_group);
	}else{
		if(cm_cur_group=="All Addresses") xbad='$$st_ct_warn_print_1abk$$';
	}
	if(xbad){
		x_alert(xbad);
		return;
	}
	var new_win=open_popup('cmd=show&page=print.htm&show=contact&sid='+sid);	
	if (new_win==null) return;	
	pending_popups[new_win]={'type':'print', 'extra':'format_boxes', 'cb':function(doc){
			var arr=['<div style="padding:30px;font-style:Arial;font-size:12pt;">'];
			var as_group=!g.isfake || g.isfav;
			arr.push('<table  class="clist_t"><th colspan="3"  class="clist_th">$$st_ct_print_for$$ '+email+' : '+cm_cur_client_abook+(as_group?'':' - '+g.name)+'</th>');		
			if(as_group){
				for(i=0;i<cids.length;i++){
					output_printlist_contact(arr,abk.data[cids[i]]);
				}
			}else{
				for(i=0;i<abk.data.length;i++){
					output_printlist_contact(arr,abk.data[i]);
				}
			}
			arr.push('</table>');
			return arr.join('');
		}};		
}

function output_printlist_contact(arr,c)
{
	var i;
	var name=c_name(c); 
	var len=mymax(c.email,c.phone);
	if(!name && len==0) return;
	for(i=0;i<len;i++){
		if(i>0) name='';
		var format=(i==len-1?'clist_td':'clist_td2');
		arr.push('<tr><td class="'+format+'">'+name+'</td><td class="'+format+'">'+c_email_x(c,i)+'</td><td class="'+format+'">'+c_phone_x(c,i)+'</td><tr>');				
	}

}
function get_svr_cid2(abook,cid)
{
 	var abk=abooks[abook];
 	if(!abk) return '';
 	var c=abk.data[cid];
 	if(!c) return '';
 	return c.svr_id;
}
function get_svr_cid()
{
	if(!cm_cur_client_abook) return '';
 	var abk=abooks[cm_cur_client_abook];
 	if(!abk) return '';
 	var c=abk.data[cm_cur_client_cid];
 	if(!c) return '';
 	return c.svr_id;
}
function get_group()
{
	if(!cm_cur_group) return '';
	return cm_cur_group;
}
function get_abook()
{	
	if(!cm_cur_client_abook) return 'User';
	return cm_cur_client_abook;
}

function split_to_addresses(txt)
{
	var in_quote=false;
	var arr=[], i=0, start=0, last_c, c, subtxt;
	for(i=0;i<txt.length;i++,last_c=c){
		c=txt[i];
		
		if(in_quote){
			if(c=='"' && last_c!='\\'){
				in_quote=false;
			}
			continue;
		}
		
		if(!in_quote && c=='"'){
			in_quote=true;
			continue;
		}
		
		if(c==';' || c==',' || c=='\r' || c=='\n'){
			subtxt=txt.substring(start,i);
			start=i+1;
			if(subtxt && subtxt.length>0) arr.push(subtxt);
		}
	}
	subtxt=txt.substring(start,i);
	if(subtxt && subtxt.length>0) arr.push(subtxt);
	
	return arr;
}