// Temporarily
/*
if (ROW.pclass>0) {
	if ((LOGIN.id!=22) && (LOGIN.xid!=6542)) location.href='/apps/login.php?o=redir';
//} else if ((LOGIN.xid!=5544)) location.href='account.html';
} else if ((LOGIN.xid!=5544) && (LOGIN.xid!=6542)) location.href='account.html';
*/

var AGENDA={ justMeetings: 0, MEETINGS: {}, ixMeetings: {}, lastTime: 0, currentView: '' };
var U_TIMER;
var OTHER_LIST;

function xDate(sdate) {
 var res=new Date(sdate.replace(/-/g,'/'));
 res=res.toLocaleString().replace(/ \d\d?:.+/,'');
 return res;
}

var RESERVED_ITEMS; // Initialized now at onload due i18n calls

function getAgendaHTML(sdate,justmeetings) {
// if (QueryString.test==4) alert(CURRENT_BOM_EVENT); 
 var cdate=xDate(sdate);
 var res='<table class=bomAgenda border=0 cellspacing=0 cellpadding=2 width=100%><tr><th width=20>i18n(time)<th align=right class=px14>'.i18n() + cdate;
 for (var i in GRID) {
	var row=GRID[i], meetings=AGENDA.MEETINGS[i];
	if ((justmeetings) && (!meetings)) continue;
		
	if (row.dt==sdate) {
	
		row.rowClass=row.s>0 ? 'reserved' : 'std';
		res+='<tr class=$rowClass><th height=20 align=left valign=top class=darkGray>$t'.xParse(row);
		if (row.s>0) { res+='<td class=reserved valign=bottom align=center><b>'+RESERVED_ITEMS[row.s]+'</b>'; continue; }

		if (!meetings) { res+='<td>&nbsp;'; continue; }
		
		var count=0;		
		for (var mid in meetings) {
			if (count++) res+='<tr class="$rowClass multi"><th height=20>&nbsp;'.xParse(row);
			var meeting=meetings[mid];
			if (meeting.status<0) { res+='<td>&nbsp;'; continue; }
//		if ((!meeting) || (meeting.status<0)) { res+='<td>&nbsp;'; continue; }

			var supp=OTHERS[meeting.other]; if (!supp) alert(meeting.other);
			if (LOGIN.ROW.pclass==0)
				res+='<td valign=bottom align=left>$name<br>$city, $country &nbsp;&nbsp; <b>i18n(stand):</b> $stand'.i18n(supp);
			else
				res+='<td valign=bottom align=left>$name<br>$country'.xParse(supp);

			if (meeting.status<10) 
				if (LOGIN.ROW.pclass==0)
					res+=('<div align=right>'+
						'<a class="bold maroon px11" title="i18n(clickToConfirm)" href="" onclick="return confirmMeeting($id)">i18n(confirm)</a>'+
						'&nbsp;&nbsp;<a class="bold maroon px11" title="i18n(clickToDecline)" href="" onclick="return rejectMeeting($id)">i18n(decline)</a>'+
						'</div>').i18n(meeting);
				else
					res+='<div align=right><a class="bold maroon px11" href="" onclick="return false">i18n(notconfirmed)</a>'.i18n()+
//						'&nbsp;&nbsp;<a class="bold maroon px11" title="i18n(clickToDecline)" href="" onclick="return rejectMeeting($id)">i18n(decline)</a>'.i18n(meeting)+
						'</div>';
		}
		if (!count) res+='<td>&nbsp;';
	}
	
 }
 res+='</table>';
 return res;
}

function toggleLnk(me) {
 if (!me.prevHTML) { me.prevHTML=me.innerHTML; me.status=0; };
 me.status=1-me.status;
 me.innerHTML=me.status ? me.getAttribute('altTxt') : me.prevHTML;
 return me.status;
}

function toggleJustMeetings(me) {
 toggleLnk(me);
 AGENDA.justMeetings=me.status;
 showAgenda(AGENDA.currentDate);
 return false;
}

function toggleJustUnmet(me) {
 if (!OTHER_LIST) OTHER_LIST=getObj('supplierList');
 OTHER_LIST.hideMet=toggleLnk(me);
 showSupplierList();
 return false;
}

