# ****************************************************************************
# Surgeweb javascript - User interface handler functions
# Note: sw.js is the primary surgeweb javascript code
# ----------------------------------------------------------------------------
#  These functions are designed to be called from multipe user interface elements etc 
# ****************************************************************************

function swcmd(action,e,input)
{
#	alert("requested to:"+action+" the messages="+sel.join(','));
	if (action.length==0) return;
	if (action=='sw_delete') 	do_delete();
	else if (action=='sw_read')		do_mark_read();
	else if (action=='sw_unread')	do_mark_unread();
	else if (action=='sw_reply_all') do_reply_all(e);
	else if (action=='sw_redirect')	do_redirect(e);
	else if (action=='sw_send_asnew') do_send_asnew(e);
	else if (action=='sw_forward_attach') 	do_forward_attach(e);
	else if (action=='sw_new_note') do_new_note(e);
	else if (action=='sw_forward') 	do_forward(e);
	else if (action=='sw_reply') 	do_reply(e);
	else if (action=='sw_cache') 	do_cache();
	else if (action=='sw_compose') 	do_compose(e);
	else if (action=='sw_edit') 	do_edit(e);
	else if (action=='sw_print') 	do_print();
	else if (action=='sw_copy') 	do_copy_show(e,input);
	else if (action=='sw_move') 	move_menu(e,'more_actions',input);
	else if (action=='sw_move_forever') 	move_menu(e,'more_actions',input,true);	// QQFILE
	else if (action=='sw_spam') 	do_spam();
	else if (action=='sw_block') 	do_block();
	else if (action=='sw_notspam') 	do_notspam();
	else if (action=='sw_label') 	labels_menu(e,'more_actions',input);
	else if (action=='sw_scomment') 	edit_scomment();
	else if (action=='sw_download_msg') 	do_download_msg();
	else if (action=='sw_defer') 	do_defer_show(e,input);
	else if (action=='sw_download') do_download();
	else alert('Sorry  don\'t know how to '+action+' yet');
}

function do_reply(e)
{
	var mnu = dge('mnu_reply');
	if(mnu && mnu.as_edit) return do_edit(e);
	var sel=find_sel();
	if (!check_sel(sel,'$$st_type_replied_to$$')) return;
	var jmsg=sel_to_jmsg(sel,'reply');
	xol_activity('replying',jmsg2rcpt(jmsg),'none');
	show_edit(jmsg,e);
}

function do_resend(e)
{
	var sel=find_sel();
	if (!check_sel(sel,'$$st_type_resent$$')) return;
	var jmsg=sel_to_jmsg(sel,'resend');
	jmsg.action='resend';
	show_edit(jmsg,e);
}

function do_mark_unread()
{
	var sel=find_sel();
	if (!sel) return;
	for_each_msg(sel,function(node){class_add(node,'msg_unread')});
	ajax_set_flags(sel,'clear','seen',function(success){
		if(success) return
		for_each_msg(sel,function(node){class_remove(node,'msg_unread');});
	});
	do_select('none');
}
function do_mark_read()
{
	var sel=find_sel();
	if (!sel) return;
	for_each_msg(sel,function(node){class_remove(node,'msg_unread')});
	ajax_set_flags(sel,'set','seen',function(success){
		if(success) return
		for_each_msg(sel,function(node){class_add(node,'msg_unread');});
	});
	do_select('none');
}
function do_mark_flagged(sel,nowarn)
{
	var sel2=find_sel(nowarn);
	if (!sel || sel_multi_contains(sel2,sel)) sel=sel2; 
	if (!sel) return;
	for_each_msg(sel,function(node){
		var el = row_to_star(node);
		class_add(el,'star_sel')
#		if(new_wide()){
#			class_add(el,'star');
#		}
	});
	ajax_set_flags(sel,'set','flagged',function(success){
		if(success) return
		for_each_msg(sel,function(node){class_remove(row_to_star(node),'star_sel');});
	});
}
function do_mark_unflagged(sel,nowarn)
{
	var sel2=find_sel(nowarn);
	if (!sel || sel_multi_contains(sel2,sel)) sel=sel2; 
	if (!sel) return;
	if (sel_is_todo(sel)){
		x_confirm('$$st_dlg_remove_todo$$', function(n){
			if(!n) return;
			do_mark_unflagged_step2(sel);		
		});
		return;
	}
	do_mark_unflagged_step2(sel);
}
function sel_multi_contains(sel2,sel)
{
	if(!sel || !sel2) return false;
	if(sel.length!=1 || sel2.length<2) return false;
	var val=sel[0];
	for(i=0;i<sel2.length;i++){
		if(sel2[i]==val) return true;
	}
	return false;
}

function do_mark_unflagged_step2(sel)
{
	var refresh_mid=-1;
	for_each_msg(sel,function(row){
		var el = row_to_star(row);
		class_remove(el,'star_sel');
		if(!class_contains(el,'star_blue')) return;
		reset_deferred(row,el);
		refresh_mid=row_to_mid(row);
	});
	ajax_set_flags(sel,'clear','flagged',function(success){
		if(!success){
			for_each_msg(sel,function(node){class_add(row_to_star(node),'star_sel');});
		}else{
			for_each_msg(sel,function(node){
				var edit_xid = cache_id(sw.ident,sw.fid,row_to_mid(node));
				if(edit_xid!=preview_xid) return;
				preview_msg(preview_xid);
			});
		}
	});
}

function reset_deferred(row,el)
{
	class_remove(el,'star_blue');
	var mid=row_to_mid(row);
	var xid=cache_id(sw.ident,sw.fid,mid);
	if (sw_cache && cache_find(xid)) 
		cache_remove(xid,true);
}
# QQQ REMOVE Deferred notice



function do_set_todo(sel)
{
	if (!sel) sel=find_sel();
	if (!sel) return;
	for_each_msg(sel,function(node){
		class_remove(row_to_star(node),'star_sel');
		class_add(row_to_star(node),'star_blue');
	});
	ajax_set_todo(sel,'set','flagged',function(node){class_add(node,'action_pending_hide')})
}

function sel_is_todo(sel)
{
	var is_todo = false;
	for_each_msg(sel,function(node){
		if(node.getAttribute('msg_todo')){
			is_todo=true;
		}
	});
	return is_todo;
}



function do_copy_email(sel)
{
	if (!sel) sel=find_sel();
	if (!sel) return;
	var txt = '';
	var count = 0;
	for_each_msg(sel,function(node){
		if(count>20) return;
		if(txt.length>0) txt += ', ';
		txt += row_to_email(node);
		count++;
	});
	copy_popup(txt);
}


function check_sel(sel,type)
{
	if (!sel) return false;
	if (sel.length>1) alert($('$$st_selcheck$$',type));
	return true;
}

function do_forward(e){
	var sel=find_sel();
	if (!sel) return false;
	var jmsg=sel_to_jmsg(sel,'forward')
	show_edit(jmsg,e);
}
function do_reply_all(e){
	var sel=find_sel();
	if (!check_sel(sel,'$$st_type_replied_to$$')) return;
	var jmsg=sel_to_jmsg(sel,'reply_all')
	show_edit(jmsg,e);
}
function do_redirect(e){
	var sel=find_sel();
	if (!check_sel(sel,'$$st_type_redirected$$')) return;
	var jmsg=sel_to_jmsg(sel,'redirect')
	show_edit(jmsg,e);
}
function do_send_asnew(e){
	var sel=find_sel();
	if (!check_sel(sel,'$$st_type_sent_again$$')) return;
	var jmsg=sel_to_jmsg(sel,'send_asnew')
	show_edit(jmsg,e);
}
function do_forward_attach(e){
	var sel=find_sel();
	if (!sel) return false;
	var jmsg=sel_to_jmsg(sel,'forward_attach')
	jmsg.msg_html='';
	show_edit(jmsg,e);
}
function do_edit(e)
{
	var sel=find_sel();
	if (!sel) return;
	var jmsg=sel_to_jmsg(sel,'edit')
	show_edit(jmsg,e);
}

function do_notspam()
{
	var sel=find_sel();
	if (!sel) return;
	ajax_spam_rating(sel,'notspam',function(node){class_remove(node,'foo')})
	do_select('none');
}
function do_block()
{
	var sel=find_sel();
	if (!sel) return;
	x_confirm('$$st_spam_really_block$$',function(n){
		if(!n) return;
		ajax_spam_rating(sel,'block',function(node){class_remove(node,'foo')})
		message_done_action(sel);
	});	
}
function do_spam()
{
	var sel=find_sel();
	if (!sel) return;
	ajax_spam_rating(sel,'spam',function(node){class_remove(node,'foo')})
	message_done_action(sel);
}


function show_raw(iid,mid)
{
	dbg("show_raw");
	open_popup('cmd=msgpart&sid='+sid+'&ident='+iid+'&fld_id='+xescape(sw.fld_id)+'&msg_id='+mid+'&part_id=0');
}
function show_text(iid,mid,pid)
{
	dbg("show_html");
#	headers now say text/plain instead of text/html so no web encoding should be required
	open_popup('cmd=msgpart&sid='+sid+'&ident='+iid+'&fld_id='+xescape(sw.fld_id)+'&msg_id='+mid+'&part_id='+pid);
}
function show_html(iid,mid,pid,allow_images)
{
	dbg("show_html");
	var extra = '&process=simple_wash';
	if (allow_images=='once') extra += '&allow_images='+allow_images;
	open_popup('cmd=msgpart&sid='+sid+'&ident='+iid+'&fld_id='+xescape(sw.fld_id)+'&msg_id='+mid+'&part_id='+pid+extra);
}
function show_img(iid,mid,pid)
{
	open_popup('cmd=msgpart&sid='+sid+'&ident='+iid+'&fld_id='+xescape(sw.fld_id)+'&msg_id='+mid+'&part_id='+pid);
}

function do_customise()
{
	x_alert("Sorry, menu customise not implemented just yet.");
}

function do_na(txt)
{
	x_alert("Sorry, "+txt+" not implemented yet");
}

function do_folder_manage()
{
	sndReq('cmd=show&page=~folders.htm'+iid(), function(chan){
		node=actionReqSethtml(chan.responseText,'utility');
	});
}

function do_compose(e,ident,rcpt)
{
	if(!e) e = window.event;
	dbg('do_compose');
	if(!rcpt) rcpt=[];
	var jmsg=compose_jmsg(rcpt,ident);
	xol_activity('replying',jmsg2rcpt(jmsg),'none');
	show_edit(jmsg,e);
	return stopEvent(e);
}
function do_compose_note(e,ident)
{
	dbg('do_compose_note');
	var jmsg = compose_jmsg([],ident);
	jmsg.note=true;
	jmsg.fld_id=sw.fld_id;
	show_edit(jmsg,e);
	return stopEvent(e);
}
function do_compose_xol(e,rcpt)
{
	dbg('do_compose_xol');
	var jmsg=compose_jmsg([rcpt]);
	jmsg.sim=true;
	xol_activity('composing',jmsg2rcpt(jmsg),'none');
	show_edit(jmsg,e,'popup');
}

function edit_discard()
{
	if(!sw.active.unsaved){
		edit_discard_real();
	}else{
		x_confirm('$$st_warn_lose_msg$$',function(n){
			if (!n)return;
			edit_discard_real();
		});
	}
}
function edit_discard_real()
{
	if (sw.is_popup) {
		sw.closing=true;
		window.close();
		return;
	}
	var jmsg = sw.active.jmsg;
	ie_fixfocus();
	window_manager_killpane(sw.active);
	set_status('$$st_stat_discard$$',"success");
	window_manager_restore();
	if(jmsg.edit_uid){
		do_delete2(jmsg.edit_uid,pref.special_trash,true);
	}
}
function msg_list_dblclick(e){
	var t=target(e);
	var row=gs_find_row(sw.ml,t);
	var valid_row=row_to_sel(row);
	if (!valid_row) return;
	var mid=valid_row.id.substring(4);
	
	gs_list_dblclick(sw.ml,e);

	if (e.shiftKey || e.ctrlKey){
		msglist_select(mid);	
	}
	
	if (pref.mode=='web'){
		preview_msg(mid,undefined,undefined,keys_2horiz(e)||disable_markread_fld);
	}
	show_msg(mid,e);
	if (pref.mode=='app'&&pref.preview=='none' || pref.mode=='web'){
		mark_read(mid);
	}	
}
# QQSEL CLICK
function msg_list_click(e){
	// select more than one if we have to...
	var t=target(e);
	var tag=t.tagName.toLowerCase();
	var row=gs_find_row(sw.ml,t);
	if(!row) return;
	var web = pref.mode=='web' && tag=="a";
	var mid;

	if(class_contains(row,'multi_row')){
		alert('msg_list_click multi_row custom_click');
		return;
	}

# b4 generic list handling
	if (tag=="input"){

	} else {
		// click anywhere in a row
		var td=gs_find_td(sw.ml,t);
		if(td==row.childNodes[1]){
			if(pref.preview=='vert') return;
			if(t!=td && !new_wide()) return;
		}
		var valid_sel=row_to_sel(row);
		if (!valid_sel) return;
		var toggle_star=false;
		if (td==row.childNodes[0]) {
			if(pref.preview=='vert') toggle_star=true;
			if(pref.preview=='horiz' && t!=td) toggle_star=true;
		}
		if(toggle_star){
		 	mid=sel_to_mid(valid_sel);
		 	sel=make_sel(sw.fld_id,mid);
		 	var el=row_to_star(td.parentNode);
		 	if(class_contains(el,'star_sel') || class_contains(el,'star_blue')){
				do_mark_unflagged(sel,true);
			}else{
				do_mark_flagged(sel,true);
			}
			return;
		}
	}

	if(class_contains(row,'msg_unread')){
		xol_activity('reading',row.getAttribute('from_email'),'none');	
	}

# 	//generic list click selection
	gs_list_click(sw.ml,e);

# after generic list handling
	if (tag=="input"){
#			no_msg_nopreview();
	} else {
		var valid_sel=row_to_sel(row);
		mid=sel_to_mid(valid_sel);
		var unselect;
		unselect=valid_sel.checked;
		if (!unselect){
			msglist_select(mid,true);	
		}
		if (pref.mode=='app'&&pref.preview!='none'){
			preview_msg(mid,undefined,undefined,keys_2horiz(e)||disable_markread_fld);
		}
		if (web){
			dbg("*** new handler :-) showing msg");
			show_msg(mid,e);		// This depends on separate retrieval of actual message content
			mark_read(mid);
		}
	}
	

#	gs_shift_start_set(sw.ml,row); ??
	touch(8);
	if (tag!="input") 
		return false;
}

