
var knownuid=0;
var knownactivity=0;
var last_activity_txt='';
var last_activity_time=0;
var xol_tlast=0;
var xol_stat='$$st_xol_name$$';
var xol_xstat='';
var xol_skip_alert=0;
var xol_invalid=0;
function xol_init()
{
	if(!pref.xol_connect) return;
	class_remove(dge('xol_indicator'),'hidden');
#	xol_status('Checking for YesImOnline availability');
	setTimeout(xol_heartbeat,1000);
	setTimeout(xol_access,500);
}
function xol_heartbeat()
{
	try{
		xol_updates();
	}catch(e){
		dbg('xol hearbeat exception')
	}
	setTimeout(xol_heartbeat,1000);
}
function xol_status(status)
{
	xol_stat=status;
	xol_updates();
}
function xol_xstatus(xstatus)
{
	xol_xstat=xstatus;
	xol_updates();
}
function xol_updates()
{
	xol_show_text();
	xol_show_icon();
}
function xol_show_text()
{
	var validity='';
	if(xol_invalid>time()-10){
		validity=' <span class="xol_red">$$st_yes_unavailable$$</span>';
	}
	
	if(xol_tlast<time()-5) xol_xstat='';
	if(last_activity_time>time()-60 && xol_xstat==''){
		xol_xstat=last_activity_txt;
	}
	
	var xol_link='<a href="#" onclick="xol_clicked(event)" class="xol_link">'+xol_stat+'</a><img src="||www_base||shared/img/1pixel.gif" class="dropdown">';
	
	if(xol_xstat.length==0){
		set_xol(xol_link+validity,'info');
	}else{
		var type=(xol_xstat.substr(0,1)=='(' ? 'xol_gray' : 'xol_activity'); 
		var txt='<span class="'+type+'">'+xol_xstat+'</span>';
		set_xol(txt+' - '+xol_link+validity,'info');
	}
}
function xol_show_icon()
{
	var el=dge('xol_icon'), txt='';
	if(xol_invalid>time()-10){
		txt='xol_offline';	
	}else if(xol_tlast<time()-180) {
		// icon already set
	}else if (xol_tlast<time()-70){
		txt='xol_idle';
	}else{
		txt='xol_online';
	}
	class_set(el,txt);
}
function xol_invalid_try_later()
{
	xol_invalid=time();
	setTimeout(xol_access,5000);
}
function xol_access()
{
	dbg('sig_refetch - actioning request')
	try{
	 sndCorsReq('http://127.0.0.1:7070/checkmail','knownuid='+knownuid+'&knownactivity='+knownactivity+'&sid='+sid+'&email='+xescape(email), function(chan){
		dbg('~inline.tpl - request completed');
		if (chan.status>500){
			xol_invalid_try_later();
			return;
		}
		xol_tlast = time();
		var res = chan.responseText;
		if(res.substring(0,9)=='+TIMEOUT:'){
			xol_xstatus('(poll timeout)','info');
		}else if(res.substring(0,9)=='+REFRESH:'){
			xol_xstatus('(Message list refresh)');
			check_new_mail();		
		}else if(res.substring(0,10)=='+ACTIVITY:'){
			var arr=res.substring(10).split(':');
			knownactivity=parseInt(arr[0]);
			var skip=last_activity_time==0;
			last_activity_time=parseInt(arr[1]);
			last_activity_txt=arr[2];
			if(skip){
				last_activity_txt='';
			}else{
				xol_xstatus(arr[2]);
			}
		}else if(res.substring(0,8)=='+NEWMSG:'){
			var newuid=parseInt(res.substring(8),10);
			if(newuid > knownuid){
				if(knownuid==0){
					xol_status("YesI'mOnline!",'info');
					xol_tlast=time();
					xol_show_icon();
				}else{
					xol_xstatus('(New message uid='+newuid+')');
					xol_skip_alert=time();
#					//  not reliable enough!!
#					window.focus();
#					alert("switched to mail")
#					window.blur();
#					setTimeout(window.focus, 0);
				}
				check_new_mail();
				knownuid=newuid;
			}
		}else{
			xol_invalid_try_later();
			return;
		}
		xol_status('$$st_xol_name$$');
		setTimeout(xol_access,knownuid==0?5000:0);
	 },ch[enOL]);
	} catch(e){
		if(isIE){
			x_alert('Cross Domain data access not enabled in IE so YesImOnline integration not available.\nEnable using\n"Internet Options - Security - Custom Level - Miscellaneous - Access Data Sources Across Domains"');
		}else{
			x_alert('Cross site scripting not available on this browser sorry');
		}
	}
}