function getOtherListLinks(obj) {
 var res='';
 switch(ROW.pclass) {
  case 0: // For meeting planners
	switch(obj.meetMe) {
	 case 2: // Deprecated
	 case 10: res='&nbsp;&nbsp;&nbsp;<a title="i18n(confirmedAy) $meetingObj.t" href="" class="showSupplierPlanning" onclick="return false"><b class=darkgreen>i18n(confirmed)</b></a>'.i18n(obj);
		break;
	 case 1: res=('&nbsp;&nbsp;&nbsp;<a title="i18n(confirmRequestAt) $meetingObj.t" href="" class="showSupplierPlanning" onclick="return confirmMeeting($id)"><b class=red>*i18n(requested)*</b></a>'+
	 			'&nbsp;&nbsp;<a title="i18n(declineRequestAt) $meetingObj.t" href="" class="showSupplierPlanning" onclick="return rejectMeeting($id)"><b class=red>i18n(decline)</b></a>').i18n(obj);
		break;
	 default:res='&nbsp;&nbsp;&nbsp;<a href="" class="showSupplierPlanning" style="color: maroon" title="i18n(arrangeMeeting)" onclick="return showSupplierPlanning($id)">i18n(requestMeeting)</a>'.i18n(obj);
		break;
	};
  	break;
  default: // For suppliers
	switch(obj.meetMe) {
	 case 2: // Deprecated
	 case 10: res='&nbsp;&nbsp;&nbsp;<a title="in18(confirmedAt) $meetingObj.t" href="" class="showSupplierPlanning" onclick="return false"><b class=darkgreen>i18n(confirmed)</b></a>'.i18n(obj);
		break;
	 case 1: res='&nbsp;&nbsp;&nbsp;<a title="" href="" class="showSupplierPlanning" onclick="return false"><b class=red>*i18n(requested)*</b></a>'.i18n(obj);
		break;
	 default:res='&nbsp;&nbsp;&nbsp;<a href="" class="showSupplierPlanning" style="color: maroon" title="i18n(arrangeMeeting)" onclick="return showSupplierPlanning($id)">i18n(requestMeeting)</a>'.i18n(obj);
		break;
	};
  
 }
 return res;
}

function getSupplierListHTML(hideMet) {
 var res=[ '', '', '' ], which;
 for (var i in OTHERS) {
 	var obj=OTHERS[i];
 	if (obj.meetMe==null) obj.meetMe=0;
 	which= obj.meetMe; // which is 0,1,10 (previously was 2) same as obj.meetMe;
 	which= obj.meetMe>1 ? 2 : obj.meetMe;
 	if (ROW.pclass==0)
		res[which]+='<tr class=status$meetMe><td><a title="i18n(clickToViewProfile)" class=bold target=_blank href="../viewprofile.html?id=$id">$name</a><br>$city, $country &nbsp;&nbsp;'.i18n(obj);
	else
 		res[which]+='<tr class=status$meetMe><td><a title="i18n(clickToViewProfile)" class=bold target=_blank href="../viewprofile.html?id=$id">$name</a><br>$country &nbsp;&nbsp;'.i18n(obj);

 	res[which]+='<div align=right class=bomListLnks>' +
 				'<a target=_blank href="../viewprofile.html?id=$id" class="showSupplierPlanning" style="color: maroon" title="i18n(viewCompleteProfile)">i18n(viewProfile)</a>'.i18n(obj);
 	res[which]+=getOtherListLinks(obj);
 	res[which]+='</div>';
 }
 res='<table width=100% class=bomSuppliers border=0 cellspacing=0 cellpadding=2>' + 
 		(!hideMet ? res[2]: '') + res[1] + res[0] +
 	'</table>';
 return res;
}

function uTimerRestore() {
 if (U_TIMER) clearTimeout(U_TIMER);
 U_TIMER=setTimeout('updateMeetings()',120000);
}

function sendBomMsg(s) {
 if (U_TIMER) { clearTimeout(U_TIMER); U_TIMER=null; }
 top.feedBack.location.href=s;
 if (QueryString.test==3) alert(s);
}

