(function(){Date.prototype.format=function(mask,utc){return strftime(mask,this);};})();;(function(){var DefaultLocale={days:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],months:['January','February','March','April','May','June','July','August','September','October','November','December'],shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],AM:'AM',PM:'PM',am:'am',pm:'pm',formats:{D:'%m/%d/%y',F:'%Y-%m-%d',R:'%H:%M',T:'%H:%M:%S',X:'%T',c:'%a %b %d %X %Y',r:'%I:%M:%S %p',v:'%e-%b-%Y',x:'%D'}},defaultStrftime=new Strftime(DefaultLocale,0,false),isCommonJS=typeof module!=='undefined',namespace;if(isCommonJS){namespace=module.exports=adaptedStrftime;namespace.strftime=deprecatedStrftime;}
else{namespace=(function(){return this||(1,eval)('this');}());namespace.strftime=adaptedStrftime;}
var _require=isCommonJS?"require('strftime')":"strftime";var _deprecationWarnings={};function deprecationWarning(name,instead){if(!_deprecationWarnings[name]){if(typeof console!=='undefined'&&typeof console.warn=='function'){console.warn("[WARNING] "+name+" is deprecated and will be removed in version 1.0. Instead, use `"+instead+"`.");}
_deprecationWarnings[name]=true;}}
namespace.strftimeTZ=deprecatedStrftimeTZ;namespace.strftimeUTC=deprecatedStrftimeUTC;namespace.localizedStrftime=deprecatedStrftimeLocalized;function adaptForwards(fn){fn.localize=defaultStrftime.localize.bind(defaultStrftime);fn.timezone=defaultStrftime.timezone.bind(defaultStrftime);fn.utc=defaultStrftime.utc.bind(defaultStrftime);}
adaptForwards(adaptedStrftime);function adaptedStrftime(fmt,d,locale){if(d&&d.days){locale=d;d=undefined;}
if(locale){deprecationWarning("`"+_require+"(format, [date], [locale])`","var s = "+_require+".localize(locale); s(format, [date])");}
var strftime=locale?defaultStrftime.localize(locale):defaultStrftime;return strftime(fmt,d);}
adaptForwards(deprecatedStrftime);function deprecatedStrftime(fmt,d,locale){if(locale){deprecationWarning("`"+_require+".strftime(format, [date], [locale])`","var s = "+_require+".localize(locale); s(format, [date])");}
else{deprecationWarning("`"+_require+".strftime(format, [date])`",_require+"(format, [date])");}
var strftime=locale?defaultStrftime.localize(locale):defaultStrftime;return strftime(fmt,d);}
function deprecatedStrftimeTZ(fmt,d,locale,timezone){if((typeof locale=='number'||typeof locale=='string')&&timezone==null){timezone=locale;locale=undefined;}
if(locale){deprecationWarning("`"+_require+".strftimeTZ(format, date, locale, tz)`","var s = "+_require+".localize(locale).timezone(tz); s(format, [date])` or `var s = "+_require+".localize(locale); s.timezone(tz)(format, [date])");}
else{deprecationWarning("`"+_require+".strftimeTZ(format, date, tz)`","var s = "+_require+".timezone(tz); s(format, [date])` or `"+_require+".timezone(tz)(format, [date])");}
var strftime=(locale?defaultStrftime.localize(locale):defaultStrftime).timezone(timezone);return strftime(fmt,d);};var utcStrftime=defaultStrftime.utc();function deprecatedStrftimeUTC(fmt,d,locale){if(locale){deprecationWarning("`"+_require+".strftimeUTC(format, date, locale)`","var s = "+_require+".localize(locale).utc(); s(format, [date])");}
else{deprecationWarning("`"+_require+".strftimeUTC(format, [date])`","var s = "+_require+".utc(); s(format, [date])");}
var strftime=locale?utcStrftime.localize(locale):utcStrftime;return strftime(fmt,d);};function deprecatedStrftimeLocalized(locale){deprecationWarning("`"+_require+".localizedStrftime(locale)`",_require+".localize(locale)");return defaultStrftime.localize(locale);};if(typeof Date.now!=='function'){Date.now=function(){return+new Date();};}
function Strftime(locale,customTimezoneOffset,useUtcTimezone){var _locale=locale||DefaultLocale,_customTimezoneOffset=customTimezoneOffset||0,_useUtcBasedDate=useUtcTimezone||false,_cachedDateTimestamp=0,_cachedDate;function _strftime(format,date){var timestamp;if(!date){var currentTimestamp=Date.now();if(currentTimestamp>_cachedDateTimestamp){_cachedDateTimestamp=currentTimestamp;_cachedDate=new Date(_cachedDateTimestamp);timestamp=_cachedDateTimestamp;if(_useUtcBasedDate){_cachedDate=new Date(_cachedDateTimestamp+getTimestampToUtcOffsetFor(_cachedDate)+_customTimezoneOffset);}}
date=_cachedDate;}
else{timestamp=date.getTime();if(_useUtcBasedDate){date=new Date(date.getTime()+getTimestampToUtcOffsetFor(date)+_customTimezoneOffset);}}
return _processFormat(format,date,_locale,timestamp);}
function _processFormat(format,date,locale,timestamp){var resultString='',padding=null,isInScope=false,length=format.length,extendedTZ=false;for(var i=0;i<length;i++){var currentCharCode=format.charCodeAt(i);if(isInScope===true){if(currentCharCode===45){padding='';continue;}
else if(currentCharCode===95){padding=' ';continue;}
else if(currentCharCode===48){padding='0';continue;}
else if(currentCharCode===58){extendedTZ=true;continue;}
switch(currentCharCode){case 65:resultString+=locale.days[date.getDay()];break;case 66:resultString+=locale.months[date.getMonth()];break;case 67:resultString+=padTill2(Math.floor(date.getFullYear()/100),padding);break;case 68:resultString+=_processFormat(locale.formats.D,date,locale,timestamp);break;case 70:resultString+=_processFormat(locale.formats.F,date,locale,timestamp);break;case 72:resultString+=padTill2(date.getHours(),padding);break;case 73:resultString+=padTill2(hours12(date.getHours()),padding);break;case 76:resultString+=padTill3(Math.floor(timestamp%1000));break;case 77:resultString+=padTill2(date.getMinutes(),padding);break;case 80:resultString+=date.getHours()<12?locale.am:locale.pm;break;case 82:resultString+=_processFormat(locale.formats.R,date,locale,timestamp);break;case 83:resultString+=padTill2(date.getSeconds(),padding);break;case 84:resultString+=_processFormat(locale.formats.T,date,locale,timestamp);break;case 85:resultString+=padTill2(weekNumber(date,'sunday'),padding);break;case 87:resultString+=padTill2(weekNumber(date,'monday'),padding);break;case 88:resultString+=_processFormat(locale.formats.X,date,locale,timestamp);break;case 89:resultString+=date.getFullYear();break;case 90:if(_useUtcBasedDate&&_customTimezoneOffset===0){resultString+="GMT";}
else{var tzString=date.toString().match(/\((\w+)\)/);resultString+=tzString&&tzString[1]||'';}
break;case 97:resultString+=locale.shortDays[date.getDay()];break;case 98:resultString+=locale.shortMonths[date.getMonth()];break;case 99:resultString+=_processFormat(locale.formats.c,date,locale,timestamp);break;case 100:resultString+=padTill2(date.getDate(),padding);break;case 101:resultString+=padTill2(date.getDate(),padding==null?' ':padding);break;case 104:resultString+=locale.shortMonths[date.getMonth()];break;case 106:var y=new Date(date.getFullYear(),0,1);var day=Math.ceil((date.getTime()-y.getTime())/(1000*60*60*24));resultString+=padTill3(day);break;case 107:resultString+=padTill2(date.getHours(),padding==null?' ':padding);break;case 108:resultString+=padTill2(hours12(date.getHours()),padding==null?' ':padding);break;case 109:resultString+=padTill2(date.getMonth()+1,padding);break;case 110:resultString+='\n';break;case 111:resultString+=String(date.getDate())+ordinal(date.getDate());break;case 112:resultString+=date.getHours()<12?locale.AM:locale.PM;break;case 114:resultString+=_processFormat(locale.formats.r,date,locale,timestamp);break;case 115:resultString+=Math.floor(timestamp/1000);break;case 116:resultString+='\t';break;case 117:var day=date.getDay();resultString+=day===0?7:day;break;case 118:resultString+=_processFormat(locale.formats.v,date,locale,timestamp);break;case 119:resultString+=date.getDay();break;case 120:resultString+=_processFormat(locale.formats.x,date,locale,timestamp);break;case 121:resultString+=(''+date.getFullYear()).slice(2);break;case 122:if(_useUtcBasedDate&&_customTimezoneOffset===0){resultString+=extendedTZ?"+00:00":"+0000";}
else{var off;if(_customTimezoneOffset!==0){off=_customTimezoneOffset/(60*1000);}
else{off=-date.getTimezoneOffset();}
var sign=off<0?'-':'+';var sep=extendedTZ?':':'';var hours=Math.floor(Math.abs(off/60));var mins=Math.abs(off%60);resultString+=sign+padTill2(hours)+sep+padTill2(mins);}
break;default:resultString+=format[i];break;}
padding=null;isInScope=false;continue;}
if(currentCharCode===37){isInScope=true;continue;}
resultString+=format[i];}
return resultString;}
var strftime=_strftime;strftime.localize=function(locale){return new Strftime(locale||_locale,_customTimezoneOffset,_useUtcBasedDate);};strftime.timezone=function(timezone){var customTimezoneOffset=_customTimezoneOffset;var useUtcBasedDate=_useUtcBasedDate;var timezoneType=typeof timezone;if(timezoneType==='number'||timezoneType==='string'){useUtcBasedDate=true;if(timezoneType==='string'){var sign=timezone[0]==='-'?-1:1,hours=parseInt(timezone.slice(1,3),10),minutes=parseInt(timezone.slice(3,5),10);customTimezoneOffset=sign*((60*hours)+minutes)*60*1000;}
else if(timezoneType==='number'){customTimezoneOffset=timezone*60*1000;}}
return new Strftime(_locale,customTimezoneOffset,useUtcBasedDate);};strftime.utc=function(){return new Strftime(_locale,_customTimezoneOffset,true);};return strftime;}
function padTill2(numberToPad,paddingChar){if(paddingChar===''||numberToPad>9){return numberToPad;}
if(paddingChar==null){paddingChar='0';}
return paddingChar+numberToPad;}
function padTill3(numberToPad){if(numberToPad>99){return numberToPad;}
if(numberToPad>9){return'0'+numberToPad;}
return'00'+numberToPad;}
function hours12(hour){if(hour===0){return 12;}
else if(hour>12){return hour-12;}
return hour;}
function weekNumber(date,firstWeekday){firstWeekday=firstWeekday||'sunday';var weekday=date.getDay();if(firstWeekday==='monday'){if(weekday===0)
weekday=6;else
weekday--;}
var firstDayOfYear=new Date(date.getFullYear(),0,1),yday=(date-firstDayOfYear)/86400000,weekNum=(yday+7-weekday)/7;return Math.floor(weekNum);}
function ordinal(number){var i=number%10;var ii=number%100;if((ii>=11&&ii<=13)||i===0||i>=4){return'th';}
switch(i){case 1:return'st';case 2:return'nd';case 3:return'rd';}}
function getTimestampToUtcOffsetFor(date){return(date.getTimezoneOffset()||0)*60000;}}());(function($){var defaults={id:undefined,size:'small',type:'inline'};$.extend({createSpinner:function(opts){if(opts!==undefined&&$.type(opts)!=='object'){opts={id:opts};}
opts=$.extend({},defaults,opts);var $spinner=$('<div>',{'class':'mw-spinner','title':'...'});if(opts.id!==undefined){$spinner.attr('id','mw-spinner-'+opts.id);}
$spinner.addClass(opts.size==='large'?'mw-spinner-large':'mw-spinner-small');$spinner.addClass(opts.type==='block'?'mw-spinner-block':'mw-spinner-inline');return $spinner;},removeSpinner:function(id){return $('#mw-spinner-'+id).remove();}});$.fn.injectSpinner=function(opts){return this.after($.createSpinner(opts));};}(jQuery));(function($,OO){var ifundef=function(val,then){if(val!==undefined&&val!==null){return val;}else{return then;}};OO.ui.instantiateFromParameters=function(config,fieldMap){var className=config['class'],error,widget;fieldMap=fieldMap||{};if(typeof OO.ui[className]==='undefined'){throw'Unable to load OO.ui.'+className;}
error=OO.ui.preprocessConfig(config,fieldMap);if(error){return error;}
if(className==='FieldLayout'){widget=config.fieldWidget;delete config.fieldWidget;widget=new OO.ui.FieldLayout(widget,config);}else{widget=new OO.ui[className](config);if(config.name!==undefined){fieldMap[config.name]=widget;}}
return widget;};OO.ui.preprocessConfig=function(config,fieldMap){var newItems,error=false;fieldMap=fieldMap||{};if(config.items){newItems=[];$.each(config.items,function(index,item){var newItem=OO.ui.instantiateFromParameters(item,fieldMap);if(newItem.$element){newItems.push(newItem);}else{error=newItem;}});config.items=newItems;}
if(config.fieldWidget){config.fieldWidget=OO.ui.instantiateFromParameters(config.fieldWidget,fieldMap);}
$.each(config,function(name,value){if(String(name).substr(0,1)==='$'){config[name]=$(value);}else if(typeof value==='object'&&$.isPlainObject(value)){OO.ui.preprocessConfig(value,fieldMap);}});if(error){return error;}};OO.ui.getWidgetValue=function(widget){switch(widget.constructor){case OO.ui.ActionWidget:case OO.ui.ButtonGroupWidget:case OO.ui.ButtonWidget:case OO.ui.DecoratedOptionWidget:case OO.ui.DropdownWidget:case OO.ui.IconWidget:case OO.ui.IndicatorWidget:case OO.ui.LabelWidget:case OO.ui.MenuOptionWidget:case OO.ui.MenuSelectOptionWidget:case OO.ui.OutlineControlsWidget:case OO.ui.OutlineOptionWidget:case OO.ui.OutlineSelectWidget:case OO.ui.PopupButtonWidget:case OO.ui.PopupWidget:case OO.ui.ProgressBarWidget:case OO.ui.RadioOptionWidget:return widget.getData();case OO.ui.ButtonOptionWidget:case OO.ui.CheckboxInputWidget:return widget.isSelected();case OO.ui.RadioSelectWidget:if(widget.getSelectedItem()){return widget.getSelectedItem().getData();}else{return null;}
break;case OO.ui.ButtonInputWidget:case OO.ui.DropdownInputWidget:case OO.ui.RadioInputWidget:return ifundef(widget.getData(),widget.getValue());case OO.ui.MenuSelectWidget:case OO.ui.ButtonSelectWidget:if(widget.getSelectedItem()){return widget.getSelectedItem().getData();}else{return null;}
break;case OO.ui.ComboboxInputWidget:if(widget.getMenu().getSelectedItem()){return widget.getMenu().getSelectedItem().getData();}else{return null;}
break;case OO.ui.SearchWidget:return widget.getQuery().getValue();case OO.ui.TextInputWidget:case OO.ui.ToggleButtonWidget:case OO.ui.ToggleSwitchWidget:return widget.getValue();default:if(widget.getData){return widget.getValue();}else{return null;}}};OO.ui.setWidgetValue=function(widget,value){switch(widget.constructor){case OO.ui.ActionWidget:case OO.ui.ButtonGroupWidget:case OO.ui.ButtonWidget:case OO.ui.DecoratedOptionWidget:case OO.ui.DropdownWidget:case OO.ui.IconWidget:case OO.ui.IndicatorWidget:case OO.ui.LabelWidget:case OO.ui.MenuOptionWidget:case OO.ui.MenuSelectOptionWidget:case OO.ui.OutlineControlsWidget:case OO.ui.OutlineOptionWidget:case OO.ui.OutlineSelectWidget:case OO.ui.PopupButtonWidget:case OO.ui.PopupWidget:case OO.ui.ProgressBarWidget:case OO.ui.RadioOptionWidget:widget.setData(value);break;case OO.ui.ButtonOptionWidget:case OO.ui.CheckboxInputWidget:widget.setSelected(value);break;case OO.ui.RadioSelectWidget:widget.selectItem(widget.getItemFromData(value));break;case OO.ui.ButtonInputWidget:case OO.ui.DropdownInputWidget:case OO.ui.RadioInputWidget:widget.setData(value);break;case OO.ui.MenuSelectWidget:case OO.ui.ButtonSelectWidget:widget.selectItem(widget.getItemFromData(value));break;case OO.ui.ComboboxInputWidget:widget.getMenu().selectItem(widget.getMenu().getItemFromData(value));break;case OO.ui.SearchWidget:widget.getQuery().setValue(value);break;case OO.ui.TextInputWidget:case OO.ui.ToggleButtonWidget:case OO.ui.ToggleSwitchWidget:widget.setValue(ifundef(value,""));break;default:if(widget.setValue){return widget.setValue(value);}else{return null;}}};})(jQuery,OO);(function($,OO){var html2text=function(html){return $("<div>").html(html).text();};OO.ui.SemanticOperationsSelector=function(opts){OO.ui.SemanticOperationsSelector.super.apply(this);var meaningsLabel=opts.meaningsLabel;var meanings=opts.meanings;this.objects=opts.objects;this.actions=opts.actions;this.$element=$("<div>").addClass("semantic-operations-selector");this.meaningSelector=new OO.ui.SemanticMeaningSelector({label:meaningsLabel,meanings:meanings});this.meaningSelector.on("add",this.handleSemanticMeaningAdd.bind(this));this.$element.append(this.meaningSelector.$element);this.semanticMap={};this.$workspace=$("<div>").addClass("workspace");this.$element.append(this.$workspace);};OO.inheritClass(OO.ui.SemanticOperationsSelector,OO.ui.Widget);OO.ui.SemanticOperationsSelector.prototype.getValue=function(){var valueMap={},sos,meaning;for(meaning in this.semanticMap){if(this.semanticMap.hasOwnProperty(meaning)){sos=this.semanticMap[meaning];valueMap[meaning]=sos.getValue();}}
return valueMap;};OO.ui.SemanticOperationsSelector.prototype.setValue=function(meanings){var meaningValue,meaning,sos;this.clear();for(meaningValue in meanings){if(meanings.hasOwnProperty(meaningValue)){meaning=this.meaningSelector.getDataFor(meaningValue);this.addMeaning(meaning,meanings[meaningValue]);}}};OO.ui.SemanticOperationsSelector.prototype.handleSemanticMeaningAdd=function(){this.addMeaning(this.meaningSelector.getSelected());};OO.ui.SemanticOperationsSelector.prototype.addMeaning=function(meaning,operations){operations=operations||[];if(!meaning){alert("No meaning selected");}else if(this.semanticMap[meaning.value]!==undefined){alert("Meaning "+meaning.label+" already selected");}else{var sos=new OO.ui.SyntacticOperationsSelector({meaning:meaning,objects:this.objects,actions:this.actions,operations:operations});this.semanticMap[meaning.value]=sos;this.$workspace.append(sos.$element);sos.on('close',this.handleCloseSelector.bind(this));}
this.meaningSelector.reset();};OO.ui.SemanticOperationsSelector.prototype.handleCloseSelector=function(sos){this.removeMeaning(sos);};OO.ui.SemanticOperationsSelector.prototype.removeMeaning=function(sos){sos.$element.remove();delete this.semanticMap[sos.meaning.value];};OO.ui.SemanticOperationsSelector.prototype.clear=function(){for(var meaningValue in this.semanticMap){if(this.semanticMap.hasOwnProperty(meaningValue)){this.removeMeaning(this.semanticMap[meaningValue]);}}
this.meaningSelector.reset();};OO.ui.SemanticMeaningSelector=function(opts){OO.ui.SemanticMeaningSelector.super.apply(this);var label=opts.label,meanings=opts.meanings,items=[];this.meaningData={};this.$element=$("<div>").addClass("semantic-meaning-selector");for(var i=0;i<meanings.length;i++){var meaning=meanings[i];var $label=$('<span>').attr('title',html2text(meaning.description));this.meaningData[meaning.value]=meaning;items.push(new OO.ui.MenuOptionWidget({data:meaning,$label:$label,label:meaning.label}));}
this.dropdown=new OO.ui.DropdownWidget({label:label,menu:{items:items},classes:['meanings']});this.$element.append(this.dropdown.$element);this.button=new OO.ui.ButtonWidget({flags:['constructive','primary'],icon:'add',classes:['add']});this.$element.append(this.button.$element);this.button.on('click',this.handleButtonClick.bind(this));};OO.inheritClass(OO.ui.SemanticMeaningSelector,OO.ui.Widget);OO.ui.SemanticMeaningSelector.prototype.handleButtonClick=function(){this.emit('add');};OO.ui.SemanticMeaningSelector.prototype.getSelected=function(){if(this.dropdown.getMenu().getSelectedItem()){return this.dropdown.getMenu().getSelectedItem().getData();}else{return null;}};OO.ui.SemanticMeaningSelector.prototype.getDataFor=function(meaningValue){return this.meaningData[meaningValue];};OO.ui.SemanticMeaningSelector.prototype.reset=function(){this.dropdown.getMenu().selectItem();};OO.ui.SyntacticOperationsSelector=function(opts){OO.ui.SyntacticOperationsSelector.super.apply(this);this.meaning=opts.meaning;var objects=opts.objects;var actions=opts.actions;var operations=opts.operations;this.operationMap={};this.$element=$("<div>").addClass("syntactic-operations-selector");this.closer=new OO.ui.ButtonWidget({icon:"remove",framed:false,flags:"destructive",classes:["closer"]});this.$element.append(this.closer.$element);this.closer.on('click',this.handleCloserClick.bind(this));this.$title=$("<div>").addClass("title").text(this.meaning.label);this.$element.append(this.$title);this.$description=$("<div>").addClass("description").html(this.meaning.description);this.$element.append(this.$description);this.operationSelector=new OO.ui.OperationSelector({objects:objects,actions:actions});this.operationSelector.on('add',this.handleOperationAdd.bind(this));this.$element.append(this.operationSelector.$element);this.$workspace=$("<div>").addClass("workspace");this.$element.append(this.$workspace);for(var i=0;i<operations.length;i++){var operationValue=operations[i];var operation=this.operationSelector.getDataFor(operationValue);this.addOperation(operation);}};OO.inheritClass(OO.ui.SyntacticOperationsSelector,OO.ui.Widget);OO.ui.SyntacticOperationsSelector.prototype.getValue=function(){var key,sop,values=[];for(key in this.operationMap){if(this.operationMap.hasOwnProperty(key)){sop=this.operationMap[key];values.push({object:sop.object.value,action:sop.action.value});}}
return values;};OO.ui.SyntacticOperationsSelector.prototype.clear=function(){var key,sop;for(key in this.operationMap){if(this.operationMap.hasOwnProperty(key)){sop=this.operationMap[key];sop.close();}}};OO.ui.SyntacticOperationsSelector.prototype.setValue=function(operations){var i,key,sop,operationValue,operation;for(i=0;i<operations.length;++i){operationValue=operations[i];operation=this.operationsSelector.getDataFor(operationValue);sop=new OO.ui.SyntacticOperation({object:operation.object,action:operation.action});this.operationMap[key]=sop;}};OO.ui.SyntacticOperationsSelector.prototype.handleOperationAdd=function(){var operation=this.operationSelector.getSelected();if(operation){this.addOperation(operation);}else{}};OO.ui.SyntacticOperationsSelector.prototype.addOperation=function(operation){if(!operation){return;}
var key=operation.object.value+"-"+operation.action.value;if(this.operationMap[key]===undefined){var sop=new OO.ui.SyntacticOperation({object:operation.object,action:operation.action});sop.on('close',this.handleObjectActionClose.bind(this));this.$workspace.append(sop.$element);this.operationMap[key]=sop;}else{alert("'"+key+"' has already been added.");}};OO.ui.SyntacticOperationsSelector.prototype.handleObjectActionClose=function(sop){var key=sop.object.value+"-"+sop.action.value;delete this.operationMap[key];};OO.ui.SyntacticOperationsSelector.prototype.handleCloserClick=function(){this.close();};OO.ui.SyntacticOperationsSelector.prototype.close=function(){this.$element.remove();this.emit('close',this);};OO.ui.OperationSelector=function(opts){OO.ui.OperationSelector.super.apply(this);var objects=opts.objects,actions=opts.actions,objectItems=[],actionItems=[];this.$element=$("<div>").addClass("object-action-selector");this.objectMap={};for(var i=0;i<objects.length;i++){var object=objects[i];var $objectLabel=$('<span>').attr('title',html2text(object.description));this.objectMap[object.value]=object;objectItems.push(new OO.ui.MenuOptionWidget({data:object,$label:$objectLabel,label:object.label}));}
this.objects=new OO.ui.DropdownWidget({label:"objects",menu:{items:objectItems},classes:['objects']});this.$element.append(this.objects.$element);this.actionMap={};for(var j=0;j<actions.length;j++){var action=actions[j];var $actionLabel=$('<span>').attr('title',html2text(action.description));this.actionMap[action.value]=action;actionItems.push(new OO.ui.MenuOptionWidget({data:action,$label:$actionLabel,label:action.label}));}
this.actions=new OO.ui.DropdownWidget({label:"actions",menu:{items:actionItems},classes:['actions']});this.$element.append(this.actions.$element);this.button=new OO.ui.ButtonWidget({icon:'add',flags:'constructive',classes:['add']});this.$element.append(this.button.$element);this.button.on('click',this.handleButtonClick.bind(this));};OO.inheritClass(OO.ui.OperationSelector,OO.ui.Widget);OO.ui.OperationSelector.prototype.handleButtonClick=function(){this.emit("add");};OO.ui.OperationSelector.prototype.getSelected=function(){if(!this.objects.getMenu().getSelectedItem()){alert("No object selected.");}else if(!this.actions.getMenu().getSelectedItem()){alert("No action selected.");}else{return{object:this.objects.getMenu().getSelectedItem().getData(),action:this.actions.getMenu().getSelectedItem().getData()};}};OO.ui.OperationSelector.prototype.getDataFor=function(operationValue){return{object:this.objectMap[operationValue.object],action:this.actionMap[operationValue.action]};};OO.ui.SyntacticOperation=function(opts){OO.ui.SyntacticOperation.super.apply(this);this.object=opts.object;this.action=opts.action;this.$element=$("<div>").addClass("object-action");this.$object=$("<div>").addClass("object").text(this.object.label);this.$element.append(this.$object);this.$action=$("<div>").addClass("action").text(this.action.label);this.$element.append(this.$action);this.closer=new OO.ui.ButtonWidget({icon:"remove",framed:false,flags:'destructive',classes:["closer"]});this.$element.append(this.closer.$element);this.closer.on('click',this.handleCloserClick.bind(this));};OO.inheritClass(OO.ui.SyntacticOperation,OO.ui.Widget);OO.ui.SyntacticOperation.prototype.close=function(){this.$element.remove();this.emit('close',this);};OO.ui.SyntacticOperation.prototype.handleCloserClick=function(){this.close();};})(jQuery,OO);(function($,OO){var html2text=function(html){return $("<div>").html(html).text();};var Workspace=function(opts){this.emptyMessage=opts.emptyMessage||"";this.$element=$("<div>").addClass("workspace");this.empty(true);};Workspace.prototype.empty=function(setEmpty){if(setEmpty===undefined){return this.$element.hasClass('empty');}else{if(setEmpty){this.$element.addClass('empty');this.$element.html(this.emptyMessage);this.items={};}else{this.$element.removeClass('empty');this.$element.html("");}}};Workspace.prototype.add=function(name,$subElement){if(this.empty()){this.empty(false);}
this.$element.append($subElement);this.items[name]=$subElement;};Workspace.prototype.remove=function(name){var $subElement=this.items[name];if(!$subElement){console.log("Sub element "+name+" not found -- can't be removed.");}else{$subElement.remove();delete this.items[name];if(Object.keys(this.items).length===0){this.empty(true);}}};OO.ui.SemanticsSelector=function(opts){OO.ui.SemanticsSelector.super.apply(this);var meaningsLabel=opts.meaningsLabel;var meanings=opts.meanings;var emptyMessage=opts.emptyMessage;this.$element=$("<div>").addClass("semantics-selector");this.meaningSelector=new OO.ui.SemanticMeaningSelector({label:meaningsLabel,meanings:meanings});this.meaningSelector.on("add",this.handleSemanticMeaningAdd.bind(this));this.$element.append(this.meaningSelector.$element);this.semanticMap={};this.workspace=new Workspace({emptyMessage:emptyMessage});this.$element.append(this.workspace.$element);};OO.inheritClass(OO.ui.SemanticsSelector,OO.ui.Widget);OO.ui.SemanticsSelector.prototype.getValue=function(){var valueList=[],meaning;for(meaning in this.semanticMap){if(this.semanticMap.hasOwnProperty(meaning)){valueList.push(meaning);}}
if(valueList.length>0){return valueList;}else{return null;}};OO.ui.SemanticsSelector.prototype.setValue=function(meanings){meanings=meanings||[];var meaningValue,sm;this.clear();for(var i=0;i<meanings.length;i++){sm=this.meaningSelector.getDataFor(meanings[i]);this.addMeaning(sm);}};OO.ui.SemanticsSelector.prototype.handleSemanticMeaningAdd=function(){this.addMeaning(this.meaningSelector.getSelected());};OO.ui.SemanticsSelector.prototype.addMeaning=function(meaning){if(!meaning){alert("No meaning selected");}else if(this.semanticMap[meaning.value]!==undefined){alert("Meaning "+meaning.label+" already selected");}else{var sm=new OO.ui.SemanticMeaning({meaning:meaning});this.semanticMap[meaning.value]=sm;this.workspace.add(meaning.value,sm.$element);sm.on('close',this.handleCloseSelector.bind(this));}
this.meaningSelector.reset();};OO.ui.SemanticsSelector.prototype.handleCloseSelector=function(sm){this.removeMeaning(sm);};OO.ui.SemanticsSelector.prototype.removeMeaning=function(sm){this.workspace.remove(sm.meaning.value);delete this.semanticMap[sm.meaning.value];};OO.ui.SemanticsSelector.prototype.clear=function(){for(var meaningValue in this.semanticMap){if(this.semanticMap.hasOwnProperty(meaningValue)){this.removeMeaning(this.semanticMap[meaningValue]);}}
this.meaningSelector.reset();};OO.ui.SemanticMeaningSelector=function(opts){OO.ui.SemanticMeaningSelector.super.apply(this);var label=opts.label,meanings=opts.meanings,items=[];this.meaningData={};this.$element=$("<div>").addClass("semantic-meaning-selector");for(var i=0;i<meanings.length;i++){var meaning=meanings[i];var $label=$('<span>').attr('title',html2text(meaning.description));this.meaningData[meaning.value]=meaning;items.push(new OO.ui.MenuOptionWidget({data:meaning,$label:$label,label:meaning.label}));}
this.dropdown=new OO.ui.DropdownWidget({label:label,menu:{items:items},classes:['meanings']});this.$element.append(this.dropdown.$element);this.button=new OO.ui.ButtonWidget({flags:['constructive','primary'],icon:'add',classes:['add']});this.$element.append(this.button.$element);this.button.on('click',this.handleButtonClick.bind(this));};OO.inheritClass(OO.ui.SemanticMeaningSelector,OO.ui.Widget);OO.ui.SemanticMeaningSelector.prototype.handleButtonClick=function(){this.emit('add');};OO.ui.SemanticMeaningSelector.prototype.getSelected=function(){if(this.dropdown.getMenu().getSelectedItem()){return this.dropdown.getMenu().getSelectedItem().getData();}else{return null;}};OO.ui.SemanticMeaningSelector.prototype.getDataFor=function(meaningValue){return this.meaningData[meaningValue];};OO.ui.SemanticMeaningSelector.prototype.reset=function(){this.dropdown.getMenu().selectItem();};OO.ui.SemanticMeaning=function(opts){OO.ui.SemanticMeaning.super.apply(this);this.meaning=opts.meaning;this.$element=$("<div>").addClass("semantic-meaning");this.closer=new OO.ui.ButtonWidget({icon:"remove",framed:false,flags:"destructive",classes:["closer"]});this.$element.append(this.closer.$element);this.closer.on('click',this.handleCloserClick.bind(this));this.$title=$("<div>").addClass("title").text(this.meaning.label);this.$element.append(this.$title);this.$description=$("<div>").addClass("description").html(this.meaning.description);this.$element.append(this.$description);};OO.inheritClass(OO.ui.SemanticMeaning,OO.ui.Widget);OO.ui.SemanticMeaning.prototype.handleCloserClick=function(){this.close();};OO.ui.SemanticMeaning.prototype.close=function(){this.$element.remove();this.emit('close',this);};})(jQuery,OO);(function($){if(window.wikiLabels){throw"wikiLabels is already defined!  Exiting.";}
window.wikiLabels={config:{serverRoot:"",prefix:"wikilabels-"}};})(jQuery);(function($,WL){WL.util={applyTranslation:function(value,lookup){var str,arr,transArray,i,obj,transObj,key;if(typeof value==='string'){str=value;if(str.charAt(0)==='<'&&str.charAt(str.length-1)==='>'){return lookup(str.substr(1,str.length-2));}else{return str;}}else if($.isArray(value)){arr=value;transArray=[];for(i in arr){if(arr.hasOwnProperty(i)){transArray.push(WL.util.applyTranslation(arr[i],lookup));}}
return transArray;}else if(typeof value==='object'){obj=value;transObj={};for(key in obj){if(obj.hasOwnProperty(key)){transObj[key]=WL.util.applyTranslation(obj[key],lookup);}}
return transObj;}else{return value;}},oneOrMany:function(val){if($.isArray(val)){return val;}else{return[val];}},linkToTitle:function(title,label){var url=WL.mediawiki.urlToTitle(title);return $("<a>").attr('href',url).text(label||title);},linkToDiff:function(revId,label){var url=WL.mediawiki.urlToDiff(revId);return $("<a>").attr('target','_blank').attr('href',url).text(label||revId);},pathJoin:function(){var args=Array.prototype.slice.call(arguments);var parts=[];for(var i=0,l=args.length;i<l;i++){parts=parts.concat(String(args[i]).split("/"));}
var newParts=[];for(i=0,l=parts.length;i<l;i++){var part=parts[i];if(!part||part===".")continue;if(part==="..")newParts.pop();else newParts.push(part);}
if(parts[0]==="")newParts.unshift("");return newParts.join("/")||(newParts.length?"/":".");}};})(jQuery,wikiLabels);(function($,WL){var API=function(){};API.prototype.request=function(data){data['format']="json";var deferred=$.Deferred(),ajaxPromise=$.ajax("//"+WL.mediawiki.host+"/w/api.php",{dataType:"jsonp",data:data});ajaxPromise.done(function(doc,status,jqXHR){if(!doc.error){if(doc.warnings){console.warn(doc.warnings);}
deferred.resolve(doc);}else{console.error(doc.error);deferred.reject(doc.error);}}.bind(this));ajaxPromise.fail(function(jqXHR,status,err){var errorData={code:status,message:err};console.error(errorData);deferred.reject(errorData);}.bind(this));return deferred.promise();};API.prototype.getRevision=function(revId,params){var defaultParams={action:"query",prop:"revisions",revids:revId},deferred=$.Deferred();this.request($.extend(defaultParams,params||{})).done(function(doc){var id,page,includePage,i,rev;try{if(doc.query.badrevids){deferred.reject({code:"revision not found",message:WL.i18n('Could not get metadata for revision $1',[revId])});return;}
for(id in doc.query.pages){if(doc.query.pages.hasOwnProperty(id)){page=doc.query.pages[id];}}
includePage=$.extend({},page);delete includePage['revisions'];for(i=0;i<page.revisions.length;i++){rev=page.revisions[i];rev['page']=includePage;deferred.resolve(rev);}}catch(err){deferred.reject({code:"api error",message:WL.i18n("Could not parse MediaWiki API's response")+': '+err});}}.bind(this)).fail(function(doc){deferred.reject(doc);}.bind(this));return deferred.promise();};API.prototype.diffTo=function(revId,diffToId){var tableRows,deferred=$.Deferred();this.getRevision(diffToId,{'rvdiffto':revId}).done(function(doc){if(doc['diff']){tableRows=doc['diff']['*'];}else{tableRows="";}
deferred.resolve(tableRows);}.bind(this)).fail(function(doc){deferred.fail(doc);}.bind(this));return deferred.promise();};API.prototype.diffToPrevious=function(revId){var deferred=$.Deferred();this.getRevision(revId,{rvprop:"ids|parsedcomment"}).done(function(rev){if(rev.parentid){this.diffTo(revId,rev.parentid).done(function(tableRows){deferred.resolve({revId:rev.revid,title:rev.page.title,comment:rev.parsedcomment||"",tableRows:tableRows});}.bind(this)).fail(function(doc){deferred.reject(doc);}.bind(this));}else{this.getRevision(revId,{rvprop:"content"}).done(function(contentRev){deferred.resolve({revId:rev.revid,title:rev.page.title,tableRows:API.creationDiff(contentRev['*'])});}.bind(this)).fail(function(doc){deferred.reject(doc);});}}.bind(this)).fail(function(doc){deferred.reject(doc);}.bind(this));return deferred.promise();};API.creationDiff=function(content){return'<tr>\n'+
'<td colspan="2" class="diff-lineno">Line 1:</td>\n'+
'<td colspan="2" class="diff-lineno">Line 1:</td>\n'+
'</tr>\n'+
'<tr>\n'+
'<td colspan="2" class="diff-empty">&#160;</td>\n'+
'<td class="diff-marker">+</td>\n'+
'<td class="diff-addedline"><div>'+content+'</div></td>'+
'</tr>';};API.prototype.wikitext2HTML=function(wikitext,title){title=title||'CURRENT PAGE';var params={action:"parse",prop:"text",title:title,text:wikitext.substring(0,4000),contentmode:"wikitext"},deferred=$.Deferred();this.request(params).done(function(doc){deferred.resolve(doc['parse']['text']['*']);}.bind(this)).fail(function(doc){deferred.reject(doc);}.bind(this));return deferred.promise();};API.prototype.getSiteInfo=function(){var params={action:"query",meta:"siteinfo",siprop:"general",formatversion:2},deferred=$.Deferred();this.request(params).done(function(doc){deferred.resolve(doc.query.general);}.bind(this)).fail(function(doc){deferred.reject(doc);}.bind(this));return deferred.promise();}
wikiLabels.api=new API();})(jQuery,wikiLabels);(function($,WL){var Config=function(obj){Config.prototype.update.call(this,obj);};Config.prototype.update=function(update){$.extend(this,update,true);};WL.config=new Config(WL.config||{});}(jQuery,wikiLabels));(function($,OO,WL){var Form=function(fieldset,fieldMap){this.fieldMap=fieldMap;this.$element=$('<div>').addClass(WL.config.prefix+'form');this.$fieldset=$('<div>').addClass('fieldset');this.$element.append(this.$fieldset);this.$fieldset.append(fieldset.$element);this.$controls=$('<div>').addClass('controls');this.$element.append(this.$controls);this.abandonButton=new OO.ui.ButtonWidget({label:WL.i18n('Abandon'),align:'inline',classes:['abandon'],flags:['primary','destructive']});this.$controls.append(this.abandonButton.$element);this.abandonButton.on('click',this.handleAbandonClick.bind(this,this.abandonButton.$element));this.abandoned=$.Callbacks();this.submitButton=new OO.ui.ButtonWidget({label:WL.i18n('Save'),align:'inline',classes:['save'],flags:['primary','progressive']});this.$controls.append(this.submitButton.$element);this.submitButton.on('click',this.handleSubmitClick.bind(this,this.submitButton.$element));this.submitted=$.Callbacks();};Form.prototype.handleSubmitClick=function(button){$(button).injectSpinner(WL.config.prefix+'submit-spinner');this.submit();};Form.prototype.handleAbandonClick=function(button){var confirmed=confirm(WL.i18n('Are you sure that you want to abandon this task?'));if(!confirmed){return;}
$(button).injectSpinner(WL.config.prefix+'abandon-spinner');this.abandon();};Form.prototype.getValues=function(){var name,valueMap={};for(name in this.fieldMap){if(this.fieldMap.hasOwnProperty(name)){valueMap[name]=OO.ui.getWidgetValue(this.fieldMap[name]);}}
return valueMap;};Form.prototype.setValues=function(valueMap){var name;valueMap=valueMap||{};for(name in this.fieldMap){if(this.fieldMap.hasOwnProperty(name)){OO.ui.setWidgetValue(this.fieldMap[name],valueMap[name]);}}
return valueMap;};Form.prototype.clear=function(){this.setValues(null);};Form.prototype.hide=function(){this.$element.hide();};Form.prototype.show=function(){this.$element.show();};Form.prototype.submit=function(){var fieldName,labelData=this.getValues();for(fieldName in labelData){if(labelData.hasOwnProperty(fieldName)&&labelData[fieldName]===null){if(!confirm(WL.i18n("'$1' not completed.  Submit anyway?",[fieldName]))){return;}}}
this.submitted.fire(labelData);};Form.prototype.abandon=function(){this.abandoned.fire();};Form.fromConfig=function(config,langChain){var i,fieldset,fieldDoc,field,fieldMap,i18n=function(key){var i,lang;langChain=WL.util.oneOrMany(langChain);for(i=0;i<langChain.length;i++){lang=langChain[i];if(config.i18n&&config.i18n[lang]&&config.i18n[lang][key]){return config.i18n[lang][key];}}
return"<"+key+">";};fieldset=new OO.ui.FieldsetLayout({});fieldMap={};for(i in config.fields){if(config.fields.hasOwnProperty(i)){fieldDoc=WL.util.applyTranslation(config.fields[i],i18n);field=OO.ui.instantiateFromParameters(fieldDoc,fieldMap);fieldset.addItems([field]);}}
return new Form(fieldset,fieldMap);};WL.Form=Form;})(jQuery,OO,wikiLabels);(function($,OO,WL){var Labeler=function($element){if($element===undefined||$element.length===0){throw"$element must be a defined element";}
if(WL.Labeler.instances){for(var i=0;i<WL.Labeler.instances.length;i++){var instance=WL.Labeler.instances[i];if(instance.$element.is($html_element)){throw"Labeler is already loaded on top of "+$element.attr('id');}}}
this.$element=$element;WL.Labeler.instances.push(this)
this.$menu=$("#"+WL.config.prefix+"labeler > .wikilabels-menu");if(this.$menu===undefined||this.$menu.length!==1){throw"#"+WL.config.prefix+"labeler > .wikilabels-menu must be a single defined element";}
this.campaignList=new CampaignList();this.campaignList.worksetActivated.add(this.handleWorksetActivation.bind(this));this.connector=new Connector();this.workspace=new WL.Workspace(this.$element.find(".wikilabels-workspace"));this.$element.append(this.workspace.$element);this.workspace.labelSaved.add(this.handleLabelSaved.bind(this));this.workspace.newWorksetRequested.add(this.handleNewWorksetRequested.bind(this));WL.user.updateStatus();WL.user.statusChanged.add(this.handleUserStatusChange.bind(this));this.handleUserStatusChange();};Labeler.instances=[];Labeler.prototype.handleUserStatusChange=function(){if(WL.user.authenticated()){this.campaignList.load();this.$menu.empty();this.$menu.append(this.campaignList.$element);}else{this.$menu.empty();this.$menu.append(this.connector.$element);}};Labeler.prototype.handleWorksetActivation=function(campaign,workset){this.campaignList.selectWorkset(workset);this.workspace.loadWorkset(campaign.id,workset.id);};Labeler.prototype.handleLabelSaved=function(campaignId,worksetId,tasks,labels){var campaign,workset;campaign=this.campaignList.get(campaignId);workset=campaign.worksetList.get(worksetId);workset.updateProgress(tasks,labels);campaign.updateButtonState();};Labeler.prototype.handleNewWorksetRequested=function(){var campaign=this.campaignList.get(this.workspace.campaignId);campaign.assignNewWorkset();};var Connector=function(){this.$element=$("<div>").addClass("connector");this.button=new OO.ui.ButtonWidget({label:WL.i18n("connect to server"),flags:["progressive"]});this.$element.append(this.button.$element);this.button.on('click',this.handleButtonClick.bind(this));};Connector.prototype.handleButtonClick=function(e){WL.user.initiateOAuth();};var CampaignList=function(){this.$element=$("<div>").addClass("campaign-list");this.$header=$("<h2>").text(WL.i18n("Campaigns"));this.$element.append(this.$header);this.$container=$("<div>").addClass("container");this.$element.append(this.$container);this.campaigns={};this.selectedWorkset=null;this.worksetActivated=$.Callbacks();};CampaignList.prototype.handleWorksetActivation=function(campaign,workset){this.worksetActivated.fire(campaign,workset);};CampaignList.prototype.get=function(campaignId){return this.campaigns[campaignId];};CampaignList.prototype.clear=function(){this.$container.empty();this.campaigns={};};CampaignList.prototype.load=function(){var query;if(!WL.user.authenticated()){throw"Cannot load campaign list when user is not authenticated.";}
this.clear();query=WL.server.getCampaigns();query.done(function(doc){var i,campaign;for(i=0;i<doc['campaigns'].length;i++){campaign=new Campaign(doc['campaigns'][i]);this.push(campaign);}}.bind(this));query.fail(function(doc){this.$element.html(doc.code+":"+doc.message);}.bind(this));};CampaignList.prototype.push=function(campaign){this.campaigns[campaign.id]=campaign;this.$container.append(campaign.$element);campaign.worksetActivated.add(this.handleWorksetActivation.bind(this));};CampaignList.prototype.selectWorkset=function(workset){if(this.selectedWorkset){this.selectedWorkset.select(false);}
this.selectedWorkset=workset;if(this.selectedWorkset){this.selectedWorkset.select(true);}};var Campaign=function(campaignData){this.$element=$("<div>").addClass("campaign");this.expander=new OO.ui.ToggleButtonWidget({label:"+",value:false,classes:["expander"]});this.$element.append(this.expander.$element);this.expander.on('change',this.handleExpanderChange.bind(this));this.$name=$("<div>").addClass("name");this.$element.append(this.$name);this.worksetList=new WorksetList();this.$element.append(this.worksetList.$element);this.worksetList.worksetActivated.add(this.handleWorksetActivation.bind(this));this.$controls=$("<div>").addClass("controls");this.$element.append(this.$controls);this.newButton=new OO.ui.ButtonWidget({label:WL.i18n("request workset")});this.$controls.append(this.newButton.$element);this.newButton.on('click',this.handleNewButtonClick.bind(this));this.expanded=$.Callbacks();this.worksetActivated=$.Callbacks();this.load(campaignData);};Campaign.prototype.handleExpanderChange=function(expanded){this.expand(expanded);};Campaign.prototype.handleNewButtonClick=function(e){this.assignNewWorkset();};Campaign.prototype.handleWorksetActivation=function(workset){this.worksetActivated.fire(this,workset);};Campaign.prototype.assignNewWorkset=function(){WL.server.assignWorkset(this.id).done(function(doc){var workset=new Workset(doc['workset']);this.worksetList.push(workset);this.worksetActivated.fire(this,workset);}.bind(this)).fail(function(doc){alert(doc.code+": "+doc.message);}.bind(this));};Campaign.prototype.updateButtonState=function(){if(this.worksetList.complete()){this.newButton.setDisabled(false);}else{this.newButton.setDisabled(true);}};Campaign.prototype.load=function(campaignData){var query;this.id=campaignData['id'];this.$name.text(campaignData['name']);WL.server.getUserWorksetList(WL.user.id,campaignData['id']).done(function(doc){var i,workset;this.worksetList.clear();for(i=0;i<doc['worksets'].length;i++){workset=new Workset(doc['worksets'][i]);this.worksetList.push(workset);}
this.updateButtonState();}.bind(this)).fail(function(doc){alert(WL.i18n("Could not load workset list: $1",[JSON.stringify(doc)]));}.bind(this));};Campaign.prototype.expand=function(expanded){if(expanded===undefined){return this.$element.hasClass("expanded");}else if(expanded){this.$element.addClass("expanded");this.expander.setLabel("-");this.expanded.fire(expanded);return this;}else{this.$element.removeClass("expanded");this.expander.setLabel("+");return this;}};var WorksetList=function(){this.$element=$("<div>").addClass("workset-list");this.$container=$("<div>").addClass("container");this.$element.append(this.$container);this.worksets={};this.worksetActivated=$.Callbacks();};WorksetList.prototype.handleWorksetActivation=function(workset){this.worksetActivated.fire(workset);};WorksetList.prototype.push=function(workset){this.$container.append(workset.$element);this.worksets[workset.id]=workset;workset.activated.add(this.handleWorksetActivation.bind(this));};WorksetList.prototype.get=function(worksetId){return this.worksets[worksetId];};WorksetList.prototype.clear=function(){this.$container.empty();this.worksets={};};WorksetList.prototype.complete=function(){var key,workset;for(key in this.worksets){if(this.worksets.hasOwnProperty(key)){workset=this.worksets[key];if(!workset.completed){return false;}}}
return true;};var Workset=function(worksetData){this.$element=$("<div>").addClass("workset");this.$element.click(this.handleClick.bind(this));this.$controls=$("<div>").addClass("controls");this.$element.append(this.$controls);this.openButton=new OO.ui.ButtonWidget({label:WL.i18n("open"),classes:['button','open'],flags:['constructive']});this.openButton.on('click',this.handleButtonClick.bind(this));this.reviewButton=new OO.ui.ButtonWidget({label:WL.i18n("review"),classes:['button','review'],flags:['constructive'],framed:false});this.reviewButton.on('click',this.handleButtonClick.bind(this));this.progressContent=$("<span>");this.progress=new OO.ui.ProgressBarWidget({progress:0,content:[this.progressContent],classes:['progress']});this.$element.append(this.progress.$element);this.completed=false;this.activated=$.Callbacks();this.load(worksetData);};Workset.prototype.handleClick=function(e){this.activated.fire(this);};Workset.prototype.handleButtonClick=function(e){this.activated.fire(this);};Workset.prototype.load=function(worksetData){this.id=worksetData['id'];this.campaignId=worksetData['campaign_id'];this.created=worksetData['created'];this.updateProgress(worksetData.stats.tasks,worksetData.stats.labeled);};Workset.prototype.updateProgress=function(tasks,labeled){var percent=((labeled/tasks)||0)*100;this.completed=labeled===tasks;if(this.completed){this.$controls.html(this.reviewButton.$element);}else{this.$controls.html(this.openButton.$element);}
this.progress.setProgress(percent);this.progressContent.text(this.formatProgress(tasks,labeled));};Workset.prototype.formatProgress=function(tasks,labeled){return(new Date(this.created*1000)).format(WL.i18n("date-format"))+"  "+
"("+String(labeled)+"/"+String(tasks)+")";};Workset.prototype.select=function(selected){if(selected===undefined){return this.$element.hasClass("selected");}else if(selected){this.$element.addClass("selected");return this;}else{this.$element.removeClass("selected");return this;}};WL.Labeler=Labeler;})(jQuery,OO,wikiLabels);(function($,WL){var Home=function(host){WL.user.updateStatus().done(function(){WL.mediawiki.initialize(host).done(function(){$('html').attr('lang',wikiLabels.mediawiki.lang);$('#mw-content-text').attr('lang',wikiLabels.mediawiki.lang);if(wikiLabels.mediawiki.rtl){$('html').attr('dir','rtl');$('#mw-content-text').attr('dir','rtl');$('#mw-content-text').addClass('mw-content-rtl');}else{$('html').attr('dir','ltr');$('#mw-content-text').attr('dir','ltr');$('#mw-content-text').addClass('mw-content-ltr');}
wikiLabels.labeler=new wikiLabels.Labeler($('#wikilabels-labeler'));}).fail(function(doc){alert(JSON.stringify(doc));});}).fail(function(){window.location=WL.server.absPath("auth","initiate");});}
WL.Home=Home;})(jQuery,wikiLabels);(function(WL){var format=function(str,args){return str.replace(/\$[0-9]+/,function(m){return args[parseInt(m.substring(1),10)-1]||m;});};var i18n=function(key,args){for(i=0;i<WL.mediawiki.fallbackChain.length;i++){lang=WL.mediawiki.fallbackChain[i];if(WL.config.messages[lang]&&WL.config.messages[lang][key]){return format(WL.config.messages[lang][key],args);}}
return"<"+format(key,args)+">";};WL.i18n=i18n;})(wikiLabels);(function($,WL){var Server=function(){};Server.prototype.request=function(relPath,data,method){var deferred=$.Deferred();method=method||"GET";$.ajax(this.absPath.apply(this,relPath),{dataType:"json",method:method,jsonp:false,crossDomain:true,xhrFields:{withCredentials:true},data:data||{}}).done(function(doc,status,jqXHR){if(!doc.error){deferred.resolve(doc);}else{console.error(doc.error);deferred.reject(doc.error);}}.bind(this)).fail(function(jqXHR,status,err){try{var errorMessage=$.parseJSON(jqXHR.responseText).error.message;}
catch(parseError){var errorMessage="Unable to parse response";}
var errorData={code:jqXHR.status,status:status,message:errorMessage};console.error(errorData);deferred.reject(errorData);}.bind(this));return deferred.promise();};Server.prototype.absPath=function(){var serverRoot=WL.config.serverRoot,relPath=WL.util.pathJoin.apply(this,Array.prototype.slice.call(arguments));return serverRoot.replace(/\/+$/g,"")+"/"+relPath.replace(/^\/+/g,"")+"/";};Server.prototype.getCampaigns=function(){return this.request(["campaigns",WL.mediawiki.dbname]);};Server.prototype.whoami=function(){return this.request(["auth","whoami"]);};Server.prototype.getUserWorksetList=function(userId,campaignId){return this.request(["users",userId,campaignId],{worksets:"stats"});};Server.prototype.assignWorkset=function(campaignId){return this.request(["campaigns",WL.mediawiki.dbname,campaignId],{workset:"stats"},"POST");};Server.prototype.getWorkset=function(campaignId,worksetId){return this.request(["campaigns",WL.mediawiki.dbname,campaignId,worksetId],{tasks:"",campaign:""});};Server.prototype.getForm=function(formName){return this.request(["forms",formName]);};Server.prototype.saveLabel=function(campaignId,worksetId,taskId,labelData){return this.request(["campaigns",WL.mediawiki.dbname,campaignId,worksetId,taskId],{label:JSON.stringify(labelData)},"POST");};Server.prototype.abandonLabel=function(campaignId,worksetId,taskId){return this.request(["campaigns",WL.mediawiki.dbname,campaignId,worksetId,taskId],{},"DELETE");};WL.server=new Server();})(jQuery,wikiLabels);(function($,WL){var User=function(){this.id=null;$(window).focus(this.handleRefocus.bind(this));this.statusChanged=$.Callbacks();this.updateStatus();};User.prototype.handleRefocus=function(e){this.updateStatus();};User.prototype.updateStatus=function(){var oldId=this.id,deferred=$.Deferred();WL.server.whoami().done(function(doc){this.id=doc['user']['id'];if(oldId!==this.id){console.log("Setting user_id to "+this.id);this.statusChanged.fire();}
deferred.resolve(true);}.bind(this)).fail(function(doc){this.id=null;deferred.reject(false);}.bind(this));return deferred.promise();};User.prototype.initiateOAuth=function(){var oauthWindow=window.open(WL.server.absPath("auth","initiate"),"OAuth",'height=768,width=1024');if(window.focus){oauthWindow.focus();}};User.prototype.authenticated=function(){return this.id!==null;};WL.user=new User();})(jQuery,wikiLabels);(function($,WL){var View=function(taskListData){this.$element=$("<div>").addClass(WL.config.prefix+"view");this.taskMap=null;this.tasks=[];this.selectedTaskInfo=null;this.taskSelected=$.Callbacks();this.worksetCompleted=new WorksetCompleted();this.worksetCompleted.newWorksetRequested.add(this.handleNewWorksetRequested.bind(this));this.newWorksetRequested=$.Callbacks();this.load(taskListData);};OO.initClass(View);View.prototype.handleNewWorksetRequested=function(){this.newWorksetRequested.fire();};View.prototype.load=function(taskListData){var i,taskData,taskInfo;this.taskMap={};for(i=0;i<taskListData.length;i++){taskData=taskListData[i];taskInfo={i:i,data:taskData};this.tasks.push(taskInfo);this.taskMap[taskData.id]=i;}};View.prototype.show=function(taskId){if(this.taskMap[taskId]===undefined){throw"Could not find data for task_id="+taskId;}else{this.select(this.tasks[this.taskMap[taskId]]);}};View.prototype.select=function(taskInfo){var oldTaskInfo=this.selectedTaskInfo;this.selectedTaskInfo=taskInfo;if(oldTaskInfo!==this.selectedTaskInfo){this.taskSelected.fire(taskInfo.data.id);}
this.present(this.selectedTaskInfo);};View.prototype.present=function(taskInfo){var jsonString=JSON.stringify(taskInfo,null,2);this.$element.html($("<pre>").text(jsonString));};View.prototype.showCompleted=function(){this.$element.html(this.worksetCompleted.$element);};var DiffToPrevious=function(taskListData){DiffToPrevious.super.call(this,taskListData);this.$element.addClass(WL.config.prefix+"diff-to-previous");};OO.inheritClass(DiffToPrevious,View);DiffToPrevious.prototype.load=function(taskListData){DiffToPrevious.super.prototype.load.call(this,taskListData);this.preCacheDiffs();};DiffToPrevious.prototype.present=function(taskInfo){if(taskInfo.diff){this.presentDiff(taskInfo.diff);}else{WL.api.diffToPrevious(taskInfo.data['data']['rev_id']).done(function(diff){this.tasks[taskInfo.i].diff=diff;this.presentDiff(diff);}.bind(this)).fail(function(doc){var error=$("<pre>").addClass("error");this.$element.html(error.text(JSON.stringify(doc,null,2)));}.bind(this));}};DiffToPrevious.prototype.preCacheDiffs=function(index){var query,revId;index=index||0;if(index>=this.tasks.length){return null;}else if(this.tasks[index].diff!==undefined){this.preCacheDiffs(index+1);}else{revId=this.tasks[index].data['data']['rev_id'];query=WL.api.diffToPrevious(revId);query.done(function(diff){console.log("pre-caching diff for "+revId);this.tasks[index].diff=diff;this.preCacheDiffs(index+1);}.bind(this));query.fail(function(doc){this.preCacheDiffs(index+1);}.bind(this));}};DiffToPrevious.prototype.presentDiff=function(diff){var diffLink,title=WL.util.linkToTitle(diff.title).addClass("title"),description=$("<div>").addClass("description"),comment=$("<div>").addClass("comment"),direction=$("#mw-content-text").attr("dir"),diffTable=(direction=='rtl'?$("<table>").addClass("diff diff-contentalign-right"):$("<table>").addClass("diff diff-contentalign-left"));this.$element.empty();this.$element.append(title);diffLink=WL.util.linkToDiff(diff.revId).prop('outerHTML');description.html(WL.i18n("Diff for revision $1",[diffLink]));this.$element.append(description);this.$element.append(comment.html(diff.comment));if(diff.tableRows){diffTable.append("<col class='diff-marker' />"+
"<col class='diff-content' />"+
"<col class='diff-marker' />"+
"<col class='diff-content' />");diffTable.append(diff.tableRows);this.$element.append(diffTable);}else{this.$element.append($("<div>").addClass("no-difference").text(WL.i18n("No difference")));}};var PageAsOfRevision=function(taskListData){PageAsOfRevision.super.call(this,taskListData);this.$element.addClass(WL.config.prefix+"page-as-of-revision").addClass('display-page-html');};OO.inheritClass(PageAsOfRevision,View);PageAsOfRevision.prototype.present=function(taskInfo){if(taskInfo.title&&taskInfo.html){this.presentPage(taskInfo.title,taskInfo.html);}else{WL.api.getRevision(taskInfo.data['data']['rev_id'],{'rvprop':"content",'rvparse':true}).done(function(doc){this.tasks[taskInfo.i].html=doc['*'];this.tasks[taskInfo.i].title=doc['page']['title'];this.presentPage(doc['page']['title'],doc['*']);}.bind(this)).fail(function(doc){var error=$("<pre>").addClass("error");this.$element.html(error.text(JSON.stringify(doc,null,2)));}.bind(this));}};PageAsOfRevision.prototype.presentPage=function(title,html){this.$element.html("");this.$element.append($("<h1>").text(title).attr('id',"firstHeading").addClass("firstHeading"));this.$element.append($("<div>").html(html).addClass("mw-body-content").attr('id',"bodyContent"));};var ParsedWikitext=function(taskListData){ParsedWikitext.super.call(this,taskListData);this.$element.addClass(WL.config.prefix+"parsed-wikitext").addClass('display-page-html');};OO.inheritClass(ParsedWikitext,View);ParsedWikitext.prototype.present=function(taskInfo){if(taskInfo.html){this.presentHTML(taskInfo.html);}else{WL.api.wikitext2HTML(taskInfo.data['data']['wikitext']).done(function(html){this.tasks[taskInfo.i].html=html;this.presentHTML(html);}.bind(this)).fail(function(doc){var error=$("<pre>").addClass("error");this.$element.html(error.text(JSON.stringify(doc,null,2)));}.bind(this));}};ParsedWikitext.prototype.presentHTML=function(html){this.$element.html(html);};var WorksetCompleted=function(){this.$element=$("<div>").addClass("completed");this.$message=$("<div>").addClass("message").text(WL.i18n("Workset complete!"));this.$element.append(this.$message);this.newWorkset=new OO.ui.ButtonWidget({label:WL.i18n("Request new workset"),classes:["new-button"]});this.$element.append(this.newWorkset.$element);this.newWorkset.on('click',this.handleNewWorksetClick.bind(this));this.newWorksetRequested=$.Callbacks();};WorksetCompleted.prototype.handleNewWorksetClick=function(){this.newWorksetRequested.fire();};WL.views={View:View,DiffToPrevious:DiffToPrevious,PageAsOfRevision:PageAsOfRevision,ParsedWikitext:ParsedWikitext};}(jQuery,wikiLabels));(function($,WL){var MediaWiki=function(){};MediaWiki.prototype.initialize=function(host){var deferred=$.Deferred();this.host=host;WL.api.getSiteInfo().done(function(doc){this.initializeFromDoc(doc)
deferred.resolve(this)}.bind(this)).fail(function(doc){deferred.reject(doc)}.bind(this));return deferred.promise();}
MediaWiki.prototype.initializeFromDoc=function(doc){this.dbname=doc.wikiid;this.lang=doc.lang;this.fallbackChain=[doc.lang];for(var i=0;i<doc.fallback.lengh;i++){var fallback=doc.fallback[i];this.fallbackChain.push(fallback.code);}
this.articlepath=doc.articlepath;this.script=doc.script;this.rtl=doc.rtl;}
MediaWiki.prototype.urlToTitle=function(title){return"//"+this.host+this.articlepath.replace("$1",title);}
MediaWiki.prototype.urlToDiff=function(revId){return"//"+this.host+this.script+"?diff="+revId;}
WL.mediawiki=new MediaWiki();})(jQuery,wikiLabels);(function($,OO,WL){var Workspace=function($element){if($element===undefined||$element.length===0){throw'$element must be a defined element';}
this.$element=$element;this.$element.hide();this.campaignId=null;this.worksetId=null;this.taskList=null;this.form=null;this.view=null;this.$parent=$element.parent();this.$menu=$('<div>').addClass('wikilabels-menu');this.$element.append(this.$menu);this.fullscreenToggle=new OO.ui.ToggleButtonWidget({label:WL.i18n('fullscreen'),classes:['fullscreen']});this.$menu.append(this.fullscreenToggle.$element);this.fullscreenToggle.on('change',this.handleFullscreenChange.bind(this));this.$container=$('<div>').addClass('container');this.$element.append(this.$container);this.labelSaved=$.Callbacks();this.newWorksetRequested=$.Callbacks();};Workspace.prototype.handleFormSubmission=function(labelData){this.saveLabel(labelData);};Workspace.prototype.handleFormAbandon=function(){this.abandonLabel();};Workspace.prototype.handleTaskSelection=function(task){if(task){this.view.show(task.id);this.form.setValues(task.label.data);this.form.show();}};Workspace.prototype.handleFullscreenChange=function(e){this.fullscreen(this.fullscreenToggle.getValue());};Workspace.prototype.handleNewWorksetRequested=function(){this.newWorksetRequested.fire();};Workspace.prototype.loadWorkset=function(campaignId,worksetId){var taskList,form,view,query=WL.server.getWorkset(campaignId,worksetId);this.clear();this.$element.show();query.done(function(doc){var formQuery;try{view=new WL.views[doc['campaign']['view']](doc['tasks']);}catch(err){console.error(err.stack);alert(WL.i18n('Could not load view "$1": '
+'$2\nUsing simple task viewer.',[doc['campaign']['view'],err]));view=new WL.views.View(doc['tasks']);}
taskList=new TaskList(doc['tasks']);formQuery=WL.server.getForm(doc['campaign']['form']);formQuery.done(function(formDoc){try{form=WL.Form.fromConfig(formDoc['form'],WL.mediawiki.fallbackChain);this.load(campaignId,worksetId,taskList,form,view);}catch(err){console.error(err.stack);alert(WL.i18n('Could not load form "$1": \n$2',[doc['campaign']['form'],err]));}}.bind(this));formQuery.fail(function(errorDoc){alert(WL.i18n('Could not load form "$1": \n$2',[doc['campaign']['form'],JSON.stringify(errorDoc,null,2)]));}.bind(this));}.bind(this));};Workspace.prototype.load=function(campaignId,worksetId,taskList,form,view){var firstTask;this.clear();this.campaignId=campaignId;this.worksetId=worksetId;this.taskList=taskList;this.$container.append(taskList.$element);this.taskList.taskSelected.add(this.handleTaskSelection.bind(this));this.form=form;this.$container.append(form.$element);this.form.submitted.add(this.handleFormSubmission.bind(this));this.form.abandoned.add(this.handleFormAbandon.bind(this));this.view=view;this.$container.append(view.$element);this.view.newWorksetRequested.add(this.handleNewWorksetRequested.bind(this));this.fullscreenToggle.setDisabled(false);firstTask=this.taskList.selectByIndex(0);this.view.show(firstTask.id);};Workspace.prototype.saveLabel=function(labelData){var fieldName,fieldsMissingValues,task=this.taskList.selectedTask;if(!task){alert(WL.i18n("Can't save label. No task is selected!"));}
WL.server.saveLabel(this.campaignId,this.worksetId,task.id,labelData).done(function(doc){var tasks,labels;task.label.load(doc['label']);tasks=this.taskList.length();labels=this.taskList.labeled();this.labelSaved.fire(this.campaignId,this.worksetId,tasks,labels);if(this.taskList.last()&&this.taskList.complete()){this.taskList.select(null);this.form.clear();this.form.hide();this.view.showCompleted();}else{this.taskList.next();}
$.removeSpinner(WL.config.prefix+'submit-spinner');}.bind(this));};Workspace.prototype.abandonLabel=function(){var fieldName,fieldsMissingValues,task=this.taskList.selectedTask;if(!task){alert("Can't abandon task.  No task is selected!");}
WL.server.abandonLabel(this.campaignId,this.worksetId,task.id).done(function(doc){var tasks,labels;task.label.load({'data':true},'abandoned');tasks=this.taskList.length();labels=this.taskList.labeled();this.labelSaved.fire(this.campaignId,this.worksetId,tasks,labels);if(this.taskList.last()&&this.taskList.complete()){this.taskList.select(null);this.form.clear();this.form.hide();this.view.showCompleted();}else{this.taskList.next();}
$.removeSpinner(WL.config.prefix+'abandon-spinner');}.bind(this));};Workspace.prototype.fullscreen=function(fullscreen){if(fullscreen===undefined){return this.$element.hasClass('fullscreen');}else if(fullscreen){$('body').append(this.$element);this.$element.addClass('fullscreen');return this;}else{this.$parent.append(this.$element);this.$element.removeClass('fullscreen');return this;}};Workspace.prototype.clear=function(){this.$container.empty();this.fullscreenToggle.setDisabled(true);};var TaskList=function(taskListData){this.$element=$('<div>').addClass('task-list');this.$header=$('<div>').addClass('header').text(WL.i18n("Workset"));this.$element.append(this.$header);this.tasks=null;this.$tasks=$('<div>').addClass('tasks');this.$element.append(this.$tasks);this.$tasksTable=$('<table>').addClass('table');this.$tasks.append(this.$tasksTable);this.$tasksRow=$('<tr>').addClass('row');this.$tasksTable.append(this.$tasksRow);this.selectedTaskInfo=null;this.taskSelected=$.Callbacks();this.load(taskListData);};TaskList.prototype.handleTaskActivation=function(task){this.select(task);};TaskList.prototype.load=function(taskListData){var taskData,task,i;this.$tasksRow.empty();this.tasks=[];for(i=0;i<taskListData.length;i++){taskData=taskListData[i];task=new Task(i,taskData);task.activated.add(this.handleTaskActivation.bind(this));this.tasks.push(task);this.$tasksRow.append(task.$element);}};TaskList.prototype.select=function(task){if(this.selectedTask){this.selectedTask.select(false);}
if(task){task.select(true);}
this.selectedTask=task;this.taskSelected.fire(task);};TaskList.prototype.selectByIndex=function(index){if(index>=this.tasks.length){throw"Could not select task. Index "+index+" out of bounds.";}
this.select(this.tasks[index]);return this.tasks[index];};TaskList.prototype.shift=function(delta){var newI;if(!this.selectedTask){throw"No task assigned.  Can't shift().";}
newI=(this.selectedTask.i+delta)%this.tasks.length;this.select(this.tasks[newI]);};TaskList.prototype.next=function(){return this.shift(1);};TaskList.prototype.prev=function(){return this.shift(-1);};TaskList.prototype.last=function(){if(this.selectedTask){return this.selectedTask.i===this.tasks.length-1;}else{throw"No task selected";}};TaskList.prototype.labeled=function(){var i,task,labeledTasks=0;for(i=0;i<this.tasks.length;i++){task=this.tasks[i];labeledTasks+=task.isCompleted();}
return labeledTasks;};TaskList.prototype.complete=function(){var i,task;for(i=0;i<this.tasks.length;i++){task=this.tasks[i];if(!task.isCompleted()){return false;}}
return true;};TaskList.prototype.length=function(){return this.tasks.length;};var Task=function(i,taskData){this.$element=$('<td>').addClass('task');this.$element.click(this.handleClick.bind(this));this.i=i;this.selected=$.Callbacks();this.activated=$.Callbacks();this.load(taskData);};Task.prototype.handleClick=function(e){if(!this.disable()){this.activated.fire(this);}};Task.prototype.load=function(taskData){this.$element.empty();this.id=taskData.id;this.data=taskData['task_data'];this.label=new Label(taskData['labels'][0]);this.$element.append(this.label.$element);};Task.prototype.select=function(selected){if(selected===undefined){return this.$element.hasClass('selected');}else if(selected){this.$element.addClass('selected');this.selected.fire();return this;}else{this.$element.removeClass('selected');return this;}};Task.prototype.setWidth=function(width){this.$element.css('width',width);};Task.prototype.disable=function(disabled){if(disabled===undefined){return this.$element.hasClass('disabled');}else if(disabled){this.$element.addClass('disabled');return this;}else{this.$element.removeClass('disabled');return this;}};Task.prototype.isCompleted=function(){return this.label.isCompleted()||this.isAbandoned();};Task.prototype.isAbandoned=function(){return this.label.$element.hasClass('abandoned');};var Label=function(labelData){this.$element=$("<div>").addClass("label");this.timestamp=null;this.data=null;this.load(labelData);};Label.prototype.load=function(labelData,className){labelData=labelData||{};this.timestamp=labelData['timestamp'];this.data=labelData['data'];this.complete(this.data!==undefined&&this.data!==null,className);};Label.prototype.complete=function(completed,className){className=className||'completed';if(completed===undefined){return this.$element.hasClass(className);}else if(completed){this.$element.addClass(className);return this;}else{this.$element.removeClass(className);return this;}};Label.prototype.isCompleted=function(classNames){classNames=classNames||['completed'];for(var i in classNames){if(this.$element.hasClass(classNames[i])){return true;}}
return false;};wikiLabels.Workspace=Workspace;})(jQuery,OO,wikiLabels);