function xol_compose(email,e)
{
	dbg('xol_compose - actioning request')
	sndCorsReq('http://127.0.0.1:7070/compose','email='+email, function(chan){
		if (chan.status==200 || chan.status==0) return;
		
		xol_xstatus('(XOL native compose failed)');
		var jmsg=compose_jmsg([email]);
		jmsg.sim=true;
		show_edit(jmsg,U);
	},ch[enFG]);
}


xadd_event(window,'message',receiveMessage);
function receiveMessage(e)
{
	if(!e) e=event;
	if(!e || !e.data) return;

	var cmd=e.data;
	if(cmd.substring(0,8)=='compose:'){
		xol_compose(cmd.substring(8),e);
	}else{
#		x_alert('RX:'+cmd);
	}
#  dge('yio_hdr').innerHTML='Child Rx:'+e.data;
#  if (e.origin !== "http://example.org:8080")
#	return;
}


# ******
# Right pane smarts => includes XOL and Todo :-) Finally have both long planned features!!

function right_column_init()
{
	if(!pref.todo) return;
	var el=dge("right_column");
	var xx = el.innerHTML.length;
	if(el.innerHTML.length>0)return;
	el.innerHTML=rpane_html();
	setTimeout(function (){ 
		todo_loading();
		stc_refresh();
	},0);
}
function rpane_html()
{
#	return '<div id="rcol" class="rcol_size1" style="background:white"></div>';
	return '<div id="rcol" class="rcol_size2" style="background:white">\
#				<div id="xol_panel" style="height:200px">\
#				  <div id="xol_hdr" class="xol_hdr">YesImOnline</div>\
#				  <div id="xol_list" onclick="notify(event)"></div>\
#				</div>\
				<div id="stc_panel">\
				  <div id="todo_hdr" class="left_panel_header" style="text-align:left;padding-left:3px;" onclick="todo_menu_show(event)" title="Click for new todo item">To Do \
				  		<img src="||www_base||shared/img/1pixel.gif" class="dropdown"> \
				  	<span style="float:right; font-weight:normal;" title="Todo management">\
				  		<a href="#" class="link_blue menu_extra" onclick="todo_refresh();stopBubble(event)">Refresh</a> \
#				  	| 
#				  	<a class="link_blue menu_extra" href="#" onclick="todo_menu_show(event)">Workflow</a><img src="||www_base||shared/img/1pixel.gif" class="dropdown">\
					&nbsp;</span> \
				  </div>\
				  <div id="todo_noscroller">\
				    <div id="todo_list" class="todo_list"></div>\
				  </div>\
#				  <div id="todo_footer">Search</div>\
				</div>\
			</div>';
	return '<iframe id="rcol" class="rcol_size1" src="surgeweb/ajax/yio.htm?||vz||" frameborder="0" style="background:white"></iframe>';
}
function rpane_todo()
{
	return 	    '<div class="todo_cell">\
					Project1<br>\
					<span class="offline">due today</span></div>\
\
				<div class="todo_cell">\
					project2<br>\
					<span class="offline">due tomorrow</span></div>\
\
				<div class="todo_cell">\
					~subject description<br>\
					<span class="offline">due next week</span></div>\
\
				<div class="todo_cell">\
					~subject description<br>\
					<span class="offline">some day</span></div>';

}
function stc_congrat()
{
	return '\
	<div style="margin-left:20px;">\
#	  <img src="||www_base||shared/img/investigation/zero3.png">\
		<span style="font-size:20px;color:lightgray;">\
#			Congratulations, on clearing your Inbox!\
			Nothing in your Inbox\
		</span></div>';
}
function setTodo(html)
{
	 dge("todo_list").innerHTML=html;
	 show_todo_search();
}
function stc_refresh()
{
	queued_req_add( enQ, 'learn_word', function(){
	  sndReq('cmd=show&page=~stc.js', function(chan){
		var success=actionReqJsStat(chan);
		if(!success){
			set_status(success_string,"warning")
			return;
		}
//		dge("todo_list").innerHTML=rpane_todo();
	  },ch[enQ]);
	}, 100);
}
function todo_overlay(show)
{
	if(!pref.todo) return;
	var o=dge('stc_body');
	if(!o) return;
	shadofy(o);
	var el=dge('todo_overlay');
	elS(el,show);
	el.shown = true;
}