function addMeeting(other,sdate) {
 var obj=OTHERS[other];
 obj.currentDate=sdate;
 if (!confirm(i18n('confirmAppointment').xParse(obj).replace(/\\n/g,'\n'))) return false; 
 sendBomMsg('http://www.bestofmice.com/apps/bom_mp.js.php?l='+LANG+'&o=add&m='+other+'&t='+sdate);
 return false;
};

function confirmMeeting(mid) {
 var meeting=AGENDA.ixMeetings[mid], obj=OTHERS[meeting.other];
 obj.currentDate=meeting.t;
 if (!confirm(i18n('confirmAppointment').xParse(obj).replace(/\\n/g,'\n'))) return false; 
 sendBomMsg('http://www.bestofmice.com/apps/bom_mp.js.php?l='+LANG+'&o=accept&mid='+mid);
 return false;
}

function setMeetingObjToAgenda(meeting) { // Never call with id<>mid
 var id=meeting.id, t=meeting.t, other=OTHERS[meeting.other];
 // CHECK mid
 if (id<0) return removeMeetingFromAgenda(-id); // Esto CUÁNDO pasa???
 if ((!other) && (meeting.status>0)) { // Other no está y NO es status=-1 (reservado)
// 	if ((QueryString.test==4) && (!AGENDA.MEETINGS[t])) alert(t+': '+id+' other is #'+meeting.other);
 	if (AGENDA.MEETINGS[t]) delete AGENDA.MEETINGS[t][id];
// 	delete AGENDA.ixMeetings[id];
	return false;
 }
 if (other) { // Comprobar other.meetMe, other.meetingObj y other.mid: para qué se usan ???
//	other.meetMe=meeting.status==10 ? 2 : 1;
	other.meetMe=meeting.status;
	other.meetingObj=meeting;
	// CHECK mid
	other.mid=meeting.mid;
 }
 var meetings;
 if (!(meetings=AGENDA.MEETINGS[t])) meetings=AGENDA.MEETINGS[t]={ };
 else if (meeting.status==10)
 	for(var mid in meetings) if (mid!=id) removeMeetingFromAgenda(mid);
 AGENDA.MEETINGS[t][id]=meeting;
 AGENDA.ixMeetings[id]=meeting;
 return false;
}

// PENDING
function removeMeetingFromAgenda(id) {
 var meeting=AGENDA.ixMeetings[id];
 // PENDING FIX: arreglar esto para que no se reentregue este registro en el próximo updateMeetings()
 if (!meeting) return false;
 var other=OTHERS[meeting.other];
 if (other) {
	other.meetMe=0;
	other.meetingObj=null;
	other.mid=null;
	other.meetings=other.meetings.replace(new RegExp(',?'+meeting.t+'=\\d+,?'),'');
 }
 delete AGENDA.ixMeetings[id];
 delete AGENDA.MEETINGS[meeting.t][id];
 return false;
}

function addMeetingCallBack(ROW) {
 if (!OTHER_LIST) return false;
 var	other=OTHERS[ROW.other],
	msg='$meetType with $name\n at $time',
 	m=ROW.t.split(' '), sdate=m[0],
	aux={ meetType: ROW.status==10 ? 'Meet' : 'Meeting request', time: ROW.t, name: other ? other.name : '#'+ROW.other };
 // CHECK mid
 if (ROW.mid<0) { 
 	msg+='\n\n'+i18n('couldNotArrange')+'\n\n'; ROW.mid=-ROW.mid.toString();
 	if (other) {
 		other.meetings+=','+ROW.t+'='+ROW.status;
 		showSupplierPlanning(ROW.other);
 	}
 } else {
	msg+='was added';
	setMeetingObjToAgenda(ROW); // NEVER mid<0!
	showAgenda(sdate);
 }
 showSupplierList();
 alert(msg.xParse(aux));
// top.feedBack.location.href='about:blank';
 uTimerRestore();
}

function rejectMeeting(mid) {
 var meeting=AGENDA.ixMeetings[mid], obj=OTHERS[meeting.other];
 obj.currentDate=meeting.t;
 if (!confirm(i18n('confirmDecline').xParse(obj))) return false; 
 sendBomMsg('http://www.bestofmice.com/apps/bom_mp.js.php?l='+LANG+'&o=reject&mid='+mid);
 return false;
}

