type("PicList",["WatchList"],{renderItem:function(item){return item.draw();},addItem:function(){var addPic=new PicItem(this,'edit');this.insert(addPic,'0');},deleteItem:function(item){var self=this;var killProgress=IndicoUI.Dialogs.Util.progress();jsonRpc(Indico.Urls.JsonRpcService,'event.pic.delete',{'picId':item.id,'conference':self.confId},function(response,error){if(exists(error)){killProgress();IndicoUtil.errorReport(error);}
else{killProgress();self.remove(item);}});}},function(picslist,web_container,uploadAction,confId){this.WatchList();this.uploadAction=uploadAction;this.confId=confId
var self=this;each(picslist,function(item){self.append(new PicItem(self,'display',item));});$B($E(web_container),this,this.renderItem);});type("PicItem",["IWidget"],{_iFrameLoaded:function(iframeId){var doc;if(Browser.IE){doc=document.frames[iframeId].document;}else{doc=$E(iframeId).dom.contentDocument;}
var res=Json.read(doc.body.innerHTML);if(res.status=="ERROR"){IndicoUtil.errorReport(res.info);}else{this.id=res.info.id;this.picURL=res.info.picURL;this.chooser.set('display');}},draw:function(){var self=this;this.chooser=new Chooser(new Lookup({edit:function(){var stuffUploadForm=function(inputField,uploadType,submitText){var killProgress;var frameId=Html.generateId();var form=Html.form({target:frameId,method:'post',id:Html.generateId(),action:self.parentList.uploadAction,enctype:'multipart/form-data'});form.append(inputField);form.append(Widget.button(command(function(){self.uploading=true;killProgress=IndicoUI.Dialogs.Util.progress();form.dom.submit();},submitText)));var iframe=Html.iframe({id:frameId,name:frameId,style:{display:'none'}});var loadFunc=function(){if(self.uploading){killProgress();self.uploading=false;self._iFrameLoaded(frameId);}};if(Browser.IE){iframe.dom.onreadystatechange=loadFunc;}else{iframe.observeEvent("load",loadFunc);}
return Html.div({},[form,iframe]);};var fileUpload=stuffUploadForm(Html.input('file',{name:'file'}),'file','Upload');var closeArea=Html.div({},Widget.button(command(function(){self.parentList.remove(self);},"Close")));return this.IWidget.prototype.draw.call(this,Html.div({},[fileUpload,closeArea]));},display:function(){var image=Html.img({src:""+self.picURL,alt:'Picture preview',title:'Picture preview',style:{width:"10%",height:"10%",border:"0px"}});var linkToUse=Html.span({style:{color:'green'}});linkToUse.set(Html.a({href:self.picURL},self.picURL));var remButton=Widget.link(command(function(){self.parentList.deleteItem(self);},IndicoUI.Buttons.removeButton()));return Html.div({},[image,linkToUse,remButton]);}}));this.chooser.set(this.choice);return Widget.block(this.chooser);}},function(parentList,choice,item){this.choice=choice;this.parentList=parentList;if(item){extend(this,item);}});type("RoomBookingWidget",["IWidget"],{_favoriteDecorator:function(key,elem){var li=Html.li(this.eventFavorites.indexOf(key)===null?'bottomLine':'bottomLine favoriteItem',elem);if(key==this.lastFavorite){li.dom.style.borderBottom='1px solid #909090';}
return li;},_favoriteSort:function(e1,e2){if(this.eventFavorites.indexOf(e1)!==null&&this.eventFavorites.indexOf(e2)===null){return-1;}else if(this.eventFavorites.indexOf(e1)===null&&this.eventFavorites.indexOf(e2)!==null){return 1;}else{return SortCriteria.Integer(e1,e2);}},postDraw:function(){if(this.defaultLocation!=null){if(this.locationChooser.get()!=this.defaultLocation){this.locationChooser.set(this.defaultLocation);}}
if(this.parentInfo){this.inheritCheckbox.set(this.inheritDefault);}},draw:function(){var rbActive=Indico.Settings.RoomBookingModuleActive
this.inheritText=this.parentInfo?Html.span({},$T('Inherit from parent: '),Html.span({},this.parentInfo.get('room')+" ("+
this.parentInfo.get('location')+")")):'';return Html.div('roomWidget',Html.div({style:{width:425}},Html.div({style:{paddingTop:'10px',cssFloat:'left'}},Html.div('roomWidgetTitle',$T("Location")),Html.div({},this.locationChooser.draw())),Html.div({style:{paddingTop:'10px',paddingLeft:'10px',cssFloat:'left'}},Html.div('roomWidgetTitle',$T("Room")),Html.div({style:{cssFloat:'left'}},rbActive?this.roomChooser.draw():this.roomChooser))),Html.div({style:{paddingTop:'10px',clear:'left'}},this.parentInfo?this.inheritCheckbox:'',this.inheritText),Html.div({style:{paddingTop:'10px',clear:'left'}},Html.div({className:'roomWidgetTitle',style:{width:'210px'}},$T('Address')),this.addressArea.draw()));},_startBind:function(){if(this.oldInfo){this.info.update(this.oldInfo.getAll());}
$B(this.locationChooser,this.info.accessor('location'));$B(this.roomChooser,this.info.accessor('room'));$B(this.addressArea,this.info.accessor('address'));},_endBind:function(){bind.detach(this.locationChooser);bind.detach(this.roomChooser);bind.detach(this.addressArea);},_loadRooms:function(newLocation){var cacheEntry=this.roomCache[newLocation];if(this.loading){}
else if(cacheEntry){this.roomChooser.setOptionList(cacheEntry);this.roomChooser.setLoading(false);}else{var self=this;indicoRequest('roomBooking.rooms.fullNameList',{'location':newLocation},function(result,error){self.loading=false;if(!error){var dict={};each(result,function(value){dict[value[0]]=value[1];});self.roomCache[newLocation]=dict;self.roomChooser.setOptionList(dict);self.roomChooser.setLoading(false);}else{IndicoUtil.errorReport(error);self.roomChooser.setLoading(false);}});this.loading=true;}}},function(locations,info,parent,inheritDefault,eventFavorites,defaultLocation){var self=this;var rbActive=Indico.Settings.RoomBookingModuleActive
this.defaultLocation=defaultLocation;this.locationChooser=new FlexibleSelect(locations,177);if(rbActive){this.roomChooser=new FlexibleSelect({},177,function(e1,e2){return self._favoriteSort(self.roomChooser.list.get(e1),self.roomChooser.list.get(e2));},function(key,elem){return self._favoriteDecorator(key,elem);});}
else{this.roomChooser=Html.input('text',{className:"roomTextField",name:"_roomName"});}
this.addressArea=new RealtimeTextArea({});this.inheritCheckbox=Html.checkbox({});this.info=info;this.parentInfo=parent;this.roomCache={};this.inheritDefault=inheritDefault;this.eventFavorites=$L([]);var fav=$L(this.eventFavorites.allItems());fav.sort(SortCriteria.Integer);this.lastFavorite=fav.item(fav.length.get()-1);if(this.parentInfo){this.inheritCheckbox.observe(function(value){if(value){self.inheritText.dom.className='enhanced';self.locationChooser.disable();self.roomChooser.disable();self.addressArea.disable();self.oldInfo=$O(self.info.getAll());self.locationChooser.set(self.parentInfo.get('location'));self.roomChooser.set(self.parentInfo.get('room'));self._endBind();self.info.set('location',null);self.info.set('room',null);self.info.set('address',null);}else{self.inheritText.dom.className='';self.locationChooser.enable();self.roomChooser.enable();self.addressArea.enable();self._startBind();}});}
this.locationChooser.observe(function(value){if(rbActive&&value!==''&&locations!==null){if(locations[value]){self.roomChooser.setLoading(true);self._loadRooms(value);}else{self.roomChooser.setOptionList({});}
self.roomChooser.set('');}});this._startBind();});type("RoomBookingReservationWidget",["RoomBookingWidget"],{_convertDate:function(date){var result;if(date.split("/")[0].length!=4){var monthCorrection=date.split("/")[1].length==1?"0":"";var dayCorrection=date.split("/")[0].length==1?"0":"";result=date.split("/")[2]+"-"+monthCorrection+date.split("/")[1]+"-"+dayCorrection+date.split("/")[0];}
else
result=date.replace(/[/]/g,"-");return result;},_convertTime:function(sTime){var sTimeCorrection=sTime.length==4?"0":"";return sTimeCorrection+sTime+":00";},_calculateEndTime:function(sTime,duration){var eHours=parseInt(sTime.split(":")[0],10);var eMinutes=parseInt(sTime.split(":")[1],10);eHours+=parseInt((eMinutes+duration)/60);eMinutes=(eMinutes+duration)%60;eHours=eHours>=10?eHours:("0"+eHours);eMinutes=eMinutes>=10?eMinutes:("0"+eHours);return eHours+":"+eMinutes+":00";},_getDateTime:function(){if(this.dateTime.accessor('startDate').get()&&this.dateTime.accessor('duration').get()){var sDate=this.dateTime.accessor('startDate').get();var duration=parseInt(this.dateTime.accessor('duration').get());this.date=this._convertDate(sDate.split(" ")[0]);this.sTime=this._convertTime(sDate.split(" ")[1]);this.eTime=this._calculateEndTime(sDate.split(" ")[1],duration);}else if(this.dateTime.accessor('startDateTime').get()&&this.dateTime.accessor('endDateTime').get()){var sDate=this.dateTime.accessor('startDateTime').get();var eDate=this.dateTime.accessor('endDateTime').get();this.date=this._convertDate(sDate.split(" ")[0]);this.sTime=this._convertTime(sDate.split(" ")[1]);this.eTime=this._convertTime(eDate.split(" ")[1]);}else if(this.dateTime.accessor('date').get()&&this.dateTime.accessor('startTime').get()&&this.dateTime.accessor('endTime').get()){this.date=this.dateTime.accessor('date').get();this.sTime=this._convertTime(this.dateTime.accessor('startTime').get());this.eTime=this._convertTime(this.dateTime.accessor('endTime').get());}},_isOverlapping:function(start,end){if(start.length==7)
start="0"+start;if(end.length==7)
end="0"+end;if(this.sTime>start&&this.sTime<end||this.eTime>start&&this.eTime<end||this.sTime<=start&&this.eTime>=end||this.sTime>=start&&this.eTime<=end)
return true;else
return false;},_isInsideBooking:function(elem){var insideBooking=false;for(var resvId in this.bookedRooms.get(elem)){var resv=this.bookedRooms.get(elem)[resvId];if(this.sTime>=resv.startDateTime.time&&this.eTime<=resv.endDateTime.time&&this.date==resv.startDateTime.date){insideBooking=true;break;}}
return insideBooking},_findConflict:function(key){var conflict=null;this._getDateTime();var day=this.timetableData[this.date.replace(/-/g,"")];for(var event in day){if(event!=this.editedEvent){if(!(day[event].entries&&day[event].entries[this.editedEvent])&&key==day[event].room&&this._isOverlapping(day[event].startDate['time'],day[event].endDate['time'])){conflict=day[event];break;}
for(var entry in day[event].entries)
if(entry!=this.editedEvent&&key==day[event].entries[entry].room&&this._isOverlapping(day[event].entries[entry].startDate['time'],day[event].entries[entry].endDate['time'])){conflict=day[event].entries[entry];break;}
if(conflict)
break;}}
return conflict},_favoriteDecorator:function(key,elem){var li;if(this.bookedRooms.get(elem)){if(this.timetableData){conflict=this._findConflict(key);if(!conflict){if(this._isInsideBooking(elem))
li=Html.li('bottomLine bookedItem',elem);else{var infoDiv=Html.div({},"This room is booked for this conference during");for(var resvId in this.bookedRooms.get(elem)){var resv=this.bookedRooms.get(elem)[resvId];infoDiv.append(Html.br());infoDiv.append(resv.startDateTime.time.substring(0,5)+" - "+resv.endDateTime.time.substring(0,5)+" at "+resv.startDateTime.date)}
li=Html.div({className:'bookedItemCollisionDiv'},Html.li('bottomLine bookedItemOutsideBooking',elem),infoDiv);}}
else{var info="This room is already used by "+conflict.title+" between "+conflict.startDate['time'].substring(0,5)+" and "+conflict.endDate['time'].substring(0,5)+".";li=Html.div({className:'bookedItemCollisionDiv'},Html.li('bottomLine bookedItemCollision',elem),Html.div({},info));}}
else{li=Html.li('bottomLine',elem);}
if(!this.previousElementBooked){li=Html.div({},Html.div('bottomLine bookedItemHeader','Your booked rooms:'),li);this.previousElementBooked=true}}
else{li=Html.li('bottomLine',elem);if(this.previousElementBooked){li=Html.div({},Html.div('bottomLine bookedItemHeader','Other rooms:'),li);this.previousElementBooked=false}}
return li;},_favoriteSort:function(e1,e2){this.previousElementBooked=false;if(this.bookedRooms.get(e1)&&!this.bookedRooms.get(e2)){return-1;}else if(!this.bookedRooms.get(e1)&&this.bookedRooms.get(e2)){return 1;}else{return SortCriteria.Integer(e1,e2);}},setDateTimeInfo:function(info){this.dateTime=info;}},function(locations,info,parent,inheritDefault,eventFavorites,defaultLocation,bookedRooms,timetableData,dateTime,editedEvent){this.RoomBookingWidget(locations,info,parent,inheritDefault,[],defaultLocation)
this.bookedRooms=$D(bookedRooms||{});this.dateTime=dateTime;this.timetableData=timetableData;this.editedEvent=editedEvent;});type("RoomBookingVerticalReservationWidget",["RoomBookingReservationWidget"],{draw:function(){var rbActive=Indico.Settings.RoomBookingModuleActive
this.inheritText=this.parentInfo?Html.span({},$T('Inherit from parent: '),Html.span({},this.parentInfo.get('room')+" ("+
this.parentInfo.get('location')+")")):'';return Html.div('roomWidget',Html.div({style:{paddingTop:'5px'}},Html.div('roomVerticalWidgetTitle',$T("Room")),Html.div({style:{cssFloat:'left'}},rbActive?this.roomChooser.draw():this.roomChooser)),Html.div({style:{paddingTop:'5px',clear:'left'}},Html.div('roomVerticalWidgetTitle',$T("Location")),Html.div({style:{cssFloat:'left'}},this.locationChooser.draw())),Html.div({style:{paddingTop:'5px',clear:'left'}},this.parentInfo?this.inheritCheckbox:'',this.inheritText));}},function(locations,info,parent,inheritDefault,eventFavorites,defaultLocation,bookedRooms,timetableData,dateTime,editedEvent){this.RoomBookingReservationWidget(locations,info,parent,inheritDefault,eventFavorites,defaultLocation,bookedRooms,timetableData,dateTime,editedEvent);});type("RoomListWidget",["ListWidget"],{_drawItem:function(room){var self=this;var roomData=room.get();var removeButton=Widget.link(command(function(){self.removeProcess(room.key,function(result){if(result){self.set(room,null);}});},IndicoUI.Buttons.removeButton()));return Html.div({style:{display:'inline'}},Html.span({},Html.div({style:{cssFloat:"right",paddingRight:"10px"}},removeButton),$B(Html.span(),room.key)));}},function(style,removeProcess){this.removeProcess=removeProcess;if(!exists(style)){style="UIPeopleList";}
this.ListWidget(style);});type("ShowConcurrentEvents",["ExclusivePopup","PreLoadHandler"],{_preload:[function(hook){var killProgress=IndicoUI.Dialogs.Util.progress();var self=this;var concurrentEventsSvc=indicoSource('event.showConcurrentEvents',self.args);concurrentEventsSvc.state.observe(function(state){if(state==SourceState.Loaded){self.concurrentEvents=$O(concurrentEventsSvc);hook.set(true);killProgress();}});}],draw:function(){var self=this;if(self.concurrentEvents.isEmpty()){return this.ExclusivePopup.prototype.draw.call(this,"No events in that date");}
var table=Html.table({style:{borderSpacing:pixels(0)}});var tBody=Html.tbody();table.set(tBody);var row0=Html.tr({});var cell0=Html.td({style:{verticalAlign:"top",align:"left",fontWeight:"bold"}});cell0.set($T("Category"));row0.append(cell0);var cell1=Html.td({style:{verticalAlign:"top",align:"left",fontWeight:"bold"}});cell1.set($T("Events"));row0.append(cell1);tBody.append(row0);var pair=true;each(self.concurrentEvents,function(eventsList,categ){var confListUL=Html.ul({style:{listStyleType:"none",padding:pixels(0),paddingBottom:pixels(8),margin:pixels(0)}});each(eventsList,function(eventObj){var evtTxt=[Html.span({},eventObj[0]),Html.span({style:{fontSize:pixels(10)}}," ("+$T("from")+" "+eventObj[1]+" "+$T("to")+" "+eventObj[2]+", "+$T("tz")+": "+eventObj[3]+")")];confListUL.append(Html.li({},evtTxt));});categSpan=Html.span({style:{fontSize:pixels(12)}},categ);if(pair){color="#F5F5F5";}else{color="#FFFFFF";}
pair=!pair;var row1=Html.tr({style:{backgroundColor:color}});var cell0=Html.td({style:{paddingRight:pixels(30),verticalAlign:"top",align:"left"}});cell0.set(categSpan);row1.append(cell0);var cell1=Html.td({style:{verticalAlign:"top",align:"left"}});cell1.set(confListUL);row1.append(cell1);tBody.append(row1);});return this.ExclusivePopup.prototype.draw.call(this,table);}},function(args){var self=this;if(args){this.args=args;this.PreLoadHandler(self._preload,function(){self.open();});this.ExclusivePopup($T("Concurrent Events sorted by category:"),function(){self.close();});}});type("CategoryChooserListWidget",["RemoteListWidget"],{drawContent:function(){var self=this;if(exists(self.owner)){if(!this.source.get().accessAllowed){var popup=new ErrorPopup($T("Access forbidden"),[$T("You do not have sufficient permissions to access that category")],"");popup.open();}
self.owner.update(this.source.get().parentCateg,this.source.get().currentCateg);}
return this.RemoteListWidget.prototype.drawContent.call(this);},getList:function(){return this.source.get().categList;},_drawItem:function(pair){var self=this;var numSubcat=null;if(!pair.get().final){numSubcat=Html.em({}," ("+pair.get().subcatLength+$T(" subcategories)"));}
var itemDiv=Html.div({},pair.get().title,numSubcat);if(pair.get().final){itemDiv.setStyle('fontWeight','bold');if(self.categId==pair.get().id){itemDiv.setStyle('backgroundColor','#FFF6DF');}}
itemDiv.observeClick(function(){if(pair.get().final){self._returnChoice(pair.get());}else{self.args.categId=pair.get().id;self.source.refresh();}});return itemDiv;},_returnChoice:function(categ){if(!this.creationControl){this.owner.closeHandler(categ,'public');}else{var self=this;self.killProgress=IndicoUI.Dialogs.Util.progress();var src=indicoSource("category.canCreateEvent",{"categId":categ.id});self.resultCateg=categ;src.state.observe(function(value){if(value==SourceState.Loaded){if(self.owner){if(!src.get()["canCreate"]){var popup=new ErrorPopup($T("Creation forbidden"),[$T("You do not have permissions to create events in that category")],"");popup.open();}else{self.owner.closeHandler(self.resultCateg,src.get()["protection"]);}
self.killProgress();}}});}}},function(categId,owner,creationControl){var self=this;self.owner=owner;this.categId=categId;this.args={"categId":this.categId};this.creationControl=creationControl;this.RemoteListWidget("CategoryList",'category.getCategoryList',this.args);});type("CategoryChooserWidget",[],{update:function(parentCateg,currentCateg){this.parentCateg=parentCateg;this.currentCateg=currentCateg;this.categTitleDiv.set(currentCateg.title);this.drawBreadcrumb();},closeHandler:function(categ,protection){this.handler(categ,protection);},drawBreadcrumb:function(){this.breadcrumbs.clear();if(!this.currentCateg.breadcrumb){return;}
for(var i=0;i<this.currentCateg.breadcrumb.length;i++){cat=this.currentCateg.breadcrumb[i];if((i+1)==this.currentCateg.breadcrumb.length){this.breadcrumbs.append(cat);}else{this.breadcrumbs.append(cat);var breadcrumbArrow=Html.img({src:imageSrc("breadcrumbArrow"),alt:'>',title:''});this.breadcrumbs.append(breadcrumbArrow);}}},draw:function(){var self=this;self.catListWidget=new CategoryChooserListWidget(this.currentCateg.id,this,this.creationControl);this.categTitleDiv=Html.div("categoryTitle",this.currentCateg.title);var goBackLink=Html.a({href:'#',style:{fontSize:'17px'}},$T('Go to parent category'));goBackLink.observeClick(function(e){self.catListWidget.args.categId=self.parentCateg.id;self.catListWidget.source.refresh();});var buttonsDiv=Html.span("CategoryListButtons",goBackLink);var toolBar=Html.div({},buttonsDiv,this.categTitleDiv);this.breadcrumbs=Html.span("pathWithoutLinks",null);this.drawBreadcrumb();return Html.div({},toolBar,this.breadcrumbs,Html.div("CategoryListDiv",self.catListWidget.draw()));}},function(categ,handler,creationControl){this.currentCateg=categ;this.parentCateg=categ;this.handler=handler;this.creationControl=creationControl;});type("CategoryChooser",["ExclusivePopup"],{draw:function(){var self=this;var handler=function(categ,protection){self.categ=categ;self.protection=protection
self.close();self.categoryChooserHandler(categ,protection);};var catChooserWidget=new CategoryChooserWidget(self.categ,handler,self.creationControl);return this.ExclusivePopup.prototype.draw.call(this,Html.div({style:{width:pixels(640),height:pixels(480)}},catChooserWidget.draw()));}},function(categ,categoryChooserHandler,creationControl){var self=this;this.categ=categ;this.categoryChooserHandler=categoryChooserHandler;this.creationControl=creationControl;this.ExclusivePopup($T("Category chooser:"),function(){self.close();});});function userListNothing(data,func){each(data,function(){func(true);});}
function singleUserNothing(user,func){func(true);}
function arrayToSet(array){var set={};each(array,function(item){set[item]=true;});return set;}
function userSort(user1,user2){if(user1.familyName>user2.familyName){return 1;}else if(user1.familyName==user2.familyName){if(user1.firstName>user2.firstName){return 1;}else if(user1.firstName==user2.firstName){return 0;}else{return-1;}}else{return-1;}}
function updateFavList(favouriteList){IndicoGlobalVars['favorite-user-ids']={};IndicoGlobalVars['favorite-user-list']=[];each(favouriteList,function(user){IndicoGlobalVars['favorite-user-ids'][user.id]=true;IndicoGlobalVars['favorite-user-list'].push(user);});}
type("FoundPeopleList",["SelectableListWidget"],{_drawItem:function(pair){var self=this;var peopleData=pair.get();if(peopleData.get('isGroup')||peopleData.get('_type')==='group'){return Html.span({},peopleData.get("name"));}else{var userName=Html.span({},peopleData.get("familyName").toUpperCase(),', ',peopleData.get("firstName"));var userEmail=Html.span({id:self.id+"_"+pair.key+"_email",className:"foundUserEmail"},Html.br(),Util.truncate(peopleData.get("email"),40));if(this.showToggleFavouriteButtons&&IndicoGlobalVars.isUserAuthenticated&&peopleData.get('_type')=="Avatar"){var favouritizeButton=new ToggleFavouriteButton(peopleData.getAll(),null,null,this.favouriteButtonObserver).draw();var favouritizeButtonDiv=Html.div({style:{cssFloat:"right",paddingRight:pixels(10),paddingLeft:pixels(5),paddingTop:pixels(5)}},favouritizeButton);return[favouritizeButtonDiv,userName,userEmail];}else{return[userName,userEmail];}}}},function(style,onlyOne,selectionObserver,showToggleFavouriteButtons,favouriteButtonObserver){if(!exists(style)){style="UIPeopleList";}
this.onlyOne=any(onlyOne,false);this.showToggleFavouriteButtons=any(showToggleFavouriteButtons,true);this.favouriteButtonObserver=any(favouriteButtonObserver,null);this.SelectableListWidget(selectionObserver,this.onlyOne,style,"selectedUser","unselectedUser");});type("SimpleSearchPanel",["IWidget"],{_searchAction:function(){Dom.Event.dispatch(this.searchButton.dom,'click');},_createSearchForm:function(){},_search:function(){},_createAuthenticatorSearch:function(){var self=this;if(empty(Indico.Settings.ExtAuthenticators)){return null;}else{var authenticatorList=[];each(Indico.Settings.ExtAuthenticators,function(auth){var searchExternalCB=Html.checkbox({});$B(searchExternalCB,self.criteria.accessor('searchExternal-'+auth[0]));authenticatorList.push(["Search "+auth[1],searchExternalCB]);});return authenticatorList;}},getSelectedList:function(){return this.foundPeopleList.getSelectedList();},clearSelection:function(){this.foundPeopleList.clearSelection();},draw:function(){var self=this;this.searchForm=this._createSearchForm();this.searchButton=Html.input("button",{},$T("Search"));this.searchButtonDiv=Html.div("searchUsersButtonDiv",this.searchButton);this.searchButton.observeClick(function(){self._search();});this.foundPeopleListDiv=Html.div("UISearchPeopleListDiv",this.foundPeopleList.draw());this.container=Html.div({},this.searchForm,this.searchButtonDiv,this.foundPeopleListDiv);return this.IWidget.prototype.draw.call(this,this.container);}},function(onlyOne,selectionObserver,showToggleFavouriteButtons,favouriteButtonObserver){this.IWidget();this.onlyOne=any(onlyOne,false);this.criteria=new WatchObject();this.foundPeopleList=new FoundPeopleList(null,this.onlyOne,selectionObserver,showToggleFavouriteButtons,favouriteButtonObserver);this.foundPeopleList.setMessage("Fill any of the upper fields and click search...");this.searchForm=null;this.searchButton=null;this.searchButtonDiv=null;this.foundPeopleListDiv=null;this.container=null;});type("UserSearchPanel",["SimpleSearchPanel"],{_createSearchForm:function(){var self=this;var familyName=new EnterObserverTextBox("text",{style:{width:"100%"},id:'userSearchFocusField'},function(){self._searchAction();return false;});var firstName=new EnterObserverTextBox("text",{style:{width:"100%"}},function(){self._searchAction();return false;});var email=new EnterObserverTextBox("text",{style:{width:"100%"}},function(){self._searchAction();return false;});var organisation=new EnterObserverTextBox("text",{style:{width:"100%"}},function(){self._searchAction();return false;});var exactMatch=Html.checkbox({});$B(familyName,this.criteria.accessor('surName'));$B(firstName,this.criteria.accessor('name'));$B(organisation,this.criteria.accessor('organisation'));$B(email,this.criteria.accessor('email'));$B(exactMatch,this.criteria.accessor('exactMatch'));var fieldList=[[$T("Family name"),familyName.draw()],[$T("First name"),firstName.draw()],[$T("E-mail"),email.draw()],[$T("Organisation"),organisation.draw()],[$T("Exact Match"),exactMatch]];var authenticatorSearch=this._createAuthenticatorSearch();if(exists(authenticatorSearch)){fieldList=concat(fieldList,authenticatorSearch);}
return IndicoUtil.createFormFromMap(fieldList,true);},_search:function(){var self=this;self.searchButton.dom.disabled=true;this.foundPeopleList.setMessage(Html.div({style:{paddingTop:'20px'}},progressIndicator(false,true)));indicoRequest('search.users',self.criteria,function(result,error){if(!error){self.foundPeopleList.clearList();if(result.length===0){self.foundPeopleList.setMessage($T("No results for this search..."));}else{each(result,function(user){if(user._type==="Avatar"){self.foundPeopleList.set('existingAv'+user.id,$O(user));}else if(user._type==="ContributionParticipation"){self.foundPeopleList.set('existingAuthor'+user.id,$O(user));}});}
self.searchButton.dom.disabled=false;}else{self.foundPeopleList.clearList();IndicoUtil.errorReport(error);}});},draw:function(){return this.SimpleSearchPanel.prototype.draw.call(this);}},function(onlyOne,selectionObserver,conferenceId,showToggleFavouriteButtons,favouriteButtonObserver){this.SimpleSearchPanel(onlyOne,selectionObserver,showToggleFavouriteButtons,favouriteButtonObserver);if(exists(conferenceId)){this.criteria.set("conferenceId",conferenceId);}});type("GroupSearchPanel",["SimpleSearchPanel"],{_createSearchForm:function(){var self=this;var groupName=new EnterObserverTextBox("text",{style:{width:"100%"}},function(){self._searchAction();return false;});$B(groupName,this.criteria.accessor('group'));var fieldList=[[$T("Group name"),groupName.draw()]];var authenticatorSearch=this._createAuthenticatorSearch();if(exists(authenticatorSearch)){fieldList=concat(fieldList,authenticatorSearch);}
return IndicoUtil.createFormFromMap(fieldList,true);},_search:function(){var self=this;self.searchButton.dom.disabled=true;this.foundPeopleList.setMessage(Html.div({style:{paddingTop:'20px'}},progressIndicator(false,true)));indicoRequest('search.groups',self.criteria,function(result,error){if(!error){self.foundPeopleList.clearList();if(result.length===0){self.foundPeopleList.setMessage($T("No results for this search..."));}else{each(result,function(group){self.foundPeopleList.set(group.name,$O(group));});}
self.searchButton.dom.disabled=false;}else{self.foundPeopleList.clearList();IndicoUtil.errorReport(error);}});},draw:function(){return this.SimpleSearchPanel.prototype.draw.call(this);}},function(onlyOne,selectionObserver,conferenceId,showToggleFavouriteButtons){this.SimpleSearchPanel(onlyOne,selectionObserver,conferenceId,showToggleFavouriteButtons);});type("UserAndGroupsSearchPanel",["IWidget"],{__selectionObserver:function(panel,selectedList){if(this.onlyOne){if(panel==="users"){this.groupPanel.clearSelection();}else{this.userPanel.clearSelection();}
this.parentSelectionObserver(selectedList);}else{var totalSelection=$O();totalSelection.update(this.userPanel.getSelectedList().getAll());totalSelection.update(this.groupPanel.getSelectedList().getAll());this.parentSelectionObserver(totalSelection);}},getSelectedList:function(){var totalSelection=$O();totalSelection.update(this.userPanel.getSelectedList().getAll());totalSelection.update(this.groupPanel.getSelectedList().getAll());return totalSelection;},clearSelection:function(){this.userPanel.clearSelection();this.groupPanel.clearSelection();},draw:function(){var self=this;this.tabWidget=new TabWidget([[$T("Users"),this.userPanel.draw()],[$T("Groups"),this.groupPanel.draw()]],null,null);return this.IWidget.prototype.draw.call(this,this.tabWidget.draw());}},function(onlyOne,selectionObserver,conferenceId,showToggleFavouriteButtons,favouriteButtonObserver){this.IWidget();this.onlyOne=any(onlyOne,false);this.parentSelectionObserver=selectionObserver;var self=this;this.userPanel=new UserSearchPanel(this.onlyOne,function(selectedList){self.__selectionObserver("users",selectedList);},conferenceId,showToggleFavouriteButtons,favouriteButtonObserver);this.groupPanel=new GroupSearchPanel(this.onlyOne,function(selectedList){self.__selectionObserver("groups",selectedList);},showToggleFavouriteButtons);this.tabWidget=null;});type("SuggestedUsersPanel",["IWidget"],{getSelectedList:function(){return this.suggestedUserList.getSelectedList();},clearSelection:function(){this.suggestedUserList.clearSelection();},draw:function(){var self=this;this.titleDiv=Html.div("suggestedUsersTitle",Html.span({},$T("Suggested users")));if(this.suggestedUserList.isEmpty()){var message=Html.span({},$T("There are no suggested users for you at the moment. Why not add some "),Html.a({href:Indico.Urls.Favourites},$T("favourites")),"?");this.suggestedUserList.setMessage(message);}
this.suggestedUserListDiv=Html.div("UISuggestedPeopleListDiv",this.suggestedUserList.draw());return this.IWidget.prototype.draw.call(this,Widget.block([this.titleDiv,this.suggestedUserListDiv]));}},function(onlyOne,includeFavourites,suggestedUsers,selectionObserver,showToggleFavouriteButtons){this.IWidget();this.onlyOne=any(onlyOne,false);includeFavourites=any(includeFavourites,true);this.suggestedUserList=new FoundPeopleList(null,this.onlyOne,selectionObserver,showToggleFavouriteButtons);var self=this;if(exists(suggestedUsers)){each(suggestedUsers,function(user){if(any(user._type,null)==="Avatar"){self.suggestedUserList.set('existingAv'+user.id,$O(user));}else{self.suggestedUserList.set(user.id,$O(user));}});}
if(includeFavourites){each(IndicoGlobalVars['favorite-user-list'],function(user){var id=user.id;if(exists(IndicoGlobalVars['favorite-user-ids'][id])&&IndicoGlobalVars['favorite-user-ids'][id]&&!self.suggestedUserList.get('existingAv'+id)){self.suggestedUserList.set('existingAv'+id,$O(user));}});}
this.titleDiv=null;this.suggestedUserListDiv=null;});type("ChooseUsersPopup",["ExclusivePopupWithButtons","PreLoadHandler"],{_preload:[function(hook){var self=this;if(exists(IndicoGlobalVars['favorite-user-list'])){hook.set(true);}else{var killProgress=IndicoUI.Dialogs.Util.progress($T("Loading dialog..."));indicoRequest('user.favorites.listUsers',{},function(result,error){if(!error){updateFavList(result);killProgress();hook.set(true);}else{killProgress();IndicoUI.Dialogs.Util.error(error);}});}}],__buildSearchPanel:function(container){var self=this;if(this.enableGroups){this.searchPanel=new UserAndGroupsSearchPanel(this.onlyOne,function(selectedList){self.__selectionObserver("searchUsers",selectedList);},this.conferenceId,this.showToggleFavouriteButtons,function(avatar,action){self.__searchPanelFavouriteButtonObserver(avatar,action);});var returnedDom=this.searchPanel.draw();container.append(returnedDom);container.setStyle("paddingTop",pixels(0));}else{this.searchPanel=new UserSearchPanel(this.onlyOne,function(selectedList){self.__selectionObserver("searchUsers",selectedList);},this.conferenceId,this.showToggleFavouriteButtons,function(avatar,action){self.__searchPanelFavouriteButtonObserver(avatar,action);});var returnedDom=this.searchPanel.draw();container.append(returnedDom);}},__buildSuggestedUsersPanel:function(container){var self=this;this.suggestedUsersPanel=new SuggestedUsersPanel(this.onlyOne,this.includeFavourites,this.suggestedUsers,function(selectedList){self.__selectionObserver("suggestedUsers",selectedList);},this.showToggleFavouriteButtons);container.append(this.suggestedUsersPanel.draw());},__selectionObserver:function(panel,selectedList){if(this.onlyOne){if(panel==="searchUsers"){this.suggestedUsersPanel.clearSelection();}else{this.searchPanel.clearSelection();}
if(selectedList.isEmpty()){this.saveButton.disable();}else{this.saveButton.enable();}}else{if(!selectedList.isEmpty()){this.saveButton.enable();}else{var twoPanels=this.allowSearch&&(this.includeFavourites||exists(this.suggestedUsers));if(twoPanels){var otherSelectedList=(panel==="searchUsers")?this.suggestedUsersPanel.getSelection():this.searchPanel.getSelection();if(otherSelectedList.isEmpty()){this.saveButton.disable();}else{this.saveButton.enable();}}else{this.saveButton.disable();}}}},__save:function(){var totalSelected=$O({});if(this.allowSearch){totalSelected.update(this.searchPanel.getSelectedList().getAll());}
if(this.includeFavourites||exists(this.suggestedUsers)){totalSelected.update(this.suggestedUsersPanel.getSelectedList().getAll());}
var returnedList=new List();each(totalSelected,function(selectedItem){returnedList.append(selectedItem.getAll());});this.chooseProcess(returnedList.allItems());},__searchPanelFavouriteButtonObserver:function(avatar,addedOrRemoved){if(addedOrRemoved){this.suggestedUsersPanel.suggestedUserList.set('existingAv'+avatar.id,$O(avatar));}},draw:function(){var self=this;self.saveButton=new DisabledButton(Html.input("button",{disabled:true},self.onlyOne?$T("Choose"):$T("Add")));var saveButtonTooltip;self.saveButton.observeEvent('mouseover',function(event){if(!self.saveButton.isEnabled()){saveButtonTooltip=IndicoUI.Widgets.Generic.errorTooltip(event.clientX,event.clientY,$T("Please select at least one item"),"tooltipError");}});self.saveButton.observeEvent('mouseout',function(event){Dom.List.remove(document.body,saveButtonTooltip);});self.saveButton.observeClick(function(){self.__save();self.close();});var cancelButton=Html.input("button",{style:{marginLeft:pixels(5)}},"Cancel");cancelButton.observeClick(function(){self.close();});var mainContent=Html.tr();if(self.allowSearch){this.cellSearch=Html.td("searchUsersGroupsPanel");self.__buildSearchPanel(this.cellSearch);mainContent.append(this.cellSearch);}
if(this.includeFavourites||exists(this.suggestedUsers)){this.cellSuggested=Html.td("suggestedUsersPanel");self.__buildSuggestedUsersPanel(this.cellSuggested);mainContent.append(this.cellSuggested);}
mainContent=Html.table({cellpadding:0,cellPadding:0,cellspacing:0,cellSpacing:0},Html.tbody({},mainContent));this.buttonDiv=Html.div({},self.saveButton.draw(),cancelButton);return this.ExclusivePopupWithButtons.prototype.draw.call(this,mainContent,this.buttonDiv,{},{padding:pixels(0)});},postDraw:function(){if(this.allowSearch&&this.enableGroups){var tabContainer=this.searchPanel.tabWidget.container;tabContainer.setStyle('height',pixels(tabContainer.dom.offsetHeight));}
if(this.includeFavourites||exists(this.suggestedUsers)){this.suggestedUsersPanel.suggestedUserListDiv.setStyle('height',pixels(this.cellSuggested.dom.offsetHeight-this.suggestedUsersPanel.titleDiv.dom.offsetHeight-10));}
this.ExclusivePopupWithButtons.prototype.postDraw.call(this);$E('userSearchFocusField').dom.focus();}},function(title,allowSearch,conferenceId,enableGroups,includeFavourites,suggestedUsers,onlyOne,showToggleFavouriteButtons,chooseProcess){var self=this;this.allowSearch=allowSearch;this.conferenceId=conferenceId;this.enableGroups=enableGroups;this.includeFavourites=any(includeFavourites,true);this.suggestedUsers=suggestedUsers;this.onlyOne=any(onlyOne,false);this.showToggleFavouriteButtons=any(showToggleFavouriteButtons,true);this.chooseProcess=chooseProcess;this.saveButton=null;this.suggestedUsersPanel=null;this.searchPanel=null;this.buttonDiv=null;this.cellSearch=null;this.cellSuggested=null;this.PreLoadHandler(self._preload,function(){self.open();});this.ExclusivePopupWithButtons(title,positive);});type("SingleUserField",["IWidget"],{get:function(){return this.user.getAll();},set:function(user){this.user.replace(user);this.__userChosenObserver();},getName:function(){return this.hiddenFieldName;},isUserChosen:function(){return this.userChosen.get();},__getNotChosenUser:function(){return{id:null,name:"Choose a user"};},__userChosenObserver:function(){user=this.user.getAll();this.variableButtonsDiv.clear();if(IndicoGlobalVars.isUserAuthenticated&&this.userChosen&&user._type==="Avatar"){var favButtonDiv=Html.div({style:{display:"inline",paddingLeft:pixels(5)}},new ToggleFavouriteButton(user).draw());this.variableButtonsDiv.append(favButtonDiv);}
if(this.allowDelete&&this.userChosen){var removeButton=Widget.link(command(function(){self.userChosen.set(false);var notChosenUser=self.__getNotChosenUser();self.user.replace(notChosenUser);self.__userChosenObserver();},IndicoUI.Buttons.removeButton()));var removeButtonDiv=Html.div({style:{display:"inline"}},removeButton);this.variableButtonsDiv.append(removeButtonDiv);}},draw:function(){var self=this;var contentDiv=Html.div({style:{display:"inline"}});if(exists(this.hiddenFieldName)){contentDiv.append($B(Html.input('hidden'),{name:this.hiddenFieldName},self.user.accessor('id')));}
var userNameDiv=$B(Html.span({style:{verticalAlign:'middle'}}),self.user.accessor('name'));contentDiv.append(userNameDiv);this.variableButtonsDiv=Html.div({style:{display:'inline'}});this.__userChosenObserver();var fixedButtonsDiv=Html.div({style:{display:'inline'}});if(self.allowChoose){var chooseButton=Html.input("button",{style:{marginLeft:pixels(10),verticalAlign:'middle'}},$T('Choose'));var chooseUserHandler=function(userList){self.assignProcess(userList,function(value){if(value){var returnedUser=userList[0];self.user.replace(returnedUser);self.__userChosenObserver();self.userChosen.set(true);}});};chooseButton.observeClick(function(){var userChoosePopup=new ChooseUsersPopup("Choose user",true,self.conferenceId,self.enableGroups,self.includeFavourites,self.suggestedUsers,true,true,chooseUserHandler);userChoosePopup.execute();});fixedButtonsDiv.append(chooseButton);}
return Html.div({style:{display:'inline'}},contentDiv,this.variableButtonsDiv,fixedButtonsDiv);}},function(initialUser,hiddenFieldName,allowChoose,includeFavourites,suggestedUsers,conferenceId,enableGroups,allowNew,allowDelete,assignProcess,removeProcess){var self=this;this.user=$O(exists(initialUser)?initialUser:this.__getNotChosenUser());this.userChosen=new WatchValue(exists(initialUser));this.hiddenFieldName=hiddenFieldName;this.allowChoose=any(allowChoose,true);this.includeFavourites=any(includeFavourites,true);if(exists(suggestedUsers)){if(suggestedUsers.WatchList){this.suggestedUsers=suggestedUsers;}else{this.suggestedUsers=new WatchList();each(suggestedUsers,function(user){self.suggestedUsers.append(user);});}}else{this.suggestedUsers=null;}
this.conferenceId=any(conferenceId,null);this.enableGroups=any(enableGroups,false);this.allowNew=any(allowNew,false);this.allowDelete=any(allowDelete,true);this.assignProcess=any(assignProcess,singleUserNothing);this.removeProcess=any(removeProcess,singleUserNothing);this.buttonsDiv=Html.div({style:{display:"inline"}});});type("UserDataPopup",["ExclusivePopupWithButtons"],{draw:function(){var userData=this.userData;var self=this;self.parameterManager=new IndicoUtil.parameterManager();grant=[];if(this.grantSubmission){grant=['Grant submission rights',$B(Html.checkbox({}),userData.accessor('submission'))];}
var form=IndicoUtil.createFormFromMap([[$T('Title'),$B(Html.select({},Html.option({},""),Html.option({value:'Mr.'},$T("Mr.")),Html.option({value:'Mrs.'},$T("Mrs.")),Html.option({value:'Ms.'},$T("Ms.")),Html.option({value:'Dr.'},$T("Dr.")),Html.option({value:'Prof.'},$T("Prof."))),userData.accessor('title'))],[$T('Family Name'),$B(self.parameterManager.add(Html.edit({style:{width:'300px'}}),'text',false),userData.accessor('familyName'))],[$T('First Name'),$B(Html.edit({style:{width:'300px'}}),userData.accessor('firstName'))],[$T('Affiliation'),$B(Html.edit({style:{width:'300px'}}),userData.accessor('affiliation'))],[$T('Email'),$B(self.parameterManager.add(Html.edit({style:{width:'200px'}}),'email',true),userData.accessor('email'))],[$T('Address'),$B(Html.textarea(),userData.accessor('address'))],[$T('Telephone'),$B(Html.edit({style:{width:'150px'}}),userData.accessor('telephone'))],[$T('Fax'),$B(Html.edit({style:{width:'150px'}}),userData.accessor('fax'))],grant]);var buttons=Html.div({},Widget.link(command(curry(this.action,userData,function(){self.close();}),Html.input("button",{},$T("Save")))),Widget.link(command(function(){self.close();},Html.input("button",{},$T("Cancel")))));return this.ExclusivePopupWithButtons.prototype.draw.call(this,form,buttons);}},function(title,userData,action,grantSubmission){this.userData=userData;this.action=action;this.grantSubmission=exists(grantSubmission)?grantSubmission:false;this.ExclusivePopup(title,function(){return true;});});type("UserListWidget",["ListWidget"],{_drawItem:function(user){var self=this;var userData=user.get();var editButton=Widget.link(command(function(){editPopup=new UserDataPopup('Change user data',userData.clone(),function(newData,suicideHook){if(editPopup.parameterManager.check()){self.editProcess(userData,function(result){if(result){userData.update(newData.getAll());if(!startsWith(''+userData.get('id'),'newUser')){userData.set('id','edited'+userData.get('id'));}}});suicideHook();}});editPopup.open();},IndicoUI.Buttons.editButton()));var removeButton=Widget.link(command(function(){self.removeProcess(userData,function(result){if(result){self.set(user.key,null);}});},IndicoUI.Buttons.removeButton()));if(userData.get('isGroup')||userData.get('_fossil')==='group'){var removeButtonDiv=Html.div({style:{cssFloat:"right",paddingRight:pixels(10),paddingTop:pixels(5)}},removeButton);var groupName=$B(Html.span(),userData.accessor('name'));return Html.span({},removeButtonDiv,Html.span({style:{fontWeight:'bold'}},'Group: '),groupName);}else{var buttonDiv=Html.div({style:{cssFloat:"right",paddingRight:pixels(10),paddingTop:pixels(5)}});if(IndicoGlobalVars.isUserAuthenticated&&exists(IndicoGlobalVars['favorite-user-ids'])&&this.showToggleFavouriteButtons&&userData.get('_type')==="Avatar"){var favouritizeButton=new ToggleFavouriteButton(userData.getAll()).draw();buttonDiv.append(favouritizeButton);}
if(this.allowEdit){buttonDiv.append(editButton);}
buttonDiv.append(removeButton);var userName=Html.span({},$B(Html.span(),userData.accessor('familyName'),function(name){return name.toUpperCase();}),', ',$B(Html.span(),userData.accessor('firstName')));return Html.span({},buttonDiv,userName);}}},function(style,allowEdit,editProcess,removeProcess,showToggleFavouriteButtons){this.style=any(style,"UIPeopleList");this.allowEdit=allowEdit;this.editProcess=any(editProcess,singleUserNothing);this.removeProcess=any(removeProcess,singleUserNothing);this.showToggleFavouriteButtons=any(showToggleFavouriteButtons,true);this.ListWidget(style);});type("UserListField",["IWidget"],{_highlightNewUser:function(userId){IndicoUI.Effect.highLightBackground($E(this.userList.getId()+'_'+userId));},getUsers:function(){return $L(this.userList);},clear:function(){this.userList.clearList();},getPrivileges:function(){return this.selectedPrivileges;},draw:function(){var self=this;var select;var buttonDiv=Html.div({style:{marginTop:pixels(10)}});if(this.allowSearch||this.includeFavourites||exists(this.suggestedUsers)){var chooseUserButton=Html.input("button",{style:{marginRight:pixels(5)}},$T('Add Existing'));var title="";if(this.includeFavourites||exists(this.suggestedUsers)){title=this.enableGroups?$T("Add Users and Groups"):$T("Add Users");}else{title=this.enableGroups?$T("Search Users and Groups"):$T("Search Users");}
var peopleAddedHandler=function(peopleList){self.newProcess(peopleList,function(value){if(value){each(peopleList,function(person){var key;if(person.isGroup||person._fossil==='group'){key=person.id;}else{key=(person._type==="Avatar")?"existingAv"+person.id:person.id;}
if(person._type==="Avatar"&&self.userList.get(key)){}else{if(self.userList.get(key)){self.userList.set(key,null);}
self.userList.set(key,$O(person));}});}});};chooseUserButton.observeClick(function(){var chooseUsersPopup=new ChooseUsersPopup(title,self.allowSearch,self.conferenceId,self.enableGroups,self.includeFavourites,self.suggestedUsers,false,self.showToggleFavouriteButtons,peopleAddedHandler);chooseUsersPopup.execute();});buttonDiv.append(chooseUserButton);}
if(this.allowNew){var addNewUserButton=Html.input("button",{style:{marginRight:pixels(5)}},$T('Add New'));addNewUserButton.observeClick(function(){var newUserId='newUser'+self.newUserCounter++;var newUser=$O({'id':newUserId});newUserPopup=new UserDataPopup($T('New user'),newUser,function(newData,suicideHook){if(newUserPopup.parameterManager.check()){newUser.update(newData.getAll());self.newProcess([newUser],function(result){if(result){self.userList.set(newUserId,newUser);}});suicideHook();}});newUserPopup.open();});buttonDiv.append(addNewUserButton);}
var privilegesDiv=Html.span({style:{marginTop:pixels(10)}});var keysList=keys(this.privileges);if(keysList.length>0){privilegesDiv.append(Html.span({},$T("Grant all these users with privileges: ")));}
var comma=", ";for(var i=0;i<keysList.length;i++){if(i+1==keysList.length){comma="";}
var key=keysList[i];var value=this.privileges[key];var checkbox=Html.checkbox({style:{verticalAlign:"middle"}},value[1]?value[1]:null);checkbox.dom.name=key;$B(this.selectedPrivileges.accessor(key),checkbox);privilegesDiv.append(Html.span({},checkbox,value[0]+comma));}
return Widget.block([Html.div(this.userDivStyle,this.userList.draw()),privilegesDiv,buttonDiv]);}},function(userDivStyle,userListStyle,initialUsers,includeFavourites,suggestedUsers,allowSearch,enableGroups,conferenceId,privileges,allowNew,allowEdit,showToggleFavouriteButtons,newProcess,editProcess,removeProcess){var self=this;this.userList=new UserListWidget(userListStyle,allowEdit,editProcess,removeProcess,showToggleFavouriteButtons);this.newUserCounter=0;this.userDivStyle=any(userDivStyle,"UIPeopleListDiv");if(exists(initialUsers)){each(initialUsers,function(user){if(any(user._type,null)==='Avatar'){self.userList.set('existingAv'+user.id,$O(user));}else{self.userList.set(user.id,$O(user));}});}
this.includeFavourites=any(includeFavourites,true);if(exists(suggestedUsers)){if(suggestedUsers.WatchList){this.suggestedUsers=suggestedUsers;}else{this.suggestedUsers=new WatchList();each(suggestedUsers,function(user){self.suggestedUsers.append(user);});}}else{this.suggestedUsers=null;}
this.allowSearch=any(allowSearch,true);this.enableGroups=any(enableGroups,false);this.conferenceId=any(conferenceId,null);this.privileges=any(privileges,{});this.selectedPrivileges=new WatchObject();this.allowNew=any(allowNew,true);this.showToggleFavouriteButtons=any(showToggleFavouriteButtons,true);this.newProcess=any(newProcess,userListNothing);});type("ToggleFavouriteButton",["InlineWidget"],{draw:function(){var self=this;var imageRemove=Html.img({src:imageSrc("star"),alt:'Remove from Favorites',title:$T('Remove from your list of favorite users'),style:this.imageStyle});var imageAdd=Html.img({src:imageSrc("starGrey"),alt:'Add to Favorites',title:$T('Add to your list of favorite users'),style:this.imageStyle});var imageLoading=Html.img({src:imageSrc("loading"),alt:'Loading',title:$T('Communicating with server'),style:this.imageStyle});var starIcon=$B(Html.span(),this.stateWatchValue,function(state){if(state){return imageRemove;}else{return imageAdd;}});var content=Html.span({},starIcon);imageRemove.observeClick(function(event){content.set(imageLoading);indicoRequest('user.favorites.removeUser',{value:[{id:self.avatar.id}]},function(result,error){content.set(starIcon);if(!error){IndicoGlobalVars['favorite-user-ids'][self.avatar.id]=false;self.stateWatchValue.set(false);if(exists(self.observer)){self.observer(self.avatar,false);}}else{self._error(error);}});stopPropagation(event);});imageAdd.observeClick(function(event){content.set(imageLoading);indicoRequest('user.favorites.addUsers',{value:[{id:self.avatar.id}]},function(result,error){content.set(starIcon);if(!error){IndicoGlobalVars['favorite-user-ids'][self.avatar.id]=true;if(exists(IndicoGlobalVars['favorite-user-list'])){IndicoGlobalVars['favorite-user-list'].push(self.avatar);IndicoGlobalVars['favorite-user-list'].sort(userSort);}
self.stateWatchValue.set(true);if(exists(self.observer)){self.observer(self.avatar,true);}}else{self._error(error);}});stopPropagation(event);});return this.IWidget.prototype.draw.call(this,content);}},function(avatar,customImgStyle,initialState,observer){this.IWidget();this.avatar=avatar;customImgStyle=any(customImgStyle,{});this.imageStyle=merge({verticalAlign:'middle',cursor:'pointer'});this.observer=any(observer,null);this.stateWatchValue=null;if(!exists(IndicoGlobalVars['favorite-user-ids'])){IndicoGlobalVars['favorite-user-ids']={};}
if(!exists(IndicoGlobalVars.userFavouritesWatchValues)){IndicoGlobalVars.userFavouritesWatchValues={};}
if(!exists(IndicoGlobalVars.userFavouritesWatchValues[avatar.id])){if(exists(IndicoGlobalVars['favorite-user-ids'][avatar.id])){IndicoGlobalVars.userFavouritesWatchValues[avatar.id]=$V(IndicoGlobalVars['favorite-user-ids'][avatar.id]===true);}else{if(!exists(IndicoGlobalVars['favorite-user-ids'])&&!exists(initialState)){alert("Warning: ToggleFavouriteButton used without IndicoGlobalVars['favorite-user-ids'] variable and without initialState");}
initialState=any(initialState,false);IndicoGlobalVars.userFavouritesWatchValues[avatar.id]=$V(initialState);}}
this.stateWatchValue=IndicoGlobalVars.userFavouritesWatchValues[avatar.id];});function nullRoomInfo(info){return(!info)||(!exists(info.get('location')))||(!exists(info.get('room')));}
type("UnscheduledContributionList",["SelectableListWidget"],{_drawItem:function(pair){var self=this;var elem=pair.get();var speakers=translate(elem.get('speakerList'),function(speaker){return speaker.familyName;}).join(", ");var selected=false;var id=Html.em({style:{paddingLeft:"5px",fontSize:'0.9em'}},elem.get('id'));var item=Html.div({},elem.get('title')+(speakers?(' ('+speakers+')'):''),id);return item;},getList:function(){return this.getSelectedList();}},function(existing,observer){var self=this;this.selected=new WatchList();this.SelectableListWidget(observer,false,'UnscheduledContribList');var items={};each(existing,function(item){items[item.title+item.id]=item;});var ks=keys(items);ks.sort();for(k in ks){this.set(k,$O(items[ks[k]]));}});type("AddContributionDialog",["ExclusivePopupWithButtons","PreLoadHandler"],{_preload:[function(hook){var self=this;var killProgress=IndicoUI.Dialogs.Util.progress($T("Loading dialog..."));var source=indicoSource(self.args.session?'schedule.session.getUnscheduledContributions':'schedule.event.getUnscheduledContributions',self.args);source.state.observe(function(state){if(state==SourceState.Loaded){killProgress();self.existing=$L(source);self._processDialogState();hook.set(true);}else if(state==SourceState.Error){killProgress();IndicoUtil.errorReport(source.error.get());}});}],_processDialogState:function(){var self=this;if(this.existing.length.get()===0){var dialog=createObject(AddNewContributionDialog,self.newArgs);dialog.execute();this.open=function(){};return;}else{this.ExclusivePopupWithButtons($T("Add Contribution"),function(){self.close();});}},existingSelectionObserver:function(selectedList){if(selectedList.isEmpty()){this.button.disable();}else{this.button.enable();}},addExisting:function(contribs,date){var self=this;var killProgress=IndicoUI.Dialogs.Util.progress();var args=clone(this.args);args.ids=contribs;args.date=date;indicoRequest(self.args.session?'schedule.slot.scheduleContributions':'schedule.event.scheduleContributions',args,function(result,error){killProgress();if(error){IndicoUtil.errorReport(error);}
else{self.close();self.successFunc(result);}});},draw:function(){var self=this;var unscheduledList=new UnscheduledContributionList(self.existing,function(selectedList){self.existingSelectionObserver(selectedList);});var content=Html.div({},$T("You may choose to:"),Html.ul({},Html.li({style:{marginBottom:'10px'}},Widget.link(command(function(){var dialog=createObject(AddNewContributionDialog,self.newArgs);self.close();dialog.execute();},$T("Create a new one")))),Html.li({},$T("Choose one (or more) unscheduled"),Html.div("UnscheduledContribListDiv",unscheduledList.draw()))));this.button=new DisabledButton(Html.input("button",{disabled:true},$T("Add selected")));var tooltip;this.button.observeEvent('mouseover',function(event){if(!self.button.isEnabled()){tooltip=IndicoUI.Widgets.Generic.errorTooltip(event.clientX,event.clientY,$T("To add an unscheduled contribution, please select at least one"),"tooltipError");}});this.button.observeEvent('mouseout',function(event){Dom.List.remove(document.body,tooltip);});this.button.observeClick(function(){var ids=translate(unscheduledList.getList(),function(contrib){return contrib.get('id');});self.addExisting(ids,self.selectedDay);});return this.ExclusivePopupWithButtons.prototype.draw.call(this,content,this.button.draw());}},function(method,timeStartMethod,args,roomInfo,parentRoomData,confStartDate,dayStartDate,isConference,favoriteRooms,days,timetable,successFunc,isCFAEnabled,bookedRooms){var self=this;this.newArgs=Array.prototype.slice.call(arguments,0);this.args=args;this.selectedDay=dayStartDate;this.days=days;this.successFunc=successFunc;this.timetable=timetable;this.isCFAEnabled=isCFAEnabled;this.PreLoadHandler(self._preload,function(){self.open();});});type("AddNewContributionDialog",["ServiceDialogWithButtons","PreLoadHandler"],{_preload:[function(hook){var self=this;if(!self.timeStartMethod){hook.set(true);}else{indicoRequest(self.timeStartMethod,self.dateArgs,function(result,error){if(error){IndicoUtil.errorReport(error);}
else{var startDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);if(startDate.getHours()>=23){startDate.setHours(23);startDate.setMinutes(0);}
self.startTimeField.set(Util.formatDateTime(startDate,IndicoDateTimeFormats.Server).substr(11,5));self.info.set('startDate',Util.formatDateTime(startDate,IndicoDateTimeFormats.ServerHourless));hook.set(true);}});}},function(hook){var self=this;var parameterManager=new IndicoUtil.parameterManager();this.parameterManager=parameterManager;if(this.isConference){indicoRequest('event.getFieldsAndContribTypes',self.args,function(result,error){if(error){IndicoUtil.errorReport(error);}
else{self.fields=result[0];self.contribTypes=result[1];hook.set(true);}});}else{hook.set(true);}}],postDraw:function(){this.roomEditor.postDraw();this.ServiceDialogWithButtons.prototype.postDraw.call(this);$E('addContributionFocusField').dom.focus();},_success:function(response){},draw:function(){var newForm=this._drawNewForm();var contentDiv=newForm[0];var buttons=newForm[1];return this.ServiceDialogWithButtons.prototype.draw.call(this,contentDiv,buttons,{backgroundColor:'white'});},_configureDaySelect:function(conferenceDays){var self=this;conferenceDays.set(Util.formatDateTime(self.dayStartDate,IndicoDateTimeFormats.Ordinal,IndicoDateTimeFormats.ServerHourless));conferenceDays.observe(function(value){self.dateArgs.selectedDay=Util.formatDateTime(value,IndicoDateTimeFormats.ServerHourless,IndicoDateTimeFormats.Ordinal);if(exists(self.timetable.parentTimetable)){if(self.previousDate.substr(0,10)!=self.dateArgs.selectedDay){self.timeStartMethod=self.timetable.managementActions.methods.Event.getDayEndDate;}else{self.timeStartMethod=self.timetable.managementActions.methods.SessionSlot.getDayEndDate;}}
indicoRequest(self.timeStartMethod,self.dateArgs,function(result,error){if(error){IndicoUtil.errorReport(error);}
else{var startDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);if(startDate.getHours()>=23){startDate.setHours(23);startDate.setMinutes(0);}
info.set('startDate',Util.formatDateTime(startDate,IndicoDateTimeFormats.Server));}});self.startTimeField.dispatchEvent('change');});return[$T('Date'),conferenceDays];},_drawMainTab:function(info,conferenceDays){var self=this;info.set('roomInfo',$O(self.roomInfo));if(self.timetable)
var ttdata=self.timetable.parentTimetable?self.timetable.parentTimetable.getData():self.timetable.getData()
else
var ttdata=null
this.roomEditor=new RoomBookingReservationWidget(Indico.Data.Locations,info.get('roomInfo'),self.parentRoomData,true,self.favoriteRooms,null,self.bookedRooms,ttdata,info);var presListWidget=new UserListField('VeryShortPeopleListDiv','PeopleList',null,true,null,true,false,self.args.conference,{"presenter-grant-submission":[$T("submission rights"),true]},true,true,true,userListNothing,userListNothing,userListNothing);$B(info.accessor('presenters'),presListWidget.getUsers());info.set('privileges',presListWidget.getPrivileges());var startTimeLine,daySelect,datecomponent;if(exists(this.timetable)&&this.args.session&&this.timetable.isPoster){daySelect=[];startTimeLine=[];this.info.set('duration',self.timeField);this.info.set('startDate',Util.formatDateTime(this.timetable.contextInfo.startDate,IndicoDateTimeFormats.Server));}else if(conferenceDays){var timeTranslation={toTarget:function(value){var aux=conferenceDays.get();return Util.formatDateTime(aux,IndicoDateTimeFormats.ServerHourless,IndicoDateTimeFormats.Ordinal)+' '+value;},toSource:function(value){return value.substr(11,5);}};startTimeLine=[$T('Start time'),Html.div({className:'popUpLabel',style:{textAlign:'left'}},this.startTimeField,$T(' Duration '),this.timeField,$T('min'))];daySelect=self._configureDaySelect(conferenceDays);$B(info.accessor('startDate'),self.startTimeField,timeTranslation);$B(info.accessor('duration'),self.timeField);self.parameterManager.add(self.startTimeField,'time',false);self.parameterManager.add(self.timeField,'unsigned_int',false);}else{daySelect=[];startTimeLine=[$T(' Duration '),Html.div({className:'popUpLabel',style:{textAlign:'left'}},this.timeField,$T('min'))];$B(info.accessor('duration'),self.timeField);self.parameterManager.add(self.timeField,'unsigned_int',false);}
return IndicoUtil.createFormFromMap([[$T('Title'),$B(this.parameterManager.add(Html.edit({id:'addContributionFocusField'}),'text',false),info.accessor('title'))],[$T('Place'),Html.div({style:{marginBottom:'15px'}},this.roomEditor.draw())],daySelect,startTimeLine,[$T('Presenter(s)'),presListWidget.draw()]]);},_drawAdvancedTab:function(info){var self=this;var keywordField=IndicoUI.Widgets.keywordList('oneLineListItem');var fields=[];if(!this.isConference||!this.isCFAEnabled){fields=[[$T('Description'),$B(Html.textarea({cols:50,rows:2}),info.accessor('field_content'))]];}else{fields=translate(self.fields,function(value,key){return[value,$B(Html.textarea({cols:50,rows:2}),info.accessor('field_'+key))];});}
fields.push([$T('Keywords'),keywordField.element]);$B(info.accessor('keywords'),keywordField.accessor);if(this.isConference){fields.push([$T('Board #'),$B(Html.edit({cols:10,rows:1}),info.accessor('boardNumber'))]);}
if(this.isConference){self.contribTypes['']='';var typeSelect=bind.element(Html.select({name:'type'}),self.contribTypes,function(elem){return Html.option({value:elem.key},elem.get());});fields.push([$T('Type'),$B(typeSelect,info.accessor('type'))]);}
return IndicoUtil.createFormFromMap(fields);},_drawAuthorsTab:function(info){var self=this;var authorListWidget=new UserListField('VeryShortPeopleListDiv','PeopleList',null,true,null,true,false,this.args.conference,{"author-grant-submission":[$T("submission rights"),true]},true,true,true,userListNothing,userListNothing,userListNothing);var coauthorListWidget=new UserListField('VeryShortPeopleListDiv','PeopleList',null,true,null,true,false,this.args.conference,{"coauthor-grant-submission":[$T("submission rights"),true]},true,true,true,userListNothing,userListNothing,userListNothing);$B(info.accessor('authors'),authorListWidget.getUsers());$B(info.accessor('coauthors'),coauthorListWidget.getUsers());return IndicoUtil.createFormFromMap([[$T('Author(s)'),authorListWidget.draw()],[Html.div({style:{paddingTop:pixels(30)}},$T('Co-author(s)')),Html.div({style:{paddingTop:pixels(30)}},coauthorListWidget.draw())]]);},_drawNewForm:function(){var self=this;var submitInfo=function(){each(self.args,function(value,key){self.info.set(key,value);});if(self.parameterManager.check()){var killProgress=IndicoUI.Dialogs.Util.progress();indicoRequest(self.method,self.info,function(result,error){killProgress();if(error){IndicoUtil.errorReport(error);}
else{self.close();self.successFunc([result]);}});}};var addButton=Html.input('button',{},$T("Add"));var cancelButton=Html.input('button',{},$T("Cancel"));cancelButton.observeClick(function(){self.close();});var tabs=null;if(self.timetable){var conferenceDays=bind.element(Html.select({name:'type'}),self.days,function(elem){var d=Util.formatDateTime(elem,IndicoDateTimeFormats.DefaultHourless,IndicoDateTimeFormats.Ordinal);return Html.option({value:elem},d);});tabs=[[$T("Basic"),self._drawMainTab(self.info,conferenceDays)]];}else{tabs=[[$T("Basic"),self._drawMainTab(self.info)]];}
addButton.observeClick(function(){if(self.timetable&&!self.timetable.isPoster&&Util.formatDateTime(conferenceDays.get(),IndicoDateTimeFormats.ServerHourless,IndicoDateTimeFormats.Ordinal)!=self.previousDate.substr(0,10)){self.dayChanged=true;self.method=self.timetable.managementActions.methods.Contribution.add;}
submitInfo();});cancelButton.dom.style.marginLeft=pixels(10);if(this.isConference){tabs.push([$T("Authors"),self._drawAuthorsTab(self.info)]);}
tabs.push([$T("Advanced"),self._drawAdvancedTab(self.info)]);var tabWidget=new TabWidget(tabs,600,400);return[tabWidget.draw(),[addButton,cancelButton]];}},function(method,timeStartMethod,args,roomInfo,parentRoomData,confStartDate,dayStartDate,isConference,favoriteRooms,days,timetable,successFunc,isCFAEnabled,bookedRooms){this.args=clone(args);this.dateArgs=clone(args);this.dateArgs.selectedDay=dayStartDate;this.timeStartMethod=timeStartMethod;this.roomInfo=roomInfo;this.confStartDate=confStartDate;this.dayStartDate=dayStartDate;this.parentRoomData=parentRoomData;this.existing=existing;this.isConference=isConference;this.days=days;this.timetable=timetable;this.successFunc=successFunc;this.favoriteRooms=favoriteRooms;this.isCFAEnabled=isCFAEnabled;this.bookedRooms=bookedRooms;this.previousDate=dayStartDate;this.info=new WatchObject();if(this.timeStartMethod===null){args.schedule=false;}
if(this.args.session&&this.timetable.isPoster){this.timeStartMethod=null;}
var attributes={style:{width:'50px'}};this.startTimeField=IndicoUI.Widgets.Generic.timeField(attributes);var durationDefault=this.args.session?(this.timetable.isPoster?this.timetable.contextInfo.duration:this.timetable.contextInfo.contribDuration):20;this.timeField=IndicoUI.Widgets.Generic.durationField(durationDefault);var killProgress=IndicoUI.Dialogs.Util.progress($T("Loading dialog..."));var self=this;this.PreLoadHandler(self._preload,function(){killProgress();self.open();});this.ServiceDialogWithButtons(Indico.Urls.JsonRpcService,method,args,$T("Add Contribution"),function(){self.close();});});type("ChangeEditDialog",["ServiceDialogWithButtons","PreLoadHandler"],{_preload:[function(hook){var self=this;indicoRequest(this.timeStartMethod,this.dateArgs,function(result,error){if(error){self.killProgress();IndicoUtil.errorReport(error);}
else{var startDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);if(startDate.getHours()>=23){startDate.setHours(23);startDate.setMinutes(0);}
self.startTimeField.set(Util.formatDateTime(startDate,IndicoDateTimeFormats.Server).substr(11,5));self.info.set('startDate',Util.formatDateTime(startDate,IndicoDateTimeFormats.Server));hook.set(true);}});}],_submitInfo:function(){var self=this;each(self.args,function(value,key){self.info.set(key,value);});if(self.parameterManager.check()){var killProgress=IndicoUI.Dialogs.Util.progress();indicoRequest(self.method,self.info,function(result,error){killProgress();if(error){IndicoUtil.errorReport(error);}
else{self.close();self.successFunc(result);}});}}},function(method,args,title,successFunc){var self=this;this.successFunc=successFunc;this.killProgress=IndicoUI.Dialogs.Util.progress($T("Loading dialog..."));this.PreLoadHandler(this._preload,function(){self.killProgress();self.open();});this.ServiceDialogWithButtons(Indico.Urls.JsonRpcService,method,args,title,function(){this.close();});});type("AddBreakDialog",["ChangeEditDialog"],{postDraw:function(){this.roomEditor.postDraw();this.ChangeEditDialog.prototype.postDraw.call(this);},draw:function(){var self=this;var addButton=Html.input('button',{},this.isEdit?$T("Save"):$T("Add"));var cancelButton=Html.input('button',{},$T("Cancel"));cancelButton.dom.style.marginLeft=pixels(10);this.roomEditor=new RoomBookingReservationWidget(Indico.Data.Locations,this.info.get('roomInfo'),this.parentRoomInfo,this.isEdit?nullRoomInfo(this.info.get('roomInfo')):true,this.favoriteRooms,null,this.bookedRooms,this.managementActions.timetable.parentTimetable?this.managementActions.timetable.parentTimetable.getData():this.managementActions.timetable.getData(),this.info,this.isEdit?this.info.get("id"):null);cancelButton.observeClick(function(){self.close();});addButton.observeClick(function(){if(Util.formatDateTime(conferenceDays.get(),IndicoDateTimeFormats.ServerHourless,IndicoDateTimeFormats.Ordinal)!=self.previousDate.substr(0,10)){self.dayChanged=true;}
if(self.isEdit){self._saveInfo();}else{if(self.dayChanged){self.method=self.managementActions.methods.Break.add;}
else{if(exists(self.managementActions.timetable.parentTimetable)){self.method=self.managementActions.methods.SessionBreak.add;}}
self._submitInfo();}});var conferenceDays=bind.element(Html.select({name:'type'}),self.days,function(elem){var d=Util.formatDateTime(elem,IndicoDateTimeFormats.DefaultHourless,IndicoDateTimeFormats.Ordinal);return Html.option({value:elem},d);});conferenceDays.set(Util.formatDateTime(self.info.get('startDate'),IndicoDateTimeFormats.Ordinal,IndicoDateTimeFormats.Server));conferenceDays.observe(function(value){self.dateArgs.set("selectedDay",Util.formatDateTime(value,IndicoDateTimeFormats.ServerHourless,IndicoDateTimeFormats.Ordinal));if(self.previousDate.substr(0,10)!=self.dateArgs.get('selectedDay')){self.timeStartMethod=self.managementActions.methods.Event.dayEndDate;}else{if(exists(self.managementActions.timetable.parentTimetable)){self.timeStartMethod=self.managementActions.methods[self.originalArgs.parentType].dayEndDate;}}
indicoRequest(self.timeStartMethod,self.dateArgs,function(result,error){if(error){IndicoUtil.errorReport(error);}
else{var startDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);if(startDate.getHours()>=23){startDate.setHours(23);startDate.setMinutes(0);}
self.info.set('startDate',Util.formatDateTime(startDate,IndicoDateTimeFormats.Server));}});self.startTimeField.dispatchEvent('change');});var timeTranslation={toTarget:function(value){var aux=conferenceDays.get();return Util.formatDateTime(aux,IndicoDateTimeFormats.ServerHourless,IndicoDateTimeFormats.Ordinal)+' '+value;},toSource:function(value){return value.substr(11,5);}};invertableBind(this.info.accessor('startDate'),this.startTimeField,this.isEdit,timeTranslation);invertableBind(this.info.accessor('duration'),this.timeField,this.isEdit);invertableBind(this.info.accessor('inheritLoc'),this.roomEditor.inheritCheckbox.get(),false);invertableBind(this.info.accessor('inheritRoom'),this.roomEditor.inheritCheckbox.get(),false);self.parameterManager.add(self.startTimeField,'time',false);self.parameterManager.add(self.timeField,'non_negative_int',false);var colorPicker=new ColorPicker([],false,'#90C0F0','#202020');if(self.isEdit){colorPicker.setColors(self.info.get('textColor'),self.info.get('color'));}
self.info.set('textColor',colorPicker.getTextColor());self.info.set('bgColor',colorPicker.getBgColor());colorPicker.observe(function(colors){self.info.set('textColor',colors.textColor);self.info.set('bgColor',colors.bgColor);});colorPicker.setFixedPosition();var colorPickerComponent=['Color',Html.div({style:{padding:'5px 0 10px 0'}},colorPicker.getLink(null,'Choose a color'))];var contentDiv=IndicoUtil.createFormFromMap([[$T('Title'),$B(self.parameterManager.add(Html.edit({style:{width:'300px'}})),this.info.accessor('title'))],[$T('Description'),$B(Html.textarea({cols:40,rows:2}),this.info.accessor('description'))],[$T('Place'),this.roomEditor.draw()],[$T('Date'),conferenceDays],[$T('Start time'),Html.div({className:'popUpLabel',style:{textAlign:'left'}},this.startTimeField,$T(' Duration '),this.timeField,$T('min'))],colorPickerComponent]);var buttonDiv=Html.div({},addButton,cancelButton);return this.ServiceDialogWithButtons.prototype.draw.call(this,contentDiv,buttonDiv);},_saveInfo:function(){var self=this;var args=clone(self.info);var killProgress=IndicoUI.Dialogs.Util.progress();indicoRequest(self.managementActions.methods[self.info.get('type')].edit,args,function(result,error){killProgress();if(error){IndicoUtil.errorReport(error);}
else{if(self.dayChanged&&exists(result.slotEntry)){result.slotEntry=null;self.managementActions.timetable._updateMovedEntry(result,result.oldId);}else{self.managementActions.timetable._updateEntry(result,result.id);}
self.close();}});}},function(managementActions,args,parentRoomInfo,isEdit,days,favoriteRooms,bookedRooms){var self=this;this.managementActions=managementActions;this.isEdit=isEdit;this.days=days;this.parentRoomInfo=parentRoomInfo;this.favoriteRooms=favoriteRooms;this.bookedRooms=bookedRooms;var attributes={style:{width:'50px'}};this.startTimeField=IndicoUI.Widgets.Generic.timeField(attributes);this.timeField=IndicoUI.Widgets.Generic.durationField(20);var parameterManager=new IndicoUtil.parameterManager();this.parameterManager=parameterManager;this.originalArgs={};this.dayChanged=false;this.previousDate=args.get('startDate');each(keys(args),function(key){self.originalArgs[key]=args.get(key);});if(isEdit){this.info=args;this.ExclusivePopupWithButtons($T("Edit Break"));this.timeStartMethod=managementActions.methods[args.get('parentType')].dayEndDate;this.dateArgs=args;}else{this.info=clone(args);this.info.set('roomInfo',$O({location:args.get('roomInfo').location,room:args.get('roomInfo').room}));this.timeStartMethod=managementActions.methods[args.get('parentType')].dayEndDate;this.dateArgs=args;var sargs=args.get('args');each(sargs,function(value,key){self.info.set(key,value);});this.ChangeEditDialog(managementActions.methods[args.get('type')].add,this.info,$T("Add Break"),function(result){if(exists(managementActions.timetable.parentTimetable)&&this.dayChanged){managementActions.timetable.parentTimetable._updateEntry(result,result.id);}else{managementActions.timetable._updateEntry(result,result.id);}});}});type("MoveEntryDialog",["ExclusivePopupWithButtons"],{getChosenValue:function(){var radios=document.getElementsByName("rbID");for(var i=0;i<radios.length;i++){if(radios[i].checked){return radios[i].value;}}
return false;},_drawMoveEntryDay:function(timetableItems,currentDay){var moveEntryTable=Html.ul({className:'list',style:{overflow:'auto',height:'250px'}});var radioButtons=[];var sortedByTime=[];translate(timetableItems,function(value,key){if(key.slice(0,1)=="s"){sortedByTime.push([value.startDate.time,key]);}});for(var i=0;i<sortedByTime.length;i++){var temp=sortedByTime[i].splice(0,1);sortedByTime[i].unshift(temp);}
sortedByTime.sort();var rb=Html.radio({name:"rbID",style:{verticalAlign:'middle'}});rb.dom.value="conf:"+currentDay;if(!this.inSession&&this.startDate.replaceAll('-','')==currentDay){rb.dom.disabled='disabled';}
moveEntryTable.append(Html.li({},rb,(Html.label({style:{verticalAlign:'middle',marginLeft:'5px',fontWeight:'normal'}},$T("Top level timetable")))));radioButtons.push(rb);for(i=0;i<sortedByTime.length;i++){var value=timetableItems[sortedByTime[i][1]];rb=Html.radio({name:'rbID',style:{verticalAlign:'middle'}});rb.dom.value=value.sessionId+':'+value.sessionSlotId;if(this.inSession&&value.sessionId==this.sessionId&&value.sessionSlotId==this.slotId){rb.dom.disabled='disabled';}
radioButtons.push(rb);var colorSquare=Html.div({style:{width:'15px',height:'15px',backgroundColor:this.timetable.getById("s"+value.sessionId).color,cssFloat:'right',marginRight:'10px'}});moveEntryTable.append(Html.li({},colorSquare,rb,Html.label({style:{marginLeft:'5px',verticalAlign:'middle',fontWeight:'normal'}},Util.truncate(value.title,40),Html.span({style:{fontSize:'10px',marginLeft:'5px',color:'#999'}}," ",value.startDate.time.slice(0,5)+"-"+value.endDate.time.slice(0,5)))));}
Logic.onlyOne(radioButtons,false);return moveEntryTable;},draw:function(){var self=this;this.inSession=true;if(self.sessionId===null&&self.slotId===null){this.inSession=false;}
var tabData=self.topLevelTimetableData;var dateKeys=$L(keys(tabData));dateKeys.sort();this.tabWidget=new TabWidget(translate(dateKeys,function(key){return[$T(self._titleTemplate(key)),self._drawMoveEntryDay(tabData[key],key)];}),400,200,self._titleTemplate(self.currentDay));var contribLocation=null;if(this.inSession){contribLocation=self.topLevelTimetableData[self.currentDay]['s'+self.sessionId+'l'+self.slotId].title+" (interval #"+self.slotId+")";}else{contribLocation=Html.span({style:{fontWeight:'bold'}},$T("Top-level timetable"));}
var span1=Html.span({},this.entryType=="Contribution"?$T("This contribution currently located at: "):$T("This break is currently located at: "),contribLocation);var span2=Html.div({style:{marginTop:'10px',marginBottom:'15px',fontStyle:'italic'}},$T("Please select the place where you want to move it to."));var okButton=Html.input('button','',$T("Move Entry"));okButton.observeClick(function(){var value=self.getChosenValue();if(!value){return false;}
var killProgress=IndicoUI.Dialogs.Util.progress("Moving the entry...");indicoRequest(self.managementActions.methods[self.inSession?'SessionEntry':'Event'].moveEntry,{value:value,conference:self.confId,scheduleEntryId:self.scheduleEntryId,sessionId:self.sessionId,sessionSlotId:self.slotId},function(result,error){if(error){killProgress();IndicoUtil.errorReport(error);}else{self.managementActions.timetable._updateMovedEntry(result,result.old.id);killProgress();self.close();}});});var cancelButton=Html.input('button',{style:{marginLeft:pixels(5)}},"Cancel");cancelButton.observeClick(function(){self.close();});var content=Widget.block([Html.div({},span1,span2),this.tabWidget.draw(),Html.br()]);var buttons=Html.div({},okButton,cancelButton);return this.ExclusivePopupWithButtons.prototype.draw.call(this,content,buttons);},_titleTemplate:function(text){if(text=='all'){return'All days';}
var nDate=Util.parseJSDateTime(text,IndicoDateTimeFormats.Ordinal);return Indico.Data.WeekDays[nDate.getDay()].substring(0,3)+' '+nDate.getDate()+'/'+(nDate.getMonth()+1);},postDraw:function(){this.tabWidget.postDraw();this.ExclusivePopupWithButtons.prototype.postDraw.call(this);}},function(managementActions,timetable,entryType,sessionId,slotId,currentDay,scheduleEntryId,confId,startDate){this.managementActions=managementActions;this.timetableData=timetable.getData();this.topLevelTimetableData=timetable.parentTimetable?timetable.parentTimetable.getData():this.timetableData;this.timetable=timetable;this.entryType=entryType;this.sessionId=sessionId;this.slotId=slotId;this.currentDay=currentDay;this.scheduleEntryId=scheduleEntryId;this.confId=confId;this.startDate=startDate;var self=this;this.ExclusivePopupWithButtons($T("Move Timetable Entry"),function(){self.close();});});type("RescheduleDialog",["ExclusivePopupWithButtons"],{__getCurrentDayText:function(){return this.tt._titleTemplate(this.tt.currentDay);},__getIntervalTitle:function(){return'"'+this.tt.contextInfo.title+'"';},__drawChooseAction:function(){var self=this;var actionChooseTitle=Html.div("rescheduleTitle",$T("Step 1: Choose type of rescheduling"));var startTimeRescheduleRB=Html.radio({name:"rescheduleAction",id:"startTimeRescheduleRB",style:{verticalAlign:"middle"}});var startTimeRescheduleLabel=Html.label({style:{fontWeight:"normal"}},Html.div("rescheduleLabelTitle",$T("Adjust starting time of all entries")),Html.div("rescheduleLabelDetails",this.isTopLevelTimetable?$T("Move the entries of ")+this.__getCurrentDayText()+$T(" by changing their"):$T("Move the entries of the interval ")+this.__getIntervalTitle()+$T(" by changing their"),Html.strong({},$T(" starting times. ")),this.isTopLevelTimetable?$T("The first entry will start when the event starts (")+this.tt.eventInfo.startDate.time.slice(0,5)+"), ":$T("The first entry will start when the interval starts (")+this.tt.contextInfo.startDate.time.slice(0,5)+"), ",$T("and the other entries will follow consecutively after it. The durations of the entries will not change. "),Html.a({href:Indico.Urls.ImagesBase+'/resched_ex_1.png',rel:'lightbox',title:'Starting Time Example',onclick:"showLightbox(this); return false;"},$T("See an example"))));startTimeRescheduleLabel.dom.htmlFor="startTimeRescheduleRB";var durationRescheduleRB=Html.radio({name:"rescheduleAction",id:"durationRescheduleRB",style:{verticalAlign:"middle"}});var durationRescheduleLabel=Html.label({style:{fontWeight:"normal"}},Html.div("rescheduleLabelTitle",$T("Adjust duration of all entries")),Html.div("rescheduleLabelDetails",$T("Adjust the "),Html.strong({},$T(" duration ")),$T("of the entries of "),this.isTopLevelTimetable?this.__getCurrentDayText()+",":$T("the interval ")+this.__getIntervalTitle(),$T(" to fill the gaps between them, so that their starting time don't change. "+"If a time gap is specified, the duration will be extended up to the value of "+"this time gap before the starting time of the next entry. "),Html.a({href:Indico.Urls.ImagesBase+'/resched_ex_2.png',rel:'lightbox',title:'Duration Example',onclick:"showLightbox(this); return false;"},$T("See an example"))));durationRescheduleLabel.dom.htmlFor="durationRescheduleRB";var actionChoose=Html.table({cellpadding:0,cellPadding:0,cellspacing:0,cellSpacing:0});var actionChooseTbody=Html.tbody();var startTimeRescheduleTr=Html.tr();startTimeRescheduleTr.append(Html.td("rescheduleAction",startTimeRescheduleRB));startTimeRescheduleTr.append(Html.td({className:"rescheduleAction",style:{paddingRight:pixels(5)}},startTimeRescheduleLabel));actionChooseTbody.append(startTimeRescheduleTr);var durationRescheduleTr=Html.tr();durationRescheduleTr.append(Html.td("rescheduleAction",durationRescheduleRB));durationRescheduleTr.append(Html.td({className:"rescheduleAction",style:{paddingRight:pixels(5)}},durationRescheduleLabel));actionChooseTbody.append(durationRescheduleTr);actionChoose.append(actionChooseTbody);startTimeRescheduleRB.observeClick(function(){if(self.rescheduleAction=="startingTime"){if(self.fitInnerAction=="noFit"){self.rescheduleButton.disable();}
self.rescheduleAction="noAction";startTimeRescheduleTr.dom.className="";startTimeRescheduleRB.dom.checked=false;}
else{self.rescheduleButton.enable();self.rescheduleAction="startingTime";startTimeRescheduleTr.dom.className="selectedAction";durationRescheduleTr.dom.className="";}});durationRescheduleRB.observeClick(function(){if(self.rescheduleAction=="duration"){if(self.fitInnerAction=="noFit"){self.rescheduleButton.disable();}
self.rescheduleAction="noAction";durationRescheduleTr.dom.className="";durationRescheduleRB.dom.checked=false;}
else{self.rescheduleButton.enable();self.rescheduleAction="duration";durationRescheduleTr.dom.className="selectedAction";startTimeRescheduleTr.dom.className="";}});return Html.div("rescheduleSection",actionChooseTitle,actionChoose);},__drawChooseInterval:function(){var self=this;var intervalTitle=Html.div("rescheduleTitle",$T("Step 2: Choose time gap between entries"));this.minuteInput=Html.input("text",{style:{width:"3em",textAlign:"right",marginTop:pixels(5),marginBottom:pixels(5)}},"00");var timeInputLabel=Html.span({style:{marginLeft:pixels(5)}},"(minutes)");var intervalInputDiv=Html.div({style:{textAlign:"center"}},this.minuteInput,timeInputLabel);this.intervalExplanationDiv=Html.div();this.minuteInput.observeEvent("change",function(event){self.__intervalObserver();});return Html.div("rescheduleSection",intervalTitle,intervalInputDiv,this.intervalExplanationDiv);},__drawFitInner:function(){var self=this;var fitInnerTitle=Html.div("rescheduleTitle",$T("Step 3: Choose to fit sessions to their content"));this.fitInnerCheckBox=Html.checkbox({},false);this.fitInnerCheckBox.dom.name='fitInnerCheckBox';var fitInnerLabel=Html.label({htmlFor:'fitInnerCheckBox',className:'rescheduleLabelTitle'},"Fit all the sessions contained on "+this.__getCurrentDayText()+" to their content.");var fitInnerDiv=Html.div({style:{textAlign:"center"}},this.fitInnerCheckBox,fitInnerLabel);this.fitInnerExplanationDiv=Html.div({className:'rescheduleLabelDetails',style:{paddingLeft:pixels(30),paddingTop:pixels(8)}});this.fitInnerExplanationDiv.set($T("This changes the start and end times of the session blocks occuring on "+this.__getCurrentDayText()+" in order to fit their respective content "),Html.strong({},$T("before")),$T(" performing the rescheduling."));this.fitInnerCheckBox.observeEvent("change",function(event){self.__fitInnerObserver();});return Html.div("fitInnerSection",fitInnerTitle,fitInnerDiv,this.fitInnerExplanationDiv);},__intervalObserver:function(){var minutes=this.minuteInput.get();var errors=false;if(!IndicoUtil.isInteger(minutes)||minutes<0){return;}
minutes=parseInt(minutes,10);if(minutes===0){this.intervalExplanationDiv.set($T("There will be no gaps between consecutive entries."));}else{var h=Math.floor(minutes/60);var m=minutes%60;intervalExplanationText=$T("Entries will be separated by gaps of ");if(h===1){intervalExplanationText+=$T("1 hour ");}else if(h>0){intervalExplanationText+=h+$T(" hours ");}
if(h!==0&&m!==0){intervalExplanationText+=$T("and ");}
if(m===1){intervalExplanationText+=$T("1 minute.");}else if(m>0){intervalExplanationText+=m+$T(" minutes.");}
this.intervalExplanationDiv.set(intervalExplanationText);}},__fitInnerObserver:function(){var checked=this.fitInnerCheckBox.get();if(checked){this.rescheduleButton.enable();this.fitInnerAction="doFit";}
else{if(this.rescheduleAction=="noAction"){this.rescheduleButton.disable();}
this.fitInnerAction="noFit";}},__drawButtons:function(){var self=this;this.rescheduleButton=new DisabledButton(Html.input("button",{disabled:true,style:{marginRight:pixels(3)}},$T("Reschedule")));var rescheduleButtonTooltip;this.rescheduleButton.observeEvent('mouseover',function(event){if(!self.rescheduleButton.isEnabled()){rescheduleButtonTooltip=IndicoUI.Widgets.Generic.errorTooltip(event.clientX,event.clientY,$T("Please select type of rescheduling"),"tooltipError");}});this.rescheduleButton.observeEvent('mouseout',function(event){Dom.List.remove(document.body,rescheduleButtonTooltip);});this.rescheduleButton.observeClick(function(){self.__reschedule();});var cancelButton=Html.input("button",{style:{marginLeft:pixels(3)}},$T("Cancel"));cancelButton.observeClick(function(){self.close();});return Html.div({},this.rescheduleButton.draw(),cancelButton);},__buildParameterManager:function(){this.parameterManager=new IndicoUtil.parameterManager();this.parameterManager.add(this.minuteInput,"non_negative_int",false);},__reschedule:function(){var self=this;if(this.parameterManager.check()){var confirmHandler=function(confirm){if(confirm){if(self.isTopLevelTimetable){IndicoUI.Dialogs.Util.progress($T("Rescheduling day ")+self.__getCurrentDayText()+"...");Util.postRequest(Indico.Urls.Reschedule,{confId:self.tt.eventInfo.id},{OK:"ok",action:self.rescheduleAction,hour:"0",minute:self.minuteInput.get(),targetDay:self.tt.currentDay,fit:self.fitInnerAction});}else if(self.isIntervalTimetable){IndicoUI.Dialogs.Util.progress($T("Rescheduling interval... "));var inSessionTimetable="no";if(exists(self.tt.parentTimetable.isSessionTimetable)&&self.tt.parentTimetable.isSessionTimetable===true){inSessionTimetable="yes";}
Util.postRequest(Indico.Urls.SlotCalc,{confId:self.tt.eventInfo.id,sessionId:self.tt.contextInfo.sessionId,slotId:self.tt.contextInfo.sessionSlotId},{OK:"ok",action:self.rescheduleAction,hour:"0",minute:self.minuteInput.get(),currentDay:self.tt.currentDay,inSessionTimetable:inSessionTimetable});}}};var confirmText=Html.div({},Html.div({},$T("Are you sure you want to reschedule entries "+
(this.isTopLevelTimetable?"on "+this.__getCurrentDayText():"of the interval "+this.__getIntervalTitle())+"?")),Html.div({},this.fitInnerAction==="doFit"?$T("The entries that are part of a session will"):$T(""),this.fitInnerAction==="doFit"?(this.rescheduleAction==="noAction"?$T(""):$T(" first")):$T(""),this.fitInnerAction==="doFit"?$T(" be fitted to their content."):$T("")),this.rescheduleAction==="noAction"?Html.div({},$T("")):Html.div({},(this.fitInnerAction==="doFit"?$T("Then, all entries "):$T("All entries ")),$T(" will have their "),this.rescheduleAction==="startingTime"?$T("starting times"):$T("duration"),$T(" changed.")),Html.br(),Html.div("rescheduleWarning","This change cannot be undone."));var confirmPopup=new ConfirmPopup($T("Please review your choice"),confirmText,confirmHandler);confirmPopup.open();}},draw:function(){var self=this;var actionChooseDiv=this.__drawChooseAction();var intervalDiv=this.__drawChooseInterval();var actionFitDiv="";if(this.isTopLevelTimetable){actionFitDiv=this.__drawFitInner();}
this.mainContent=Html.div({style:{width:pixels(450)}},actionChooseDiv,intervalDiv,actionFitDiv);var buttonContent=this.__drawButtons();this.__intervalObserver();if(this.isTopLevelTimetable){this.__fitInnerObserver();}
this.__buildParameterManager();return this.ExclusivePopupWithButtons.prototype.draw.call(this,this.mainContent,buttonContent);}},function(parentTimetable){this.ExclusivePopupWithButtons(Html.div({style:{textAlign:"center"}},$T("Reschedule Entries")),positive);this.tt=parentTimetable;this.isTopLevelTimetable=exists(this.tt.TopLevelManagementTimeTable);this.isIntervalTimetable=exists(this.tt.IntervalManagementTimeTable);this.rescheduleAction="noAction";this.timeInput=null;this.fitInnerAction="noFit";this.rescheduleButton=null;});type("FitInnerTimetableDialog",["ConfirmPopup"],{__getSessionTitle:function(){return'"'+this.tt.contextInfo.title+'"';},__getContent:function(){var type;var content=Html.div("fitInnerTimetableDialog",$T("This will change the starting and ending times of the Session "),this.__getSessionTitle(),$T(" so that it encompasses all entries defined in its timetable."),Html.br(),$T("Are you sure you want to proceed?"));return content;},__handler:function(confirm){var self=this;if(confirm){if(this.tt.IntervalManagementTimeTable){IndicoUI.Dialogs.Util.progress($T("Fitting session to content"));Util.postRequest(Indico.Urls.FitSessionSlot,{confId:self.tt.contextInfo.conferenceId,sessionId:self.tt.contextInfo.sessionId,slotId:self.tt.contextInfo.sessionSlotId,day:self.tt.currentDay},{});}}}},function(parentTimetable){this.tt=parentTimetable;this.ConfirmPopup($T("Fit timetable to content"),this.__getContent(),this.__handler);});type("ScaleEditWidget",["InlineEditWidget"],{__buildStructure:function(minValue,maxValue,warning){var div=Html.div({style:{paddingLeft:'2px'}});var spanTitle=Html.span({className:'dataCaptionFormat'},"Scale for each answer: ")
var structure=Html.table({},Html.tbody({},Html.tr({},Html.td("supportEntry","From :"),Html.td({},minValue)),Html.tr({},Html.td("supportEntry","To :"),Html.td({},maxValue))));div.append(spanTitle);div.append(structure)
if(warning){div.append(warning);}
return div;},_handleEditMode:function(value){this.min=Html.edit({size:2},value.min);this.max=Html.edit({size:2},value.max);this.warning=Html.div({className:'changeScaleWarning'},"Please note that when the scale is changed all the previous ratings are set to the new scale values.");this.__parameterManager.add(this.min,'int_pos_or_neg',false);this.__parameterManager.add(this.max,'int_pos_or_neg',false);return this.__buildStructure(this.min,this.max,this.warning);},_handleDisplayMode:function(value){return this.__buildStructure(value.min,value.max,null);},_getNewValue:function(){return{min:this.min.get(),max:this.max.get()};},_verifyInput:function(){if(!this.__parameterManager.check()){return false;}
if(parseInt(this.min.dom.value)>=parseInt(this.max.dom.value)){alert("The \"From\" value must be lower than \"To\" value.");return false;}else if((parseInt(this.max.dom.value)-parseInt(this.min.dom.value))>100){alert("The maximun difference between limits is 100 units.");return false;}
return true;},_handleSuccess:function(){previewQuestion.draw();}},function(method,attributes,initValue){this.InlineEditWidget(method,attributes,initValue);this.__parameterManager=new IndicoUtil.parameterManager();});type("NumberAnswersEditWidget",["InlineEditWidget"],{__buildStructure:function(num){return Html.table({className:'editLinkInLine'},Html.tbody({},Html.tr({},Html.td("dataCaptionFormat","Number of answers per question :"),Html.td({},num))));},_handleEditMode:function(value){this.num=Html.edit({size:2},value);this.__parameterManager.add(this.num,'unsigned_int',false,function(value){if(value>20||value<2){var error=Html.span({},"Number must be in a range between 2 and 20");return error;}else{return null;}});return this.__buildStructure(this.num);},_handleDisplayMode:function(value){return this.__buildStructure(value);},_getNewValue:function(){return this.num.get();},_verifyInput:function(){if(!this.__parameterManager.check()){return false;}
return true;},_handleSuccess:function(){previewQuestion.draw();}},function(method,attributes,initValue){this.InlineEditWidget(method,attributes,initValue);this.__parameterManager=new IndicoUtil.parameterManager();});type("ExampleQuestionWidget",["InlineWidget"],{draw:function(){this.numReq+=1;var self=this;indicoRequest(this.method,this.attributes,function(result,error){if(!error){var numberAnswers=result.numberAnswers;var labels=result.labels;var rbValues=result.rbValues;var content=Html.div({className:'questionPreview'});content.append(Html.span(null,question));content.append(Html.br());content.append(new RadioButtonPreviewQuestion(numberAnswers,labels,self.numReq).draw());$E('inPlaceShowExample').set(content);for(var j=0;j<numberAnswers.length;j++){$E("_GID"+self.numReq+"_"+j).dom.onmouseover=function(event){var value=rbValues[this.defaultValue];IndicoUI.Widgets.Generic.tooltip(this,event,"<span style='padding:3px'>"+value+"</span>");};}}else{IndicoUtil.errorReport(error);}});}},function(method,attributes){this.method=method;this.attributes=attributes;this.numReq=0;this.InlineWidget();});type("RadioButtonSimpleField",["ErrorAware"],{_checkErrorState:function(){var checked=false;each(this.radioButtons,function(radio){if(radio.get()){checked=true;}});return!checked;},_setErrorState:function(text){},get:function(){},draw:function(){var groupName=Html.generateId();var radioButtons=[];for(var i=0;i<this.options.length;i++){var rb=Html.radio({name:groupName,id:groupName+"_"+i,className:"radioButtonAnswer"});rb.dom.value=this.options[i];radioButtons.push(rb);}
Logic.onlyOne(radioButtons,false);if(this.initialValue){for(var j=0;j<this.options.length;j++){if(this.options[j]==this.initialValue){radioButtons[j].dom.defaultChecked=true;}}}
var table=Html.table();table.dom.style.display='inline';var tbody=Html.tbody();table.set(tbody);var row1=Html.tr();var row2=Html.tr();for(var l=0;l<radioButtons.length;l++){var cell1=Html.td();cell1.dom.vAlign='bottom';cell1.dom.align='center';cell1.append(Html.label({htmlFor:groupName+"_"+l},this.labels[l]));row1.append(cell1);var cell2=Html.td();cell2.append(radioButtons[l]);row2.append(cell2);}
cellMessage=Html.td();cellMessage.dom.style.verticalAlign="middle";cellMessage.dom.rowSpan=2;tbody.append(row1);tbody.append(row2);if(this.element){this.element.set(table);}
this.radioButtons=radioButtons;return table;}},function(element,options,labels,initialValue,handler){this.element=element;this.options=options;this.labels=labels;this.initialValue=initialValue;this.handler=handler;});type("RadioButtonPreviewQuestion",[],{draw:function(){var groupName="_GID"+this.numId;var radioButtons=[];for(var i=0;i<this.options.length;i++){var rb=Html.radio({name:groupName,id:groupName+"_"+i,className:"radioButtonAnswer"});rb.dom.value=this.options[i];radioButtons.push(rb);}
Logic.onlyOne(radioButtons,false);var table=Html.table();table.dom.style.display='inline';var tbody=Html.tbody();table.set(tbody);var row1=Html.tr();var row2=Html.tr();for(var l=0;l<radioButtons.length;l++){var cell1=Html.td();cell1.dom.vAlign='bottom';cell1.dom.align='center';cell1.append(Html.label({htmlFor:groupName+"_"+l},this.labels[l]));row1.append(cell1);var cell2=Html.td();cell2.append(radioButtons[l]);row2.append(cell2);}
cellMessage=Html.td();cellMessage.dom.style.verticalAlign="middle";cellMessage.dom.rowSpan=2;tbody.append(row1);tbody.append(row2);return table;}},function(options,labels,numId){this.options=options;this.labels=labels;this.numId=numId;});type("ManageListOfElements",[],{draw:function(){this.widgetContent=Html.div();this._buildStructure(this.methods.get,this.attributes);return this.widgetContent;},_buildStructure:function(method,attributes){var self=this;indicoRequest(method,attributes,function(result,error){if(!error){self.widgetContent.append(self._drawListOfElements(result));self.widgetContent.append(self._drawFooter());}});},_createConfirmPopup:function(method,spanId,previousText,popupContent,title,buttonText){var self=this;var popup=new ConfirmPopup(title,popupContent,function(action){if(action){var attr=self.attributes;attr['id']=spanId;if(previousText){attr['text']=popupContent.dom.value;}
self._buildStructure(method,attr);}},buttonText);return popup;},_createSpecialRemovePopup:function(method,spanId,popupContent,title,button1,button2){var self=this;var popup=new SpecialRemovePopup(title,popupContent,function(option){if(option==0){null;}else{var attr=self.attributes;attr['id']=spanId;if(option==1){attr['keepJud']=true;}
if(option==2){attr['keepJud']=false;}
self._buildStructure(method,attr);}},button1,button2);return popup;},_drawListOfElements:function(result){this.i=0;var self=this;if($E(this.divsIdRoot+'Elements')){this.widgetContent.remove($E(this.divsIdRoot+'Elements'));}
if(result.length){var content=Html.div({id:this.divsIdRoot+'Elements'});var table=Html.table({className:'infoQuestionsTable',cellpadding:0,cellPadding:0,cellspacing:0,cellSpacing:0});var tbody=Html.tbody({});table.append(tbody);content.append(table);var tr;var spanRemoveList=[];var spanEditList=[];var tdEdit;var tdRemove;for(var i=0;i<result.length;i++){tr=Html.tr({className:'infoTR'});tdElement=Html.td({className:'questionContent'},result[i].text);tdElement.dom.id="TEID_"+result[i].id;tdEdit=Html.td({className:'content'});var spanEdit=Html.span({className:'link'},'Edit');spanEdit.dom.id="QEID_"+result[i].id;spanEdit.dom.name=result[i].text;spanEditList.push(spanEdit);tdEdit.append(spanEdit);spanEditList[i].observeClick(function(event){if(event.target){var spanId=event.target.id.split('_')[1];}else{var spanId=event.srcElement.id.split('_')[1];}
var previousText=$E('TEID_'+spanId).dom.innerHTML;var popupContent=Html.textarea({id:'modifyArea',cols:'40',rows:'7'},previousText);var popup=self._createConfirmPopup(self.methods.edit,spanId,previousText,popupContent,'Edit '+self.kindOfElement,'Save');popup.open();});tdRemove=Html.td({className:'content'});var spanRemove=Html.span({className:'link'},'Remove');spanRemove.dom.id="QRID_"+result[i].id;spanRemoveList.push(spanRemove);tdRemove.append(spanRemove);spanRemoveList[i].observeClick(function(event){if(event.target){var spanId=event.target.id.split('_')[1];}else{var spanId=event.srcElement.id.split('_')[1];}
var attr=self.attributes;attr['value']=spanId;if(!self.specialRemove){var popupContent=Html.span({},'Are you sure you want to remove the '+self.kindOfElement+'?');var popup=self._createConfirmPopup(self.methods.remove,spanId,null,popupContent,'Remove '+self.kindOfElement,'Remove');}else{var popupContent=Html.span({},'Do you want to keep the ratings of the judgements for this question (if any)?');var popup=self._createSpecialRemovePopup(self.methods.remove,spanId,popupContent,'Remove '+self.kindOfElement,'Keep ratings','Remove ratings');}
popup.open();});tbody.append(tr);tr.append(tdElement);tr.append(tdEdit);tr.append(tdRemove);}}
return content;},_drawFooter:function(){var self=this;if($E(this.divsIdRoot+'Footer')){this.widgetContent.remove($E(this.divsIdRoot+'Footer'));}
var content=Html.div({id:this.divsIdRoot+'Footer',style:{paddingTop:'10px'}});var edit=Html.edit({size:'30'});var addButton=Html.input('button','popUpButton',$T('Add '+this.kindOfElement));addButton.observeClick(function(){var element=edit.get();if(element!=''){var attr=self.attributes;attr['value']=element;self._buildStructure(self.methods.add,attr);edit.set('');}});content.append(edit);content.append(addButton);return content;}},function(methods,attributes,kindOfElement,divsIdRoot,specialRemove){this.methods=methods;this.attributes=attributes;this.kindOfElement=kindOfElement;this.divsIdRoot=divsIdRoot;this.specialRemove=specialRemove;});var currentArea;var inputCursor=0;function selected(id){currentArea=$E(id);if(currentArea.dom.id=='notificationTplSubject'&&document.selection){inputCursor=getInputPosition();}}
function insertTag(tag){if(checkID()){var value=currentArea.dom.value;var countChars=getCursorPosition();var cursor=countChars[0];var posToMove=countChars[1];var end=currentArea.dom.value.length;value=value.substr(0,cursor)+tag+value.substr(cursor,end);currentArea.dom.value=value;if(document.selection){setCursorPosition(posToMove);}else{currentArea.dom.selectionStart=cursor+tag.length;currentArea.dom.selectionEnd=cursor+tag.length;currentArea.dom.focus();}}else{alert("You can only insert tags in Subject or Body.\nPlease click in the Subject or Body text box before inserting.");}}
function getCursorPosition(){var cursor=0;var charsAfter=0;if(document.selection){if(currentArea.dom.id=='notificationTplBody'){currentArea.dom.focus();var oSel=document.selection.createRange();var oSelDup=document.selection.createRange();var counter=-2;var previousLength=0;var nextLength=0;while(oSel.text==oSel.htmlText){previousLength=oSel.text.length;oSel.moveStart('character',-1);nextLength=oSel.text.length;if(previousLength==nextLength)
counter+=2;}
cursor=oSel.text.length+counter;counter=-1;while(oSelDup.text==oSelDup.htmlText){previousLength=oSelDup.text.length;oSelDup.moveEnd('character',1);nextLength=oSelDup.text.length;if(previousLength==nextLength)
counter+=1;}
charsAfter=oSelDup.text.length-counter;}else{cursor=inputCursor;charsAfter=currentArea.dom.value.length-cursor;}}
else if(currentArea.dom.selectionStart>=0){cursor=currentArea.dom.selectionEnd;charsAfter=0;}
return[cursor,charsAfter];}
function setCursorPosition(pos){if(currentArea.dom.id=='notificationTplBody'){currentArea.dom.focus();var oSel=document.selection.createRange();if(pos>0){oSel.moveStart('character',-pos);oSel.moveEnd('character',-pos);}
oSel.select();}}
function getInputPosition(){currentArea.dom.focus();var oSel=document.selection.createRange();oSel.moveStart('character',-currentArea.dom.value.length);return oSel.text.length;}
function checkID(){if(currentArea==null)
return false
else if(currentArea.dom.id=='notificationTplBody'||currentArea.dom.id=='notificationTplSubject')
return true;else
return false;}
function aspectListNothing(data,func){each(data,function(){func(true);});}
function singleAspectNothing(user,func){func(true);}
type("MapAspectDataPopup",["ExclusivePopupWithButtons"],{param:function(aspectData,label,propertyName){var edit=Html.edit({style:{width:'300px'}});var accessor=aspectData.accessor(propertyName);this.parameterManager.add(edit,'text',false);var binding=$B(edit,accessor);return[$T(label),binding];},draw:function(){var aspectData=this.aspectData;var self=this;self.parameterManager=new IndicoUtil.parameterManager();var form=IndicoUtil.createFormFromMap([this.param(aspectData,'Name','name'),this.param(aspectData,'Center latitude','centerLatitude'),this.param(aspectData,'Center longitude','centerLongitude'),this.param(aspectData,'Top-left latitude','topLeftLatitude'),this.param(aspectData,'Top-left longitude','topLeftLongitude'),this.param(aspectData,'Bottom-right latitude','bottomRightLatitude'),this.param(aspectData,'Bottom-right longitude','bottomRightLongitude'),this.param(aspectData,'Zoom level','zoomLevel'),[$T('Default on start-up'),$B(Html.checkbox({}),aspectData.accessor('defaultOnStartup'))]]);var buttons=Html.div({},Widget.link(command(curry(this.action,aspectData,function(){self.close();}),Html.input("button",{},$T("Save")))),Widget.link(command(function(){self.close();},Html.input("button",{},$T("Cancel")))));return this.ExclusivePopupWithButtons.prototype.draw.call(this,form,buttons);}},function(title,aspectData,action){this.aspectData=aspectData;this.action=action;this.ExclusivePopup(title,function(){return true;});});type("MapAspectListWidget",["ListWidget"],{_drawItem:function(aspect){var self=this;var aspectData=aspect.get();var editButton=Widget.link(command(function(){editPopup=new MapAspectDataPopup('Change map aspect data',aspectData.clone(),function(newData,suicideHook){if(editPopup.parameterManager.check()){self.editProcess(aspectData,function(result){if(result){aspectData.update(newData.getAll());if(!exists(newAspect.get('defaultOnStartup'))){newAspect.set('defaultOnStartup',false);}
if(!startsWith(aspectData.get('id'),'newAspect')){aspectData.set('id','edited'+aspectData.get('id'));}}},newData);suicideHook();}});editPopup.open();},IndicoUI.Buttons.editButton()));var removeButton=Widget.link(command(function(){self.removeProcess(aspectData,function(result){if(result){self.set(aspect.key,null);}});},IndicoUI.Buttons.removeButton()));var buttonDiv=Html.div({style:{cssFloat:"right",paddingRight:pixels(10),paddingTop:pixels(5)}});buttonDiv.append(editButton);buttonDiv.append(removeButton);var b1=$B(Html.span(),aspectData.accessor('name'));var b2=$B(Html.span(),aspectData.accessor('defaultOnStartup'),function(x){return x?' ('+$T('Default')+')':''});var aspectName=Html.span({},b1,b2);return Html.span({},buttonDiv,aspectName);}},function(style,editProcess,removeProcess){this.style=any(style,"UIAspectsList");this.editProcess=any(editProcess,singleAspectNothing);this.removeProcess=any(removeProcess,singleAspectNothing);this.ListWidget(style);});type("MapAspectListField",["IWidget"],{getAspects:function(){return $L(this.aspectList);},clear:function(){this.aspectList.clearList();},draw:function(){var self=this;var select;var buttonDiv=Html.div({style:{marginTop:pixels(10)}});var addNewAspectButton=Html.input("button",{style:{marginRight:pixels(5)}},$T('Add Map Aspect'));addNewAspectButton.observeClick(function(){var newAspectId=self.newAspectCounter++;var newAspect=$O({'id':newAspectId});newAspectPopup=new MapAspectDataPopup($T('New map aspect'),newAspect,function(newData,suicideHook){if(newAspectPopup.parameterManager.check()){newAspect.update(newData.getAll());if(!exists(newAspect.get('defaultOnStartup'))){newAspect.set('defaultOnStartup',false);}
self.newProcess(newAspect,function(result){if(result){self.aspectList.set(newAspectId,newAspect);}});suicideHook();}});newAspectPopup.open();});buttonDiv.append(addNewAspectButton);return Widget.block([Html.div(this.aspectDivStyle,this.aspectList.draw()),buttonDiv]);}},function(aspectDivStyle,aspectListStyle,initialAspects,newProcess,editProcess,removeProcess){var self=this;this.aspectList=new MapAspectListWidget(aspectListStyle,editProcess,removeProcess);if(initialAspects.length>0){this.newAspectCounter=initialAspects[initialAspects.length-1].id+1;}else{this.newAspectCounter=0;}
this.aspectDivStyle=any(aspectDivStyle,"UIAspectsListDiv");if(exists(initialAspects)){each(initialAspects,function(aspect){self.aspectList.set(aspect.id,$O(aspect));});}
this.newProcess=any(newProcess,aspectListNothing);});