function toggle_todo()
{
	if(!pref.todo) return;
	var el=dge('todo_overlay');
	todo_overlay(el.shown?true:false);

	var el = dge("todo_congrat");
	if(!el) return;
	el.innerHTML = stc_congrat();
}
function todo_msglist_box()
{
	toggle_todo();
}
function todo_msg_box()
{
	toggle_todo();
}
function todo_refresh()
{
	todo_loading();
	stc_refresh();
}
function todo_loading()
{
	setTodo('&nbsp;loading...')
}
function todo_hdr()
{
	todo_edit();
}
function todo_menu_show(e){
	class_update(dge('smarts_show_todo'),'sel',!pref.show_todo);
#	class_update(dge('smarts_categories'),'sel',pref.todo_categ);
	class_update(dge('smarts_cal'),'sel',pref.todo_cal);
	do_menu_show('pg_menu_todo',e);
}
function smarts_toggle_todo()
{
	pref.show_todo=!pref.show_todo;
	ajax_pref_save('pref_show_todo='+pref.show_todo);
	F(sw.fld_id);
}
function smarts_toggle_categories()
{
	pref.todo_categ=!pref.todo_categ;
	ajax_pref_save('pref_todo_categ='+pref.todo_categ);
}
function smarts_toggle_cal()
{
	pref.todo_cal=!pref.todo_cal;
	ajax_pref_save('pref_todo_cal='+pref.todo_cal);
}


function swtodo_cbx(e,el,ticked)
{
	if(!e) e=window.event;
	var t=target(e);
	var cbox=ancestor_by_class(t,'cbox_outer');
	var el=ancestor_by_class(t,'todo_cell');
	if(ticked){
		el.nohide=false;
		class_add(el,'todo_done');
		el.timer = setTimeout(function(){
			class_add(el,"todo_fade_animated");
			el.animating=true;

			el.timer = setTimeout(function(){
				class_add(el,"todo_hide_animated");
				el.animating=true;

				el.timer = setTimeout(function(){
					var cal_id=el.getAttribute('event_cal');
					var evt_id=el.getAttribute('event_uid');
					remove_node(el);
					todo_done(cal_id,evt_id);
				}, 100);
			},1000)			
		},600)
	}else{
		el.nohide=true;
		if(el.timer) clearTimeout(el.timer);
		class_remove(el,'todo_done');
		class_remove(el,'todo_fade_animated');
	}
	stopEvent(e);
}



function xol_activity(activity,to,mid)
{
	if(!pref.xol_connect) return;
	if(!to || to.length==0) return;
	sndCorsReq('http://127.0.0.1:7070/activity','activity='+activity+'&to='+xescape(to)+'&mid='+xescape(mid), function(chan){
		dbg('activity.tpl - request completed');
	},ch[enQ]);
}
function xol_favs(cb)
{
	if(!pref.xol_connect) return;
	sndCorsReq('http://127.0.0.1:7070/favs','', function(chan){
		dbg('activity.tpl - request completed');
		if (chan.status!=200){
			x_alert('Error fetching friends from YesI\'mOnline');
			return false;
		}
		var arr=chan.responseText.split('\n');
		cb(arr)
	},ch[enQ]);
}
function xol_presence(txt,classes)
{
	return '<span class="'+classes+'">'+txt+'</span>'
}
function xol_clicked(e)
{
	xol_favs(function(favs){
	
		var el=dge('top_menu_xol');
		while(class_contains(el.firstChild,'yes_fav')){
			remove_node(el.firstChild);
		}
		var child=el.firstChild;
		for(var i=0;i<favs.length;i++){
			var item=favs[i].split(':');
			if(item.lenght<7) continue;
			if(item[0]!='+F') continue;
			var f={};
			f.name=item[1];f.email=item[2]; f.state=item[3]; f.nice_age=item[4]; 
			f.isonline=item[5]; f.devname=item[6]; f.activity=item[7]; f.age=item[8];
			if(f.age>30*24*60*60) continue;
			var html='';
			if(f.state=='online'){
				html+=xol_presence(f.name,'xol_menu_present')+' &nbsp';
				var presence=(f.activity.length>0 ? f.activity : f.devname);
				html+=xol_presence(presence,'xol_menu_present xol_menu_small');
			}else{
				if(f.age>7*24*60*60){
					html+=xol_presence(f.name+' &nbsp','xol_menu_absent');
				}else{
					html+=f.name+' &nbsp';
				}
				html+=xol_presence(f.nice_age,'xol_menu_absent xol_menu_small');
			}
			var a=new_anchor_b4('a',html,child);
			a.href='#';
			a.setAttribute('xol_name',f.name);
			a.setAttribute('xol_email',f.email);
			a.onclick=xol_newmsg;
			a.className='yes_fav';
		}
		do_menu_show('top_menu_xol',e,true);
	});
}
function xol_newmsg(e)
{
	var t=target(e); 
	if(!t) return;
	t=ancestor_by_tag(t,'a');
	if(!t) return;
	
	var name=t.getAttribute('xol_name');
	var email=t.getAttribute('xol_email');
	if (n_mod(e)==3) {
#		// As normal email		
		var rcpt=name+' <'+email+'>';
		do_compose(e,U,[rcpt]);	
	}else if(keys_2horiz(e)){
		conv_limit(email,name);
	}else if(primary_modifier(e) && shift(e)){
# 		// As surgweb sim message
		var rcpt=name+' <'+email+'>';
		do_compose_xol(e,rcpt);
		if(primary_modifier(e)){
			conv_limit(email,name);
		}
	}else {
#		// As native xol
		xol_compose(email,e)
		if(primary_modifier(e)){
			conv_limit(email,name);
		}
	}
}