function rejectMeetingCallBack(mid) {
 if (!OTHER_LIST) return false;
 var meeting=AGENDA.ixMeetings[mid], other=OTHERS[meeting.other];
 other.currentDate=meeting.t;
 removeMeetingFromAgenda(mid);
 showSupplierList(); showAgenda();
 alert(i18n('meetWasDeclined').xParse(other));
 uTimerRestore();
}

function showAgenda(sdate) {
 if (!sdate) sdate=AGENDA.currentDate;
 getObj('pageDay').innerHTML=getAgendaHTML(sdate,AGENDA.justMeetings);
 if (AGENDA.currentDateLnk) AGENDA.currentDateLnk.className='';
 if (AGENDA.currentDateLnk=getObj('bomDateLnk'+sdate)) AGENDA.currentDateLnk.className='active';
 AGENDA.currentDate=sdate;
 AGENDA.currentView='AGENDA';
 return false;
};

function printAgenda(sdate) {
 var HTML=sdate ? getAgendaHTML(sdate) : getMyPlanningHTML();
 window.printHTML=HTML.replaceAll(i18n('confirm'),i18n('requestBySupplier')).replaceAll(i18n('decline'),'');
// window.printHTML=HTML.replaceAll(i18n('confirm'),i18n('requestBySupplier')); // .replaceAll(i18n('decline'),'');
// alert(window.printHTML);
 var w=window.open('../bom_agenda.html','PrintAgenda','width=840,height=500,menubar=yes');
 return false;
}

function setPrintPage(me) {
 me.document.getElementById('AdSpace1').innerHTML='<h1>Best of Mice <b>$name</b></h1><span style="font-size: 15px">$city, $countryname<br>$dstart</span>'.xParse(EVENT);
 me.document.getElementById('div1').innerHTML='<div style="padding: 4px; font-size: 14px"><b class="maroon">$name</b> ($city)</div>'.xParse(ROW);
 me.document.getElementById('div2').innerHTML=window.printHTML;
 me.print();
// me.close();
}

function getSupplierPlanningHTML(id) {
 var	cdt='', aux={ }, supplier=OTHERS[id], meets=supplier.meetings,
	res='<div style="padding: 4px"><b class="px12 maroon">$name</b><br>$country</div>'.xParse(supplier) +
		'<table class=bomSupplierPlanning border=0 cellspacing=0 cellpadding=2><tr><th>&nbsp;';
// var dbg='';
 if (QueryString.test==4) alert(meets);
 for (var d in GRID) {
 	var obj=GRID[d], meetings=AGENDA.MEETINGS[d];
 		
  	if (obj.dt!=cdt) { res+='<th>'+obj.xdt; cdt=obj.dt; }
 	if (!aux[obj.t]) aux[obj.t]='<tr><th>'+obj.t;
 	aux[obj.t]+='<td align=center>';
 	if (obj.s>0) { aux[obj.t]+='-'; continue; }
 	supplier.currentMeeting=d;
 	
 	if (meetings) {
		var count=0;
 		for(var mid in meetings) {
 		count++;
 		var meeting=meetings[mid];
 		if (meeting.status<0) { aux[obj.t]+='<b> - </b>'; continue; }
 		if (meeting.other==id) {
// 			alert(meeting.status<10);
 			if (meeting.status<10) // Only view as required meeting for this supplier
 				aux[obj.t]+='<b title="i18n(requestedAppointment)" class=maroon>i18n(requested)</b>'.i18n(); // Already meet with this supplier
			else
 				aux[obj.t]+='<b title="i18n(takenAppointment)" class=darkgray>i18n(confirmed)</b>'.i18n(); // Already meet with this supplier
		} else {
 			var other=OTHERS[meeting.other];
 			if (meeting.status<10)
	 			aux[obj.t]+='<b title="i18n(alreadyRequest)" class=darkgray>i18n(requested)</b>'.i18n(other); // Already meet with other
			else	 			
	 			aux[obj.t]+='<b title="i18n(alreadyAppointment)" class=darkgreen>i18n(confirmed)</b>'.i18n(other); // Already meet with other
		}
 
		}
		if (count) continue;
	}
	var m;
//	if (QueryString.test==4) alert(new RegExp(d+'=(\\d+)'));
	if ( (m=meets.match(d+'=(-?\\d+)')) && ( (LOGIN.pclass==0) || (m[1]==10) ) )
//	if ( (m=meets.indexOf(d+'=') && ( (LOGIN.pclass==0) || (m[1]==10) ) )
		aux[obj.t]+=i18n('Unavailable'); // This members has some other meet yet at this time
	else	// Time for meet with this supplier is OK
		aux[obj.t]+='<a title="i18n(scheduleMeeting)" href="" onclick="return addMeeting($id,\'$currentMeeting\')">i18n(available)</a>'.i18n(supplier);
 }
 for (var d in aux) res+=aux[d];
 res+='</table>';
// if (QueryString.test==22) alert(dbg);
 return res;
};