var last_retr_mid, last_retr_time;
function retrieve_msg(fld,mid,cb,extra,nostatus)
{
	var now=mtime();
	if(last_retr_mid==mid && last_retr_time>now-1000) {
		dbg("IGNORING retrieve_msg request - too soon, mid="+mid);
		return;
	}
	dbg("retrieve_msg request mid="+mid);
	last_retr_time=now;
	last_retr_mid=mid;
	if(!extra) extra='';
	amsg=U;
||iftrue(using_api)||
	apiGet('message?v=sw&msg_id='+mid+"&fld_id="+xescape(fld)+iid()+plain()+eil()+extra, function(chan){
||else||
	sndReq('cmd=show&page=~msg.js&msg_id='+mid+"&fld_id="+xescape(fld)+iid()+plain()+eil()+extra, function(chan){
||endif||
		if (chan.status!=200){
			dbg('chan.status='+chan.status)
			success_string=err_general(chan,2);
			set_status('$$st_stat_retr_fail$$ '+success_string,'warning');
			if(cb) cb(false);
			return;
		}else{
			if(!nostatus) set_status();
		}

		var success=actionReqJsStat(chan);
		cache_add(cache_id(sw.ident,sw.fid,mid), amsg);
		if(cb) cb(chan, true);
	});
}
function to_msg_display(el)
{
	return el.childNodes[1];
}

function assign_destination_html(destination,mid,txt)
{
	var el=dge(destination);
	el.innerHTML=txt;
	scroll_top(el);	
	if(destination=='message_preview')
		preview_mid=mid;
}

var seen_timer;
var amsg,allmsgs;
var preview_mid;
var preview_xid;
# Asynchronously retrieve message (and do any requested completion action - only used for preview)
# This should really start using the actual retrieve_msg function
function preview_msg(mid,cb,nostatus,disable_markread)	// cf n show_preview
{
	if (seen_timer) clearTimeout(seen_timer);

	todo_overlay(false);

	var destination;
	if (pref.preview=='none')
		return;

	destination='message_preview';

	var fld=sw.fld_id;

	dbg("preview message id=="+mid+" display 2");

	var xid=cache_id(sw.ident,sw.fid,mid);
	preview_xid = xid;
	
#	All getting a bit messy - should try and tidy this up
	var new_cursor_mid=(sw.xfolder?just_fid_mid(xid):just_mid(mid));
	gs_set_cursor_mid(sw.ml,new_cursor_mid);
	if(sw_cache && cache_find(xid)){
		dbg("attempting to load message id="+mid+" from cache");
		var qmsg=cache_find(xid);
		assign_destination_html(destination,mid,html_from_qmsg(qmsg));
		special_processing(destination,qmsg);	

# _scroll_not_yet_
#		dge("message_preview").scrollTop=dge("msg_headers").scrollHeight;

		set_status();
		if(!disable_markread && !pref.markread_onopen) mark_read(mid);
		check_rrcpt(qmsg);
		update_replyedit(qmsg);
		animate_in_msg();
//		xol_activity('reading',qmsg2rcpt(qmsg),'none');			

	}else{
		if (destination) set_loading(destination);		
		retrieve_msg(sw.fld_id,mid, function(chan,success){
			if (destination) doneloading();
			if (!success) {
				dge(destination).innerHTML='$$st_pane_failed$$';
				return;
			}
			if (xid!=preview_xid) return;
			var qmsg=cache_find(xid);
			if(qmsg==U) {
				assign_destination_html(destination,mid,"")
				set_status('Message retrieve failed failed (msg id='+xid+')','warning');
				return;
			}
			assign_destination_html(destination,mid,html_from_qmsg(qmsg));
			special_processing(destination,qmsg);	
# _scroll_not_yet_
#			dge("message_preview").scrollTop=dge("msg_headers").scrollHeight;

			if(!disable_markread && !pref.markread_onopen) mark_read(mid)
			check_rrcpt(qmsg);				
			update_replyedit(qmsg);
			animate_in_msg();
//			xol_activity('reading',qmsg2rcpt(qmsg),'none');			
		},nostatus);	
	}
}

function special_processing(destination,qmsg)
{
	if(destination=='message_preview'){
		var o=dge('msg_to');
		if(!class_contains(o.parentNode,'hidden_in_preview') && !class_contains(dge('msg_cc').parentNode,'hidden') && qmsg.data.nrcpts_to<=2)
			class_add(o.parentNode, 'float_left');
		set_ads_targeted(qmsg.data['subject']);		
||ifdef||_note_not_yet_||
		if(!pref.notes_oldformat){
			class_update(dge(destination),'note_itself',qmsg.data.note);
		}
||endif||
	}
}


function do_logout(reason)
{
	logging_out=true;
	sw.closing=true;
	var f=document.main;
	f.sid.value=sid;
	f.logout_reason.value=reason;
	f.submit();
}


function do_delete(force)
{
	if (sw.is_popup){
		sw_win.do_delete2(sw.mid);
		window.close();
		return;
	}

	var sel=find_sel(true);
	if (!sel) return;

	if (!pref['confirm_delete'] || force || sel.length==1 ){
		do_delete_step2(sel);
		return;
	}
	x_confirm($('$$st_dlg_del$$',sel.length),function(n){
		if (!n)return;
		do_delete_step2(sel);
	});
}
function do_delete_step2(sel)
{
	set_status("$$st_stat_del$$","info");
	do_select('none');
	ajax_delete(sel);
	message_done_action(sel);
}

function options_show_iframe(name, show)
{
	if(show){
		class_remove(dge(name),'hidden');
		class_add(dge(name+'_other'),'hidden');
	}else{
		class_add(dge(name),'hidden');
		dge(name).src = '';
		class_remove(dge(name+'_other'),'hidden');
	}
}

var options_late_init, options_late_cmd;
function do_usercgi_inline(type, cmd)
{
	var options_visible = class_contains(sw.active,'options');
	if(type=='log_only' || type=='spam2' || !options_visible ){
		options_late_init = type;
		options_late_cmd = cmd;
		do_options();
	}else{
 		if(type=='password'){
 			do_usercgi_inline_step2('usercgi_general_iframe',cgibase+cmd);
 		} else if(type=='log' || type=='responder' || type=='forwarding' || type=='filtering' || type=='whitelist' || type=='friends'){
 			do_usercgi_inline_step2('usercgi_filter_iframe',cgibase+cmd);
 		} else if(type=='legal' || type=='notify' || type=='lists' || type=='import' || type=='aliases'  ){
 			do_usercgi_inline_step2('usercgi_extra_iframe',cgibase+cmd);
 		} else {
 			alert('unkown action ['+type+'] in do_usercgi_inline');
 		}
	}
}

function do_usercgi_inline_step2(frame,url)
{
	options_show_iframe(frame, true);
	do_resize_real();
	dge(frame).src = url;
}

function do_options(showall,extra)
{
	node=sw.active;
	if (node && node.className=="compose")
		window_manager_minimise(node);
	var cmd='cmd=show&page=~options.htm';
	if(extra) cmd+=extra;
	if(showall)
		cmd+='&lang_showall=true';

	sndReq(cmd, function(chan){
#		// Similar in manage_folders / manage_page - refactor?
		if (chan.status!=200){
			success_string=err_general(chan,3);
			set_status(success_string,'warning');
			return false;
		}
		node=actionReqSethtml(http.responseText,'utility');
		if (global_auth_error){
			global_auth_error=false;
			window_manager_restore();
		}		
		if(options_late_init!=U){
			switch(options_late_init){
			  case 'password':{
				vtab_init('o',1);
				do_usercgi_inline_step2('usercgi_general_iframe',cgibase+options_late_cmd);
			  } break;
			  case 'log_only':{
				vtab_init('o',2);
				do_usercgi_inline_step2('usercgi_filter_iframe',cgibase+options_late_cmd);
			  } break;
			  case 'spam2':{
				vtab_init('o',8);
				do_usercgi_inline_step2('usercgi_spam_iframe',cgibase+options_late_cmd);
			  } break;
			}
			options_late_init=U;
		}				
	});
}

function options_discard(show_alert)
{
	ie_fixfocus();
	window_manager_killpane(sw.active);
	if(show_alert){
		set_status('$$st_stat_opt_discarded$$',"success");
	}
	window_manager_restore();	
}

function options_refresh_fingerprint()
{
	return pref.windows +'|'+ pref.preview +'|'+ pref.mode +'|'+ pref.language;
}

function options_save(type)
{
	var fake_form, real_form, pane, recache;
	var finger=options_refresh_fingerprint();
	ie_fixfocus();
	real_form=document.options;

	var btns=toolbar_buttons_get();

#	Send everything to the server
	fake_form='cmd=save_options,show&page=~result.js';

	if(type=='general' || type==U){
		fake_form+='&pref_language='+real_form.pref_language.value;
		fake_form+='&language='+real_form.pref_language.value;
		fake_form+='&pref_allow_images='+real_form.pref_allow_images.value;
		fake_form+='&pref_sounds='+real_form.pref_sounds.value;
		if(real_form.pref_alert_cal){
			fake_form+='&pref_alert_cal='+real_form.pref_alert_cal.value;
		}
		fake_form+='&pref_alert_eml='+real_form.pref_alert_eml.value;
		fake_form+='&pref_image_resize='+real_form.pref_image_resize.value;
		fake_form+='&pref_spellcheck_language='+real_form.pref_spellcheck_language.value;
		if(real_form.pref_reply)
			fake_form+='&pref_reply='+encodeURIComponent(real_form.pref_reply.value);
		fake_form+='&pref_timezone='+real_form.pref_timezone.value;
		fake_form+='&pref_signature='+xescape(real_form.pref_signature.value);		
	}

	if(type=='layout' || type==U){
		debugger
		fake_form+='&pref_mode='+real_form.pref_mode.value;
		fake_form+='&pref_preview='+radio_value(real_form.pref_preview);
		fake_form+='&pref_windows='+radio_value(real_form.pref_windows);
	}	

	if(type=='custom' || type==U){
		fake_form+='&pref_toolbar_buttons='+btns;
	}

	if(type=='advanced' || type==U){
		fake_form+='&pref_date_format='+real_form.pref_date_format.value;
		fake_form+='&pref_time_format='+real_form.pref_time_format.value;
		fake_form+='&pref_message_done_action='+real_form.pref_message_done_action.value;
		fake_form+='&pref_message_done_action2='+real_form.pref_message_done_action2.value;
		fake_form+='&pref_edit_mode='+real_form.pref_edit_mode.value;
		fake_form+='&pref_sticky_menus='+real_form.pref_sticky_menus.checked;
		fake_form+='&pref_remember_sort='+real_form.pref_remember_sort.checked;
		fake_form+='&pref_contact_sort='+real_form.pref_contact_sort.value;
		fake_form+='&pref_autologout_type='+real_form.pref_autologout_type.value;
		fake_form+='&pref_show_snippets='+real_form.pref_show_snippets.value;
		fake_form+='&pref_snippet_lines='+real_form.pref_snippet_lines.value;	
		fake_form+='&pref_rrcpt_local='+real_form.pref_rrcpt_local.value;
		fake_form+='&pref_rrcpt_whitelist='+real_form.pref_rrcpt_whitelist.value;
		fake_form+='&pref_rrcpt_unknown='+real_form.pref_rrcpt_unknown.value;
		fake_form+='&pref_attach_flash='+real_form.pref_attach_flash.value;
		fake_form+='&pref_purge_confirm='+real_form.pref_purge_confirm.value;
		fake_form+='&pref_https_required_user='+real_form.pref_https_required_user.checked;
		if(!pref.defer_disable){
	||if(not(istrue(context_disable)))||
			fake_form+='&pref_hide_widehist='+real_form.pref_hide_widehist.value;
	||endif||
		}
		//
		fake_form+='&pref_nocompress='+real_form.pref_nocompress.checked;
		fake_form+='&pref_nocache='+real_form.pref_nocache.checked;
		fake_form+='&pref_noautoadd='+real_form.pref_noautoadd.checked;
		fake_form+='&pref_no_short_reply_hdr='+real_form.pref_no_short_reply_hdr.checked;
		fake_form+='&pref_no_fancy_rcpt='+real_form.pref_no_fancy_rcpt.checked;
		fake_form+='&pref_no_filtermenus='+real_form.pref_no_filtermenus.checked;
		fake_form+='&pref_no_replycolor='+real_form.pref_no_replycolor.checked;
		fake_form+='&pref_no_auto_timezone='+real_form.pref_no_auto_timezone.checked;
		fake_form+='&pref_no_pending_hide='+real_form.pref_no_pending_hide.checked;
		fake_form+='&pref_no_interleaved='+real_form.pref_no_interleaved.checked;
		fake_form+='&pref_editor_textonly='+real_form.pref_editor_textonly.checked;
		fake_form+='&pref_clean_resend='+real_form.pref_clean_resend.checked;
		fake_form+='&pref_imap_refresh='+real_form.pref_imap_refresh.checked;
		fake_form+='&pref_show_inline='+real_form.pref_show_inline.checked;
		fake_form+='&pref_send_mode='+real_form.pref_send_mode.value;
		
	}

	if(type=='dev' || type==U){
		fake_form+='&pref_devt_mode='+real_form.pref_devt_mode.checked;
		fake_form+='&pref_custom='+real_form.pref_custom.value;
		fake_form+='&pref_nocheck='+real_form.pref_nocheck.checked;
		fake_form+='&pref_nocontacts='+real_form.pref_nocontacts.checked;
		fake_form+='&pref_unimplemented='+real_form.pref_unimplemented.checked;
		fake_form+='&pref_colour='+real_form.pref_colour.value;
	}

/*
	for(var i=1;i<=6;i++){
		if(!real_form['pref_folder_move_'+i]) break;
		fake_form+='&pref_folder_move_'+i+'='+xescape(real_form['pref_folder_move_'+i].value);
	}
*/

	pane=sw.active;
	set_status("$$st_saving_options$$","info");
	sndReqPost(fake_form, function(chan){
		var success=actionReqJsStat(chan);			
		

		// Do success fail check
		set_status($('$$st_stat_opt_saved$$','<a href="#" onclick="do_reload()">','</a>'),"success");		

		
		if(type=='general' || type==U){
			pref.language=real_form.pref_language.value
			if(pref.allow_images!=real_form.pref_allow_images.value){
				pref.allow_images=real_form.pref_allow_images.value;
				cache_clear();
			}
			pref.sounds=real_form.pref_sounds.value;
			if(real_form.pref_alert_cal){
				pref.alert_cal=real_form.pref_alert_cal.value;
			}
			pref.alert_eml=real_form.pref_alert_eml.value;
			if(pref.show_inline!=real_form.pref_show_inline.checked){
				pref.show_inline=real_form.pref_show_inline.checked;
				cache_clear();
			}
			if (real_form.pref_reply)
				pref_reply=real_form.pref_reply.value;
		}
		if(type=='layout' || type==U){
			pref.mode=real_form.pref_mode.value
			pref.preview=radio_value(real_form.pref_preview)
			pref.windows=radio_value(real_form.pref_windows)
		}
		if(type=='custom' || type==U){
		}
		if(type=='advanced' || type==U){
			pref.message_done_action=real_form.pref_message_done_action.value;
			pref.message_done_action2=real_form.pref_message_done_action2.value;
			pref.sticky_menus=real_form.pref_sticky_menus.checked

			pref.no_short_reply_hdr=real_form.pref_no_short_reply_hdr.checked;
			pref.no_fancy_rcpt=real_form.pref_no_fancy_rcpt.checked;
			pref.no_filtermenus=real_form.pref_no_filtermenus.checked;
			pref.no_replycolor=real_form.pref_no_replycolor.checked
			pref.clean_resend=real_form.pref_clean_resend.checked;
			pref.send_mode=real_form.pref_send_mode.value;
		}
		if(type=='dev' || type==U){

		}

#	Update relevant local settings
		
		if(pref.nocache!=real_form.pref_nocache.checked || !done_cache){
			pref.nocache=real_form.pref_nocache.checked;
			if (pref.nocache){
				cache_clear();
			}else{
				var fld=sw.fld_id;
				if(fld=='INBOX'){
					var msgs=find_msgs();
					if (msgs.length==0) return;
					setTimeout(function(){		
						done_cache=true;
						ajax_cache_messages(msgs);	
					},400);
				}
			}
		}
		if(pref.toolbar_buttons!=btns){
			pref.toolbar_buttons=btns;
			toolbar_buttons_customise(btns);
			toolbar_buttons_customise2(btns);
		}
		if(type==U){		
			window_manager_killpane(sw.active);
			window_manager_restore();	
		}	
		if(finger!=options_refresh_fingerprint()){
			x_confirm('$$st_dlg_reload$$',function(n){
				if (!n)return;
				do_reload();
			});
		}
	});	
}

function msglist_rows(o)
{
	return o.getElementsByTagName("tr");
}

function select_mailbox_all(type)
{
	if(sw.nav_count==sw.nav_total)	return;
	var ex=dge('list_extra');
	class_remove(ex,'hint')
	if(type=='all'){
		if (sw.nav_total>0 && !sw.search_input.valid){
			class_remove(ex,'hidden');
			class_remove(ex,'all_sel');
			ex.innerHTML=$('$$st_selectall_pg$$',sw.nav_count)+' <a href="#" onclick="select_mailbox_all(\'folder_all\')">'+$('$$st_selectall$$',sw.nav_total,fld_id2name(sw.fld_id))+'</a>';
		}
		sw.sel_all=false;
	}else if(type=='folder_all'){
		class_remove(ex,'hidden')
		class_add(ex,'all_sel');
		ex.innerHTML=$('$$st_selectall_fld$$',sw.nav_total,fld_id2name(sw.fld_id))+' <a href="#" onclick="do_select(\'none\')">$$st_selectall_none$$</a>';
		sw.sel_all=true;
	}else{
		class_add(ex,'hidden')
		sw.sel_all=false;
	}
}

function deselect_mailbox_all()
{
	var ex=dge('list_extra');
	class_add(ex,'hidden')
	sw.sel_all=false;
}


function clear_indexes()
{
	dbg('Clearing indexes serverside');
	x_confirm('$$st_dlg_reset$$',function(n){
		if (!n) return;
		sndReq('cmd=clear_indexes,show&page=~result.js'+iid(), function(chan){
			dbg('response came back, unknown status');
			do_logout('');
		});
	});
}

function manage_page(e, cmd)
{
	sndReq(cmd+iid(), function(chan){
		if (chan.status!=200){
			success_string=err_general(chan);
			set_status(success_string,'warning');
			return false;
		}
		node=actionReqSethtml(chan.responseText,'utility');
		if (global_auth_error){
			global_auth_error=false;
			window_manager_restore();
		}		
	});
	stopEvent(e);
	return false;
}


function manage_folders(e)
{
	return manage_page(e, 'cmd=show&page=~folders.htm');
}

function manage_hints(e)
{
	return manage_page(e, 'cmd=show&page=~hints.htm');
}

function manage_labels(e)
{
	return manage_page(e, 'cmd=show&page=~labels.htm');
}
function manage_calendars(e)
{
	cal_spinner_stop();
	return manage_page(e, 'cmd=cal_action,show&page=~calendars.htm');
}

function index_dump()
{
	sndReq('cmd=index_dump&page=~folders.htm&fld_id='+xescape(sw.fld_id)+iid(), function(chan){
//		node=actionReqSethtml(http.responseText,'utility');
	});
}
function folders_done()
{
	window_manager_minimise(sw.active);
	window_manager_restore();	
}
function calendars_done(old)
{
	if(old) pref.newcal=false;
	app_menu('calendar',dge('app_calendar').parentNode);
}

function tab_close(id){
	var tabtokill=document.getElementById(id);
	tabtokill.closing=true;
	if(tabtokill.node_ref==sw.active){
		window_manager_killpane(tabtokill.node_ref);
		window_manager_restore();
	}else{
		window_manager_killpane(tabtokill.node_ref);
	}
	
#	Make sure we remove the additional nodes too??	

# 	does not work FF/Saf (does in IE) so use tabtokill.closing instead
#	return stopEvent();		
}

function do_save_draft(auto,cb)
{
	var node,win,src_win;
	if(sw.is_popup){
		node=sw.active;
		node.sw_win = sw_win;
		node.is_popup=true;
		win=sw_win;// Pass the send through the parent frame if we can
		if(sw.run_spellcheck_once) win.sw.run_spellcheck_once=true;
	}else{
		win=window;
		node=sw.active;
	}
	src_win=window;
	
	spellcheck_markup_removeall(!auto&&!sw.run_spellcheck_once);	
	win.popup_spellcheck=window;
	
	var jmsg=jmsg_update(node);
	if(jmsg.note){
		jmsg.keep_open=true;
		win.ajax_save_note(jmsg,undefined,function(jsmsg){
			var o=src_win.document.getElementById('compose_info');
			if (o) o.innerHTML=$((auto?'$$st_stat_note_saved1$$':'$$st_stat_note_saved2$$'),time_str());
#			if (cb) cb();
		});
	}else{
		win.ajax_save_draft(jmsg,undefined,function(jsmsg){
			var o=src_win.document.getElementById('compose_info');
			if (o) o.innerHTML=$((auto?'$$st_stat_draft_saved1$$':'$$st_stat_draft_saved2$$'),time_str());
			if (cb) cb();
		});
	}
	if(autosave_timer){
		clearTimeout(autosave_timer);
		autosave_timer=null;
	}
}
function do_save(keep_open)
{
	var node,win,src_win;
	if(sw.is_popup){
		node=sw.active;
		node.sw_win = sw_win;
		node.is_popup=true;
		win=sw_win; // Pass the send through the parent frame if we can
	}else{
		win=window;
		node=sw.active;
	}
	src_win=window;
	spellcheck_markup_removeall(true);	
	var jmsg=jmsg_update(node);
	jmsg.keep_open=keep_open;
	var auto=false;
	win.ajax_save_note(jmsg,undefined,function(jsmsg){
		var o=src_win.document.getElementById('compose_info');
		if (o) o.innerHTML=$((auto?'$$st_stat_note_saved1$$':'$$st_stat_note_saved2$$'),time_str());
	});
}

function sel_and_action(id)
{
	setTimeout(function(){
		var sel=find_sel(true);
		if (!sel) return;
		if (sel.join(',')==id.join(',')){
			do_select('none');			
			message_done_action(sel);
		}
	},150);
}

function do_send_move(e)	// cf ajax_send, do_move, 
{
	var node=sw.active;
	if(sw.is_popup){
		node.sw_win = sw_win;
		node.is_popup=true;
		var jmsg=jmsg_update(node);
		sw_win.ajax_send(jmsg,true,undefined,e.shiftKey==true);
		sw_win.sel_and_action(jmsg.sel_mids);
		sw_win.focus();
		sw.closing=true;
		window.close();
	}else{
		var jmsg=jmsg_update(node);
		ajax_send(jmsg,true,undefined,e.shiftKey==true);
		sel_and_action(jmsg.sel_mids);
		ie_fixfocus()
	}
}
function do_send()
{
	var node=sw.active;
	if(sw.is_popup){
		node=sw.active;
		node.sw_win = sw_win;
		node.is_popup=true;
		if(!main_window_check(node)) return;
		var jmsg=jmsg_update(node);
		sw_win.ajax_send(jmsg);
		sw_win.sel_and_action(jmsg.sel_mids);
		sw_win.focus();
		sw.closing=true;
		window.close();
	}else{
		var jmsg=jmsg_update(sw.active);
		ajax_send(jmsg);
		sel_and_action(jmsg.sel_mids);
		ie_fixfocus()
	}
}

#var app_warning=true;
function do_old(type)
{
	var cmd;

#	if (type!="mail" && type!="contacts" && !pref.hide_integration_warning){
#		x=$('$$st_appmenu_warn$$');
#		if(x)alert(x);
#		ajax_pref_save('pref_hide_integration_warning=true');
#		pref.hide_integration_warning=true;
#	}

	if (type=='mail'){
		if (sw.active && sw.active.id=='iframe_panel'){
			window_manager_killpane(sw.active);
			window_manager_restore();	
		}
	}else if (type=='blogs'){
		cmd=cgibase+'cmd=doauto_login&product=usercgi&type=blogs&sid='+sid;
	}else if (type=='photos'){
		cmd=cgibase+'cmd=doauto_login&product=surgeplus&type=photos&sid='+sid+'&id='+mtime();
	}else if (type=='filestore'){
		cmd=cgibase+'cmd=doauto_login&product=surgeplus&type=filestore&sid='+sid+'&id='+mtime();
	}else if (type=='calendar'){
		cmd=cgibase+'cmd=doauto_login&product=surgeplus&type=calendar&sid='+sid+'&id='+mtime();
	}else if (type=='contacts'){
		return contacts_mgt_sw();
	}else if (type=='todo'){
		cmd=cgibase+'cmd=doauto_login&product=toodledoo&type=todo&sid='+sid+'&id='+mtime();
	}
	if (!cmd) return true;


	sndReq('cmd=show&page=~iframe.htm', function(chan){
		node=actionReqSethtml(chan.responseText,'utility');		
		el=document.getElementById('an_iframe');
		el.src=cmd;		
	});
	return true;
}

var first_contact_warn;
function contacts_mgt_sw()
{
	if (!sw.abooks_old){
		if(first_contact_warn && (first_contact_warn<time()-10)){
			x_alert('$$st_ct_err_fault$$')
		}else{
			x_alert('$$st_ct_err_nodl$$');
			if(!first_contact_warn) first_contact_warn=time();
		}
		return false;
	}

#	sndReq('cmd=show&page=~contacts.htm', function(chan){
	sndReqCached('cmd=show&page=~contacts.htm'+'&if=ajax&static=||web_ref_path||&||vz||', function(chan){
#		// Same in manage_folders
		if (chan.status!=200){
			success_string=err_general(chan,5);
			set_status(success_string,'warning');
			return false;
		}
		node=actionReqSethtml(http.responseText,'utility');
		if (global_auth_error){
			global_auth_error=false;
			window_manager_restore();
		}
		first_contact_warn=U;
		class_add(sw.active,'contacts');
		var gsel=new Object();
		gs_init(gsel,"csel",dge("cm_contacts"));
		gs_callbacks(gsel,contactlist_rows,cl_row_to_sel,cl_sel_to_row,cl_sel_to_mid,cl_find_row,cl_show_soon);
		sw.cl = gsel;
	},ch[enFG]);
	return true;
}	
function contactlist_rows(o) { 
	var elements = o.getElementsByTagName("div");
	var arr = [];
	for(var i=0;i<elements.length;i++){
		var el=elements[i];
		if(class_contains(el,'cm_contact')) arr.push(el);
	}
	return arr;
}
function cl_row_to_sel(o){ return o.childNodes[1].firstChild;};
function cl_sel_to_row(node){ return ancestor_by_tag(node,'div');}
function cl_sel_to_mid(node){ return node.id.substring(5);}
function cl_find_row(o,node){ return ancestor_by_class(node,'cm_contact');}

function contacts_mgt_sp()
{
	var cmd='/surgeplus/web?utoken='+utoken+'&cmd=sp_address_book&hide_menu=true';
	sndReq('cmd=show&page=~iframe.htm', function(chan){
		node=actionReqSethtml(chan.responseText,'utility');		
		el=document.getElementById('an_iframe');
		el.src=cmd;		
	});
}

function allow_images(type,jmsg)
{
	if(!jmsg) jmsg=sw.active.jmsg;
	if(sw.is_popup){
		sw_win.allow_images(type,jmsg);
		show_msg_step2_popup();
		return;	
	}
	var mid,fld,ident;
	if(jmsg){
		ident=jmsg.ident;
		fld_id=jmsg.fld_id;
		fid=jmsg.fid;
		mid=jmsg.cache_mid;
		jmsg_reset(jmsg);
	}else{
		ident=sw.ident;
		fld_id=sw.fld_id;
		fid=sw.fid;
		mid=gs_cursor_mid(sw.ml);
	}

	var xid=cache_id(ident,fid,mid);
	if (sw_cache && cache_find(xid)) 
		cache_remove(xid,true);

	retrieve_msg(sw.fld_id,mid,function(){
			if(class_contains(sw.active,'message')&&sw.active.jmsg.cache_mid==mid)
				show_msg_step2_inline(jmsg,sw.active.instance);
			if(preview_mid==mid)
				preview_msg(mid);
		},'&allow_images='+type);
}
function allow_rpath(type,jmsg)
{
	if(!jmsg) jmsg=sw.active.jmsg;
	if(sw.is_popup){
		sw_win.allow_images(type,jmsg);
		show_msg_step2_popup();
		return;	
	}
	var mid,fld,ident;
	if(jmsg){
		ident=jmsg.ident;
		fld_id=jmsg.fld_id;
		fid=jmsg.fid;
		mid=jmsg.cache_mid;
		jmsg_reset(jmsg);
	}else{
		ident=sw.ident;
		fld_id=sw.fld_id;
		fid=sw.fid;
		mid=gs_cursor_mid(sw.ml);
	}

	var xid=cache_id(ident,fid,mid);
	if (sw_cache && cache_find(xid)) 
		cache_remove(xid,true);

	retrieve_msg(sw.fld_id,mid,function(){
			if(class_contains(sw.active,'message')&&sw.active.jmsg.cache_mid==mid)
				show_msg_step2_inline(jmsg,sw.active.instance);
			if(preview_mid==mid)
				preview_msg(mid);
		},'&allow_rpath=yes');
}
# combine with allow_images??
function attached_messages(action,state,jmsg)
{
	if(!jmsg) jmsg=sw.active.jmsg;
	if(sw.is_popup){
		sw_win.attached_messages(action,state,jmsg);
		show_msg_step2_popup();
		return;	
	}
	if(!state) state=['false','false'];
	var mid,fld,ident;
	if(jmsg){
		ident=jmsg.ident;
		fld_id=jmsg.fld_id;
		fid=jmsg.fid;
		mid=jmsg.cache_mid;
		jmsg_reset(jmsg);
	}else{
		ident=sw.ident;
		fld_id=sw.fld_id;
		fid=sw.fid;
		mid=gs_cursor_mid(sw.ml);
	}

	var xid=cache_id(ident,fid,mid);
	if (sw_cache && cache_find(xid)) 
		cache_remove(xid,true);

	var param='';
	if (action=='mpr_attach'){
		param+='&mpr_as=attach';
	}else if (action=='no_inline'){
		param+='&show_attach_inline=false';
	}else if (action=='inline' || state[0]=='true' || pref.show_inline){
		param+='&show_attach_inline=true';
	}
	if (action=='save') param+='&save_attach_folder=true';
	if (state[1]=='true') param+='&saved_attach_folder=true';	

	if(action=='save') 
		set_loading("messages_list");
	retrieve_msg(sw.fld_id,mid,function(){
			if(class_contains(sw.active,'message')&&sw.active.jmsg.cache_mid==mid)
				show_msg_step2_inline(jmsg,sw.active.instance);
			if(preview_mid==mid)
				preview_msg(mid);
			if(action=='save') 
				FolderShow(sw.fld_id,{refresh:true,noreset:true});
		},param);
}



# mostly copy of above function see if we can combine
function show_all(type,jmsg)
{
	if(!jmsg) jmsg=sw.active.jmsg;
	if(sw.is_popup){
		sw_win.show_all(type,jmsg);
		show_msg_step2_popup();
		return;	
	}
	var ident,mid,fld;
	if(jmsg){
		ident=jmsg.ident;
		fld_id=jmsg.fld_id;
		fid=jmsg.fid;
		mid=jmsg.cache_mid;
		jmsg_reset(jmsg);
	}else{
		ident=sw.ident;
		fld_id=sw.fld_id;
		fid=sw.fid;
		mid=gs_cursor_mid(sw.ml);
	}

	var xid=cache_id(ident,fid,mid);
	if (sw_cache && cache_find(xid)) 
		cache_remove(xid,true);

	retrieve_msg(sw.fld_id,mid,function(){
			if(class_contains(sw.active,'message')&&sw.active.jmsg.cache_mid==mid)
				show_msg_step2_inline(jmsg,sw.active.instance);
			if(preview_mid==mid)
				preview_msg(mid);
		},(type=='attach'?'&all_attach=true':'&all_rcpts=true'));
}

function app_menu(type,o,display_only)
{
	cal_spinner_stop();
	if (!display_only) {
		if (type=='calendar' && pref.newcal){
			swcal_show_newcal();
		}else if (type=='cloud'){
			show_cld_ui();
		}else{
			if(do_old(type)==false)
				return false;
		}
	}
	if(sw.cur_app_menu)
		class_remove(sw.cur_app_menu,"sel");
	var el=document.getElementById("app_"+type);
	if (el){
		class_add(el,"sel");
		sw.cur_app_menu=el;
	}
	if (o) {
		var txt=o.firstChild.innerHTML;
		if (type=='mail' && sw.quota && (pref.always_show_quota || sw.quota.pct>80)) 
			txt='<span class="quota_info'+(sw.quota.pct>80?' quota_warn':'')+'">'+quota_info()+' </span>'+txt;
		dge('lpanel_hdr_text').innerHTML=txt;
		var q1=dge('lpanel_body');
		if(q1.active_pane) 
			class_add(q1.active_pane,'hidden');
		var q2=dge('lpanel_'+type);
		if(type=='calendar'){
			swcal_lcol_update(q2);
		} else if(type=='cloud'){
#			remove_children(q2);
#			new_anchor('div','<div id="cloud_lpane" style="padding:5px">'+cloud_lpane_html()+'</div>',q2);
		}
		if (!q2) {
			q2=new_anchor('div','<div style="padding:5px">'+$('$$st_appmenu_warn2$$',txt)+'</div>',q1);
			q2.id='lpanel_'+type;
		}
		class_remove(q2,'hidden');
		q1.active_pane=q2;
	}
	if (type=='mail'){
		fldmsg_display(enFLD);
	}
}
function app_menu_mail()
{
	if(sw.cur_app_menu  && sw.cur_app_menu.id!='app_mail')	
		app_menu('mail',dge('app_menu_mail'),true);
}


function textMode()
{
	alert("sorry switching to plain text not implemented yet");
}


function do_move(e,id){
	if (!e) e = window.event;
	var t = target(e);
	if (t.tagName.toLowerCase()=='a'){		
		if (class_contains(t,'fake')){
			fld_expand(e);
			stopEvent(e)
			return;
		}		
		do_move_hide(id);
		do_move_actual(t.fname)
	}
}

function do_move_actual(fld,unlabel)
{
	var sel=find_sel();
	if (!sel) return;
	if (!fld) return;
	set_move_status(sel,fld);
	dbg('do_move - selection ['+sel+']');
	ajax_msg_move(sel,fld,false,unlabel);
	do_select('none');
	message_done_action(sel);
}
function do_move_hide(id)
{
	var el=document.getElementById(id);
	class_add(el,'hidden');
}

function do_copy_show(e,input)
{
	do_folder_menu_setup(e,'folder_menu');
#	do_generic_menu_setup('folder','folder_menu',(e&&e.shiftKey));
	do_menu_show('folder_menu', e, true, function(result,fld_id,create,del_menu){
		var sel=find_sel();
		if (!sel) return;

		filtermenu_search_clear(dge('folder_menu').menu_list);
		msglist_select(sel[sel.length-1]);

		if(result!='ok'){
			input.value='';
			return;	
		}
		set_status("$$st_stat_copying$$","info");
		ajax_msg_copy(sel,fld_id,create,del_menu);
		input.value='';
	});
}
# cf do_label_show, do_copy_show
function do_move_show(e,more_actions,forever)
{
	var options={};
	if(more_actions) options.t=more_actions;
	do_folder_menu_setup(e,'folder_menu');
#	do_generic_menu_setup('folder','folder_menu',(e&&e.shiftKey));
	do_menu_show('folder_menu',e,true,	function(result,fld_id,create,del_menu){
		var sel=find_sel(true);
		if (!sel) return;

		filtermenu_search_clear(dge('folder_menu').menu_list);
		msglist_select(sel[sel.length-1]);

		if(more_actions) more_actions.value='';
		if(result!='ok'){
			return;	
		}
		if(sw.is_popup){
			sw_win.do_move_popup(sw.mid,sw.fld_id,fld_id,create,del_menu);
			window.close();
			return;
		}
		set_move_status(sel,fld_id);
		dbg('do_move - selection ['+sel+']');
		ajax_msg_move(sel,fld_id,create,del_menu,forever);
		do_select('none');
		message_done_action(sel);
	},options);
}



function do_move_popup(mid,src,dst,create,del_menu)
{
	var msgs=[mid];
	set_move_status(msgs,dst);
	msgs.fld_id=src;
	ajax_msg_move(msgs,dst,create,del_menu);
}

function refresh(e){
	var t=target(e);
	var el=ancestor_by_class(t,'full_cursor');
	var row=el.parentNode;
	FolderShow(row.getAttribute('fld_id'),{fld_type:row.getAttribute('fld_type'),refresh:true});
	stopEvent(e);
}

function which_messages(fld_id, opt)
{
	var txt='';
	if(opt.endless){
		txt+=endless_api_param("",fld_id,opt.endless);
	}else{
		if(opt.start!=undefined) txt+="&start="+opt.start;	
	}
	return txt;
}

# Display folder with particular fld_id		// Used to be called F(
# Parameter consolidation:
# opt: refresh, 
# opt: noreset: skip reset of search fields etc
# opt(preexisting): refresh_allmsgs, noselect, opanel, msg_wanted, same_cached, no_msg, multiple, filter_state 
# opt: disable_markread: ctl-alt disabling of msg mark read
# opt: xcmd + xiid, xfld, xfid: must all be specified for account switching
function FolderShow(fld_id, opt)
{
	if(!opt) opt={};
	if(!opt.xiid) opt.xiid=sw.ident;
	if(!opt.xfld) opt.xfld=sw.fld_id;
	if(!opt.xfid) opt.xfid=sw.fid;
	var alt=(altlist!=U);
	if(alt) opt.noreset = true;
	var trycache=true;
	if(fld_id==opt.xfld && sw.ident==opt.xiid && !opt.same_cached) trycache=false;
	if(opt.endless) store_sel();
	if(!alt){
		fldmsg_display(enFLD);
		menu_custom_fld(opt.fld_type,fld_id);
		select_mailbox_all('none');
		gs_fastselect_reset(sw.ml);
	}
	if(!opt.noreset) search_init(undefined,pref.search_type);
	var extra="";
	extra+=which_messages(fld_id, opt);
	extra+=(opt.refresh==true||fld_id=='INBOX')?"&refresh=true":"";
	extra+='&sort='+sw.sort_type+'&rev='+sw.sort_rev;
	extra+='&pin_star='+pref.pin_star+'&show_todo='+pref.show_todo;
	if(alt){
		extra+='&alt=true&search='+xescape(altsearch);
	}
	var o=sw.search_input;
	if(o.valid){
		if(sw.search_type=='body') extra+='&search_type=imap&search='+xescape(sw.search_input.value);
		if(sw.search_type=='folder') extra+='&search='+xescape(sw.search_input.value);
	}
	if(opt.refresh_allmsgs) extra+='&refresh_allmsgs=true';
	if(opt.no_select || alt) extra+='&no_select=true';
	if(opt.opanel) extra+='&opanel=true';
	if(opt.msg_wanted) extra+='&msg_wanted='+opt.msg_wanted;
	if(opt.disable_markread || alt) extra+='&disable_markread=true';
	if(opt.endless) extra+='&endless=true';

||iftrue(filter_dev)||
	if(opt.filter_state) extra+='&filter_mode='+opt.filter_state;
	filter_hide();
||endif||
#--	
	if(!alt && !opt.endless){
		if(opt.endless){
			// No screen updates on req start
		} else{
			set_loading('messages_list');
		}
		var cached_sel = sw.cached_sel;
		var msg_restored = false;
		if(pref.mode=='app'){
			no_msg_sel();	
		}
		class_add(sw.busy,'busy_loading');
	}
	disable_markread_fld=opt.disable_markread;
	extra+='&conv_limit='+sw.conv_search_email;
	extra+='&tz='+(-((new Date()).getTimezoneOffset())/60*100);
||iftrue(using_api)||
	var cmd='messages?v=sw&fld_id='+xescape(fld_id)+iid()+extra;
||else||
	var cmd='cmd=show&page=~msgs.js&fld_id='+xescape(fld_id)+iid()+extra;
||endif||
	if(opt.xcmd) cmd=opt.xcmd;
	todo_overlay(false);
||iftrue(using_api)||
	apiGet(cmd, function(chan){
||else||
	sndReq(cmd, function(chan){
||endif||
		doneloading();
		if(!opt.nostatus)set_status();
		var new_sel = find_sel(true);
		endless_api_complete(opt.endless_t);
		success = actionReqJs(chan);
		if (global_auth_error){
			global_auth_error=false;
			global_request_reissue=cmd;
		}
		if (!success){
			if (!success_string) success_string=err_general(chan,6);
			set_status('$$st_stat_retr_fail$$ '+success_string,'warning');
			return;
		}
		
		if(!alt){
			switch_selfld(fld_id);
			msgdnd_init();
			if(o.valid && (sw.search_type=='body' || sw.search_type=='folder')) {
				sw.search_input.focus();
			}
			class_remove(sw.busy,'busy_loading');
			todo_overlay(fld_id=='INBOX' && sw.nav_total==0);
		}
		if(opt.endless) restore_sel();
	});	
#--
	touch(7);
	if(!alt){
		switch_selfld(fld_id,opt);
		if(opt.fld_type){
			sw.fld_type=opt.fld_type;
			menu_arrange(opt.fld_type);
		}
		stop_shift();
	}
}


function L(id)
{
	if(id.indexOf(' ')!=-1) id='"'+id+'"';
	search_init('label:'+id+' folders:recent');
	FolderShow(sw.fld_id,{noreset:true});
}



function show_prev(mid,nofocus)
{
	var jmsg=sw.active.jmsg;
	if(sw.is_popup){
		if(!compare_folders(jmsg.fld_id,sw_win.sw.fld_id)) return;
		sw.active.innerHTML='$$st_pane_loading$$';
		sw_win.jmsg_reset(jmsg);
#		Switch to using just find_next + retrieve message??
		jmsg.cache_mid=sw_win.show_prev_preview(mid,true);
		show_msg_step2_popup();
	} else if(class_contains(sw.active,'message')){
		if(!compare_folders(jmsg.fld_id,sw.fld_id)) return;
		jmsg_reset(jmsg);
		jmsg.cache_mid=show_prev_preview(mid,true);
		show_msg_step2_inline(jmsg,sw.active.instance);
	}else{
		show_prev_preview(mid,nofocus);
	}
}
function show_prev_preview(mid,nofocus)
{	
	gs_none_fast(sw.ml);
	var xmid=gs_show_prev_real(sw.ml,sw.multiple?mid:just_mid(mid),true);
	msg_show_soon(xmid,undefined,nofocus);
	return xmid;
}


function show_next(mid,nofocus)
{
	var jmsg=sw.active.jmsg;
	if(sw.is_popup){
		if(!compare_folders(jmsg.fld_id,sw_win.sw.fld_id)) return;
		sw.active.innerHTML='$$st_pane_loading$$';
		sw_win.jmsg_reset(jmsg);
#		Switch to using just find_next + retrieve message??
		jmsg.cache_mid=sw_win.show_next_preview(mid,true);
		show_msg_step2_popup();
	} else if(class_contains(sw.active,'message')){
		if(!compare_folders(jmsg.fld_id,sw.fld_id)) return;
		jmsg_reset(jmsg);
		jmsg.cache_mid=show_next_preview(mid,true);
		show_msg_step2_inline(jmsg,sw.active.instance);
	}else{
		show_next_preview(mid,nofocus);
	}
}
function show_next_preview(mid,nofocus)
{	
	gs_none_fast(sw.ml);
	var xmid=gs_show_next_real(sw.ml,sw.multiple?mid:just_mid(mid),true);
	msg_show_soon(xmid,undefined,nofocus);
	return xmid;
}

var showsoon_timer;
# Update message list selection ('cursor') and try download the mesage "soon"
function msg_show_soon(mid,tick,nofocus,nostatus)
{
#	// Can get here from 1) Arrow keys on list page, but may already have opened a message => ignore	(NOW IN gs_show_soon)
#						 2) Prev next arrows in preview pane => show it in preview
#						 4) Prev next arrows in popup/tabbed/inline message => show it in msg display (also in preview)
#						 5) Various message_done_action configurations => action it...
	if(mid==null) {
		no_msg_sel();
		return false;
	}
	msglist_select(mid,tick,nofocus);	
	if(showsoon_timer) clearTimeout(showsoon_timer);	
#	if(pref.preview=='none') return;	// Needed for popup Prev / Next buttons
	showsoon_timer=setTimeout(function(){ 
		msg_show_preview(mid,undefined,undefined,nofocus,nostatus,disable_markread_fld);
		showsoon_timer=null; 
	},150);
}


function message_done_action(sel)
{
#	if (sw.util.fldmsg_current==enMSG){
#		or select next message
	var x=pref.message_done_action;
	var x2=pref.message_done_action2;
	var fwd=true;
#	if(!class_contains(sw.active,'fldmsg')){

	if (sw.active!=sw.msgs_pane){
		if(pref.windows=='inline' && x2!='list'){
			x=x2;
		}else{
			if(pref.windows=='tabbed')
				window_manager_killpane(sw.active);
			layout_fldmsg(enFLD);
		}
	}
	if (x=='none') {
		no_msg_sel();
		return;
	}
#	Select next message in list or in message	
	if (x=='prev') fwd=false;
dbg('ZZ 1');
	if (fwd) 
		msg_show_soon(gs_show_next_real(sw.ml,sel[sel.length-1],false,true),undefined,undefined,true);
	else
		msg_show_soon(gs_show_prev_real(sw.ml,sel[0],false,true),undefined,undefined,true);
}
function nav(item){
	FolderShow(sw.fld_id,{fld_type:sw.fld_type,start:item,noreset:true});	
}


function popout_msg(mid)
{
	show_msg(mid,null,'popup');
	if (sw.active!=sw.msgs_pane){
		if(pref.windows=='inline'){
			layout_fldmsg(enFLD);
		}else{
			window_manager_killpane(sw.active);
			window_manager_restore();
		}
	}	
}

function popin_msg(mid)
{
	sw_win.show_msg(mid,null,'inline');
	window.close();
}

function minimise_edit()
{
	dbg('minimise message clicked');
	
	// if not a message displayed then return for now
	if (pref.windows!='tabbed'){
		if (!confirm('$$st_dlg_enabletabs$$'))
			return;
			
		pref.windows='tabbed';
		ajax_pref_save('pref_windows='+pref.windows);
		class_remove(document.getElementById('switcher'),'hidden');
	}
	window_manager_minimise(sw.active);	
}

function popout_edit()
{
	var jmsg=jmsg_update(sw.active);
	jmsg.not_new = true;
	show_edit(jmsg,null,'popup');
	if (sw.active!=sw.msgs_pane){
		if(pref.windows=='inline'){
			layout_fldmsg(enFLD);
		}else{
			window_manager_killpane(sw.active);
			window_manager_restore();
		}
	}
}
function popin_edit()
{
	var node=sw.active;
	if(!main_window_check(node)) return;
	var jmsg=jmsg_update(node);
	if (sw_win.pref.windows!='tabbed' && class_contains(sw_win.sw.active,'compose')){
		if (!confirm('$$st_dlg_enabletabs2$$'))
			return;
		sw_win.pref.windows='tabbed';
		sw_win.ajax_pref_save('pref_windows='+sw_win.pref.windows);
		sw_win.class_remove(sw_win.document.getElementById('switcher'),'hidden');

	}
	jmsg.from_popout=true;
	jmsg.not_new = true;
	sw_win.show_edit(jmsg,null,'inline');
	sw.closing=true;
	window.close();	
}
function expand_preview()
{
	alert('expanded preview');
}
function do_reload(interface_ex)
{
	logging_out=true;
	sw.closing=true;
	if (!interface_ex) interface_ex='ajax';
	document.reload.sid.value=sid;
	document.reload.fld_id.value=sw.fld_id;
	document.reload.interface_ex.value=interface_ex;
	document.reload.submit()
}
function live_refresh(){
	do_reload();
}

function toggle_note_email()
{
	var node = sw.active;
	var want_note=!class_contains(node,'donote');
	compose_menu_update(node,node.jmsg,want_note)
	email_or_note(node,want_note);
	gen_resize();
}

function compose_type_update(node,jmsg)
{
	if(!node) node = sw.active;
	if(!jmsg) jmsg = node.jmsg;
	compose_menu_update(node,jmsg,jmsg.note);
	compose_msg_update(node,jmsg,jmsg.note);
}

# update toolbar & message for display
function compose_menu_update(node,jmsg,want_note)
{
	var as_template = jmsg.fld_type==enDraft && jmsg.fld_id=='Templates';
	var as_note = ((want_note && jmsg.note) || jmsg.fld_id=='$$Notes$$') && !as_template;
	var reply_done = jmsg.fld_type==enInbox || jmsg.fld_type==enUser;

#	// update display of buttons	
	if(!pref.hide_surgevault){
		elS(dge('send_encrypt'),!as_note);
	}
	elS(dge('send_normal'),!as_note);
	elS(dge('send_move'),!as_note && reply_done);

	elS(dge('save_draft'),!as_note);
	elS(dge('save_note1'),as_note || as_template);
	elS(dge('save_note2'),as_note & !as_template);
	
	elS(dge('send_extra'),(jmsg && jmsg.note) && !as_template);
	
#	// update any needed button texts
	dge('save_note1').value=as_template?'$$st_cmd_resave_template$$':'$$st_cmd_save_template$$';
	dge('send_extra').value=as_note?'$$st_cmd_send_note$$':'$$st_cmd_send_note2$$';

}
function compose_msg_update(node,jmsg,want_note)
{
	var as_template = (jmsg.fld_type==enDraft && jmsg.fld_id=='Templates');
	if(as_template) want_note=false;
	email_or_note(node,want_note)
#	// sim_init
}

function update_replyedit(qmsg)
{
	el=dge('mnu_reply');
	var as_edit = qmsg.data.draft;
	el.as_edit = as_edit;
	el.value = as_edit?'$$st_cmd_edit$$':'$$st_cmd_reply$$';
	el.title = as_edit?'$$st_cmd_edit_tt$$':'$$st_cmd_reply_tt$$';
}

function email_or_note(node,want_note)
{
	if(want_note){
		class_add(node,'donote');
		// QQNOTE
		//toggle_editor("eframe"+sw.active.instance);
	}else{
		class_remove(node,'donote');
	}
||ifdef||_note_not_yet_||
	if(!pref.notes_oldformat){
		class_update(node.field_eframe.contentWindow.document.body,"note_itself",want_note);
	}
||endif||
}
// toggle_sim
function sim_from_menu()
{
	var node=sw.active;
	sim_init(true);		
	class_add(node.editor_bar, 'hidden');
}

function sim_init(visible,late) 	// QQQSIM 
{
	var xwin=get_edit_win();
	var o=sw.active.field_subject;
	var sig=sw.active.field_signature;
	var jmsg=sw.active.jmsg;
	var po=ancestor_by_class(o,'compose_hdr_row');
	if(visible){
		o.value=jmsg.subject
		class_remove(po,'hidden');
		class_add(po.previousSibling,'hidden');	
		class_remove(sw.active.editor_bar, 'hidden');
		if(late){
			sig.value=decide_sig(jmsg.ident)
			toggle_signature(sig);
		}
	}else{
		class_add(po,'hidden');
		class_remove(po.previousSibling,'hidden');	
		if(xwin) xwin.orig_sig='';
		if(late){
			sig.value='';
			toggle_signature(sig);
		}
		sim_warn();
	}
}



#Update compose display for normal compose, note or SIM message	 //cf sim_init


function show_cc(type,node,nosave)	// QQQSIM show_cc('subject')
{
	var base=node?node:sw.active;

	dbg('show_cc '+type);

	var o=base.field_cc;
	if (type=='bcc')
		o=base.field_bcc;
	else if (type=='extra')
		o=base.field_priority;
	else if (type=='subject')
		o=base.field_subject;
	
	var po=ancestor_by_class(o,'compose_hdr_row');
	if(class_contains(po,'hidden'))	{
		class_remove(po,'hidden');
		if (type=='subject') sim_init(true,true);	
	}else{
		class_add(po,'hidden');
		o.value='';
		if (type=='subject') sim_init(false,true);
	}
	
	if(sw.is_popup){
		popup_resize();
	}else{
		do_resize_real();
		stop_shift();
	}

 	if(!nosave) save_sticky();
 	
#	FUDGE to make sure buttons are correctly redrawn in IE
	force_redraw(po.parentNode)
}
function sim_warn()
{
	return;
	x_alert('<div style="margin-left:70px;">$$st_sim_txt_info1$$<br>$$st_sim_txt_info2$$<br>$$st_sim_txt_info3$$<br><br><span style="color:#999;">$$st_sim_txt_info4$$</span></div>');
}
function toggle_sim()
{	
	show_cc('subject');
}

function check_folder_name(name)
{
	if (name.indexOf('/')==-1 && name.indexOf('\\')==-1) return true;
	x_alert('$$st_fldmng_fldname_bad$$');
	return false;
}
function do_folder_create()
{
	var new_name;
	var el=dge('folder_new_under');
	var new_name=(el.value.length>0)?el.value+'/':'';
	el=dge('folder_new_name');
	if(!check_folder_name(el.value)) return;
	new_name+=el.value;
	sndReq('cmd=folder_create,show&new_name='+xescape(new_name)+'&page=~folders.htm'+iid(), function(chan){
		node=actionReqSethtml(chan.responseText,'utility');
	});
}
function folder_create_cx()
{	
	var name=sw.menu_fld?sw.menu_fld:'$$st_ftree_more_fld$$';
	x_prompt( $('$$st_fldmng_create_under$$',name),'$$st_fldmng_newname$$',function(val){
		if(!val || !check_folder_name(val)) return;
		var new_name=(sw.menu_fld!=null?sw.menu_fld+'/':'')+val;
		sndReq('cmd=folder_create,show&new_name='+xescape(new_name)+'&page=~folders.htm'+iid(), function(chan){
			node=actionReqSethtml(chan.responseText,'utility');
		});
	});
}
function delete_folder(name)
{
	x_confirm($('$$st_fldmng_deletefld$$',name),function(n){
		if (!n)return;
		sndReq('cmd=folder_delete,show&delete_name='+xescape(name)+'&page=~folders.htm'+iid(), function(chan){
			node=actionReqSethtml(chan.responseText,'utility');
		});
	});
}


function rename_folder(name,short_name)
{
	var page='~folders.htm';
	var html=true;

	if(!name){
		name=sw.menu_fld;
		short_name=sw.menu_short;
	}

	x_prompt($('$$st_fldmng_renameto$$',short_name),short_name,function(val){
		if(!val || !check_folder_name(val)) return;
		var folders='&folder_rename_src='+xescape(name)+'&folder_rename_dst='+xescape(val);
		dbg('renaming '+short_name+' to '+val)
		sndReq('cmd=folder_rename,show&'+folders+'&page='+page+iid(), function(chan){
			if(html){ 
				node=actionReqSethtml(chan.responseText,'utility');
			}else{
#				alert(sw.fld_id+':'+sw.menu_fld)
#				success=actionReqJsStat(chan);
#				if(sw.fld_id==sw.menu_fld) 
#				alert(sw.fld_id+':'+sw.menu_fld)
#					FolderShow('INBOX',{noreset:true});
			}
		});
	});
}

function move_folder(name,short_name)	// QQDLG
{		
	x_custom_dlg($('$$st_fldmng_moveto$$',short_name),
				 '<select name="folder_move_dst">'+dge('folder_new_under').innerHTML+'</select>',
				 function(btn){
		val=dge("folder_move_dst").value;
		if(!btn) return;
		var folders='&folder_move_src='+xescape(name)+'&folder_move_dst='+xescape(val);
		dbg('renaming '+name+' to '+val)
		sndReq('cmd=folder_move,show&'+folders+'&page=~folders.htm'+iid(), function(chan){
			node=actionReqSethtml(chan.responseText,'utility');
		});
	});
}

function showhide_folder(name,action)
{
	sndReq('cmd=folder_showtop,show&folder_showhide='+xescape(name)+'&action='+action+'&page=~folders.htm'+iid(), function(chan){
		node=actionReqSethtml(chan.responseText,'utility');
	});
}


function do_cache()
{
	var sel=find_sel();
	if (!sel) return;
	if(sel.sel_all) {
		select_mailbox_all('disable');
		alert('$$st_dlg_cannot_cacheall$$');
	}
	ajax_cache_messages(sel)
}

# IE does not support indexOf on arrays so do it ourselves
function my_indexOf(obj,id){
	if(obj.indexOf) 
		return obj.indexOf(id);

	for(var i=0; i<obj.length; i++){
		if(obj[i]==id){
			return i;
		}
	}
	return -1;
}

function do_purge(e){
	var t=target(e);
	var el=ancestor_by_class(t,'full_cursor');
	var row=el.parentNode;
	var fld_id=row.getAttribute('fld_id');	
	var fld_type=row.getAttribute('fld_type');	
	stop_shift();
	stopEvent(e);
	
	var ask_name=''; 
	if(fld_type==enTrash && (pref.confirm_purge=='trash' || pref.confirm_purge=='both')) { ask_name=pref.special_trash_vis; }
	if(fld_type==enSpam && pref.confirm_purge=='both') { ask_name=pref.special_spam_vis; }
	
	if(ask_name.length>0){
		x_confirm($('$$st_fldmng_deletefld$$',ask_name),function(n){
			if (!n)return;
			do_purge_step2(fld_id, fld_type);
		});
	}else{
		do_purge_step2(fld_id, fld_type);
	}
}

function do_purge_step2(fld_id, fld_type)
{
	ajax_purge(fld_id,fld_type);
	if(sw.fld_id==fld_id){
		no_msgs_fld();
		no_msg_sel();
		update_unread_folders({'fld_id':fld_id,unread:0});
		navigator_set(0,0,0,"")
	}
}


function do_print()
{
	var sel=find_sel();
	if (!check_sel(sel,'$$st_type_printed$$')) return;
	open_popup('cmd=show&page=print.htm&fld_id='+xescape(sw.fld_id)+'&msg_id='+sel[0]+'&all_rcpts=true'+iid()+'&sid='+sid);
}
function do_conversation()
{
	var sel=find_sel();
	var jmsg=sel_to_jmsg(sel,'reply')
	if(jmsg.to.length==0) return;
	var c=text2contact(jmsg.to[0]);
	var email=c.email[0].value;
	conv_limit(email,email);
}
function contacts_close()
{
	app_menu('mail',dge('app_menu_mail'));
}

function contacts_new()
{
	if(abooks.write_books.length>1)
		contacts_new_shared();
	else
		cm_contact_edit();
}
# TODO: make this dialog more generic
function contacts_import(type)
{
	var cmd='cmd=show&page=hdialogs.htm&dlg_type=contacts_import&dlg_tab='+type+'&sid='+sid;
	x_custom_dlg2('$$st_ct_import_title$$','<iframe id="dlg_iframe" src="'+cgibase+cmd+'" style="width:100%;height:'+px(290)+';background:#ECE9D8;" frameborder="0"></iframe>',
		function(btn){
#			if(!btn) return;
			cm_contacts_refresh();
		}, function(){}, {'width':560,'nopad':true,'nobtns':true});
}

function abks_select(book, selected)
{	
	var txt;
	var abks=sw.abooks_write;
	for(var i=0;i<abks.length;i++){
		txt+='<option value="'+abks[i]+'" '+(abks[i]==cm_cur_client_abook?'selected':'')+'>'+abks[i]+'</option>';
	}
	return '<select name="'+book+'">'+txt+'</select>';
}
function contacts_new_shared(name,short_name)
{	

	x_custom_dlg('$$st_ct_new_inabk$$',
				 abks_select("contact_abk_select",cm_cur_client_abook),
				 function(btn){
		var val=dge("contact_abk_select").value;
		if(!btn || !val) return;
		abook_new=val;
		cm_contact_edit();
	});
}
var abook_new="User";


function contacts_copy_shared(name,short_name)
{	
	if(!sw.curr_contact){
		x_alert("$$st_ct_err_select_tocopy$$")
		return;
	}
	x_custom_dlg($('$$st_ct_copy_to_abk$$','<b><i>'+c_name(sw.curr_contact)+'</i></b>'),
				 abks_select("contact_abk_select"),
				 function(btn){
		var val=dge("contact_abk_select").value;
		if(!btn || !val) return;
		contact_copy_one(sw.curr_contact,val);
	});
}



function cm_email_vcard(e,abook,cid)
{
	app_menu('mail',dge('app_menu_mail'));
	var jmsg=compose_jmsg([]);
	jmsg.vcard_abk=abook; jmsg.vcard_cid=get_svr_cid2(abook,cid);
	show_edit(jmsg,e);
}
function do_contact_email(abook,id)
{
	var e=window.event;
	c=abooks[abook].data[id];
	var rcpt=c_name_co(c)+' <'+c_email(c)+'>';
	var jmsg=compose_jmsg([rcpt]);
	if(pref.windows!='popup' && !e.shiftKey){
		app_menu_mail();
	}
	show_edit(jmsg,e);
}
function do_contact_email2(abook,id,email)
{
	var e=window.event;
	c=abooks[abook].data[id];
	var rcpt=c_name_co(c)+' <'+email+'>'
	var jmsg=compose_jmsg([rcpt]);

	if(pref.windows!='popup'){
		app_menu_mail();
	}
	show_edit(jmsg,e);
}
function do_new_email(name,address)
{
	var e=window.event;
	var rcpt=name+' <'+address+'>';
	var jmsg=compose_jmsg([rcpt]);
	if(pref.windows!='popup' && !(e&&e.shiftKey)){
		app_menu_mail();
	}
	show_edit(jmsg,e);
}

function sort_to_desc(val,rev)
{
	if(rev){
		switch(val){
			case 'date': return '$$st_mshow_bar_date_rev$$';
			case 'to':	return '$$st_mshow_bar_to_rev$$';
			case 'from':	return '$$st_mshow_bar_from_rev$$';
			case 'subject': return '$$st_mshow_bar_subj_rev$$';
			case 'size':	return '$$st_mshow_bar_size_rev$$';
		}
	}else{
		switch(val){
			case 'date': return '$$st_mshow_bar_date$$';
			case 'to':	return '$$st_mshow_bar_to$$';
			case 'from':	return '$$st_mshow_bar_from$$';
			case 'subject': return '$$st_mshow_bar_subj$$';
			case 'size':	return '$$st_mshow_bar_size$$';
		}
	}
	return val;
}

function sort_init(txt,rev)
{
	if(!txt || txt.length==0){
		txt='date'; rev=true;	
	}
	sw.sort_type=txt;
	sw.sort_rev=rev;
	dge('sort_menu_txt').innerHTML=sort_to_desc(txt,sw.sort_rev);
}

function do_sort(txt,desc)
{
	if (txt!=sw.sort_type){
		sw.sort_rev=(txt=='date'||txt=='size')?true:false;
	} else {
		sw.sort_rev=!sw.sort_rev;
	}
	dge('sort_menu_txt').innerHTML=sort_to_desc(txt,sw.sort_rev);
	sw.sort_type=txt;
	FolderShow(sw.fld_id,{noreset:true});
}

function view_filter_init()
{
	var el = dge('view_menu_txt');
	if(!el) return;
	el.innerHTML="normal";
}


function do_move_done(e)
{
	var unlabel=(e.shiftKey==true) ;
	do_move_actual(pref.special_done,unlabel);
}

function display_to_desc(val)
{
	switch(val){
		case 'all': return '$$st_mshow_bar_all$$';
		case 'flagged': return '$$st_mshow_bar_starred$$';
		case 'attach': return '$$st_mshow_bar_attach$$';
		case 'unread': return '$$st_mshow_bar_unread$$';
		case 'read': return '$$st_mshow_bar_read$$';
		case 'unreplied': return '$$st_mshow_bar_unreplied$$';
		case 'replied': return '$$st_mshow_bar_replied$$';
		case 'day': return '$$st_mshow_bar_day$$';
		case 'week': return '$$st_mshow_bar_week$$';
	}
	return val;
}

function do_display(txt)
{
	var search;
	dge('display_menu_txt').innerHTML=display_to_desc(txt);

	// QQTD	
	if(txt=='day'||txt=='week') search='date:'+txt;
	if(txt=='unread') search='-flag:seen';
	if(txt=='unreplied') search='-flag:replied';
	if(txt=='read') search='flag:seen';
	if(txt=='replied') search='flag:replied';
	if(txt=='flagged') search='flag:star';
	if(txt=='attach') search='attachments:any';

	search_init(search);

	FolderShow(sw.fld_id,{noreset:true});
}

# Revamp of search... 
function search_init(value,type,location,opt)
{	
#	return;
	if (!type) type='folder';
	if (value){
		if(value.indexOf('folders:recent')!=-1) location='recent'; 
		if(value.indexOf('folders:all')!=-1) location='all'; 
	}
	var id=0;
	if(type=='folder') id=1;
	if(type=='body') id=2;
	var el=dge('pg_menu_search').childNodes[id];
	do_stype(el,type,value,location,opt);
}
# QQSRCH	do_stype
function do_stype_mnu(el,txt)
{
	do_stype(el,txt);
	pref.search_type=txt;
	ajax_pref_save("pref_search_type="+txt);
	sw.search_input.value='';
	search_info(sw.search_type,'single');
	class_remove(sw.search_limit,"hidden");	
}
# Iniatise from scratch any kind of search...
function do_stype(el,txt,search,location)
{
#	if(txt=='all'){
#		alert('IMAP search not yet implemented');
#		return;
#	}
	if(!search && txt!='quick') msglist_unsearch(true);
	sw.search_type=txt;
	if(el){
#		Select menu tickmark
		var o=el.parentNode;
		for (var i=0;i<o.childNodes.length;i++){
			var cc=child_by_class(o.childNodes[i],'menu_tick');
			if (cc && cc.className) class_remove(cc,'selected');
		}
#		if(el==o.childNodes[2]) el=o.childNodes[0];
		class_add(child_by_class(el,'menu_tick'),'selected');
		
		var icon='search_icon';
		if(txt=='folder') icon+='2';
		if(txt=='body') icon+='3';
		
		class_set(dge('search_bar_icon'),icon);
#		Setup search field as blank or with required search params
		if(search) {
			search_field_set(search,location);
			try{
				sw.search_input.focus();
			}catch(e){}
		}else{
			search_field_set();
		}
	}
}	

function search_keyup(e)
{
	if (!e) e = window.event;
	dbg("doing search keyup");

	var t = target(e);
	if (e.keyCode==vkEsc){
		msglist_unsearch();
#		search_init();
		dge("mnu_reply").focus();
	}
	switch(e.keyCode){
#		ESC or backtick
		case vkEsc:
			return;
#		Enter
		case 13:
			if(sw.search_type=='quick'){
				var v=t.value;
				if (sw.nav_count!=sw.nav_total || e.ctrlKey || v.indexOf(':')!=-1 || v.indexOf('-')!=-1 || v.indexOf('"')!=-1){
					do_search_folders(e.ctrlKey?'recent':undefined);
				}
				return;
			}else if (sw.search_type=='folder'){
				if (e.ctrlKey)
					do_search_folders('single','body');
			}
			dge('display_menu_txt').innerHTML='$$st_mshow_bar_custom$$';
			var opt={};
			if(sw.seach_location!='single') opt.multiple=true;
			opt.noreset=true;
			action_search(sw.fld_id,opt)
			return;
		default:
			if(sw.search_type=='quick'){
				apply_quick_search(t.value);
			}	
			return;
	
	}
}
function search_field_set(search,location)
{
	if(search==undefined){
		var o=sw.search_input;
		if(sw.search_type=='quick'){
			o.value="$$st_msrch_quick$$";
		}else if(sw.search_type=='folder'){
			o.value="$$st_msrch_idx$$";
			dge('display_menu_txt').innerHTML='$$st_mshow_bar_all$$';
		}else if(sw.search_type=='body'){
			o.value="$$st_msrch_body$$";
		}
		o.style.color='#777';
		o.valid=false;
		class_add(sw.search_limit,"hidden");	
	}else{
		var o=sw.search_input;
		o.value=(search?search:"");
		o.valid=true;
		o.style.color='black';
		deselect_mailbox_all();
		if (!location) location=pref.search_default;
		search_info(sw.search_type,location);
		class_remove(sw.search_limit,"hidden");	
	}
}
#	QQSRCH msglist_unsearch
function msglist_unsearch(simple)
{
	sw.search_input.value='';
	if(sw.search_type=='folder'){
		if(simple) return;
		FolderShow(sw.fld_id,{noreset:true});
	}else{
		var count=apply_quick_search('');
		if (count>0){
			class_remove(sw.search_limit,"hidden");	
		}else{
			class_add(sw.search_limit,"hidden");	
		}		
	}
}
# QQSRCH	do_search_folders
function do_search_folders(location,type)
{
	var opt={};
	class_add(sw.search_limit,"hidden");
	if (!location) location=pref.search_default;
	var txt=sw.search_input.value;
#	Clear out any existing folder specification
	var srch=txt.split(' ');
	for(var i=0;i<srch.length;i++)
		if(srch[i]=='folders:single' || srch[i]=='folders:recent' || srch[i]=='folders:all')
			srch.splice(i,1);
# 	Specify the folders if required
	if(location!=pref.search_default) 
		srch.push('folders:'+location);
	txt=srch.join(' ');
	sw.search_input.value=txt;	
#	Now action it
	if(location!='single')
		opt.multiple=true;
	search_init(txt,type,location);
	opt.noreset=true;
	action_search(sw.fld_id,opt)
}

function action_search(p1,p2)
{
	if(sw.search_type=='body'){
		var warning;
		if(sw.quota){
			warning=$('$$st_msrch_body_warn$$',sw.quota.used);
		}else{
			warning='$$st_msrch_body_warn2$$';
		}
		x_confirm(warning,function(n){
			if(!n)return;
			FolderShow(p1,p2);	
		});
		return;
	}
	FolderShow(p1,p2);	
}

function search_info(type,location)
{
	flds='recent';
	var sel='style="background:#888;"';
	if(!location) location='single';
	if (type=='quick'){
		info='<td>$$st_msrch_local$$ </td>'
		+'<td><input type="button" value="$$st_msrch_more$$" class="mnu_small" onclick="do_search_folders(undefined,\'folder\')"></td>';
	}else if(type=='folder'){
		var info='<td>$$st_msrch_search$$ </td> '
		+'<td '+(location=='single'?sel:'')+'><input type="button" value="'+dge('foldername1').innerHTML+'" class="mnu_small" onclick="do_search_folders(\'single\',\'folder\')"></td>'
		+'<td '+(location=='recent'?sel:'')+'><input type="button" value="$$st_msrch_recent$$" class="mnu_small" onclick="do_search_folders(\'recent\',\'folder\')"></td> '
		+'<td '+(location=='all'?sel:'')+'><input type="button" value="$$st_msrch_all$$" class="mnu_small" onclick="do_search_folders(\'all\',\'folder\')"></td>'
		+'<td><a href="#" class="mnu_small link_blue" onclick="do_search_save()">$$st_msrch_save$$</a><td>';
	}else{
		var sel='style="background:#888;"';
		var info='<td>$$st_msrch_imap$$ </td> '
		+'<td '+(location=='single'?sel:'')+'><input type="button" value="'+dge('foldername1').innerHTML+'" class="mnu_small" onclick="do_search_folders(\'single\',\'body\')"></td>'
		+'<td '+(location=='recent'?sel:'')+'><input type="button" value="$$st_msrch_recent$$" class="mnu_small" onclick="do_search_folders(\'recent\',\'body\')"></td> '
		+'<td '+(location=='all'?sel:'')+'><input type="button" value="$$st_msrch_all$$" class="mnu_small" onclick="do_search_folders(\'all\',\'body\')"></td>'
		+(location=='single'?'':'<td> <i>$$st_msrch_slow$$</i><td>');
	}
	sw.search_limit.innerHTML='<table><tr>'+info+'</tr></table> ';
	sw.search_location=location;
}


function show_thread(mid){
	if(sw.is_popup){
		return sw_win.show_thread(mid);
		return;
	}
	qmsg=cache_find(cache_id(sw.ident,sw.fid,mid));	
	var txt='subject:"'+qmsg.data['subject']+'"';
	if(pref.search_default!='recent') txt+=' folders:recent';
	var opt={};
	opt.multiple=true;
#	if(list){
#		altlist=list;
#	}else{
		search_init(txt);
#	}
	opt.noreset=true;
	FolderShow(sw.fld_id,opt);
}
function show_history(email, list, opt){
	if (!opt) opt={};
	if(sw.is_popup){
		return sw_win.show_history(email);
		return;
	}
	var txt='email:'+email;
	if(pref.search_default!='recent') txt+=' folders:recent';
#	opt.opanel = true;
	opt.multiple=true;
	if(opt.opanel && list){
		altlist=list;
		altsearch=txt;
	}else{
		search_init(txt);
	}
	opt.noreset=true;
	FolderShow(sw.fld_id,opt);
}
var altlist;

function do_search_save()
{
	var rule=sw.search_input.value;
	if(rule.indexOf('folders:')==-1) rule+=' folder:"'+sw.fld_id+'"';
	x_prompt('$$st_ssearch_info1$$<br><br><div class="smart_folder_rule">'+encode_lt_gt(rule)+'</div>','$$st_ssearch_info2$$',function(val){
		if (!val) return;
		save_search(val,rule);
	});
}
function save_search(name,rule)
{
	var param='&saved_search_name='+xescape(name)+'&saved_search_rule='+xescape(rule);
	sndReq('cmd=save_search,show&'+param+'&page=~result.js', function(chan){
		success=actionReqJsStat(chan);
		if(success){
			set_status('$$st_ssearch_success$$',"success");
		}else{
			set_status('$$st_ssearch_fail$$ ('+success_string+')','warning');
		}
	});
}

function delete_search(e,name)
{
	stopEvent(e);
	x_confirm('$$st_dlg_ssearch_del$$ '+name, function(n){
		if(!n) return;
		save_search(name,'');
	});
}

var rcpt_contact;
function rcpt_mousedown(e)
{
	if(e.button!=2)return;
	var t=target(e);
	if(t && class_contains(t,'rcpt')){
		rcpt_contact=t;
		do_menu_show('context_menu_rcpt',e,undefined,undefined,{cursor:true})
	}
}
function rcpt_menu_contact(type)
{
	var t=rcpt_contact;
	var email=t.getAttribute('rcpt_addr');
	var name=t.getAttribute('rcpt_name');
	switch (type){
		case 'send': 
			contact_click_send(email,name); 
			break;
		case 'vaultsafe': 
		case 'add': 
			contact_click_add(email,name,type=='vaultsafe'); 
			break;
		case 'copy1': 
			copy_popup(email);
			break;
		case 'copy2': 
			copy_popup(sw_format_address(name,email));
			break;
	}
}

function contact_click(e)
{
	var t=target(e);
	var email=t.getAttribute('rcpt_addr');
	var name=t.getAttribute('rcpt_name');
	contact_click_send(email,name); 
}

# cf: msg_list_click
function msg_list_mouseup(e){return false;}
function msg_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=gs_find_row(sw.ml,t);
	if(class_contains(row,"nonselect_row")) return false;
	var td=gs_find_td(sw.ml,t);
	if(td==row.childNodes[1]){
		if(!new_wide()){
			return;
		}
	}

	gs_mousedown(sw.ml,e);

	if(el_to_date_etc(t) && !pref.defer_disable){
		defer_menu(e,'cx');
	}else  if(el_to_labels(t)){
		labels_cx(e);
	}else if(td==row.childNodes[0]){
		do_menu_show('pg_menu_mark',e,undefined,undefined,{cursor:true})
	}else{
		do_menu_show('pg_menu_message',e,undefined,undefined,{cursor:true})
	}
	stop_def_action(e)
	return false;
}

function folder_mousedown(e)
{
	if(cx_menu(e)){
		t=target(e);
		var row=ancestor_by_tag(t,'li');
		id=row.getAttribute('fld_id');
		if(id && id.length>0 || class_contains(row,'fake')){
			sw.menu_fld=id;
			sw.menu_short=row.getAttribute('fld_short');
			cx_menu_init(row.getAttribute('fld_type'), row.getAttribute('fld_active'))
			do_menu_show('context_menu_folder',e,undefined,undefined,{cursor:true})
		}
	}
}

function cx_menu_init(type, active)
{
	m=[];
	m.push('<a href="#" onmouseup="folder_create_cx()">$$st_cmd_mfld_create$$</a>');
	if(type==5&&type!=null) m.push('<a href="#" onmouseup="delete_folder(sw.menu_fld)">$$st_cmd_mfld_delete$$</a>');
	if(type==5&&type!=null) m.push('<a href="#" onmouseup="rename_folder()">$$st_cmd_mfld_rename$$</a>');
	if(type!=null) m.push('<a href="#" onmouseup="do_refresh2(\'folder\')">$$st_cmd_mfld_refresh$$</a>');
	if(active=='true') m.push('<a href="#" onmouseup="do_filing()">$$st_cmd_mfld_filing$$</a>');
	mnu=dge('context_menu_folder')
	mnu.shadofied=false;
	mnu.innerHTML=m.join('');
}

function do_remind(sec)
{
	if(!pref.todo) return;
	do_set_todo();
}

function do_refresh2(type)
{
	if(type=='folder')
		return  FolderShow(sw.menu_fld,{refresh:true,refresh_allmsgs:true});

	x_confirm('$$st_dlg_rfrall_check$$', function(n){
		if(!n) return;
		set_status('$$st_stat_rfrall_start$$','info');
		refresh_flds(true);
	});
}
function do_filing()	// QQFILE
{
	x_alert('$$st_folder_filter$$');
}

function filtermenu_new(txt,txt2)
{
	return 	'<div class="filtermenu_search" onkeydown="stopBubble(event)" onkeyup="stopBubble(event)"><img src="||www_base||shared/img/1pixel.gif" class="search_icon mnu_filter" /><input type="text" class="filtermenu_input" onmouseup="stopBubble(event)" onkeydown="filtermenu_onkeydown(this,event)" onkeyup="filtermenu_onkeyup(this,event)" onclick="stopEvent(event)"></div>'+
			'<div class="filtermenu_scrolling">'+txt+'</div>'+
			'<div>'+txt2+'</div>';
}
function menu_to_filter(el){
	return el.firstChild.childNodes[1];
}
function menu_to_ctl(el){
	return el.firstChild.childNodes[1];
}
function ctl_to_list(el){
	return el.parentNode.nextSibling.firstChild;
}
function list_to_menu(el){
	return ancestor_by_class(el,'xmenu');
}

function filtermenu_new_label(e)
{
	el=dge('label_menu');
	if(el.match_text && el.match_text) {
		do_label_set(el.match_text,true);
		return;
	}
	x_prompt('$$st_lblmng_createnew$$','$$st_lblmng_newname$$',function(val){
		if (!val) return;
		do_label_set(val,true);
	});
}
function filtermenu_newitem(e,type)
{
	stopBubble(e);	
	var mnu=dge(type+'_menu');
	if(mnu.match_text && mnu.match_text) {
		filtermenu_action(mnu,mnu.match_text,true);
		return;
	}
	var text = type=='folder' ? '$$st_fldmng_createnew$$' : '$$st_lblmng_createnew$$';
	var item = type=='folder' ? '$$st_fldmng_newname$$' : '$$st_lblmng_newname$$';

	x_prompt(text,item,function(val){
		if (!val) return;
		filtermenu_action(mnu,val,true);
	});
}

function filtermenu_onkeydown(ctl,e)	// cf contact_search_do
{
	stopBubble(e);	
	t=target(e);
	var list=ctl_to_list(t);
	var x_list=list.getElementsByTagName('li');
	var mnu=list_to_menu(list);
	switch(e.keyCode){
		case vkUpArrow:
		case vkDownArrow:
			if(list.select_id==undefined) 
				list.select_id=-1;
			if(list.select_id>=0) 
				class_remove(x_list[list.select_id].firstChild,'selected');
			for(var count=x_list.length;count>0;count--){
				list.select_id+=(e.keyCode==40?1:-1);
				if (list.select_id<0) list.select_id=x_list.length-1;
				if (list.select_id>=x_list.length) list.select_id=0;
				var row = x_list[list.select_id];
				if(class_contains(row,'hidden')) continue;
				if(class_contains(row,'menu_spacer')) continue;
				break;
			}
			if(count>0)
				class_add(x_list[list.select_id].firstChild,'selected')
			break;
		case vkEsc:
		case vkBTick:
			menu_hide(mnu.id);
			filtermenu_search_clear(mnu.menu_list);
			break;
		default:
			setTimeout(function(){filtermenu_search_real(ctl)},10);
			break;

	}	
}
function filtermenu_onkeyup(ctl,e)	// cf contact_search_do
{
	stopBubble(e);	
	t=target(e);
	var list=ctl_to_list(t);
	var x_list=list.getElementsByTagName('li');
	
	var mnu=list_to_menu(list);
	switch(e.keyCode){
		case vkEnter:
			var id;
			if(mnu.match_text && mnu.match_text.length>0){
				id=mnu.match_text;
				filtermenu_action(mnu,id,true)
			}else {
				id=x_list[list.select_id].getAttribute(mnu.search_attrib);
				if(mnu.last_count==-1 && !pref.pickmenu_create){
					x_alert('<div style="margin-left:60px;">Please create '+mnu.menu_type+' first: '+mnu.ctl_value+'<br><br> (or have administrator enable the setting "pref_pickmenu_create true")</div>');
				}else{
					filtermenu_action(mnu,id,false,mnu.del_menu)
				}
			}
			menu_hide(mnu.id);
			filtermenu_search_clear(mnu.menu_list);
			break;
		default:
			break;
	}	
}
function filtermenu_search_real(ctl,unselect)
{
	var match=ctl.value;
	var match_lwr=match.toLowerCase();
	var items=ctl_to_list(ctl);
	var mnu=list_to_menu(items);
	mnu.ctl_value = ctl.value;
#	Hide / show each row in the menu	
	var x_items=items.getElementsByTagName('li');
	for(var i=0;i<x_items.length;i++){
		row=x_items[i];
		var ids=[];
		var match=false;
		if(ctl.filtermenu.menu_type=='folder' || ctl.filtermenu.menu_type=='label'){
			var id=row.getAttribute(mnu.search_attrib);
			if(!id) {
				class_add(row,"hidden");
				continue;
			}
			ids=id.split('/');
			x=ids[ids.length-1].substring(0,match_lwr.length).toLowerCase();
			if(x==match_lwr){
				match=true;
			}
		}else if(ctl.filtermenu.menu_type=='qpick' || ctl.filtermenu.menu_type=='defer'){
			var txt = row.firstChild.innerHTML.toLowerCase();
			if(txt.substring(0,match_lwr.length)==match_lwr || txt.indexOf(' '+match_lwr)!=-1){
				match = true;
			}
		}
        if(match){
            class_remove(row,"hidden");
            if(ids.length>0){
            	var el=row;
            	while(el.parentNode.tagName.toLowerCase()=='ul' && !(class_contains(el.parentNode,'ftree') || class_contains(el.parentNode,'ltree') || class_contains(el.parentNode,'xtree'))){
            		el=ancestor_by_tag(el.parentNode,'li');
					class_remove(el,"hidden");
					if(x.length>0 && class_contains(el,'closed')) fld_expand(undefined,undefined,el);
            	}
            }
            row.match=true;
        }else{
	        class_add(row,"hidden");
	        row.match=false;
        }
    }

# 	Remove any previous selection   
	dbg('filtermenu_search_real select_id='+items.select_id)
    if(items.select_id && items.select_id>=0){
    	if(!class_contains(x_items[items.select_id],'hidden')) return;
#		if(unselect || class_contains(x_items[items.select_id],'hidden'))
		class_remove(x_items[items.select_id].firstChild,'selected');
    }
#    if(unselect) items.select_id=-1;
    mnu.match_text='';

	if(mnu.create_item){
		var txt = mnu.menu_type=='folder' ? '$$st_fldmng_newfld2$$' : '$$st_lblmng_newlbl2$$';
		mnu.create_item.innerHTML=txt;
	}
#    var el=dge('label_menu_newlabel')
#    var el=dge('folder_menu_newfolder')
#    el.innerHTML='New Label';
	if(match.length==0) return;

#	Now select the first plausible match or allow new item to be created
#	var x_items=items.getElementsByTagName('li');
	var len=x_items.length;
	for(var count=0;count<=x_items.length;count++){
		if(count==len){
			count=-1;
			break;
		}
		row=x_items[count];
		if(!row.match) continue;
		if(!class_contains(row,'hidden'))
			break;
	}
	if (count>=0){
		items.select_id=count;
		class_add(x_items[count].firstChild,'selected');
    } else if(count==-1){
		if(mnu.create_item){
			mnu.create_item.innerHTML+=' "'+match+'"';
		}
		mnu.match_text=match;
    }
    mnu.last_count = count;
}
function filtermenu_search_clear(zlist)
{
	var list=zlist.firstChild;
	dbg('QQQQ '+list.select_id);
	if (list.select_id==undefined) {
		list.select_id=-1;
		return;
	}
	if (list.select_id<0) return;
	var x_list=list.getElementsByTagName('li');
	dbg('QQQQ REMOVING SEL:'+list.select_id+'x_items.length'+x_list.length);
	class_remove(x_list[list.select_id].firstChild,'selected');
	list.select_id=-1;
}
function filtermenu_action(mnu,id,create_new)
{
	if (!mnu.cb || id.length==0) return;
	mnu.cb('ok',id,create_new,mnu.del_menu);
}
function do_label_menu(e,el) 
{
}
function ltree_mouseup(e)
{
	var t=target(e);
	var el=ancestor_by_class(t,'qlabel');
	var label=el.getAttribute('labelid');
	if(!label || label.length==0) return;
	var mnu=dge('label_menu');
	filtermenu_action(mnu,label);
}
//cf do_folder_menu & no ftree_mouseup 

# cf do_folder_create
function labels_create()
{
	var sw_label=dge('label_new_type').checked;
	sndReq('cmd=labels_manage,show&action=create&label_name='+xescape(dge('label_new_name').value)+'&sw_label='+sw_label+'&page=~labels.htm', function(chan){
		node=actionReqSethtml(chan.responseText,'utility');
		if(!success) set_status(success_string,'warning');
	});
}
function labels_rename(tag,name)
{
	x_prompt( $('$$st_lblmng_rename$$',name),name,function(val){
		if(!val) return;
		sndReq('cmd=labels_manage,show&action=rename&label_name='+xescape(tag)+'&label_name_dst='+xescape(val)+'&page=~labels.htm', function(chan){
			node=actionReqSethtml(chan.responseText,'utility');
			if(!success) set_status(success_string,'warning');
			else label_cache_reset();
		});
	});
}
function labels_delete(tag,name)
{
	x_confirm($('$$st_lblmng_delete$$',name), function(n){
		if(!n) return;
		sndReq('cmd=labels_manage,show&action=delete&label_name='+xescape(tag)+'&page=~labels.htm', function(chan){
			node=actionReqSethtml(chan.responseText,'utility');
			if(!success) set_status(success_string,'warning');
			else label_cache_reset();
		});
	});
}
function labels_show(label)
{
	sndReq('cmd=labels_manage,show&action=show&label_name='+xescape(label)+'&page=~labels.htm', function(chan){
		node=actionReqSethtml(chan.responseText,'utility');
		if(!success) set_status(success_string,'warning');
		else label_cache_reset();
	});
}
function labels_hide(label)
{
	sndReq('cmd=labels_manage,show&action=hide&label_name='+xescape(label)+'&page=~labels.htm', function(chan){
		node=actionReqSethtml(chan.responseText,'utility');
		if(!success) set_status(success_string,'warning');
		else label_cache_reset();
	});
}
function labels_clientmap_apply()
{
	sndReq('cmd=labels_manage,show&action=mapping&mail_client='+xescape(dge('labels_clientmap').value)+'&page=~labels.htm', function(chan){
		node=actionReqSethtml(chan.responseText,'utility');
		if(!success) set_status(success_string,'warning');
	});
}

# WARNING: label cols now defined in editor_plain.js
function color_swatches(per_line)
{
	var txt='';
	for(var i=0;i<label_cols.length;i++){
  		if( i%per_line == 0 )txt += '<tr>'; 	
		txt+='<td class="swatch_hover"><div class="swatch" style="background:'+label_cols[i][0]+';border:1px solid '+label_cols[i][1]+';" pickid="'+i+'"></div>';
	}
	return txt;
}

function labels_color(e,label)
{
	var el=dge('picker_menu');
	el.innerHTML='<table onmouseup="label_color_select(event)">'+color_swatches(5,'labels')+'</table>';
	el.cur_item=label;
	do_menu_show('picker_menu',e,undefined,undefined,{cursor:true})
}
function label_color_select(e)
{
	var el=target(e);
	var picked=el.getAttribute('pickid');
	if(!picked) return;
	var el=dge('picker_menu');	
	sndReq('cmd=labels_manage,show&action=color&label_name='+xescape(el.cur_item)+'&color='+picked+'&page=~labels.htm', function(chan){
		node=actionReqSethtml(chan.responseText,'utility');
		if(!success) set_status(success_string,'warning');
		else label_cache_reset();
	});
}
function label_cache_reset()
{
	cache_clear();
	sw.msglist_refresh=true;
}
function labels_done()
{
	window_manager_minimise(sw.active);
	window_manager_restore();	
}
function el_to_labels(el)
{
	return ancestor_by_class(el,'labels');
}
function el_to_date_etc(el)
{
	return ancestor_by_class(el,'date_etc');
}
function do_label_cxmenu_setup(el)
{
	var txt='';
	txt+='<a href="#" onmousedown="do_label_clear(\'all\',true)">$$st_mnu_removeall_lbls$$</a>'
	txt+='<i>&nbsp;$$st_mnu_remove_lbl$$</i>'
	for (var i=0;i<el.childNodes.length;i++){
		var id=el.childNodes[i].getAttribute('label_id');
		txt+='<a href="#" onmouseup="cx_label_remove(this,event)" label_id="'+id+'"> &nbsp;&nbsp;&nbsp;- '+id+'</a>';
	}
	txt+='<hr><a href="#" onclick="labels_menu(event,\'cx_menu\')">$$st_cmd_add_label$$</a>'
	txt+='<hr><i>&nbsp;$$st_mnu_show_lbl$$</i>'
	for (var i=0;i<el.childNodes.length;i++){
		var id=el.childNodes[i].getAttribute('label_id');
		txt+='<a href="#" onmouseup="cx_label_show(this,event)" label_id="'+id+'"> &nbsp;&nbsp;&nbsp;'+id+'</a>';
	}
	var mnu=dge('context_menu_label');
	mnu.innerHTML=txt;
	mnu.shadofied=false;	
}
function labels_cx(e)
{		  	
	var t=target(e);
	do_label_cxmenu_setup(el_to_labels(t))
	do_menu_show('context_menu_label',e,U,U,{cursor:true})
}		  	
function cx_label_remove(el,e)
{
	t=target(e);
	do_label_clear(el.getAttribute('label_id'));
}
function cx_label_show(el,e)
{
	var label=el.getAttribute('label_id');
	if(sw.is_popup) {
		sw_win.L(label);
	}else{
		L(label);
	}
}
function msgpanel_to_msglabels(el)
{
	return el.childNodes[1].childNodes[0].childNodes[1];
}

# cf n allow_images
function do_label_set(id,force,el)
{
	if(sw.is_popup){
		sw_win.do_label_set(id,force,dge('msg_headers').childNodes[1]);
		return;	
	}
	var sel=find_sel();
	if (!sel) return;

	if(class_contains(sw.active,'message')) 
		el=msgpanel_to_msglabels(sw.active.container.popup_message);

	ajax_label(sel,(force?'xset':'set'),id,function(node){},el)
}
function do_label_clear(id,all,el)
{
	if(sw.is_popup){
		sw_win.do_label_clear(id,all,dge('msg_headers').childNodes[1]);
		return;	
	}
	var sel=find_sel();
	if (!sel) return;

	if(class_contains(sw.active,'message')) 
		el=msgpanel_to_msglabels(sw.active.container.popup_message);

	ajax_label(sel,(all?'xclear':'clear'),id,function(node){},el)
}

function shadofy(o)
{
	var el;
	if(!o || o.shadofied) return;
	var shadows=['top_left','top_edge','top_right','left_edge','right_edge','bottom_left','bottom_edge','bottom_right'];
	for(var i=0;i<shadows.length;i++){
		el=new_element(o,'div');
		class_add(el,shadows[i]);
		class_add(el,'shadow');
		el.onclick=function(){dbg("SHADOW onclick")};
	}
	o.shadofied=true;
}


# Preliminary stuff for the label / folder menus
function move_menu(e,source,ctl,forever)
{
#	do_folder_menu_setup(e,'folder_menu');
#	do_generic_menu_setup('folder','folder_menu',(e&&e.shiftKey));
	if(source=='button'){
		do_move_show(e)
	}else if(source=='more_actions'){
		do_move_show(e,ctl,forever);
	}else if(source=='kbd'){
		do_move_show(e,dge('mnu_more'));
	}
}
function labels_menu(e,source,ctl)
{
	if(sw.alt_account&&!sw.labels_force_allow) {
		return no_labels();
	}
	if(source=='button'){
		do_label_show(e);
	}else if(source=='more_actions'){
		do_label_show(e,ctl);
	}else if(source=='cx_menu'){
		setTimeout(function(){
			do_label_menu_setup(undefined,'label_menu');
			var el=dge('mnu_more');
			if(sw.is_popup || class_contains(sw.active,'message')) el=dge('menu_message_label');
			do_label_show(undefined,el);
		},5);
	}else if(source=='kbd'){
		do_label_show(e,dge('mnu_more'));
	}
}
function do_label_show(e,input)
{
	do_generic_show('label_menu', e, input, function(del_menu,id,create_new){
		if(del_menu)
			do_label_clear(id);
		else
			do_label_set(id,create_new);
	});
	return;

	var options={};
	if(input) options.t=input;

	do_label_menu_setup(e,'label_menu');
	do_menu_show('label_menu',e,true,	function(result,id,create_new,del_menu){

		var sel=find_sel(true);
		if (!sel) return;

		filtermenu_search_clear(dge('label_menu').menu_list);
		msglist_select(sel[sel.length-1]);
		if(result!='ok'){
			return;	
		}

		if(del_menu)
			do_label_clear(id);
		else
			do_label_set(id,create_new);

	}, options);
}


function mark_read(mid,delay,type)
{
	var el=dge('sel_'+mid);
	if (!el || !class_contains(sel_to_row(el),'msg_unread')) return;		

	if(delay){
		var sel=make_sel(sw.fld_id,mid);
		seen_timer=setTimeout(function(){set_seen(sel)},(type=='initial'?7000:2500));		
	}else{
		var sel=make_sel(sw.fld_id,gs_cursor_mid(sw.ml));
		for_each_msg(sel,function(node){class_remove(node,'msg_unread')});
		ajax_set_flags(sel,'set','seen',function(success){
			if(success) return
			for_each_msg(sel,function(node){class_add(row_to_star(node),'msg_unread');});
		});
	}
}
function set_seen(sel){
	for_each_msg(sel,function(node){class_remove(node,'msg_unread')});
	ajax_set_flags(sel,'set','seen',function(success){
		if(success) return
		for_each_msg(sel,function(node){class_add(row_to_star(node),'msg_unread');});
	});
	seen_timer=null;
}

function icon_upload(abook,cid)
{
	x_custom_dlg2('$$st_icon_title$$ ','<iframe id="dlg_iframe" src="" style="width:100%;height:'+px(300)+';background:#ECE9D8;" frameborder="0"></iframe>',
		function(btn){
#			if(!btn) return;
			alert('$$st_icon_warn$$');
		},
		function(){
			arr=[];
			arr.push('<html><head><body style="background:#ECE9D8;">');
			arr.push('<b>$$st_icon_info1$$</b> <br><br>$$st_icon_info2$$<br><br>');
			arr.push('<form action="||cgi||" method="POST" enctype="multipart/form-data">$$st_attach_txt_file$$ <input type="file" name="attach"><br><br>');
			arr.push('<input name="sid" type="hidden" value="'+sid+'">');
			arr.push('<input name="upload" type="hidden" value="true">');
			arr.push('<input name="abook" type="hidden" value="'+abook+'">');
			arr.push('<input name="server_cid" type="hidden" value="'+cid+'">');
			arr.push('<input name="cmd_contact_icon" type="submit" value="$$st_icon_upload$$"><br>');
			arr.push('</form></body></html>')
			x_custom_dlg2_body(arr.join(''));
		});
	
}
function contacts_export(type)
{
#	return alert("export is not yet available");
	var cmd='cmd=contact_export,show&page=hdialogs.htm&dlg_type=contacts_export&dlg_tab='+type+'&abook='+xescape(get_abook())+'&server_cid='+xescape(get_svr_cid())+'&export_group='+xescape(get_group())+'&sid='+sid;
	x_custom_dlg2('$$st_ct_export_title$$','<iframe id="dlg_iframe" src="'+cgibase+cmd+'" style="width:100%;height:'+px(290)+';background:#ECE9D8;" frameborder="0"></iframe>',
		function(btn){
#			if(!btn) return;
#			cm_contacts_refresh();
		}, function(){}, {'width':560,'nopad':true,'nobtns':true});
}

function do_identity(showall)
{
	node=sw.active;
	if (node && node.className=="compose")
		window_manager_minimise(node);
	var cmd='cmd=show&page=~identities.htm';
#	if(showall)
#		cmd+='&lang_showall=true';

	sndReq(cmd, function(chan){
		node=actionReqSethtml(http.responseText,'utility');
	});
}

function identity_done()
{
	window_manager_minimise(sw.active);
	window_manager_restore();
	account_sel(sw.ident);
}

function do_download()
{
	var sel, url;
	sel=find_sel();
	if (!sel || sel.length==0){
		x_alert('$$st_select_some$$');
		return;
	}
	if(sel.length==1){
		url=cgibase+'cmd=msgpart&sid='+sid+iid()+'&fld_id='+xescape(sw.fld_id)+'&msg_id='+sel[0]+'&part_id=0&attachment=true';
	}else{
		url=cgibase+'cmd=download_all&whole_msgs=true&sid='+sid+iid()+'&fld_id='+xescape(sw.fld_id)+'&sel='+sel+'&attachment=true';
	}
	dge('an_iframe').src=url;
}
function do_download_msg()
{
	var sel=find_sel();
	var url=cgibase+'cmd=msgpart&sid='+sid+iid()+'&fld_id='+xescape(sw.fld_id)+'&msg_id='+sel[0]+'&part_id=0&attachment=true';
	dge('an_iframe').src=url;
}
function download_part(iid,fld_id,mid,pid)
{
	var url=cgibase+'cmd=msgpart&sid='+sid+'&ident='+iid+'&fld_id='+xescape(fld_id)+'&msg_id='+mid+'&part_id='+pid+'&attachment=true';
	dge('an_iframe').src=url;
}
function download_all(iid,fld_id,mid,mpr_attach)
{
	var url=cgibase+'cmd=download_all&sid='+sid+'&ident='+iid+'&fld_id='+xescape(fld_id)+'&msg_id='+mid;
	if(mpr_attach) url+='&mpr_as=attach';
	dge('an_iframe').src=url;
}

function folder_recalc(el)
{
	var row=ancestor_by_tag(el,'tr');
	class_add(row,'fld_update');	
	fld_id=row.getAttribute('fld_id')
	if(!fld_id)return;
	refresh_type="size_only";
	refresh_folder(row,fld_id);	// cf do_refresh2	
}
function folders_recalc(type)	// size or refresh
{
	var fld_id,row;
	var rows=folder_rows();
	for(var i=0;i<rows.length;i++){
		row=rows[i];
		fld_id=row.getAttribute('fld_id')
		if(!fld_id)continue;
		class_add(row,'fld_update');
	}
	//start refreshing...
	refresh_type=type;
	refresh_next();
}
function folder_rows()
{
	var el=dge('manage_folders');
	if(!el)return;
	var rows=el.getElementsByTagName("tr");
	return rows;
}
var refresh_data;
var refresh_type;
function refresh_next()
{
	var rows=folder_rows();
	for(var i=0;i<rows.length;i++){
		row=rows[i];
		if(!class_contains(row,'fld_update')) continue;
		fld_id=row.getAttribute('fld_id')
		if(!fld_id) continue;
		if(fld_id=='More Folders') continue;
		setTimeout(function(){refresh_folder(row,fld_id)},(refresh_type=='size_only'?0:0));
		break;
	}				
}
function refresh_folder(row,name)
{
	sndReq('cmd=refresh_folder,show&folder_refresh='+xescape(name)+'&refresh_type='+refresh_type+'&disable_background=true&page=~result.js'+iid(), function(chan){
		var success=actionReqJsStat(chan);
		class_remove(row,'fld_update');
		if(!success){
			set_status('$$st_err_fld_refresh$$ ('+success_string+')','warning');
			return;
		}
		for(var i=1;i<=3;i++){
			row.childNodes[i].innerHTML=refresh_data[i];
		}		
		set_status($('$$st_fld_updated$$',name),"success")
		refresh_next();
	});
}
function folder_recalc_results(data)
{
	refresh_data=data;
}
function touchStart(e)
{
	dbg('touchStart');
}
function touchMove(e)
{
	dbg('touchMove');
#	e.preventDefault();
#	cancelTouch();
#    curX = e.targetTouches[0].pageX - startX;
#    curY = e.targetTouches[0].pageY - startY;
#    e.targetTouches[0].target.style.webkitTransform = 'translate(' + curX + 'px, ' + curY + 'px)';	

   var touch = e.touches[0],
   // simulating a mousemove event
   simulatedEvent = document.createEvent("MouseEvent");
   simulatedEvent.initMouseEvent("mousemove", true, true, window, 1,
        touch.screenX, touch.screenY,
        touch.clientX, touch.clientY, false,
        false, false, false, 0, null);

   // dispatching the simulated event
   touch.target.dispatchEvent(simulatedEvent);
   e.preventDefault();
}

function touchEnd(e)
{
	dbg('touchEnd');
}

function touchCancel(e)
{
	dbg('touchCancel');
}


# cf select_mailbox_all
function show_hint()
{
	if (time() < sw.hint_at) return;
	var hint = pref.hint_next;
	if (!hint || hint[0]<1) return
	var ex=dge('list_extra');
	class_remove(ex,'hidden')
	class_add(ex,'hint');
	var close_links = '<span class="hint_style" style="padding-left:5px;"><a href="#" onclick="hide_hint()">$$st_hint_hide$$</a>, <a href="#" onclick="manage_hints(event)">$$st_hint_configure$$</a></span>';
	ex.innerHTML = '<table class="hint_table" width="100%"><tr><td><span class="hint_style">'+hint[2]+'</span></td><td width="90px">'+close_links+'</td></tr></table>';
}
function hint_unshow()
{
	pref.hint_next=U;
	class_add(dge('list_extra'),'hidden');
}
function hide_hint()
{
	var hint = pref.hint_next;
	if (!hint || hint[0]<1) return;
	hint_unshow();
	sndReq('cmd=hint_update,show&hint_seen='+hint[0]+'&custom_hint='+hint[1]+'&page=~result.js'+iid(), function(chan){
		var success=actionReqJsStat(chan);
	});
}
function options_tab(tab)
{	
	do_options(false,'&vtab='+tab);
}
function hint_update_all(e, action)
{
	hint_unshow();
	return manage_page(e, 'cmd=hint_update,show&hint_all=yes&hint_action='+action+'&page=~hints.htm');
}
function hint_update_one(e, number, custom)
{
	hint_unshow();
	return manage_page(e, 'cmd=hint_update,show&hint_seen='+number+'&custom_hint='+custom+'&page=~hints.htm');
}

function no_labels()
{
	x_alert('<div style="margin-left:70px;">$$st_lblmng_alt_acct$$<br><br><span style="color:#999;">$$st_lblmng_alt_acct2$$</span></div>');
}
function update_alt_account(alt_account,labels_force_allow)
{
	sw.alt_account=alt_account;
	sw.labels_force_allow=labels_force_allow;
}
	

function do_calendar_create()
{
	el=dge('calendar_new_name');
	var clrs=cal_colors();
	var ncol=sw.cal_count % clrs.length;
	var clr=clrs[ncol];
	var new_name=el.value;
	sndReq('cmd=cal_action,show&cal_action=create&new_name='+xescape(new_name)+'&new_color='+xescape(clr)+'&page=~calendars.htm'+iid(), function(chan){
		node=actionReqSethtml(chan.responseText,'utility');
	});
}

function do_new_note(e)
{
	do_compose_note(e)
}
function iframe_close()
{
	app_menu_mail();
}


function defer_menu(e,source)
{
	var opt = {};
	opt.nomanage=true;
#	if(source=='cx') opt.cursor=true;
#	do_generic_menu_setup('defer','defer_menu',(e&&e.shiftKey),opt)
	if(source=='cx'){
		opt.cursor=true;
		do_defer_show(e,dge('mnu_more'),opt);
	}else if(source=='button'){
		do_defer_show(e,U,opt)
	}else if(source=='more_actions'){
		do_defer_show(e,ctl,opt);
	}else if(source=='kbd'){
		do_defer_show(e,dge('mnu_more'),opt);
	}else if(source=='cxmenu'){
		setTimeout(function(){ do_defer_show(e,dge('mnu_more'),opt); }, 20);
	}
}
function defer_cx(e)	// labels_cx
{		  	
	var t=target(e);
	do_label_cxmenu_setup(el_to_labels(t))
	do_menu_show('context_menu_label',e,undefined,undefined,{cursor:true})
}		  	



function do_generic_show(id,e,input,cb,opt)
{
	if(!opt) opt={};
	if(input) opt.t=input;

	var type = id.substring(0,id.indexOf('_'));
	do_generic_menu_setup(type,id,(e&&e.shiftKey),opt);

	do_menu_show(id,e,true, function(result,item,create_new,del_menu){

		var sel=find_sel(true);
		if (!sel) return;
#		filtermenu_search_clear(dge(id).menu_list);
		msglist_select(sel[sel.length-1]);
		if(result!='ok'){
			return;	
		}

		cb(del_menu, item, create_new);
	}, opt);
}

#swcal_delta

# Maybe make this function generic sometime
function do_defer_menu(e,el)
{
	if(sw.alt_account) {
		return no_defer();
	}
	if (!e) e = window.event;
	var t = target(e);
	var row=ancestor_by_tag(t,'li');
	var mnu = list_to_menu(row);
	var item=row.getAttribute(mnu.search_attrib)

	menu_hide('defer_menu',item);
	var o=dge('defer_menu');
	class_add(o,'hidden');

	if (!item) return;
	if (o.cb)
		o.cb('ok',item);
}
function do_defer(e,type,custom)
{
	if(sw.alt_account) {
		return no_defer();
	}

	if(type=='inbox'){
		return do_move_actual('INBOX',false);
	}
	var sel=find_sel(true);
	do_select('none');
	ajax_defer(sel,type,custom);
	message_done_action(sel);
}


function do_defer_show(e,input,opt)
{
	if(sw.alt_account) {
		return no_defer();
	}
	do_generic_show('defer_menu', e, input, function(del_menu,type,create_new){
		if(type=='none') return;
		if(type=='custom'){ custom_picker(); return;}
		do_defer(e,type);
	},opt);
}
function custom_picker()
{
	x_confirm(U,function(n){
		var ctl=defer_ctl;
		defer_ctl = null;
		if(!n) return;
		var offset = PDefer.day_offset(ctl);
		do_defer(event,'custom', offset);
	},U,{title:'$$st_defer_msg_until$$', view_init:defer_view_init});
}
var defer_ctl;
function defer_view_init(el)
{
	defer_ctl = PDefer.init(el);
	defer_ctl.oncomplete = function(){ dlg_clk(1); }
}

function no_defer()
{
	x_alert('<div style="margin-left:70px;">$$st_defer_alt_acct$$</div>');
}



function reset_mid(row,new_mid)
{
	row_to_sel(row).id='sel_'+new_mid;
	row.setAttribute('msg_id',new_mid);
	sw.ml.cursor_mid = new_mid;
}

function animate_in_msg()
{
	var el;
	if(!pref.animation_enable) return;
	var len = sw.msgs_preview.childNodes.length;
	for(i=0;i<len;i++){
		el=sw.msgs_preview.childNodes[i];
		class_add(el,"msg_animate_in");
	}
}

function endless_show_dots(show_dots, endless_mode)
{
	if(!endless.enabled) return;
	var el = dge('msglist_dots');
	if(!el) return;
	if(show_dots){
		el.innerHTML='<div class="wait_dots"><div class="dot1"></div><div class="dot2"></div><div class="dot3"></div></div>';
	}else if(istrue(endless_mode)){
		el.innerHTML='<div class="wait_dots_filler"></div>';
	}else{
		el.innerHTML='';
	}
}

var endless={};

function endless_init()
{
	var o={};
	o.next_id=0;
	o.next_t=0;
	o.enabled = pref.endless_enable;
	o.xdelta=100;
	o.normal_pg_sz=100;
	o.more = false;
	o.chunk = 0;
	o.loading = false;
	o.xstart=0;
	o.tlast=0;
	o.added=false;
	
	endless = o;
}

function endless_list_init(init,endless_id,endless_t)
{
	if(!endless.enabled) return;
	if(init){
		if(endless.xstart==0) endless.xstart=100;
		endless.more_items = true;
		endless.next_id = endless_id;
		endless.next_t = endless_t;
		endless.tlast = mtime();
	}else{
		endless.more_items = false;
		endless.xstart=0;
		endless.tlast=0;
		endless.added=false;
	}
	endless_show_dots(false, endless.more_items);
}

function msglist_scrolled(e)
{
	if(!endless.enabled) return;
	if(!endless.more_items) return;
	if(endless.loading) return;

#	if(ctl_cmd_key(event)) return;

	if(endless.timer) {
		// allow cancel?
		return;
	}
	
	var el = dge('msglist_box');
#	dbg('scroll scrollTop+clientHeight='+(el.scrollTop+el.clientHeight)+' scrollHeight='+el.scrollHeight);
	if(el.scrollTop+el.clientHeight<el.scrollHeight-70) return;
	if(endless.tlast>mtime()-700) return;

	endless.timer = setTimeout(function(){
		endless_show_dots(true);
		FolderShow(sw.fld_id,{endless:true, endless_id:endless.next_id, endless_t:endless.next_t});	
		endless.timer = U;
		endless.loading = true;
	},100);
}

function endless_api_param(extra,fld,want_endless)
{
	if(endless.more_items && istrue(want_endless)) {
		var want = endless.xstart==0 ? endless.normal_pg_sz : endless.xdelta;
		extra='&start='+endless.xstart;
		extra+='&num='+want;
		endless.xstart+=want;
	} else {
		endless.xstart=0;
		endless.chunk=0;
		endless.tlast=0;
	}
	return extra;
}

function endless_api_complete(was_endless)
{
	endless.loading = false;	
	if(!was_endless) return;
	endless.added = true;
	var el = dge('msglist_box');
	if(el!=U){
		var prev_scroll_top = el.scrollTop;
		setTimeout(function(){
			var el = dge('msglist_box');
			if(el!=U){
				el.scrollTop = prev_scroll_top;
			}
		},1);
	}
}