function conv_set(email,name)
{
	sw.conv_search_email=email;
	sw.conv_search_name=name;
}
function conv_update()
{
	var txt='';
	if(sw.conv_search_email.length>0){
		txt+=' | Conversation: '+sw.conv_search_name+' <img src="||www_base||shared/img/1pixel.gif" class="closeconv" onclick="close_conv(true)">';
	}
	dge('conv_navigator').innerHTML=txt;
	if(!isIE7) { 
#		note: This messes up rest of toolbar behaviour for IE7
		class_add(dge('nav_outer'),'nav_outer');
	}
}
function conv_limit(email,name)
{
	conv_set(email,name);
	conv_update();
	setTimeout(function(){
		F(sw.fld_id,0,0,false,false);
	},200);
}
function close_conv(update)
{
	conv_set('','')
	conv_update();
	if(!update)return;
	setTimeout(function(){
		F(sw.fld_id,0,0,false,false);
	},200);
}


function show_todo_search()
{
	var el=dge('todo_search');
	if(el)return;
	var el2=dge('todo_noscroller_outer');
	if(!el2)return;
	class_add(el2,'todo_search_outer');
	var txt=pref.todo_focus?pref.todo_focus:'Task Context';
	el=new_anchor('div','<input id="todo_search_ip" type="text" value="'+txt+'" class="todo_search_ip">',el2);
	el.id='todo_search';
	class_add(el,'todo_search');
	var ip=dge('todo_search_ip');
	ip.onkeydown=stopBubble;
	ip.onkeyup=function(e){
		todo_reshow_soon();
		stopBubble(e);
	}
	ip.onfocus=function(e){
		if(ip.value=='Task Context'){
			ip.value='';
			ip.style.color='black';
		}
		x_todo_vfocus=ip.value;
	}
	ip.onblur=function(e){
		var new_pref=ip.value;
		if(ip.value==''){
			ip.value='Task Context';
			ip.style.color='gray';
		}
		if(new_pref=='Task Context') new_pref='';
		if(pref.todo_focus!=new_pref){
			pref.todo_focus=new_pref;
			ajax_pref_save('pref_todo_focus='+new_pref);
		}
	}
}

function todo_task_html(task,search)
{
	var extra='';
	if(!search || search.length==0){
		// nothing hidden
	} else {
		extra='hidden';
		if (task.desc.indexOf(search)!=-1){ extra='';} 
		else if(task.mtags.indexOf(search)!=-1){ extra='';}
	}
	var txt='\
	<div class="todo_cell '+extra+'" event_uid="'+task.uid+'" event_cal="'+task.cal_id+'" title="cal_id='+task.cal_id+'\ntask_uid='+task.uid+'">\
		<div style="float:left">'+cbx('todo_'+task.uid,'#bcd8fd','swtodo_cbx','')+'</div>\
		<div style="margin-left:18px;">\
		'+task.desc+'<br>\
		<span class="offline">';	
	if(task.location_alert){
		txt+=task.location_action+' '+task.location_name;
	}
	if(task.event_hasdue){
		txt+='due in '+task.due_in;
	}
	txt+='</span></div></div>';
	return txt;
}


function setTodos(tasks, cal_id)	// cf setEvents
{
	x_todo_cal = cal_id;
	x_todo_tasks = tasks;
	todo_reshow()
}

function todo_reshow(search)
{
	var tasks = x_todo_tasks;
	var html='';
	for(i=0;i<tasks.length;i++){
		html+=todo_task_html(tasks[i],search);
	}		
	setTodo(html);
}

function todo_reshow_soon()
{
	if(x_todo_timer) clearTimeout(x_todo_timer);
	x_todo_timer = setTimeout(todo_complete, 140);
}

function todo_complete()
{
	val=dge('todo_search_ip').value;
	todo_reshow(val);
}