function getMyPlanningHTML() {
 var	cdt='', rows={ }, cols={ }, debug='';
	res='<table class=bomSupplierPlanning width=800 border=0 cellspacing=0 cellpadding=2><tr><th>&nbsp;';
 var odd=0;	
 for (var d in GRID) {
 	var obj=GRID[d], meetings=AGENDA.MEETINGS[d];
 		
	if (!rows[obj.t]) rows[obj.t]={ };
	var row=rows[obj.t];

 	row[obj.dt]='<td align=center>';
	cols[obj.dt]=1;
	
 	switch(true) {
 	 case obj.s>0:
 		row[obj.dt]+='<div class=reserved style="background: #468; padding: 3px; color: #fff; font-size: 14px; letter-spacing: 1px">'+RESERVED_ITEMS[obj.s].bold()+'</div>'; // 'Reserved';
 		break;
// 	 case ((meetings) && (meeting.status>0)):
	 case (meetings!=null):
	 	var count=0;
	 	for (var mid in meetings) {
	 		var meeting=meetings[mid];
			var supplier=OTHERS[meeting.other], tmp='';
	 		if (!supplier) {
	 			if (meeting.status>-1) { debug+=d+': '+meeting.status; continue; }
	 			tmp+='<b class="darkgray disabled">-</b>';
			} else {
			if (ROW.pclass==0)
				tmp+='<b class=darkgray>$name</b><br>$city, $country &nbsp;&nbsp; <b>i18n(stand):</b> $stand'.i18n(supplier);
			else
				tmp+='<b class=darkgray>$name</b><br>$country &nbsp;&nbsp;'.xParse(supplier);
			if (meeting.status<10)
				tmp+='<div align=right class="bold maroon">('+i18n('meetingRequest')+')</div>';
			}	
			if (count++) tmp='<div class=multi>'+tmp+'</div>';
			row[obj.dt]+=tmp;
		}
		break;
	 default: // There is no meeting here, or maybe it is reserved/unavailable (status=-1)
		row[obj.dt]+='&nbsp;';
	}	
 	if (obj.dt!=cdt) {
 		res+='<th>'+obj.xdt;
 		cdt=obj.dt;
 	}
 	odd=1-odd;
 }

 rows=objSort(rows,'#'), odd=0;
 for (var i in rows) {
 	odd=1-odd;
 	res+='<tr class="row'+odd+'"><th valign=top>'+i;
 	for (var j in cols)
 		res+=rows[i][j] || '<td align=center class=disabled>-';
 }
 		
 res+='</table>';
 return res;
}

function showSupplierPlanning(n) {
 var other=OTHERS[n];
// if ((other.meetMe) && (other.meetMe==2)) return alert(i18n('alreadyAppointment').xParse(other)) && false;
 if ((other) && (other.meetMe==10)) return alert(i18n('alreadyAppointment').xParse(other)) && false;
 if ((other) && (other.meetMe>0)) return alert(i18n('alreadyRequest').xParse(other)) && false;
 var obj=getObj('pageDay');
 if (!n) n=obj.lastID;
 obj.innerHTML=getSupplierPlanningHTML(n);
 obj.lastID=n;
 AGENDA.currentView='PLANNING';
// AGENDA.lastSupplierPlanning=n;
 return false;
};

