IndicoUI.Widgets={roomParamsShow:function(target,source){var info=source.get();target.set([Html.div({},Html.span("innerWidgetLabel",$T("Location: ")),info.get('location')),Html.div({},Html.span("innerWidgetLabel",$T("Room: ")),info.get('room')),Html.div({},Html.span("innerWidgetLabel",$T("Address: ")),info.get('address'))]);},keywordList:function(kindOfList,method,attributes,handler,icontitle){var list=new WatchList();var image=Html.img({src:imageSrc("remove"),alt:'Remove status',title:$T('Remove this status from the list')});var getElement=function(){var text=Html.edit();var buttonBlock;var message=Html.span({style:{marginLeft:'5px'}});var addButton=Html.input('button','popUpButton',$T('Add'));addButton.observeClick(function(){var elem=text.get();if(!search(list,match(elem))&&elem!==''){list.append(elem);text.set('');message.set('');}});if(!handler){handler=function(result,error){if(error){message.set('Error');message.dom.style.color='red';}else{message.set('Saved');message.dom.style.color='green';}};}
if(method){var saveButton=Html.input('button','popUpButton',$T('Add'));saveButton.observeClick(function(){var elem=text.get();if(!search(list,match(elem))&&elem!==''){list.append(elem);text.set('');message.set('');}
indicoRequest(method,extend(clone(attributes),{'value':list}),handler);});buttonBlock=Widget.inline([saveButton]);}else{buttonBlock=Widget.inline([addButton]);}
var wordList=Html.div({style:{width:'300px',overflow:'auto'}});return Widget.block([Widget.block([Html.label($T('Keywords:')),text,buttonBlock,message,$B(wordList,list.length,function(length){return length===0?Html.div({style:{height:pixels(25),margin:pixels(5),fontStyle:'italic'}},$T("No items")):$B(Html.ul("keywordList"),list,function(value,index){var style=index==(list.length.get()-1)?kindOfList+"_last":kindOfList;return Html.li(style,[value,Widget.link(command(function(){list.remove(value);var elem=text.get();if(!search(list,match(elem))&&elem!==''){list.append(elem);text.set('');}
indicoRequest(method,extend(clone(attributes),{'value':list}),handler);message.set('');},Html.span({style:{marginLeft:'5px'}},Html.img({style:{verticalAlign:"bottom",width:'15px',height:'15px'},src:imageSrc("remove"),title:icontitle}))))]);});})])]);};return{element:getElement(),accessor:list};},tripleSelectWidget:function(name,selectBox,info,usingCRBS,parentInfo,roomStyler){var selectRadio;var radioSet=new WatchValue();var radios=[];var radioMapping={};var formAction=Html.input("hidden",{'name':name+'Action'});var addRadio=(usingCRBS||parentInfo)?function(key,elem,val){var radio=Html.radio({'name':Html.generateId()});radios.push(radio);radioMapping[key]=radio;$B(elem.accessor("disabled"),radio,invert);radio.observe(function(value){if(value){formAction.set(val);bind.detach(info.accessor(name));if(key=='inherit'){info.accessor(name).set(null);}else if(key=='other'){$B(elem,info.accessor(name));}}});return[radio,elem];}:function(key,elem,val){formAction.set(val);if(key=='inherit'){info.accessor(name).set(null);}else{$B(elem,info.accessor(name));}
return elem;};return IndicoUtil.waitLoad([function(hook){var sBox;if(usingCRBS){sBox=selectBox(info,function(){radioSet.set('list');},roomStyler);sBox.returnValue.observe(function(_){selectRadio=addRadio('list',sBox.returnValue.get(),'set');hook.set(true);});sBox.run();}else{hook.set(true);}}],function(retValue){var choices=[formAction];radioSet.set('other');if(usingCRBS){choices.push(selectRadio);}
var other=addRadio('other',Html.input("text",{'name':name+"Name"}),'set');if(usingCRBS||parentInfo){other[1].set(info.get(name));}
choices.push(other);if(parentInfo){var parentChoice=parentInfo.get(name);var withRadio=addRadio('inherit',Html.span({},$T("Inherit from Parent")+" ("+parentChoice+")"),'inherit');choices.push(withRadio);if(info.get(name)===null){radioSet.set('inherit');}}
if(usingCRBS||parentInfo){Logic.onlyOne(radios,false);var setRadios=function(){radioMapping[radioSet.get()].set(true);};radioSet.observe(setRadios);setRadios();}
retValue.set(choices);});},Options:{setAdvancedOptions:function(state,handler){jsonRpc(Indico.Urls.JsonRpcService,'user.personalinfo.set',{'value':{'tabAdvancedMode':state}},function(response,error){if(exists(error)){IndicoUtil.errorReport(error);}
else{handler();}});}},Generic:{tooltip:function(in_this,event,content){domTT_activate(in_this,event,'content',content,'type','greasy','caption',false,'trail',false,'delay',0,'maxWidth',500,'styleClass','tip');return function(in_event){domTT_mouseout(in_this,in_event);domTT_tooltips.set(in_this.id,null)};},errorTooltip:function(mouseX,mouseY,content,klass){var div=Html.div({style:{top:pixels(mouseY),left:pixels(mouseX),marginTop:pixels(10),marginLeft:pixels(10),position:'fixed',zIndex:IndicoUI.__globalLayerLevel+1}},content);if(!klass){klass="tooltip";}
div.dom.className=klass;Dom.Content.add(document.body,div);return div;},simpleButton:function(elem,method,attributes,handler,caption){var button=Widget.button(command(function(){indicoRequest(method,attributes,handler);},caption));elem.set(button);return button;},switchOptionButton:function(method,attributes,caption,messageId){var button=new SwitchOptionButton(method,attributes,caption,messageId);return button.draw();},sourceSelectionField:function(elem,source,options){IndicoUI.Effect.mouseOver(elem.dom);var context=new WidgetEditableContext();$B(elem,[Widget.selectEditableClickable(options,source,context),Widget.text(" "),Widget.text($B(new Chooser({view:[Widget.link(command(context.edit,$T("(edit)")))],edit:[Widget.button(command(context.save,$T("Save"))),Widget.button(command(context.view,$T("Cancel")))]}),context))]);},selectionField:function(elem,method,attributes,options,cachedValue,observer){var cachedRpcValue=IndicoUtil.cachedRpcValue(Indico.Urls.JsonRpcService,method,attributes,cachedValue);IndicoUI.Widgets.Generic.sourceSelectionField(elem,cachedRpcValue,options);if(observer){cachedRpcValue.observe(observer);}},sourceTextField:function(elem,source){IndicoUI.Effect.mouseOver(elem.dom);var context=new WidgetEditableContext();var editable=new WidgetEditable(WidgetEditable.getClickableView(WidgetEditable.getTemplatedTextView(getBlankTemplate(Html.span({style:{fontStyle:'italic'}},$T("None"))))),WidgetEditable.textEdit);var chooser=new Chooser({view:Widget.link(command(context.edit,$T("(edit)"))),edit:Html.div({},Widget.button(command(context.save,$T("Save"))),Widget.button(command(context.view,$T("Cancel"))))});$B(elem,Html.div({},editable(source,context),Widget.text(" "),Widget.text($B(chooser,context))));},textField:function(elem,method,attributes,cachedValue){IndicoUI.Widgets.Generic.sourceTextField(elem,IndicoUtil.cachedRpcValue(Indico.Urls.JsonRpcService,method,attributes,cachedValue));},richTextField:function(elem,method,attributes,width,height,cachedValue){var context=new WidgetEditableContext();extend(attributes,{'value':elem.dom.innerHtml});var editable=new WidgetEditable(WidgetEditable.getClickableView(WidgetEditable.getTemplatedTextView(getBlankTemplate(Html.span({style:{fontStyle:'italic'}},$T("None"))))),IndicoUI.Aux.RichTextEditor.getEditor(width,height));$B(elem,[editable(IndicoUtil.cachedRpcValue(Indico.Urls.JsonRpcService,method,attributes,cachedValue),context),Widget.text(" "),Widget.text($B(new Chooser({view:[Widget.link(command(context.edit,$T("(edit)")))],edit:[Widget.button(command(context.save,$T("Save"))),Widget.button(command(context.view,$T("Cancel")))]}),context))]);},remoteSelectField:function(element,method,params,setter,accObj,accOldObj,onChange){var options=new JsonRpcSource(method,params,Indico.Urls.JsonRpcService);var thizz=this;Control.remoteData(element,options,function(element,loadedItemsSrc){var id=undefined;var val=element.innerHTML;$C(loadedItemsSrc.data).each(function(pair){if(pair.value==val){id=pair.key;}});accObj.set(id);accOldObj.set(id);var result=Field.editable(element,accObj,selectEditor.bind({items:$H(loadedItemsSrc.data.get())}),setter.bind($H(loadedItemsSrc.data.get())),null,null,onChange);Binding.fieldObject(result,accObj);result.updateSource=function(key,value){options.setParam(key,value);options.update();};thizz.notifyEnd(result);});options.update();},keywordField:function(element,kindOfList,method,attributes,icontitle,handler){var keywordList=IndicoUI.Widgets.keywordList(kindOfList,method,attributes,handler,icontitle);indicoRequest(method,attributes,function(result,error){if(!error){each(result,function(value){keywordList.accessor.append(value);});}});element.set(keywordList.element);return keywordList;},radioButtonField:function(element,kind,options,labels,initialValue,method,attributes,handler){var groupName=Html.generateId();var t;var radioGroupValue=function(groupName,length){for(var i=0;i<length;i++){if($E(groupName+"_"+i).get()){return $E(groupName+"_"+i).dom.value;}}
return false;};var message=Html.span({style:{marginLeft:'5px'}},'\u00A0');message.dom.id="message"+groupName;var messageUpdater=function(result,error){if(error){message.set('Error');message.dom.style.color='red';}else{message.set('Updated');message.dom.style.color='green';}
if(t){clearTimeout(t);}
t=setTimeout("$E(\""+"message"+groupName+"\").set(\'\u00A0\')",2000);};var returnHandler=function(result,error){messageUpdater(result,error);if(handler){handler(result,error);}};var buttonClicked=function(){message.set($T('Updating...'));message.dom.style.color='orange';indicoRequest(method,extend(clone(attributes),{'value':radioGroupValue(groupName,options.length)}),returnHandler);};var radioButtons=[];for(var i=0;i<options.length;i++){var rb=Html.radio({name:groupName,id:groupName+"_"+i});rb.dom.value=options[i];rb.observeClick(buttonClicked);radioButtons.push(rb);}
Logic.onlyOne(radioButtons,false);if(initialValue){for(var j=0;j<options.length;j++){if(options[j]==initialValue){radioButtons[j].dom.defaultChecked=true;}}}else{initialValueHandler=function(result,error){if(!error){radioButtons[result].dom.checked=true;}};indicoRequest(method,attributes,initialValueHandler);}
if(kind=="vertical"||kind=="horizontal1"){var itemsList=[];for(var k=0;k<radioButtons.length;k++){itemsList.push(radioButtons[k]);itemsList.push(Html.label({htmlFor:groupName+"_"+k},labels[k]));if(kind=="vertical"&&k!=radioButtons.length-1){itemsList.push(Html.br());}}
itemsList.push(message);var block=Widget.block(itemsList);if(element){element.set(block);}
return block;}
else if(kind=="horizontal2"){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},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;cellMessage.append(message);row1.append(cellMessage);tbody.append(row1);tbody.append(row2);if(element){element.set(table);}
return table;}
else{alert($T("developer error: kind of radioButtonField is not correct, should be 'vertical', 'horizontal1', 'horizontal2'"));}},twoListField:function(element,size,width,items1,items2,title1,title2,method,attributes,handler){var uniqueId=Html.generateId();var t;var watchList1;var watchList2;var message=Html.span('','\u00A0');message.dom.id="message"+uniqueId;var loadInitialValues=function(result,error,watchList){if(error){message.set($T('Error loading initial values'));message.dom.style.color='red';}else{watchList.appendMany(result);}};if(items1){items1.sort();watchList1=$L(items1);}else{watchList1=$L([]);indicoRequest(method,extend(clone(attributes),{'destination':'left'}),function(result,error){loadInitialValues(result,error,watchList1);});}
if(items2){items2.sort();watchList2=$L(items2);}else{watchList2=$L([]);indicoRequest(method,extend(clone(attributes),{'destination':'right'}),function(result,error){loadInitialValues(result,error,watchList2);});}
if(!size){size=10;}
if(!width){width="200px";}
var select1=Html.select({style:{width:width}});select1.dom.multiple=true;select1.dom.size=size;bind.element(select1,watchList1,function(value){return Html.option({},value);});var select2=Html.select({style:{width:width}});select2.dom.multiple=true;select2.dom.size=size;bind.element(select2,watchList2,function(value){return Html.option({},value);});var rightButton=Html.img({Alt:'Move right',title:'Move right',src:imageSrc("arrow_next")});var leftButton=Html.img({Alt:'Move left',title:'Move left',src:imageSrc("arrow_previous")});var messageUpdater=function(result,error){if(error){message.set('Error');message.dom.style.color='red';}else{message.set('Updated');message.dom.style.color='green';}
if(t){clearTimeout(t);}
t=setTimeout("$E(\""+"message"+uniqueId+"\").set(\'\u00A0\')",2000);};var returnHandler=function(result,error){messageUpdater(result,error);if(handler){handler(result,error);}};rightButton.observeClick(function(){var selectedItems=getSelectedItems(select1);watchList2.appendMany(selectedItems);watchList1.removeMany(selectedItems);IndicoUtil.sortWatchList(watchList2);message.set('Updating...');message.dom.style.color='orange';indicoRequest(method,extend(clone(attributes),{'value':selectedItems,'destination':'right'}),returnHandler);});leftButton.observeClick(function(){var selectedItems=getSelectedItems(select2);watchList1.appendMany(selectedItems);watchList2.removeMany(selectedItems);IndicoUtil.sortWatchList(watchList1);message.set('Updating...');message.dom.style.color='orange';indicoRequest(method,extend(clone(attributes),{'value':selectedItems,'destination':'left'}),returnHandler);});var table=Html.table();var tBody=Html.tbody();table.set(tBody);var row1=Html.tr();var row2=Html.tr();var row3=Html.tr();var row4=Html.tr();var cell0=Html.td();cell0.set(title1);cell0.dom.align="center";row1.append(cell0);var cell1=Html.td();row1.append(cell1);var cell2=Html.td();cell2.set(title2);cell2.dom.align="center";row1.append(cell2);var cell3=Html.td();cell3.dom.rowSpan=2;cell3.append(select1);row2.append(cell3);var cell4=Html.td();cell4.dom.vAlign="bottom";cell4.append(rightButton);row2.append(cell4);var cell5=Html.td();cell5.dom.rowSpan=2;cell5.append(select2);row2.append(cell5);var cell6=Html.td();cell6.dom.vAlign="top";cell6.append(leftButton);row3.append(cell6);var cell7=Html.td();cell7.dom.colSpan=3;cell7.dom.align="center";cell7.append(message);row4.append(cell7);tBody.append(row1);tBody.append(row2);tBody.append(row3);tBody.append(row4);element.set(table);return table;},input2dateField:function(elem,showTime,hiddenFields,trigger,format){if(showTime===undefined){showTime=false;}
elem.processDate=function(){var d;if(showTime){if(exists(format)){d=Util.parseJSDateTime(elem.get(),format);}else{d=IndicoUtil.parseDateTime(elem.get());}}else{if(exists(format)){d=Util.parseJSDateTime(elem.get(),format);if(d!=null){d=getDate(d);}}else{d=parseDate(elem.get());}}
var ret=false;if(d){if(isArray(hiddenFields)){$E(hiddenFields[0]).set(!showTime?d[0]:d.getDate());$E(hiddenFields[1]).set(!showTime?d[1]:d.getMonth()+1);$E(hiddenFields[2]).set(!showTime?d[2]:d.getFullYear());if(showTime){$E(hiddenFields[3]).set(d.getHours());$E(hiddenFields[4]).set(d.getMinutes());}}else if(hiddenFields){$E(hiddenFields).set(elem.get());}
ret=true;}else{if(isArray(hiddenFields)){$E(hiddenFields[0]).set('');$E(hiddenFields[1]).set('');$E(hiddenFields[2]).set('');if(showTime){$E(hiddenFields[3]).set('');$E(hiddenFields[4]).set('');}}else if(hiddenFields){$E(hiddenFields).set('');}}
return ret;};if(hiddenFields){elem.observe(elem.processDate);}
if(!exists(format)){if(showTime){format="%d/%m/%Y %H:%M";}else{format="%d/%m/%Y";}}
var onSelect=function(cal){var p=cal.params;var update=(cal.dateClicked||exists(cal.activeDiv._range));if(update&&p.inputField){p.inputField.value=cal.date.print(p.ifFormat);if(typeof p.inputField.onchange=="function")
p.inputField.onchange();}
if(update&&p.displayArea)
p.displayArea.innerHTML=cal.date.print(p.daFormat);if(update&&typeof p.onUpdate=="function")
p.onUpdate(cal);};Calendar.setup({inputField:elem.dom,button:trigger==undefined?elem.dom:trigger.dom,displayArea:elem,align:"",eventName:"click",ifFormat:format,showsTime:showTime,onSelect:onSelect});},removeCalendar:function(elem){elem.dom.onclick=nothing;},dateField:function(showTime,attributes,hiddenFields,elemInfo,format){attributes=attributes||{};elemInfo=elemInfo||{};extend(elemInfo,attributes);var elem=Html.input("text",elemInfo);var trigger=Html.img({src:imageSrc("calendarWidget")});var tab=Html.div("dateField",elem,trigger);IndicoUI.Widgets.Generic.input2dateField(elem,showTime,hiddenFields,trigger,format);elem.set("");tab.set=function(string){elem.set(string);};tab.get=function(){return elem.get();};tab.observe=function(fun){elem.observe(fun);};tab.observeChange=function(fun){elem.dom.onchange=fun;};tab.dom.onchange=function(){if(typeof(elem.dom.onchange)==='function'){elem.dom.onchange();}};tab.processDate=elem.processDate;return tab;},dateField_sdate:function(showTime,attributes,hiddenFields){return IndicoUI.Widgets.Generic.dateField(showTime,attributes,hiddenFields,{'id':'sdate','name':'sdate'});},dateField_edate:function(showTime,attributes,hiddenFields){return IndicoUI.Widgets.Generic.dateField(showTime,attributes,hiddenFields,{'id':'edate','name':'edate'});},timeField:function(attributes,hiddenFields){attributes=attributes||{};var elem=Html.input("text",attributes);return elem;},dateEditor:function(elem,method,attributes,cachedValue){IndicoUI.Effect.mouseOver(elem.dom);var context=new WidgetEditableContext();var editable=new WidgetEditable(WidgetEditable.getClickableView(WidgetEditable.getTemplatedTextView(getBlankTemplate(Html.span({style:{fontStyle:'italic'}},"None")))),WidgetEditable.getFieldEditor(curry(IndicoUI.Widgets.Generic.dateField,true)));$B(elem,[editable(IndicoUtil.cachedRpcValue(Indico.Urls.JsonRpcService,method,attributes,cachedValue),context),Widget.text(" "),IndicoUI.Aux.defaultEditMenu(context)]);},dateStartEndTimeField:function(defaultStartTime,defaultEndTime,additional){var obj=new WatchObject();obj.set('startTime',defaultStartTime);obj.set('endTime',defaultEndTime);var attributes={style:{width:'50px'}};var dash=Html.span({style:{padding:'0 10px'}});dash.dom.innerHTML='&ndash;';var startTimeField=IndicoUI.Widgets.Generic.timeField(attributes);var endTimeField=IndicoUI.Widgets.Generic.timeField(attributes);var element=Widget.block([$B(startTimeField,obj.accessor('startTime')),dash,$B(endTimeField,obj.accessor('endTime')),additional||'']);return{'element':element,'accessor':obj,'startTimeField':startTimeField,'endTimeField':endTimeField};},durationField:function(defaultVal,attributes){attributes=attributes||{};attributes.style={width:'40px'};return Html.edit(attributes,defaultVal);},applyForParticipationForm:function(conf){}}};extend(IndicoUI.Dialogs,{addSession:function(method,timeStartMethod,args,roomInfo,parentRoomInfo,dayStartDate,favoriteRooms,days,successFunc,bookedRooms,timetable){var parameterManager=new IndicoUtil.parameterManager();var info=new WatchObject();var dateArgs=clone(args);dateArgs.selectedDay=dayStartDate;var killLoadProgress=IndicoUI.Dialogs.Util.progress($T("Loading dialog..."));IndicoUtil.waitLoad([function(hook){indicoRequest(timeStartMethod,dateArgs,function(result,error){if(error){killLoadProgress();IndicoUtil.errorReport(error);}
else{var startDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);var endDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);if(startDate.getHours()>=23){startDate.setHours(23);startDate.setMinutes(0);endDate.setHours(23);endDate.setMinutes(59);}else{endDate.setHours(startDate.getHours()+1);}
info.set('startDateTime',Util.formatDateTime(startDate,IndicoDateTimeFormats.Server));info.set('endDateTime',Util.formatDateTime(endDate,IndicoDateTimeFormats.Server));dateArgs.startDate=startDate;dateArgs.endDate=endDate;hook.set(true);}});}],function(retValue){killLoadProgress();var submitInfo=function(){each(args,function(value,key){info.set(key,value);});if(parameterManager.check()){var killProgress=IndicoUI.Dialogs.Util.progress();indicoRequest(method,info,function(result,error){killProgress();if(error){IndicoUtil.errorReport(error);}else{popup.close();successFunc(result);}});}};var popup=new ExclusivePopupWithButtons($T('Add Session'));var roomEditor;popup.postDraw=function(){roomEditor.postDraw();this.ExclusivePopup.prototype.postDraw.call(this);};popup.draw=function(){var self=this;var addButton=Html.input('button',{},$T("Add"));var cancelButton=Html.input('button',{},$T("Cancel"));cancelButton.dom.style.marginLeft=pixels(10);info.set('roomInfo',$O(roomInfo));roomEditor=new RoomBookingReservationWidget(Indico.Data.Locations,info.get('roomInfo'),parentRoomInfo,true,favoriteRooms,null,bookedRooms,timetable.parentTimetable?timetable.parentTimetable.getData():timetable.getData(),info);cancelButton.observeClick(function(){self.close();});addButton.observeClick(function(){submitInfo();});var convListWidget=new UserListField('VeryShortPeopleListDiv','PeopleList',null,true,null,true,false,null,null,true,true,true,userListNothing,userListNothing,userListNothing);$B(info.accessor('conveners'),convListWidget.getUsers());var sesType=new RadioFieldWidget([['standard',$T('Standard')],['poster',$T('Poster')]],'nobulletsListInline');$B(info.accessor('sessionType'),sesType);sesType.select('standard');var conferenceDays=bind.element(Html.select({name:'type'}),days,function(elem){var d=Util.formatDateTime(elem,IndicoDateTimeFormats.DefaultHourless,IndicoDateTimeFormats.Ordinal);return Html.option({value:elem},d);});conferenceDays.set(Util.formatDateTime(dayStartDate,IndicoDateTimeFormats.Ordinal,IndicoDateTimeFormats.ServerHourless));conferenceDays.observe(function(value){dateArgs.selectedDay=Util.formatDateTime(value,IndicoDateTimeFormats.ServerHourless,IndicoDateTimeFormats.Ordinal);indicoRequest(timeStartMethod,dateArgs,function(result,error){if(error){IndicoUtil.errorReport(error);}
else{var startDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);var endDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);var diffHours=dateArgs.endDate.getHours()-dateArgs.startDate.getHours();var diffMinutes=Math.abs(dateArgs.endDate.getMinutes()-dateArgs.startDate.getMinutes());if(startDate.getHours()>=23){startDate.setHours(23);startDate.setMinutes(0);endDate.setHours(23);endDate.setMinutes(59);}else{endDate.setHours(startDate.getHours()+diffHours);endDate.setMinutes(startDate.getMinutes()+diffMinutes);}
info.set('startDateTime',Util.formatDateTime(startDate,IndicoDateTimeFormats.Server));info.set('endDateTime',Util.formatDateTime(endDate,IndicoDateTimeFormats.Server));}});startEndTimeField.startTimeField.dispatchEvent('change');startEndTimeField.endTimeField.dispatchEvent('change');});var startEndTimeField=IndicoUI.Widgets.Generic.dateStartEndTimeField(info.get('startDateTime').substr(11,5),info.get('endDateTime').substr(11,5));var startEndTimeComponent;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);}};$B(info.accessor('startDateTime'),startEndTimeField.accessor.accessor('startTime'),timeTranslation);$B(info.accessor('endDateTime'),startEndTimeField.accessor.accessor('endTime'),timeTranslation);parameterManager.add(startEndTimeField.startTimeField,'time',false);parameterManager.add(startEndTimeField.endTimeField,'time',false);startEndTimeComponent=[$T('Time'),startEndTimeField.element];var colorPicker=new ColorPicker([],false);info.set('textColor',colorPicker.getTextColor());info.set('bgColor',colorPicker.getBgColor());colorPicker.observe(function(colors){info.set('textColor',colors.textColor);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=Html.div({},IndicoUtil.createFormFromMap([[$T('Title'),$B(parameterManager.add(Html.edit({style:{width:'300px'}}),'text',false),info.accessor('title'))],[$T('Description'),$B(Html.textarea({cols:40,rows:2}),info.accessor('description'))],[$T('Date'),conferenceDays],startEndTimeComponent,[$T('Place'),Html.div({style:{marginBottom:'15px'}},roomEditor.draw())],colorPickerComponent,[$T('Convener(s)'),convListWidget.draw()],[$T('Session type'),sesType.draw()]]));var buttonDiv=Html.div({},addButton,cancelButton);return this.ExclusivePopupWithButtons.prototype.draw.call(this,contentDiv,buttonDiv);};popup.open();}).run();},addSessionSlot:function(method,timeStartMethod,params,roomInfo,parentRoomInfo,confStartDate,dayStartDate,favoriteRooms,days,successFunc,editOn,bookedRooms,timetable){var parameterManager=new IndicoUtil.parameterManager();var isEdit=exists(editOn)?editOn:false;var args=isEdit?params:params.args;var dateArgs=clone(args);dateArgs.selectedDay=dayStartDate;var info=new WatchObject();var parentRoomData;previousDay=dateArgs.selectedDay;var killLoadProgress=IndicoUI.Dialogs.Util.progress($T("Loading dialog..."));IndicoUtil.waitLoad([isEdit?function(hook){dateArgs.startDate=new Date(dateArgs.startDate.date.substr(0,4),dateArgs.startDate.date.substr(5,2),dateArgs.startDate.date.substr(8,2),dateArgs.startDate.time.substr(0,2),dateArgs.startDate.time.substr(3,2),dateArgs.startDate.time.substr(6,2));dateArgs.endDate=new Date(dateArgs.endDate.date.substr(0,4),dateArgs.endDate.date.substr(5,2),dateArgs.endDate.date.substr(8,2),dateArgs.endDate.time.substr(0,2),dateArgs.endDate.time.substr(3,2),dateArgs.endDate.time.substr(6,2));hook.set(true);}:function(hook){indicoRequest(timeStartMethod,dateArgs,function(result,error){if(error){killLoadProgress();IndicoUtil.errorReport(error);}
else{var startDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);var endDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);if(startDate.getHours()>=23){startDate.setHours(23);startDate.setMinutes(0);endDate.setHours(23);endDate.setMinutes(59);}else{endDate.setHours(startDate.getHours()+1);}
dateArgs.startDate=startDate;dateArgs.endDate=endDate;info.set('startDateTime',Util.formatDateTime(startDate,IndicoDateTimeFormats.Server));info.set('endDateTime',Util.formatDateTime(endDate,IndicoDateTimeFormats.Server));hook.set(true);}});}],function(retVal){killLoadProgress();var submitInfo=function(){each(info,function(value,key){args[key]=value;});if(parameterManager.check()){var killProgress=IndicoUI.Dialogs.Util.progress();indicoRequest(method,args,function(result,error){killProgress();if(error){IndicoUtil.errorReport(error);}
else{popup.close();successFunc(result);}});}};var popup=new ExclusivePopupWithButtons(isEdit?$T('Edit session block'):$T('Add session block'),function(){popup.close();});var roomEditor;popup.postDraw=function(){roomEditor.postDraw();this.ExclusivePopupWithButtons.prototype.postDraw.call(this);};popup.draw=function(){var self=this;var addButton=Html.input('button',{},isEdit?$T("Save"):$T("Add"));var cancelButton=Html.input('button',{},$T("Cancel"));cancelButton.dom.style.marginLeft=pixels(10);if(isEdit){info.set('sessionTitle',params.title);info.set('startDateTime',IndicoUtil.formatDateTime(IndicoUtil.parseJsonDate(params.startDate)));info.set('endDateTime',IndicoUtil.formatDateTime(IndicoUtil.parseJsonDate(params.endDate)));info.set('title',params.slotTitle);info.set('scheduleEntry',params.scheduleEntryId);info.set('roomInfo',$O({"location":params.inheritLoc?null:params.location,"room":params.inheritRoom?null:params.room,"address":params.inheritLoc?'':params.address}));info.set("conveners",params.conveners);}
else{info.set("conveners",params.sessionConveners);info.set('roomInfo',$O({location:null,room:null}));}
if(timetable){roomEditor=new RoomBookingReservationWidget(Indico.Data.Locations,info.get('roomInfo'),parentRoomInfo,nullRoomInfo(info.get('roomInfo')),favoriteRooms,null,bookedRooms,timetable.parentTimetable?timetable.parentTimetable.getData():timetable.getData(),info,editOn?params.id:null);}else{roomEditor=new RoomBookingWidget(Indico.Data.Locations,info.get('roomInfo'),parentRoomInfo,nullRoomInfo(info.get('roomInfo')),favoriteRooms,null);}
cancelButton.observeClick(function(){self.close();});addButton.observeClick(function(){submitInfo();});var sessionRename=new SessionRenameWidget(info.get('sessionTitle'),parameterManager,this,info);var convListWidget=new UserListField('VeryShortPeopleListDiv','PeopleList',isEdit?params.conveners:params.sessionConveners,true,null,true,false,null,null,true,true,true,userListNothing,userListNothing,userListNothing);var conferenceDays=bind.element(Html.select({name:'type'}),days,function(elem){var d=Util.formatDateTime(elem,IndicoDateTimeFormats.DefaultHourless,IndicoDateTimeFormats.Ordinal);return Html.option({value:elem},d);});conferenceDays.set(Util.formatDateTime(dayStartDate,IndicoDateTimeFormats.Ordinal,IndicoDateTimeFormats.ServerHourless));conferenceDays.observe(function(value){dateArgs.selectedDay=Util.formatDateTime(value,IndicoDateTimeFormats.ServerHourless,IndicoDateTimeFormats.Ordinal);indicoRequest(timeStartMethod,dateArgs,function(result,error){if(error){IndicoUtil.errorReport(error);}
else{var startDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);var endDate=Util.parseJSDateTime(result,IndicoDateTimeFormats.Server);var diffHours=dateArgs.endDate.getHours()-dateArgs.startDate.getHours();var diffMinutes=Math.abs(dateArgs.endDate.getMinutes()-dateArgs.startDate.getMinutes());if(startDate.getHours()>=23){startDate.setHours(23);startDate.setMinutes(0);endDate.setHours(23);endDate.setMinutes(59);}else{endDate.setHours(startDate.getHours()+diffHours);endDate.setMinutes(startDate.getMinutes()+diffMinutes);}
info.set('startDateTime',Util.formatDateTime(startDate,IndicoDateTimeFormats.Server));info.set('endDateTime',Util.formatDateTime(endDate,IndicoDateTimeFormats.Server));}});startEndTimeField.startTimeField.dispatchEvent('change');startEndTimeField.endTimeField.dispatchEvent('change');});var timezoneMsg='';if(params.conference&&params.conference.timezone){timezoneMsg=' ('+$T('Timezone')+': '+params.conference.timezone+')';}
var startEndTimeField=IndicoUI.Widgets.Generic.dateStartEndTimeField(info.get('startDateTime').substr(11,5),info.get('endDateTime').substr(11,5),timezoneMsg);var startEndTimeComponent;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);}};$B(info.accessor('startDateTime'),startEndTimeField.accessor.accessor('startTime'),timeTranslation);$B(info.accessor('endDateTime'),startEndTimeField.accessor.accessor('endTime'),timeTranslation);parameterManager.add(startEndTimeField.startTimeField,'time',false);parameterManager.add(startEndTimeField.endTimeField,'time',false);startEndTimeComponent=[$T('Time'),startEndTimeField.element];sessionRenameComponent=isEdit?[$T('Session'),$T(Html.div({},sessionRename.draw()))]:[];$B(info.accessor('conveners'),convListWidget.getUsers());var content=IndicoUtil.createFormFromMap([sessionRenameComponent,isEdit?[$T('Sub-Title'),$B(Html.edit({style:{width:'300px'}}),info.accessor('title'))]:[],[$T('Date'),conferenceDays],startEndTimeComponent,[$T('Place'),Html.div({style:{marginBottom:'15px'}},roomEditor.draw())],[$T('Convener(s)'),convListWidget.draw()]]);var buttons=Html.div({},addButton,cancelButton);return this.ExclusivePopupWithButtons.prototype.draw.call(this,content,buttons);};popup.open();}).run();},addSubContribution:function(contribId,conferenceId){var args={conference:conferenceId};IndicoUtil.waitLoad([function(hook){var self=this;var source=indicoSource('user.favorites.listUsers',{});source.state.observe(function(state){if(state==SourceState.Loaded){favorites=$L(source);hook.set(true);}});}],function(retVal){var parameterManager=new IndicoUtil.parameterManager();var info=new WatchObject();var submitInfo=function(){info.set('conference',conferenceId);info.set('contribution',contribId);if(parameterManager.check()){var killProgress=IndicoUI.Dialogs.Util.progress();indicoRequest("contribution.addSubContribution",info,function(result,error){if(error){killProgress();IndicoUtil.errorReport(error);}else{window.location.reload(true);}});popup.close();}};var popup=new ExclusivePopup($T('Add Subcontribution'),function(){popup.close();});popup.draw=function(){var self=this;var addButton=Html.input('button',{},$T("Add"));var cancelButton=Html.input('button',{},$T("Cancel"));cancelButton.dom.style.marginLeft=pixels(10);cancelButton.observeClick(function(){self.close();});addButton.observeClick(function(){submitInfo();});var presListWidget=new UserListField('VeryShortPeopleListDiv','PeopleList',null,true,null,true,false,null,null,true,true,true,userListNothing,userListNothing,userListNothing);var keywordField=IndicoUI.Widgets.keywordList('oneLineListItem');$B(info.accessor('presenters'),presListWidget.getUsers());$B(info.accessor('keywords'),keywordField.accessor);return self.ExclusivePopup.prototype.draw.call(this,Widget.block([IndicoUtil.createFormFromMap([[$T('Title'),$B(parameterManager.add(Html.edit({style:{width:'300px'}}),'text',false),info.accessor('title'))],[$T('Description'),$B(Html.textarea({cols:40,rows:2}),info.accessor('description'))],[$T('Keywords'),keywordField.element],[$T('Duration (min) '),$B(parameterManager.add(IndicoUI.Widgets.Generic.durationField(),'int',false),info.accessor('duration'))],[$T('Presenter(s)'),presListWidget.draw()]]),Html.div({style:{marginTop:pixels(10),textAlign:'center',background:'#DDDDDD',padding:pixels(2)}},[addButton,cancelButton])]));};popup.open();}).run();},writeMinutes:function(confId,sessId,contId,subContId,compile){var changedText=new WatchValue(false);var wasChanged=false;var compileMinutes=exists(compile)?compile:false;var killProgress=null;var saveAndClose=false;var rtWidget=new ParsedRichTextEditor(700,400,'IndicoFull');var saveButton;var intToStr=function(id){if(IndicoUtil.isInteger(id)){return id+'';}else{return null;}};var popup=new ExclusivePopupWithButtons($T('My minutes'),function(){popup.closeMinutesPopup();});var closeMinutes=function(){popup.close();rtWidget.destroy();if(wasChanged){window.location.reload(true);}};var req=indicoSource('minutes.edit',{'confId':intToStr(confId),'sessionId':intToStr(sessId),'contribId':intToStr(contId),'subContId':intToStr(subContId),'compile':compileMinutes});req.state.observe(function(state){if(state==SourceState.Error){if(killProgress){killProgress();}
IndicoUtil.errorReport(req.error.get());}else if(state==SourceState.Loaded){rtWidget.set(req.get(),!req.get());rtWidget.observe(function(value){changedText.set(true);});if(killProgress){killProgress();changedText.set(false);wasChanged=true;saveButton.dom.disabled=true;if(saveAndClose){closeMinutes();}}}});changedText.observe(function(value){if(value){saveButton.dom.disabled=false;}});popup.draw=function(){var self=this;var content=Html.div({},rtWidget.draw());var commitChanges=function(){killProgress=IndicoUI.Dialogs.Util.progress($T('Saving...'));if(rtWidget.clean()){changedText.set(false);wasChanged=true;saveButton.dom.disabled=true;req.set(rtWidget.get());}
killProgress();};var commitChangesAndClose=function(){saveAndClose=true;commitChanges();};self.closeMinutesPopup=function(){var confirmation=function(confirmed){if(confirmed==1){commitChangesAndClose();}
else if(confirmed==2){closeMinutes();}};if(changedText.get()){var popupConfirm=new SaveConfirmPopup($T("Confirm"),Html.div({},Html.div({style:{paddingBottom:pixels(16)}},$T("You have modified your text since you last saved.")),Html.div({},$T("Do you want to save your changes?"))),confirmation);popupConfirm.open();}else{closeMinutes();}};saveButton=Widget.button(command(commitChanges,$T("Save")));saveButton.dom.disabled=!compileMinutes;return this.ExclusivePopupWithButtons.prototype.draw.call(this,content,Html.div({style:{marginTop:pixels(20)}},saveButton,Widget.button(command(self.closeMinutesPopup,$T("Close")))));};popup.open();},__addSessionSlot:function(slotId,sessionId,confId){var slot=undefined;indicoRequest("schedule.slot.getFossil",{"slotId":slotId,"confId":confId,"sessionId":sessionId},function(slot,error){if(!error){slot.sessionId=slot.session.id;slot.confId=slot.conference.id;slot.title=slot.session.title;slot.scheduleEntry=slot.sessionSlotId;var days=[];var stDay=Util.parseJSDateTime(slot.conference.startDate.date,'%Y-%m-%d');var eDay=Util.parseJSDateTime(slot.conference.endDate.date,'%Y-%m-%d');while(stDay<=eDay){days.push(IndicoUtil.formatDate2(stDay));stDay.setDate(stDay.getDate()+1);}
IndicoUI.Dialogs.addSessionSlot('schedule.session.editSlotById','schedule.event.getDayEndDate',slot,slot,$O(slot.session),slot.startDate,slot.startDate.date.replace(/-/g,"/"),[],days,function(){location.reload(true);},true,[],null)}});}});var IndicoUtil={findFormFields:function(){var formNodes=[];for(var i=0;i<arguments.length;i++){var xelement=arguments[i];var inputNodes=xelement.dom.getElementsByTagName("input");var selectNodes=xelement.dom.getElementsByTagName("select");var textAreaNodes=xelement.dom.getElementsByTagName("textArea");for(var j=0;j<inputNodes.length;j++){formNodes.push(inputNodes[j]);}
for(var j=0;j<selectNodes.length;j++){formNodes.push(selectNodes[j]);}
for(var j=0;j<textAreaNodes.length;j++){formNodes.push(textAreaNodes[j]);}}
return formNodes;},getFormValues:function(components,values){if(!exists(values)){values={};}else{each(values,function(value,key){delete values[key];});}
for(var i=0;i<components.length;i++){var component=components[i];if(isDom(component)){var node=component;if(exists(node.name)&&node.name){if(node.type=="checkbox"){if(!exists(values[node.name])){values[node.name]=[];}
if(node.checked){values[node.name].push(node.value);}}else if(node.type=="radio"){if(node.checked){values[node.name]=node.value;}}else{values[node.name]=node.value;}}}else{if(exists(component.get)&&exists(component.getName)){values[component.getName()]=component.get();}}}
return values;},setFormValues:function(components,values){for(var i=0;i<components.length;i++){var component=components[i];if(isDom(component)){var node=component;if(node.type=="checkbox"){if(node.name in values&&exists($L(values[node.name]).indexOf(node.value))){node.checked=true;}else{node.checked=false;}}else if(node.type=="radio"){if(node.name in values&&values[node.name]==node.value){node.checked=true;}else{node.checked=false;}}else{node.value=values[node.name];}}else{if(exists(component.set)&&exists(component.getName)){component.set(values[component.getName()]);}}}},enableDisableForm:function(containerElement,enableDisable){var nodesToDisable={button:'',input:'',optgroup:'',option:'',select:'',textarea:''};var node,nodes;nodes=containerElement.dom.getElementsByTagName('*');if(!nodes)return;var i=nodes.length;while(i--){node=nodes[i];if(node.nodeName&&node.nodeName.toLowerCase()in nodesToDisable){node.disabled=!enableDisable;}}},appender:function(func){function f(list){list.append(func.apply(this,Array.prototype.slice.call(arguments,1)));}
return f;},changeClassCss:function(cls,style){if(!document.styleSheets){return;}
if(document.styleSheets[0].cssRules){css=document.styleSheets[0].cssRules;}
else{css=document.styleSheets[0].rules;}
for(i=0;i<css.length;i++){if(css[i].selectorText.toLowerCase()==cls.toLowerCase()){css[i].style.cssText=style;}}},createFormFromMap:function(map,expand){expand=any(expand,false);var labelStyle={style:{textAlign:'right',verticalAlign:'top'}};var fieldStyle={style:{verticalAlign:'top'}};if(expand){labelStyle.style.whiteSpace="nowrap";fieldStyle.style.width="100%";}
var list=[];$L(map).each(function(item){if(item.length==2){list.push(Html.tr({style:{marginTop:'10px'}},Html.td(labelStyle,Html.label("popUpLabel",item[0])),Html.td(fieldStyle,Html.div('popUpTdContent',item[1]))));}else{list.push(Html.tr({style:{marginTop:'10px'}},Html.td(),Html.td(fieldStyle,item[0])));}});var tbody=Html.tbody();each(list,function(row){tbody.append(row);});return Html.table({},tbody);},formatDateTime:function(date,weekDayOption){if(!exists(weekDayOption)){weekDayOption=0;}
var dateText=zeropad(date.getDate())+'/'+zeropad(date.getMonth()+1)+'/'+date.getFullYear()+' '+zeropad(date.getHours())+':'+zeropad(date.getMinutes());switch(weekDayOption){case 1:return Indico.Data.WeekDays[date.getDay()]+" "+dateText;case 2:return Indico.Data.WeekDays[date.getDay()].substring(0,3)+" "+dateText;case 3:return dateText+" ("+Indico.Data.WeekDays[date.getDay()]+")";case 4:return dateText+" ("+Indico.Data.WeekDays[date.getDay()].substring(0,3)+")";default:return dateText;}},formatDate:function(date){return zeropad(date.getDate())+'/'+zeropad(date.getMonth()+1)+'/'+date.getFullYear();},formatDate2:function(date){return''+date.getFullYear()+zeropad(date.getMonth()+1)+zeropad(date.getDate());},formatJustTime:function(date){return zeropad(date.getHours())+':'+zeropad(date.getMinutes());},parseDateTime:function(strDateTime){strDateTime=strDateTime.split(' ');if(strDateTime.length!=2){return null;}
var sdatetime=new Date();var sdate=parseDate(strDateTime[0]);var stime=parseTime(strDateTime[1]);if(!sdate||!stime){return null;}
var sdatetime=new Date(sdate[2],sdate[1]-1,sdate[0]);setTime(sdatetime,stime);return sdatetime;},parseDate:function(strDate){var sdatetime=new Date();var sdate=parseDate(strDate);if(!sdate){return null;}
var sdatetime=new Date(sdate[2],sdate[1]-1,sdate[0]);setTime(sdatetime,[0,0,0,0]);return sdatetime;},formatJsonDate:function(jsonDate){return jsonDate.date+' at '+jsonDate.time.substring(0,5);},parseJsonDate:function(date){var year=parseInt(date.date.substr(0,4),10);var month=parseInt(date.date.substr(5,2),10);var day=parseInt(date.date.substr(8,2),10);var hour=parseInt(date.time.substr(0,2),10);var min=parseInt(date.time.substr(3,2),10);return new Date(year,month-1,day,hour,min);},cachedRpcValue:function(endPoint,method,attributes,cachedValue){if(exists(cachedValue)){var self;self=new WatchValue();self.set(cachedValue);self.observe(function(value){jsonRpcCommit(endPoint,method,attributes,value,function(result,error){if(exists(error)){IndicoUtil.errorReport(error);}else{if(exists(result.hasWarning)&&result.hasWarning===true){var popup=new WarningPopup(result.warning.title,result.warning.content);popup.open();}}});});return self;}else{return jsonRpcValue(endPoint,method,attributes);}},isInteger:function(s){var isEmpty=function(s){return(!exists(s)||(s.length===0));};var isDigit=function(c){return((c>="0")&&(c<="9"));};var i;if(isEmpty(s)){return false;}
for(i=0;i<s.length;i++){var c=s.charAt(i);if(!isDigit(c)){return false;}}
return true;},isTime:function(s){var regExp=new RegExp("(^([0-9]|[0-1][0-9]|[2][0-3]):([0-5][0-9])$)");return regExp.test(s);},parseShortURL:function(s){var regExp=new RegExp("[^A-Za-z0-9\._-]");return!regExp.test(s);},markInvalidField:function(component,error,passive){if(startsWith(component.dom.type,'select')){if(component.dom.className.slice(-13)!="invalidSelect"){component.dom.className+=' invalidSelect';}}else{if(component.dom.className.slice(-7)!="invalid"){component.dom.className+=' invalid';}}
var tooltip;var oList=[];var stopObserving=function(){each(oList,function(value){value();});};oList.push(function(){Dom.List.remove(document.body,tooltip);component.dom.className=component.dom.className.substring(0,component.dom.className.length-8);});oList.push(component.observeEvent('mouseover',function(event){tooltip=IndicoUI.Widgets.Generic.errorTooltip(event.clientX,event.clientY,error,"tooltipError");}));oList.push(component.observeEvent('mouseout',function(event){Dom.List.remove(document.body,tooltip);}));if(!passive){oList.push(component.observeEvent('keypress',function(event){stopObserving();}));oList.push(component.observeEvent('change',function(event){stopObserving();}));if(startsWith(component.dom.type,'select')){oList.push(component.observeEvent('click',function(event){stopObserving();}));}}
return[tooltip,oList];},parameterManager:function(){var entryList=new WatchList();var classList={};var eventList={};var radioButtonLabelStopObserving={};this.clear=function(){entryList=new WatchList();classList={};eventList={};};this.check=function(){var self=this;var hasErrors=false;entryList.each(function(value){var component=value[0];var dataType=value[1];var allowEmpty=value[2];var extraCheckFunction=value[3];var error=null;if(component.ErrorAware){component.setError(false);}else{component.dom.className=classList[component.dom.id];if(exists(eventList[component.dom.id])){$L(eventList[component.dom.id]).each(function(value){value();});delete eventList[component.dom.id];}}
if(dataType=="radio"){if(!allowEmpty&&!self.checkRadioButton(component)){error=Html.span({},"Please choose an option");}}
else if(dataType=='int'&&!(allowEmpty&&trim(component.get())==='')&&!IndicoUtil.isInteger(component.get())){error=Html.span({},"Field must be a number");}
else if(dataType=='int_pos_or_neg'&&!(allowEmpty&&trim(component.get())==='')&&!IndicoUtil.isInteger(component.get())){if(!(component.get()[0]=='-'&&IndicoUtil.isInteger(component.get().slice(1)))){error=Html.span({},"Field must be a number");}}
else if(dataType=='unsigned_int'&&!(allowEmpty&&trim(component.get())==='')&&(!IndicoUtil.isInteger(component.get())||component.get()<=0)){error=Html.span({},"Field must be a positive number");}
else if(dataType=='non_negative_int'&&!(allowEmpty&&trim(component.get())==='')&&(!IndicoUtil.isInteger(component.get())||component.get()<0)){error=Html.span({},"Field must be a positive number");}
else if(dataType=='datetime'&&!(allowEmpty&&trim(component.get())==='')&&!IndicoUtil.parseDateTime(component.get())){error=Html.span({},"Date format is not valid. It should be dd/mm/yyyy hh:mm");}
else if(dataType=='email'&&!(allowEmpty&&trim(component.get())==='')&&!Util.Validation.isEmailAddress(component.get())){error=Html.span({},"Invalid e-mail address");}
else if(dataType=='emaillist'&&!(allowEmpty&&trim(component.get())==='')&&!Util.Validation.isEmailList(component.get())){error=Html.span({},"List contains invalid e-mail address or invalid separator");}
else if(dataType=='url'&&!(allowEmpty&&trim(component.get())==='')&&!Util.Validation.isURL(component.get())){error=Html.span({},"Invalid URL");}
else if(dataType=='ip'&&!(allowEmpty&&trim(component.get())==='')&&!Util.Validation.isIPAddress(component.get())){error=Html.span({},"That doesn't seem like a valid IP Address. Example of valid IP Address: 132.156.31.38");}
else if(dataType=='time'&&!IndicoUtil.isTime(trim(component.get()))){error=Html.span({},"Time format is not valid. It should be hh:mm");}
else if(dataType=='shortURL'&&!IndicoUtil.parseShortURL(component.get())){error=Html.span({},"The short URL contains invalid characters. The allowed characters are alphanumeric, _, - and .");}
else if(exists(extraCheckFunction)){error=extraCheckFunction(component.get());}else if(!allowEmpty&&trim(component.get())===''){error=Html.span({},"Field is mandatory");}
if(exists(error)){hasErrors=true;var oList;if(component.ErrorAware){oList=component.setError(error);}else if(component.dom.type!='radio'){var result=IndicoUtil.markInvalidField(component,error);oList=result[1];}else{component.dom.className+=' invalid';$E(component.dom.id+'Label').dom.className+=' invalidLabel';var tooltip;oList=[];var stopObserving=component.observeEvent('mouseover',function(event){tooltip=IndicoUI.Widgets.Generic.errorTooltip(event.clientX,event.clientY,error,"tooltipError");});oList.push(stopObserving);var stopObservingLabel=$E(component.dom.id+'Label').observeEvent('mouseover',function(event){tooltip=IndicoUI.Widgets.Generic.errorTooltip(event.clientX,event.clientY,error,"tooltipError");});if(!exists(radioButtonLabelStopObserving[component.dom.name])){radioButtonLabelStopObserving[component.dom.name]=[]}
radioButtonLabelStopObserving[component.dom.name].push(stopObserving);radioButtonLabelStopObserving[component.dom.name].push(stopObservingLabel);oList.push(component.observeEvent('mouseout',function(event){Dom.List.remove(document.body,tooltip);}));$E(component.dom.id+'Label').observeEvent('mouseout',function(event){Dom.List.remove(document.body,tooltip);});each($N(component.dom.name),function(component){component.observeEvent('click',function(event){each($N(component.dom.name),function(component){component.dom.className=component.dom.className.substring(0,component.dom.className.length-8);$E(component.dom.id+'Label').dom.className=component.dom.className.substring(0,component.dom.className.length-13);});if(exists(radioButtonLabelStopObserving[component.dom.name])){each(radioButtonLabelStopObserving[component.dom.name],function(stopObserver){stopObserver()});}
Dom.List.remove(document.body,tooltip);});});}
if(!component.ErrorAware){eventList[component.dom.id]=oList;}}});return!hasErrors;};this.checkRadioButton=function(component){var name=component.dom.name;var radioButtonChecks=false;var radioButtons=$N(name);each(radioButtons,function(rb){if(rb.dom.checked){radioButtonChecks=true;}});return radioButtonChecks;};this.add=function(component,dataType,allowEmpty,extraCheckFunction){entryList.append([component,dataType,allowEmpty,extraCheckFunction]);if(!component.ErrorAware){if(!component.dom.id){component.dom.id=Html.generateId();}
classList[component.dom.id]=component.dom.className;}
return component;};this.remove=function(component){var removeEntry=null;each(entryList,function(entry){if(entry[0]==component){removeEntry=entry;}});if(removeEntry){entryList.remove(removeEntry);}};},waitLoad:function(preLoad,process){var counter=preLoad.length;var retVal=new WatchValue();var run=(counter===0)?curry(process,retVal):function(){$L(preLoad).each(function(value){var hook=new WatchValue();hook.set(false);hook.observe(function(value){if(value){bind.detach(hook);counter--;if(counter===0){process(retVal);}}});value(hook);});};return{'returnValue':retVal,'run':run};},detectTextFormat:function(text){if(/<.*>.*<\/.*>/.exec(text)){return"html";}else{return"plain";}},sortWatchList:function(watchList){var old=watchList.clear();var sortedItems=old.sort();watchList.appendMany(sortedItems);},onclickHandlerAdd:function(f){IndicoUtil.onclickFunctions.append(f);},onclickHandlerRemove:function(f){var idx=this.onclickFunctions.indexOf(f);this.onclickFunctions.replaceAt(idx,null);},onclickFunctions:new WatchList(),errorReport:IndicoUI.Dialogs.Util.error};function is_valid_int(s)
{var i=parseInt(s,10)
if(i.toString()=='NaN'||((i.toString()!=s)&&('0'+i.toString()!=s)))
return false
return true}
function is_valid_date(day,month,year)
{if(!is_valid_int(day)||!is_valid_int(month)||!is_valid_int(year))
return false
var dayl=parseInt(day,10);var monthl=parseInt(month,10)-1;var yearl=parseInt(year,10)
var dteDate=new Date(yearl,monthl,dayl)
if(dteDate.valueOf().toString()=='NaN')
return false
if((dayl!=dteDate.getDate())||(monthl!=dteDate.getMonth())||(yearl!=dteDate.getFullYear()))
return false
return true}
function is_valid_time(time)
{var TIME_PATTERN=/^(\d){1,2}\:(\d){1,2}$/;if((time).match(TIME_PATTERN)==null)
return false
var ix=time.indexOf(':')
var hour=time.substr(0,ix)
var minute=time.substr(ix+1,2)
var hour=parseInt(hour,10)
var minute=parseInt(minute,10)
if(hour<0||hour>23)
return false
if(minute<0||minute>59)
return false
return true}
function isBefore(sTime,eTime)
{var sDTime=new Date()
var eDTime=new Date()
var ix=sTime.indexOf(':')
var hour=sTime.substr(0,ix)
var minute=sTime.substr(ix+1,2)
var hour=parseInt(hour,10)
var minute=parseInt(minute,10)
sDTime.setHours(hour)
sDTime.setMinutes(minute)
sDTime.setSeconds(0)
ix=eTime.indexOf(':')
hour=eTime.substr(0,ix)
minute=eTime.substr(ix+1,2)
hour=parseInt(hour,10)
minute=parseInt(minute,10)
eDTime.setHours(hour)
eDTime.setMinutes(minute)
eDTime.setSeconds(0)
return sDTime.valueOf()<eDTime.valueOf()}
function required_fields(fieldNames)
{var isValid=true
for(i=0;i<fieldNames.length;++i)
{fieldName=fieldNames[i]
if(trim($F(fieldName)).length==0)
{$(fieldName).className='invalid'
isValid=false}}
return isValid}
function valid_email(emailString)
{return(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailString))}
function findPos(obj){var curleft=curtop=0;if(obj.offsetParent){curleft=obj.offsetLeft
curtop=obj.offsetTop
while(obj=obj.offsetParent){curleft+=obj.offsetLeft
curtop+=obj.offsetTop}}
return[curleft,curtop];}
function add_load_event(func){var oldonload=window.onload;if(typeof window.onload!='function'){window.onload=func;}else{window.onload=function(){if(oldonload){oldonload();}
func();}}}
function validate_period(f1,withRepeatability,allowPast,what)
{var DATES_AND_TIMES=0;var ONLY_DATES=1;var ONLY_TIMES=2;if(withRepeatability==null)withRepeatability=true;if(allowPast==null)allowPast=false;if(what==null)what=DATES_AND_TIMES;var isValid=true;if(what!=ONLY_TIMES)
{if(!is_valid_date($F('sDay'),$F('sMonth'),$F('sYear')))
{f1.sDay.className=f1.sMonth.className=f1.sYear.className=f1.sdate.className='invalid';isValid=false;}
if(!is_valid_date($F('eDay'),$F('eMonth'),$F('eYear')))
{f1.eDay.className=f1.eMonth.className=f1.eYear.className=f1.edate.className='invalid';isValid=false;}
var sDate=new Date(parseInt($F('sYear'),10),parseInt($F('sMonth'),10)-1,parseInt($F('sDay'),10));var eDate=new Date(parseInt($F('eYear'),10),parseInt($F('eMonth'),10)-1,parseInt($F('eDay'),10));if(isValid)
{todayDate=new Date();todayDate.setHours(0,0,0,0);if(!allowPast&&(sDate.valueOf()<(todayDate).valueOf()))
{f1.eDay.className=f1.eMonth.className=f1.eYear.className=f1.edate.className='invalid';f1.sDay.className=f1.sMonth.className=f1.sYear.className=f1.sdate.className='invalid';isValid=false;}}}
if(what!=ONLY_DATES)
{if(!is_valid_time($F('sTime')))
{f1.sTime.className='invalid';isValid=false}
if(!is_valid_time($F('eTime')))
{f1.eTime.className='invalid';isValid=false;}
if(!isBefore($F('sTime'),$F('eTime')))
{f1.sTime.className=f1.eTime.className='invalid';isValid=false;}}
if(withRepeatability){var ms_in_one_day=1000*60*60*24;var isRepeatabilityValid=true;switch($F('repeatability')){case"None":if(sDate.valueOf()!=eDate.valueOf()){isRepeatabilityValid=false;}
break;case"0":if(Math.floor((eDate.getTime()-sDate.getTime())/ms_in_one_day)<1)
{isRepeatabilityValid=false;}
break;case"1":if(Math.floor((eDate.getTime()-sDate.getTime())/ms_in_one_day)<7)
{isRepeatabilityValid=false;}
break;case"2":if(Math.floor((eDate.getTime()-sDate.getTime())/ms_in_one_day)<14)
{isRepeatabilityValid=false;}
break;case"3":if(Math.floor((eDate.getTime()-sDate.getTime())/ms_in_one_day)<21)
{isRepeatabilityValid=false;}
break;case"4":if(eDate.getFullYear()==sDate.getFullYear()&&(eDate.getMonth()<=sDate.getMonth()||(eDate.getMonth()-sDate.getMonth()==1&&eDate.getDate()<sDate.getDate())))
{isRepeatabilityValid=false;}
break;default:isRepeatabilityValid=false;break;}
if(!isRepeatabilityValid){f1.repeatability.className='invalid';f1.edate.className='invalid';isValid=false;}}
return isValid}