function updateMeetings() {
 sendBomMsg('http://www.bestofmice.com/apps/bom_mp.js.php?l='+LANG+'&o=js&upd='+AGENDA.lastTime);
 return false;
}

function updateMeetingsCallBack(newMeetings) {
// if (QueryString.test==3) alert(124);
 // CHECK mid
 if (newMeetings) setMeetingObjsToAgenda(newMeetings); // Here ALWAYS id==mid; CAN BE id<0 for removing ????
 if (AGENDA.currentView=='AGENDA')
 	showAgenda(AGENDA.currentDate);
 else
	showSupplierPlanning();
 showSupplierList();
 uTimerRestore();
}

function updateView() {
 if (AGENDA.currentView=='AGENDA')
 	return showAgenda(AGENDA.currentDate);
 return showSupplierPlanning();
}

function showSupplierList(hideMet) {
 if (!OTHER_LIST) OTHER_LIST=getObj('supplierList');
 if (hideMet==null) hideMet=OTHER_LIST.hideMet; else OTHER_LIST.hideMet=hideMet;
 OTHER_LIST.innerHTML=getSupplierListHTML(OTHER_LIST.hideMet);
 return false;
}

function setMeetingObjsToAgenda(MEETINGS) { // ALWAYS id==mid; CAN BE id<0 !!!
 var meeting;
 for (var i in MEETINGS) {
// 	if (QueryString.test==4) alert(i);
 	meeting=MEETINGS[i];
 	if (i==0) {
 		AGENDA.lastTime=meeting.u;
 		continue;
 	}
 	if (i<0) { removeMeetingFromAgenda(-i); continue; }
 	if (!meeting.id) meeting.id=i;
 	// CHECK mid
 	setMeetingObjToAgenda(meeting); // ??? Here ALWAYS id=mid, CAN BE id<0
 }
}

function initAgenda(){
 var cdt='', dateIndex='';
 for (var i in GRID) {
 	var obj=GRID[i];
 	obj.id=i;
 	var m=i.split(' ');
 	obj.dt=m[0]; obj.t=m[1];
 	if (obj.dt!=cdt) {
		obj.xdt=xDate(cdt=obj.dt);
 		dateIndex+='<a id=bomDateLnk$dt href="" onclick="return showAgenda(\'$dt\')">$xdt</a><br>'.xParse(obj);
 	}
 }
 AGENDA.dateIndex=dateIndex;
}

chainOnload(function() {
 RESERVED_ITEMS={
	'-1': i18n('disabled'),
	'1': i18n('commonSessions'),
	'2': i18n('speedNetworking'),
	'3': i18n('transfer'),
	'4': i18n('coffeeBreak'),
	'5': i18n('breakfast'),
	'6': i18n('lunch'),
	'7': i18n('dinner'),
	'8': i18n('conference'),
	'9': i18n('prizeDraw'),
	'10': i18n('setup'),
	'99': i18n('other')
 };

 var F;
 top.feedBack.location.href='about:blank';
 if (F=document.formBOM0) {
 	var ctl=F.CURRENT_BOM_EVENT;
// 	if (QueryString.test) alert(ctl);
 	for (var i in EVENTS) {
 		var obj=EVENTS[i];
// 		if (QueryString.test) alert(obj.name);
 		ctl.options.add(new Option('Best of Mice "$name", $city, $dates'.xParse(obj),i));
 	}
 	ctl.value=EVENT.id;
 }
 initAgenda();
// initMeetings();
 setMeetingObjsToAgenda(MEETINGS); // ??? Here ALWAYS id==mid, NEVER id<0
 if (QueryString.test==4) alert(CURRENT_BOM_EVENT+' --');
 getObj('dateIndex').innerHTML=AGENDA.dateIndex;
// OTHER_LIST=getObj('supplierList');
 showSupplierList(0);
 showAgenda(EVENT.dstart);
 uTimerRestore();
 var other=QueryString.plan;
 if (other) showSupplierPlanning(other);
 if (QueryString.o=='print') setTimeout('printAgenda()',500);
});
