(function($){var locationWrapper={put:function(hash,win){(win||window).location.hash=this.encoder(hash);},get:function(win){return(win||window).location.toString().split('#',2)[1]||'';},encoder:encodeURIComponent};var iframeWrapper={id:"__jQuery_history",init:function(){var html='<iframe id="'+this.id+'" style="display:none" src="javascript:false;" />';$("body").prepend(html);return this;},_document:function(){return $("#"+this.id)[0].contentWindow.document;},put:function(hash){var doc=this._document();doc.open();doc.close();locationWrapper.put(hash,doc);},get:function(){return locationWrapper.get(this._document());}};function initObjects(options){options=$.extend({unescape:false},options||{});locationWrapper.encoder=encoder(options.unescape);function encoder(unescape_){if(unescape_===true){return function(hash){return hash;};}
if(typeof unescape_=="string"&&(unescape_=partialDecoder(unescape_.split("")))||typeof unescape_=="function"){return function(hash){return unescape_(encodeURIComponent(hash));};}
return encodeURIComponent;}
function partialDecoder(chars){var re=new RegExp($.map(chars,encodeURIComponent).join("|"),"ig");return function(enc){return enc.replace(re,decodeURIComponent);};}}
var implementations={};implementations.base={callback:undefined,type:undefined,check:function(){},load:function(hash){},init:function(callback,options){initObjects(options);self.callback=callback;self._options=options;self._init();},_init:function(){},_options:{}};implementations.timer={_appState:undefined,_init:function(){var current_hash=locationWrapper.get();self._appState=current_hash;self.callback(current_hash);setInterval(self.check,100);},check:function(){var current_hash=locationWrapper.get();if(current_hash!=self._appState){self._appState=current_hash;self.callback(current_hash);}},load:function(hash){if(hash!=self._appState){locationWrapper.put(hash);self._appState=hash;self.callback(hash);}}};implementations.hashchangeEvent={_init:function(){self.callback(locationWrapper.get());$(window).bind('hashchange',self.check);},check:function(){self.callback(locationWrapper.get());},load:function(hash){locationWrapper.put(hash);}};var self=$.extend({},implementations.base);if("onhashchange"in window){self.type='hashchangeEvent';}else{self.type='timer';}
$.extend(self,implementations[self.type]);$.history=self;})(jQuery);(function($){$.fn.TextAreaExpander=function(minHeight,maxHeight){function ResizeTextarea(e){e=e.target||e;var vlen=e.value.length,ewidth=e.offsetWidth;if(vlen!=e.valLength||ewidth!=e.boxWidth){if(vlen<e.valLength||ewidth!=e.boxWidth)e.style.height="0px";var h=Math.max(e.expandMin,Math.min(e.scrollHeight,e.expandMax));e.style.overflow=(e.scrollHeight>h?"auto":"hidden");e.style.height=h+"px";e.valLength=vlen;e.boxWidth=ewidth;}
return true;};this.each(function(){if(this.nodeName.toLowerCase()!="textarea")return;var p=this.className.match(/expand(\d+)\-*(\d+)*/i);this.expandMin=minHeight||(p?parseInt('0'+p[1],10):0);this.expandMax=maxHeight||(p?parseInt('0'+p[2],10):99999);ResizeTextarea(this);if(!this.Initialized){this.Initialized=true;$(this).css("padding-top",0).css("padding-bottom",0);$(this).bind("keyup",ResizeTextarea).bind("focus",ResizeTextarea);}});return this;};})(jQuery);$(document).ready(function(){$("textarea[class*=expand]").TextAreaExpander();});;(function($){'use strict';var lock=function(func){var free,locked;free=function(){locked=false;};return function(){var args;if(locked)return;locked=true;args=toArray(arguments);args.unshift(free);func.apply(this,args);};};var toArray=function(args){var result;result=Array.prototype.slice.call(args);return result;};var getStyles=(function(){var color;color=$('<div></div>').css(['color']).color;if(typeof color!=='undefined'){return function($el,properties){return $el.css(properties);};}else{return function($el,properties){var styles;styles={};$.each(properties,function(i,property){styles[property]=$el.css(property);});return styles;};}})();var identity=function(obj){return obj;};var memoize=function(func){var memo={};return function(term,callback){if(memo[term]){callback(memo[term]);}else{func.call(this,term,function(data){memo[term]=(memo[term]||[]).concat(data);callback.apply(null,arguments);});}};};var include=function(array,value){var i,l;if(array.indexOf)return array.indexOf(value)!=-1;for(i=0,l=array.length;i<l;i++){if(array[i]===value)return true;}
return false;};var Completer=(function(){var html,css,$baseWrapper,$baseList,_id;html={wrapper:'<div class="textcomplete-wrapper"></div>',list:'<ul class="dropdown-menu"></ul>'};css={wrapper:{position:'relative'},list:{position:'absolute',top:0,left:0,zIndex:'100',display:'none'}};$baseWrapper=$(html.wrapper).css(css.wrapper);$baseList=$(html.list).css(css.list);_id=0;function Completer($el){var focus;this.el=$el.get(0);focus=this.el===document.activeElement;this.$el=wrapElement($el);this.id='textComplete'+_id++;this.strategies=[];if(focus){this.initialize();this.$el.focus();}else{this.$el.one('focus.textComplete',$.proxy(this.initialize,this));}}
$.extend(Completer.prototype,{initialize:function(){var $list,globalEvents;$list=$baseList.clone();this.listView=new ListView($list,this);this.$el.before($list).on({'keyup.textComplete':$.proxy(this.onKeyup,this),'keydown.textComplete':$.proxy(this.listView.onKeydown,this.listView)});globalEvents={};globalEvents['click.'+this.id]=$.proxy(this.onClickDocument,this);globalEvents['keyup.'+this.id]=$.proxy(this.onKeyupDocument,this);$(document).on(globalEvents);},register:function(strategies){this.strategies=this.strategies.concat(strategies);},renderList:function(data){if(this.clearAtNext){this.listView.clear();this.clearAtNext=false;}
if(data.length){if(!this.listView.shown){this.listView.setPosition(this.getCaretPosition()).clear().activate();this.listView.strategy=this.strategy;}
data=data.slice(0,this.strategy.maxCount);this.listView.render(data);}
if(!this.listView.data.length&&this.listView.shown){this.listView.deactivate();}},searchCallbackFactory:function(free){var self=this;return function(data,keep){self.renderList(data);if(!keep){free();self.clearAtNext=true;}};},onKeyup:function(e){var searchQuery,term;if(this.skipSearch(e)){return;}
searchQuery=this.extractSearchQuery(this.getTextFromHeadToCaret());if(searchQuery.length){term=searchQuery[1];if(this.term===term)return;this.term=term;this.search(searchQuery);}else{this.term=null;this.listView.deactivate();}},skipSearch:function(e){if(this.skipNextKeyup){this.skipNextKeyup=false;return true;}
switch(e.keyCode){case 40:case 38:return true;}},onSelect:function(value){var pre,post,newSubStr;pre=this.getTextFromHeadToCaret();post=this.el.value.substring(this.el.selectionEnd);newSubStr=this.strategy.replace(value);if($.isArray(newSubStr)){post=newSubStr[1]+post;newSubStr=newSubStr[0];}
pre=pre.replace(this.strategy.match,newSubStr);this.$el.val(pre+post).trigger('change').trigger('textComplete:select',value);this.el.focus();this.el.selectionStart=this.el.selectionEnd=pre.length;this.skipNextKeyup=true;},onClickDocument:function(e){if(e.originalEvent&&!e.originalEvent.keepTextCompleteDropdown){this.listView.deactivate();}},onKeyupDocument:function(e){if(this.listView.shown&&e.keyCode===27){this.listView.deactivate();this.$el.focus();}},destroy:function(){var $wrapper;this.$el.off('.textComplete');$(document).off('.'+this.id);if(this.listView){this.listView.destroy();}
$wrapper=this.$el.parent();$wrapper.after(this.$el).remove();this.$el.data('textComplete',void 0);this.$el=null;},getCaretPosition:function(){if(this.el.selectionEnd===0)return;var properties,css,$div,$span,position,dir;dir=this.$el.attr('dir')||this.$el.css('direction');properties=['border-width','font-family','font-size','font-style','font-variant','font-weight','height','letter-spacing','word-spacing','line-height','text-decoration','text-align','width','padding-top','padding-right','padding-bottom','padding-left','margin-top','margin-right','margin-bottom','margin-left'];css=$.extend({position:'absolute',overflow:'auto','white-space':'pre-wrap',top:0,left:-9999,direction:dir},getStyles(this.$el,properties));$div=$('<div></div>').css(css).text(this.getTextFromHeadToCaret());$span=$('<span></span>').text('.').appendTo($div);this.$el.before($div);position=$span.position();position.top+=$span.height()-this.$el.scrollTop();if(dir==='rtl'){position.left-=this.listView.$el.width();}
$div.remove();return position;},getTextFromHeadToCaret:function(){var text,selectionEnd,range;selectionEnd=this.el.selectionEnd;if(typeof selectionEnd==='number'){text=this.el.value.substring(0,selectionEnd);}else if(document.selection){range=this.el.createTextRange();range.moveStart('character',0);range.moveEnd('textedit');text=range.text;}
return text;},extractSearchQuery:function(text){var i,l,strategy,match;for(i=0,l=this.strategies.length;i<l;i++){strategy=this.strategies[i];match=text.match(strategy.match);if(match){return[strategy,match[strategy.index]];}}
return[];},search:lock(function(free,searchQuery){var term;this.strategy=searchQuery[0];term=searchQuery[1];this.strategy.search(term,this.searchCallbackFactory(free));})});var wrapElement=function($el){return $el.wrap($baseWrapper.clone().css('display',$el.css('display')));};return Completer;})();var ListView=(function(){function ListView($el,completer){this.data=[];this.$el=$el;this.index=0;this.completer=completer;this.$el.on('click.textComplete','li.textcomplete-item',$.proxy(this.onClick,this));}
$.extend(ListView.prototype,{shown:false,render:function(data){var html,i,l,index,val;html='';for(i=0,l=data.length;i<l;i++){val=data[i];if(include(this.data,val))continue;index=this.data.length;this.data.push(val);html+='<li class="textcomplete-item" data-index="'+index+'"><a>';html+=this.strategy.template(val);html+='</a></li>';if(this.data.length===this.strategy.maxCount)break;}
this.$el.append(html);if(!this.data.length){this.deactivate();}else{this.activateIndexedItem();}},clear:function(){this.data=[];this.$el.html('');this.index=0;return this;},activateIndexedItem:function(){this.$el.find('.active').removeClass('active');this.getActiveItem().addClass('active');},getActiveItem:function(){return $(this.$el.children().get(this.index));},activate:function(){if(!this.shown){this.$el.show();this.completer.$el.trigger('textComplete:show');this.shown=true;}
return this;},deactivate:function(){if(this.shown){this.$el.hide();this.completer.$el.trigger('textComplete:hide');this.shown=false;this.data=[];this.index=null;}
return this;},setPosition:function(position){this.$el.css(position);return this;},select:function(index){var self=this;this.completer.onSelect(this.data[index]);setTimeout(function(){self.deactivate();},0);},onKeydown:function(e){if(!this.shown)return;if(e.keyCode===38){e.preventDefault();if(this.index===0){this.index=this.data.length-1;}else{this.index-=1;}
this.activateIndexedItem();}else if(e.keyCode===40){e.preventDefault();if(this.index===this.data.length-1){this.index=0;}else{this.index+=1;}
this.activateIndexedItem();}else if(e.keyCode===13||e.keyCode===9){e.preventDefault();this.select(parseInt(this.getActiveItem().data('index'),10));}},onClick:function(e){var $e=$(e.target);e.originalEvent.keepTextCompleteDropdown=true;if(!$e.hasClass('textcomplete-item')){$e=$e.parents('li.textcomplete-item');}
this.select(parseInt($e.data('index'),10));},destroy:function(){this.deactivate();this.$el.off('click.textComplete').remove();this.$el=null;}});return ListView;})();$.fn.textcomplete=function(strategies){var i,l,strategy,dataKey;dataKey='textComplete';if(strategies==='destroy'){return this.each(function(){var completer=$(this).data(dataKey);if(completer){completer.destroy();}});}
for(i=0,l=strategies.length;i<l;i++){strategy=strategies[i];if(!strategy.template){strategy.template=identity;}
if(strategy.index==null){strategy.index=2;}
if(strategy.cache){strategy.search=memoize(strategy.search);}
strategy.maxCount||(strategy.maxCount=10);}
return this.each(function(){var $this,completer;$this=$(this);completer=$this.data(dataKey);if(!completer){completer=new Completer($this);$this.data(dataKey,completer);}
completer.register(strategies);});};})(window.jQuery||window.Zepto);function diff_match_patch(){this.Diff_Timeout=1.0;this.Diff_EditCost=4;this.Match_Threshold=0.5;this.Match_Distance=1000;this.Patch_DeleteThreshold=0.5;this.Patch_Margin=4;this.Match_MaxBits=32;}
var DIFF_DELETE=-1;var DIFF_INSERT=1;var DIFF_EQUAL=0;diff_match_patch.Diff;diff_match_patch.prototype.diff_main=function(text1,text2,opt_checklines,opt_deadline){if(typeof opt_deadline=='undefined'){if(this.Diff_Timeout<=0){opt_deadline=Number.MAX_VALUE;}else{opt_deadline=(new Date).getTime()+this.Diff_Timeout*1000;}}
var deadline=opt_deadline;if(text1==null||text2==null){throw new Error('Null input. (diff_main)');}
if(text1==text2){if(text1){return[[DIFF_EQUAL,text1]];}
return[];}
if(typeof opt_checklines=='undefined'){opt_checklines=true;}
var checklines=opt_checklines;var commonlength=this.diff_commonPrefix(text1,text2);var commonprefix=text1.substring(0,commonlength);text1=text1.substring(commonlength);text2=text2.substring(commonlength);commonlength=this.diff_commonSuffix(text1,text2);var commonsuffix=text1.substring(text1.length-commonlength);text1=text1.substring(0,text1.length-commonlength);text2=text2.substring(0,text2.length-commonlength);var diffs=this.diff_compute_(text1,text2,checklines,deadline);if(commonprefix){diffs.unshift([DIFF_EQUAL,commonprefix]);}
if(commonsuffix){diffs.push([DIFF_EQUAL,commonsuffix]);}
this.diff_cleanupMerge(diffs);return diffs;};diff_match_patch.prototype.diff_compute_=function(text1,text2,checklines,deadline){var diffs;if(!text1){return[[DIFF_INSERT,text2]];}
if(!text2){return[[DIFF_DELETE,text1]];}
var longtext=text1.length>text2.length?text1:text2;var shorttext=text1.length>text2.length?text2:text1;var i=longtext.indexOf(shorttext);if(i!=-1){diffs=[[DIFF_INSERT,longtext.substring(0,i)],[DIFF_EQUAL,shorttext],[DIFF_INSERT,longtext.substring(i+shorttext.length)]];if(text1.length>text2.length){diffs[0][0]=diffs[2][0]=DIFF_DELETE;}
return diffs;}
if(shorttext.length==1){return[[DIFF_DELETE,text1],[DIFF_INSERT,text2]];}
longtext=shorttext=null;var hm=this.diff_halfMatch_(text1,text2);if(hm){var text1_a=hm[0];var text1_b=hm[1];var text2_a=hm[2];var text2_b=hm[3];var mid_common=hm[4];var diffs_a=this.diff_main(text1_a,text2_a,checklines,deadline);var diffs_b=this.diff_main(text1_b,text2_b,checklines,deadline);return diffs_a.concat([[DIFF_EQUAL,mid_common]],diffs_b);}
if(checklines&&text1.length>100&&text2.length>100){return this.diff_lineMode_(text1,text2,deadline);}
return this.diff_bisect_(text1,text2,deadline);};diff_match_patch.prototype.diff_lineMode_=function(text1,text2,deadline){var a=this.diff_linesToChars_(text1,text2);text1=a.chars1;text2=a.chars2;var linearray=a.lineArray;var diffs=this.diff_main(text1,text2,false,deadline);this.diff_charsToLines_(diffs,linearray);this.diff_cleanupSemantic(diffs);diffs.push([DIFF_EQUAL,'']);var pointer=0;var count_delete=0;var count_insert=0;var text_delete='';var text_insert='';while(pointer<diffs.length){switch(diffs[pointer][0]){case DIFF_INSERT:count_insert++;text_insert+=diffs[pointer][1];break;case DIFF_DELETE:count_delete++;text_delete+=diffs[pointer][1];break;case DIFF_EQUAL:if(count_delete>=1&&count_insert>=1){diffs.splice(pointer-count_delete-count_insert,count_delete+count_insert);pointer=pointer-count_delete-count_insert;var a=this.diff_main(text_delete,text_insert,false,deadline);for(var j=a.length-1;j>=0;j--){diffs.splice(pointer,0,a[j]);}
pointer=pointer+a.length;}
count_insert=0;count_delete=0;text_delete='';text_insert='';break;}
pointer++;}
diffs.pop();return diffs;};diff_match_patch.prototype.diff_bisect_=function(text1,text2,deadline){var text1_length=text1.length;var text2_length=text2.length;var max_d=Math.ceil((text1_length+text2_length)/2);var v_offset=max_d;var v_length=2*max_d;var v1=new Array(v_length);var v2=new Array(v_length);for(var x=0;x<v_length;x++){v1[x]=-1;v2[x]=-1;}
v1[v_offset+1]=0;v2[v_offset+1]=0;var delta=text1_length-text2_length;var front=(delta%2!=0);var k1start=0;var k1end=0;var k2start=0;var k2end=0;for(var d=0;d<max_d;d++){if((new Date()).getTime()>deadline){break;}
for(var k1=-d+k1start;k1<=d-k1end;k1+=2){var k1_offset=v_offset+k1;var x1;if(k1==-d||(k1!=d&&v1[k1_offset-1]<v1[k1_offset+1])){x1=v1[k1_offset+1];}else{x1=v1[k1_offset-1]+1;}
var y1=x1-k1;while(x1<text1_length&&y1<text2_length&&text1.charAt(x1)==text2.charAt(y1)){x1++;y1++;}
v1[k1_offset]=x1;if(x1>text1_length){k1end+=2;}else if(y1>text2_length){k1start+=2;}else if(front){var k2_offset=v_offset+delta-k1;if(k2_offset>=0&&k2_offset<v_length&&v2[k2_offset]!=-1){var x2=text1_length-v2[k2_offset];if(x1>=x2){return this.diff_bisectSplit_(text1,text2,x1,y1,deadline);}}}}
for(var k2=-d+k2start;k2<=d-k2end;k2+=2){var k2_offset=v_offset+k2;var x2;if(k2==-d||(k2!=d&&v2[k2_offset-1]<v2[k2_offset+1])){x2=v2[k2_offset+1];}else{x2=v2[k2_offset-1]+1;}
var y2=x2-k2;while(x2<text1_length&&y2<text2_length&&text1.charAt(text1_length-x2-1)==text2.charAt(text2_length-y2-1)){x2++;y2++;}
v2[k2_offset]=x2;if(x2>text1_length){k2end+=2;}else if(y2>text2_length){k2start+=2;}else if(!front){var k1_offset=v_offset+delta-k2;if(k1_offset>=0&&k1_offset<v_length&&v1[k1_offset]!=-1){var x1=v1[k1_offset];var y1=v_offset+x1-k1_offset;x2=text1_length-x2;if(x1>=x2){return this.diff_bisectSplit_(text1,text2,x1,y1,deadline);}}}}}
return[[DIFF_DELETE,text1],[DIFF_INSERT,text2]];};diff_match_patch.prototype.diff_bisectSplit_=function(text1,text2,x,y,deadline){var text1a=text1.substring(0,x);var text2a=text2.substring(0,y);var text1b=text1.substring(x);var text2b=text2.substring(y);var diffs=this.diff_main(text1a,text2a,false,deadline);var diffsb=this.diff_main(text1b,text2b,false,deadline);return diffs.concat(diffsb);};diff_match_patch.prototype.diff_linesToChars_=function(text1,text2){var lineArray=[];var lineHash={};lineArray[0]='';function diff_linesToCharsMunge_(text){var chars='';var lineStart=0;var lineEnd=-1;var lineArrayLength=lineArray.length;while(lineEnd<text.length-1){lineEnd=text.indexOf('\n',lineStart);if(lineEnd==-1){lineEnd=text.length-1;}
var line=text.substring(lineStart,lineEnd+1);lineStart=lineEnd+1;if(lineHash.hasOwnProperty?lineHash.hasOwnProperty(line):(lineHash[line]!==undefined)){chars+=String.fromCharCode(lineHash[line]);}else{chars+=String.fromCharCode(lineArrayLength);lineHash[line]=lineArrayLength;lineArray[lineArrayLength++]=line;}}
return chars;}
var chars1=diff_linesToCharsMunge_(text1);var chars2=diff_linesToCharsMunge_(text2);return{chars1:chars1,chars2:chars2,lineArray:lineArray};};diff_match_patch.prototype.diff_charsToLines_=function(diffs,lineArray){for(var x=0;x<diffs.length;x++){var chars=diffs[x][1];var text=[];for(var y=0;y<chars.length;y++){text[y]=lineArray[chars.charCodeAt(y)];}
diffs[x][1]=text.join('');}};diff_match_patch.prototype.diff_commonPrefix=function(text1,text2){if(!text1||!text2||text1.charAt(0)!=text2.charAt(0)){return 0;}
var pointermin=0;var pointermax=Math.min(text1.length,text2.length);var pointermid=pointermax;var pointerstart=0;while(pointermin<pointermid){if(text1.substring(pointerstart,pointermid)==text2.substring(pointerstart,pointermid)){pointermin=pointermid;pointerstart=pointermin;}else{pointermax=pointermid;}
pointermid=Math.floor((pointermax-pointermin)/2+pointermin);}
return pointermid;};diff_match_patch.prototype.diff_commonSuffix=function(text1,text2){if(!text1||!text2||text1.charAt(text1.length-1)!=text2.charAt(text2.length-1)){return 0;}
var pointermin=0;var pointermax=Math.min(text1.length,text2.length);var pointermid=pointermax;var pointerend=0;while(pointermin<pointermid){if(text1.substring(text1.length-pointermid,text1.length-pointerend)==text2.substring(text2.length-pointermid,text2.length-pointerend)){pointermin=pointermid;pointerend=pointermin;}else{pointermax=pointermid;}
pointermid=Math.floor((pointermax-pointermin)/2+pointermin);}
return pointermid;};diff_match_patch.prototype.diff_commonOverlap_=function(text1,text2){var text1_length=text1.length;var text2_length=text2.length;if(text1_length==0||text2_length==0){return 0;}
if(text1_length>text2_length){text1=text1.substring(text1_length-text2_length);}else if(text1_length<text2_length){text2=text2.substring(0,text1_length);}
var text_length=Math.min(text1_length,text2_length);if(text1==text2){return text_length;}
var best=0;var length=1;while(true){var pattern=text1.substring(text_length-length);var found=text2.indexOf(pattern);if(found==-1){return best;}
length+=found;if(found==0||text1.substring(text_length-length)==text2.substring(0,length)){best=length;length++;}}};diff_match_patch.prototype.diff_halfMatch_=function(text1,text2){if(this.Diff_Timeout<=0){return null;}
var longtext=text1.length>text2.length?text1:text2;var shorttext=text1.length>text2.length?text2:text1;if(longtext.length<4||shorttext.length*2<longtext.length){return null;}
var dmp=this;function diff_halfMatchI_(longtext,shorttext,i){var seed=longtext.substring(i,i+Math.floor(longtext.length/4));var j=-1;var best_common='';var best_longtext_a,best_longtext_b,best_shorttext_a,best_shorttext_b;while((j=shorttext.indexOf(seed,j+1))!=-1){var prefixLength=dmp.diff_commonPrefix(longtext.substring(i),shorttext.substring(j));var suffixLength=dmp.diff_commonSuffix(longtext.substring(0,i),shorttext.substring(0,j));if(best_common.length<suffixLength+prefixLength){best_common=shorttext.substring(j-suffixLength,j)+
shorttext.substring(j,j+prefixLength);best_longtext_a=longtext.substring(0,i-suffixLength);best_longtext_b=longtext.substring(i+prefixLength);best_shorttext_a=shorttext.substring(0,j-suffixLength);best_shorttext_b=shorttext.substring(j+prefixLength);}}
if(best_common.length*2>=longtext.length){return[best_longtext_a,best_longtext_b,best_shorttext_a,best_shorttext_b,best_common];}else{return null;}}
var hm1=diff_halfMatchI_(longtext,shorttext,Math.ceil(longtext.length/4));var hm2=diff_halfMatchI_(longtext,shorttext,Math.ceil(longtext.length/2));var hm;if(!hm1&&!hm2){return null;}else if(!hm2){hm=hm1;}else if(!hm1){hm=hm2;}else{hm=hm1[4].length>hm2[4].length?hm1:hm2;}
var text1_a,text1_b,text2_a,text2_b;if(text1.length>text2.length){text1_a=hm[0];text1_b=hm[1];text2_a=hm[2];text2_b=hm[3];}else{text2_a=hm[0];text2_b=hm[1];text1_a=hm[2];text1_b=hm[3];}
var mid_common=hm[4];return[text1_a,text1_b,text2_a,text2_b,mid_common];};diff_match_patch.prototype.diff_cleanupSemantic=function(diffs){var changes=false;var equalities=[];var equalitiesLength=0;var lastequality=null;var pointer=0;var length_insertions1=0;var length_deletions1=0;var length_insertions2=0;var length_deletions2=0;while(pointer<diffs.length){if(diffs[pointer][0]==DIFF_EQUAL){equalities[equalitiesLength++]=pointer;length_insertions1=length_insertions2;length_deletions1=length_deletions2;length_insertions2=0;length_deletions2=0;lastequality=diffs[pointer][1];}else{if(diffs[pointer][0]==DIFF_INSERT){length_insertions2+=diffs[pointer][1].length;}else{length_deletions2+=diffs[pointer][1].length;}
if(lastequality&&(lastequality.length<=Math.max(length_insertions1,length_deletions1))&&(lastequality.length<=Math.max(length_insertions2,length_deletions2))){diffs.splice(equalities[equalitiesLength-1],0,[DIFF_DELETE,lastequality]);diffs[equalities[equalitiesLength-1]+1][0]=DIFF_INSERT;equalitiesLength--;equalitiesLength--;pointer=equalitiesLength>0?equalities[equalitiesLength-1]:-1;length_insertions1=0;length_deletions1=0;length_insertions2=0;length_deletions2=0;lastequality=null;changes=true;}}
pointer++;}
if(changes){this.diff_cleanupMerge(diffs);}
this.diff_cleanupSemanticLossless(diffs);pointer=1;while(pointer<diffs.length){if(diffs[pointer-1][0]==DIFF_DELETE&&diffs[pointer][0]==DIFF_INSERT){var deletion=diffs[pointer-1][1];var insertion=diffs[pointer][1];var overlap_length1=this.diff_commonOverlap_(deletion,insertion);var overlap_length2=this.diff_commonOverlap_(insertion,deletion);if(overlap_length1>=overlap_length2){if(overlap_length1>=deletion.length/2||overlap_length1>=insertion.length/2){diffs.splice(pointer,0,[DIFF_EQUAL,insertion.substring(0,overlap_length1)]);diffs[pointer-1][1]=deletion.substring(0,deletion.length-overlap_length1);diffs[pointer+1][1]=insertion.substring(overlap_length1);pointer++;}}else{if(overlap_length2>=deletion.length/2||overlap_length2>=insertion.length/2){diffs.splice(pointer,0,[DIFF_EQUAL,deletion.substring(0,overlap_length2)]);diffs[pointer-1][0]=DIFF_INSERT;diffs[pointer-1][1]=insertion.substring(0,insertion.length-overlap_length2);diffs[pointer+1][0]=DIFF_DELETE;diffs[pointer+1][1]=deletion.substring(overlap_length2);pointer++;}}
pointer++;}
pointer++;}};diff_match_patch.prototype.diff_cleanupSemanticLossless=function(diffs){function diff_cleanupSemanticScore_(one,two){if(!one||!two){return 6;}
var char1=one.charAt(one.length-1);var char2=two.charAt(0);var nonAlphaNumeric1=char1.match(diff_match_patch.nonAlphaNumericRegex_);var nonAlphaNumeric2=char2.match(diff_match_patch.nonAlphaNumericRegex_);var whitespace1=nonAlphaNumeric1&&char1.match(diff_match_patch.whitespaceRegex_);var whitespace2=nonAlphaNumeric2&&char2.match(diff_match_patch.whitespaceRegex_);var lineBreak1=whitespace1&&char1.match(diff_match_patch.linebreakRegex_);var lineBreak2=whitespace2&&char2.match(diff_match_patch.linebreakRegex_);var blankLine1=lineBreak1&&one.match(diff_match_patch.blanklineEndRegex_);var blankLine2=lineBreak2&&two.match(diff_match_patch.blanklineStartRegex_);if(blankLine1||blankLine2){return 5;}else if(lineBreak1||lineBreak2){return 4;}else if(nonAlphaNumeric1&&!whitespace1&&whitespace2){return 3;}else if(whitespace1||whitespace2){return 2;}else if(nonAlphaNumeric1||nonAlphaNumeric2){return 1;}
return 0;}
var pointer=1;while(pointer<diffs.length-1){if(diffs[pointer-1][0]==DIFF_EQUAL&&diffs[pointer+1][0]==DIFF_EQUAL){var equality1=diffs[pointer-1][1];var edit=diffs[pointer][1];var equality2=diffs[pointer+1][1];var commonOffset=this.diff_commonSuffix(equality1,edit);if(commonOffset){var commonString=edit.substring(edit.length-commonOffset);equality1=equality1.substring(0,equality1.length-commonOffset);edit=commonString+edit.substring(0,edit.length-commonOffset);equality2=commonString+equality2;}
var bestEquality1=equality1;var bestEdit=edit;var bestEquality2=equality2;var bestScore=diff_cleanupSemanticScore_(equality1,edit)+
diff_cleanupSemanticScore_(edit,equality2);while(edit.charAt(0)===equality2.charAt(0)){equality1+=edit.charAt(0);edit=edit.substring(1)+equality2.charAt(0);equality2=equality2.substring(1);var score=diff_cleanupSemanticScore_(equality1,edit)+
diff_cleanupSemanticScore_(edit,equality2);if(score>=bestScore){bestScore=score;bestEquality1=equality1;bestEdit=edit;bestEquality2=equality2;}}
if(diffs[pointer-1][1]!=bestEquality1){if(bestEquality1){diffs[pointer-1][1]=bestEquality1;}else{diffs.splice(pointer-1,1);pointer--;}
diffs[pointer][1]=bestEdit;if(bestEquality2){diffs[pointer+1][1]=bestEquality2;}else{diffs.splice(pointer+1,1);pointer--;}}}
pointer++;}};diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch.whitespaceRegex_=/\s/;diff_match_patch.linebreakRegex_=/[\r\n]/;diff_match_patch.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/;diff_match_patch.prototype.diff_cleanupEfficiency=function(diffs){var changes=false;var equalities=[];var equalitiesLength=0;var lastequality=null;var pointer=0;var pre_ins=false;var pre_del=false;var post_ins=false;var post_del=false;while(pointer<diffs.length){if(diffs[pointer][0]==DIFF_EQUAL){if(diffs[pointer][1].length<this.Diff_EditCost&&(post_ins||post_del)){equalities[equalitiesLength++]=pointer;pre_ins=post_ins;pre_del=post_del;lastequality=diffs[pointer][1];}else{equalitiesLength=0;lastequality=null;}
post_ins=post_del=false;}else{if(diffs[pointer][0]==DIFF_DELETE){post_del=true;}else{post_ins=true;}
if(lastequality&&((pre_ins&&pre_del&&post_ins&&post_del)||((lastequality.length<this.Diff_EditCost/2)&&(pre_ins+pre_del+post_ins+post_del)==3))){diffs.splice(equalities[equalitiesLength-1],0,[DIFF_DELETE,lastequality]);diffs[equalities[equalitiesLength-1]+1][0]=DIFF_INSERT;equalitiesLength--;lastequality=null;if(pre_ins&&pre_del){post_ins=post_del=true;equalitiesLength=0;}else{equalitiesLength--;pointer=equalitiesLength>0?equalities[equalitiesLength-1]:-1;post_ins=post_del=false;}
changes=true;}}
pointer++;}
if(changes){this.diff_cleanupMerge(diffs);}};diff_match_patch.prototype.diff_cleanupMerge=function(diffs){diffs.push([DIFF_EQUAL,'']);var pointer=0;var count_delete=0;var count_insert=0;var text_delete='';var text_insert='';var commonlength;while(pointer<diffs.length){switch(diffs[pointer][0]){case DIFF_INSERT:count_insert++;text_insert+=diffs[pointer][1];pointer++;break;case DIFF_DELETE:count_delete++;text_delete+=diffs[pointer][1];pointer++;break;case DIFF_EQUAL:if(count_delete+count_insert>1){if(count_delete!==0&&count_insert!==0){commonlength=this.diff_commonPrefix(text_insert,text_delete);if(commonlength!==0){if((pointer-count_delete-count_insert)>0&&diffs[pointer-count_delete-count_insert-1][0]==DIFF_EQUAL){diffs[pointer-count_delete-count_insert-1][1]+=text_insert.substring(0,commonlength);}else{diffs.splice(0,0,[DIFF_EQUAL,text_insert.substring(0,commonlength)]);pointer++;}
text_insert=text_insert.substring(commonlength);text_delete=text_delete.substring(commonlength);}
commonlength=this.diff_commonSuffix(text_insert,text_delete);if(commonlength!==0){diffs[pointer][1]=text_insert.substring(text_insert.length-
commonlength)+diffs[pointer][1];text_insert=text_insert.substring(0,text_insert.length-
commonlength);text_delete=text_delete.substring(0,text_delete.length-
commonlength);}}
if(count_delete===0){diffs.splice(pointer-count_insert,count_delete+count_insert,[DIFF_INSERT,text_insert]);}else if(count_insert===0){diffs.splice(pointer-count_delete,count_delete+count_insert,[DIFF_DELETE,text_delete]);}else{diffs.splice(pointer-count_delete-count_insert,count_delete+count_insert,[DIFF_DELETE,text_delete],[DIFF_INSERT,text_insert]);}
pointer=pointer-count_delete-count_insert+
(count_delete?1:0)+(count_insert?1:0)+1;}else if(pointer!==0&&diffs[pointer-1][0]==DIFF_EQUAL){diffs[pointer-1][1]+=diffs[pointer][1];diffs.splice(pointer,1);}else{pointer++;}
count_insert=0;count_delete=0;text_delete='';text_insert='';break;}}
if(diffs[diffs.length-1][1]===''){diffs.pop();}
var changes=false;pointer=1;while(pointer<diffs.length-1){if(diffs[pointer-1][0]==DIFF_EQUAL&&diffs[pointer+1][0]==DIFF_EQUAL){if(diffs[pointer][1].substring(diffs[pointer][1].length-
diffs[pointer-1][1].length)==diffs[pointer-1][1]){diffs[pointer][1]=diffs[pointer-1][1]+
diffs[pointer][1].substring(0,diffs[pointer][1].length-
diffs[pointer-1][1].length);diffs[pointer+1][1]=diffs[pointer-1][1]+diffs[pointer+1][1];diffs.splice(pointer-1,1);changes=true;}else if(diffs[pointer][1].substring(0,diffs[pointer+1][1].length)==diffs[pointer+1][1]){diffs[pointer-1][1]+=diffs[pointer+1][1];diffs[pointer][1]=diffs[pointer][1].substring(diffs[pointer+1][1].length)+
diffs[pointer+1][1];diffs.splice(pointer+1,1);changes=true;}}
pointer++;}
if(changes){this.diff_cleanupMerge(diffs);}};diff_match_patch.prototype.diff_xIndex=function(diffs,loc){var chars1=0;var chars2=0;var last_chars1=0;var last_chars2=0;var x;for(x=0;x<diffs.length;x++){if(diffs[x][0]!==DIFF_INSERT){chars1+=diffs[x][1].length;}
if(diffs[x][0]!==DIFF_DELETE){chars2+=diffs[x][1].length;}
if(chars1>loc){break;}
last_chars1=chars1;last_chars2=chars2;}
if(diffs.length!=x&&diffs[x][0]===DIFF_DELETE){return last_chars2;}
return last_chars2+(loc-last_chars1);};diff_match_patch.prototype.diff_prettyHtml=function(diffs){var html=[];var pattern_amp=/&/g;var pattern_lt=/</g;var pattern_gt=/>/g;var pattern_para=/\n/g;for(var x=0;x<diffs.length;x++){var op=diffs[x][0];var data=diffs[x][1];var text=data.replace(pattern_amp,'&amp;').replace(pattern_lt,'&lt;').replace(pattern_gt,'&gt;').replace(pattern_para,'&para;<br>');switch(op){case DIFF_INSERT:html[x]='<ins style="background:#e6ffe6;">'+text+'</ins>';break;case DIFF_DELETE:html[x]='<del style="background:#ffe6e6;">'+text+'</del>';break;case DIFF_EQUAL:html[x]='<span>'+text+'</span>';break;}}
return html.join('');};diff_match_patch.prototype.diff_text1=function(diffs){var text=[];for(var x=0;x<diffs.length;x++){if(diffs[x][0]!==DIFF_INSERT){text[x]=diffs[x][1];}}
return text.join('');};diff_match_patch.prototype.diff_text2=function(diffs){var text=[];for(var x=0;x<diffs.length;x++){if(diffs[x][0]!==DIFF_DELETE){text[x]=diffs[x][1];}}
return text.join('');};diff_match_patch.prototype.diff_levenshtein=function(diffs){var levenshtein=0;var insertions=0;var deletions=0;for(var x=0;x<diffs.length;x++){var op=diffs[x][0];var data=diffs[x][1];switch(op){case DIFF_INSERT:insertions+=data.length;break;case DIFF_DELETE:deletions+=data.length;break;case DIFF_EQUAL:levenshtein+=Math.max(insertions,deletions);insertions=0;deletions=0;break;}}
levenshtein+=Math.max(insertions,deletions);return levenshtein;};diff_match_patch.prototype.diff_toDelta=function(diffs){var text=[];for(var x=0;x<diffs.length;x++){switch(diffs[x][0]){case DIFF_INSERT:text[x]='+'+encodeURI(diffs[x][1]);break;case DIFF_DELETE:text[x]='-'+diffs[x][1].length;break;case DIFF_EQUAL:text[x]='='+diffs[x][1].length;break;}}
return text.join('\t').replace(/%20/g,' ');};diff_match_patch.prototype.diff_fromDelta=function(text1,delta){var diffs=[];var diffsLength=0;var pointer=0;var tokens=delta.split(/\t/g);for(var x=0;x<tokens.length;x++){var param=tokens[x].substring(1);switch(tokens[x].charAt(0)){case'+':try{diffs[diffsLength++]=[DIFF_INSERT,decodeURI(param)];}catch(ex){throw new Error('Illegal escape in diff_fromDelta: '+param);}
break;case'-':case'=':var n=parseInt(param,10);if(isNaN(n)||n<0){throw new Error('Invalid number in diff_fromDelta: '+param);}
var text=text1.substring(pointer,pointer+=n);if(tokens[x].charAt(0)=='='){diffs[diffsLength++]=[DIFF_EQUAL,text];}else{diffs[diffsLength++]=[DIFF_DELETE,text];}
break;default:if(tokens[x]){throw new Error('Invalid diff operation in diff_fromDelta: '+
tokens[x]);}}}
if(pointer!=text1.length){throw new Error('Delta length ('+pointer+') does not equal source text length ('+text1.length+').');}
return diffs;};diff_match_patch.prototype.match_main=function(text,pattern,loc){if(text==null||pattern==null||loc==null){throw new Error('Null input. (match_main)');}
loc=Math.max(0,Math.min(loc,text.length));if(text==pattern){return 0;}else if(!text.length){return-1;}else if(text.substring(loc,loc+pattern.length)==pattern){return loc;}else{return this.match_bitap_(text,pattern,loc);}};diff_match_patch.prototype.match_bitap_=function(text,pattern,loc){if(pattern.length>this.Match_MaxBits){throw new Error('Pattern too long for this browser.');}
var s=this.match_alphabet_(pattern);var dmp=this;function match_bitapScore_(e,x){var accuracy=e/pattern.length;var proximity=Math.abs(loc-x);if(!dmp.Match_Distance){return proximity?1.0:accuracy;}
return accuracy+(proximity/dmp.Match_Distance);}
var score_threshold=this.Match_Threshold;var best_loc=text.indexOf(pattern,loc);if(best_loc!=-1){score_threshold=Math.min(match_bitapScore_(0,best_loc),score_threshold);best_loc=text.lastIndexOf(pattern,loc+pattern.length);if(best_loc!=-1){score_threshold=Math.min(match_bitapScore_(0,best_loc),score_threshold);}}
var matchmask=1<<(pattern.length-1);best_loc=-1;var bin_min,bin_mid;var bin_max=pattern.length+text.length;var last_rd;for(var d=0;d<pattern.length;d++){bin_min=0;bin_mid=bin_max;while(bin_min<bin_mid){if(match_bitapScore_(d,loc+bin_mid)<=score_threshold){bin_min=bin_mid;}else{bin_max=bin_mid;}
bin_mid=Math.floor((bin_max-bin_min)/2+bin_min);}
bin_max=bin_mid;var start=Math.max(1,loc-bin_mid+1);var finish=Math.min(loc+bin_mid,text.length)+pattern.length;var rd=Array(finish+2);rd[finish+1]=(1<<d)-1;for(var j=finish;j>=start;j--){var charMatch=s[text.charAt(j-1)];if(d===0){rd[j]=((rd[j+1]<<1)|1)&charMatch;}else{rd[j]=(((rd[j+1]<<1)|1)&charMatch)|(((last_rd[j+1]|last_rd[j])<<1)|1)|last_rd[j+1];}
if(rd[j]&matchmask){var score=match_bitapScore_(d,j-1);if(score<=score_threshold){score_threshold=score;best_loc=j-1;if(best_loc>loc){start=Math.max(1,2*loc-best_loc);}else{break;}}}}
if(match_bitapScore_(d+1,loc)>score_threshold){break;}
last_rd=rd;}
return best_loc;};diff_match_patch.prototype.match_alphabet_=function(pattern){var s={};for(var i=0;i<pattern.length;i++){s[pattern.charAt(i)]=0;}
for(var i=0;i<pattern.length;i++){s[pattern.charAt(i)]|=1<<(pattern.length-i-1);}
return s;};diff_match_patch.prototype.patch_addContext_=function(patch,text){if(text.length==0){return;}
var pattern=text.substring(patch.start2,patch.start2+patch.length1);var padding=0;while(text.indexOf(pattern)!=text.lastIndexOf(pattern)&&pattern.length<this.Match_MaxBits-this.Patch_Margin-
this.Patch_Margin){padding+=this.Patch_Margin;pattern=text.substring(patch.start2-padding,patch.start2+patch.length1+padding);}
padding+=this.Patch_Margin;var prefix=text.substring(patch.start2-padding,patch.start2);if(prefix){patch.diffs.unshift([DIFF_EQUAL,prefix]);}
var suffix=text.substring(patch.start2+patch.length1,patch.start2+patch.length1+padding);if(suffix){patch.diffs.push([DIFF_EQUAL,suffix]);}
patch.start1-=prefix.length;patch.start2-=prefix.length;patch.length1+=prefix.length+suffix.length;patch.length2+=prefix.length+suffix.length;};diff_match_patch.prototype.patch_make=function(a,opt_b,opt_c){var text1,diffs;if(typeof a=='string'&&typeof opt_b=='string'&&typeof opt_c=='undefined'){text1=(a);diffs=this.diff_main(text1,(opt_b),true);if(diffs.length>2){this.diff_cleanupSemantic(diffs);this.diff_cleanupEfficiency(diffs);}}else if(a&&typeof a=='object'&&typeof opt_b=='undefined'&&typeof opt_c=='undefined'){diffs=(a);text1=this.diff_text1(diffs);}else if(typeof a=='string'&&opt_b&&typeof opt_b=='object'&&typeof opt_c=='undefined'){text1=(a);diffs=(opt_b);}else if(typeof a=='string'&&typeof opt_b=='string'&&opt_c&&typeof opt_c=='object'){text1=(a);diffs=(opt_c);}else{throw new Error('Unknown call format to patch_make.');}
if(diffs.length===0){return[];}
var patches=[];var patch=new diff_match_patch.patch_obj();var patchDiffLength=0;var char_count1=0;var char_count2=0;var prepatch_text=text1;var postpatch_text=text1;for(var x=0;x<diffs.length;x++){var diff_type=diffs[x][0];var diff_text=diffs[x][1];if(!patchDiffLength&&diff_type!==DIFF_EQUAL){patch.start1=char_count1;patch.start2=char_count2;}
switch(diff_type){case DIFF_INSERT:patch.diffs[patchDiffLength++]=diffs[x];patch.length2+=diff_text.length;postpatch_text=postpatch_text.substring(0,char_count2)+diff_text+
postpatch_text.substring(char_count2);break;case DIFF_DELETE:patch.length1+=diff_text.length;patch.diffs[patchDiffLength++]=diffs[x];postpatch_text=postpatch_text.substring(0,char_count2)+
postpatch_text.substring(char_count2+
diff_text.length);break;case DIFF_EQUAL:if(diff_text.length<=2*this.Patch_Margin&&patchDiffLength&&diffs.length!=x+1){patch.diffs[patchDiffLength++]=diffs[x];patch.length1+=diff_text.length;patch.length2+=diff_text.length;}else if(diff_text.length>=2*this.Patch_Margin){if(patchDiffLength){this.patch_addContext_(patch,prepatch_text);patches.push(patch);patch=new diff_match_patch.patch_obj();patchDiffLength=0;prepatch_text=postpatch_text;char_count1=char_count2;}}
break;}
if(diff_type!==DIFF_INSERT){char_count1+=diff_text.length;}
if(diff_type!==DIFF_DELETE){char_count2+=diff_text.length;}}
if(patchDiffLength){this.patch_addContext_(patch,prepatch_text);patches.push(patch);}
return patches;};diff_match_patch.prototype.patch_deepCopy=function(patches){var patchesCopy=[];for(var x=0;x<patches.length;x++){var patch=patches[x];var patchCopy=new diff_match_patch.patch_obj();patchCopy.diffs=[];for(var y=0;y<patch.diffs.length;y++){patchCopy.diffs[y]=patch.diffs[y].slice();}
patchCopy.start1=patch.start1;patchCopy.start2=patch.start2;patchCopy.length1=patch.length1;patchCopy.length2=patch.length2;patchesCopy[x]=patchCopy;}
return patchesCopy;};diff_match_patch.prototype.patch_apply=function(patches,text){if(patches.length==0){return[text,[]];}
patches=this.patch_deepCopy(patches);var nullPadding=this.patch_addPadding(patches);text=nullPadding+text+nullPadding;this.patch_splitMax(patches);var delta=0;var results=[];for(var x=0;x<patches.length;x++){var expected_loc=patches[x].start2+delta;var text1=this.diff_text1(patches[x].diffs);var start_loc;var end_loc=-1;if(text1.length>this.Match_MaxBits){start_loc=this.match_main(text,text1.substring(0,this.Match_MaxBits),expected_loc);if(start_loc!=-1){end_loc=this.match_main(text,text1.substring(text1.length-this.Match_MaxBits),expected_loc+text1.length-this.Match_MaxBits);if(end_loc==-1||start_loc>=end_loc){start_loc=-1;}}}else{start_loc=this.match_main(text,text1,expected_loc);}
if(start_loc==-1){results[x]=false;delta-=patches[x].length2-patches[x].length1;}else{results[x]=true;delta=start_loc-expected_loc;var text2;if(end_loc==-1){text2=text.substring(start_loc,start_loc+text1.length);}else{text2=text.substring(start_loc,end_loc+this.Match_MaxBits);}
if(text1==text2){text=text.substring(0,start_loc)+
this.diff_text2(patches[x].diffs)+
text.substring(start_loc+text1.length);}else{var diffs=this.diff_main(text1,text2,false);if(text1.length>this.Match_MaxBits&&this.diff_levenshtein(diffs)/text1.length>this.Patch_DeleteThreshold){results[x]=false;}else{this.diff_cleanupSemanticLossless(diffs);var index1=0;var index2;for(var y=0;y<patches[x].diffs.length;y++){var mod=patches[x].diffs[y];if(mod[0]!==DIFF_EQUAL){index2=this.diff_xIndex(diffs,index1);}
if(mod[0]===DIFF_INSERT){text=text.substring(0,start_loc+index2)+mod[1]+
text.substring(start_loc+index2);}else if(mod[0]===DIFF_DELETE){text=text.substring(0,start_loc+index2)+
text.substring(start_loc+this.diff_xIndex(diffs,index1+mod[1].length));}
if(mod[0]!==DIFF_DELETE){index1+=mod[1].length;}}}}}}
text=text.substring(nullPadding.length,text.length-nullPadding.length);return[text,results];};diff_match_patch.prototype.patch_addPadding=function(patches){var paddingLength=this.Patch_Margin;var nullPadding='';for(var x=1;x<=paddingLength;x++){nullPadding+=String.fromCharCode(x);}
for(var x=0;x<patches.length;x++){patches[x].start1+=paddingLength;patches[x].start2+=paddingLength;}
var patch=patches[0];var diffs=patch.diffs;if(diffs.length==0||diffs[0][0]!=DIFF_EQUAL){diffs.unshift([DIFF_EQUAL,nullPadding]);patch.start1-=paddingLength;patch.start2-=paddingLength;patch.length1+=paddingLength;patch.length2+=paddingLength;}else if(paddingLength>diffs[0][1].length){var extraLength=paddingLength-diffs[0][1].length;diffs[0][1]=nullPadding.substring(diffs[0][1].length)+diffs[0][1];patch.start1-=extraLength;patch.start2-=extraLength;patch.length1+=extraLength;patch.length2+=extraLength;}
patch=patches[patches.length-1];diffs=patch.diffs;if(diffs.length==0||diffs[diffs.length-1][0]!=DIFF_EQUAL){diffs.push([DIFF_EQUAL,nullPadding]);patch.length1+=paddingLength;patch.length2+=paddingLength;}else if(paddingLength>diffs[diffs.length-1][1].length){var extraLength=paddingLength-diffs[diffs.length-1][1].length;diffs[diffs.length-1][1]+=nullPadding.substring(0,extraLength);patch.length1+=extraLength;patch.length2+=extraLength;}
return nullPadding;};diff_match_patch.prototype.patch_splitMax=function(patches){var patch_size=this.Match_MaxBits;for(var x=0;x<patches.length;x++){if(patches[x].length1<=patch_size){continue;}
var bigpatch=patches[x];patches.splice(x--,1);var start1=bigpatch.start1;var start2=bigpatch.start2;var precontext='';while(bigpatch.diffs.length!==0){var patch=new diff_match_patch.patch_obj();var empty=true;patch.start1=start1-precontext.length;patch.start2=start2-precontext.length;if(precontext!==''){patch.length1=patch.length2=precontext.length;patch.diffs.push([DIFF_EQUAL,precontext]);}
while(bigpatch.diffs.length!==0&&patch.length1<patch_size-this.Patch_Margin){var diff_type=bigpatch.diffs[0][0];var diff_text=bigpatch.diffs[0][1];if(diff_type===DIFF_INSERT){patch.length2+=diff_text.length;start2+=diff_text.length;patch.diffs.push(bigpatch.diffs.shift());empty=false;}else if(diff_type===DIFF_DELETE&&patch.diffs.length==1&&patch.diffs[0][0]==DIFF_EQUAL&&diff_text.length>2*patch_size){patch.length1+=diff_text.length;start1+=diff_text.length;empty=false;patch.diffs.push([diff_type,diff_text]);bigpatch.diffs.shift();}else{diff_text=diff_text.substring(0,patch_size-patch.length1-this.Patch_Margin);patch.length1+=diff_text.length;start1+=diff_text.length;if(diff_type===DIFF_EQUAL){patch.length2+=diff_text.length;start2+=diff_text.length;}else{empty=false;}
patch.diffs.push([diff_type,diff_text]);if(diff_text==bigpatch.diffs[0][1]){bigpatch.diffs.shift();}else{bigpatch.diffs[0][1]=bigpatch.diffs[0][1].substring(diff_text.length);}}}
precontext=this.diff_text2(patch.diffs);precontext=precontext.substring(precontext.length-this.Patch_Margin);var postcontext=this.diff_text1(bigpatch.diffs).substring(0,this.Patch_Margin);if(postcontext!==''){patch.length1+=postcontext.length;patch.length2+=postcontext.length;if(patch.diffs.length!==0&&patch.diffs[patch.diffs.length-1][0]===DIFF_EQUAL){patch.diffs[patch.diffs.length-1][1]+=postcontext;}else{patch.diffs.push([DIFF_EQUAL,postcontext]);}}
if(!empty){patches.splice(++x,0,patch);}}}};diff_match_patch.prototype.patch_toText=function(patches){var text=[];for(var x=0;x<patches.length;x++){text[x]=patches[x];}
return text.join('');};diff_match_patch.prototype.patch_fromText=function(textline){var patches=[];if(!textline){return patches;}
var text=textline.split('\n');var textPointer=0;var patchHeader=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;while(textPointer<text.length){var m=text[textPointer].match(patchHeader);if(!m){throw new Error('Invalid patch string: '+text[textPointer]);}
var patch=new diff_match_patch.patch_obj();patches.push(patch);patch.start1=parseInt(m[1],10);if(m[2]===''){patch.start1--;patch.length1=1;}else if(m[2]=='0'){patch.length1=0;}else{patch.start1--;patch.length1=parseInt(m[2],10);}
patch.start2=parseInt(m[3],10);if(m[4]===''){patch.start2--;patch.length2=1;}else if(m[4]=='0'){patch.length2=0;}else{patch.start2--;patch.length2=parseInt(m[4],10);}
textPointer++;while(textPointer<text.length){var sign=text[textPointer].charAt(0);try{var line=decodeURI(text[textPointer].substring(1));}catch(ex){throw new Error('Illegal escape in patch_fromText: '+line);}
if(sign=='-'){patch.diffs.push([DIFF_DELETE,line]);}else if(sign=='+'){patch.diffs.push([DIFF_INSERT,line]);}else if(sign==' '){patch.diffs.push([DIFF_EQUAL,line]);}else if(sign=='@'){break;}else if(sign===''){}else{throw new Error('Invalid patch mode "'+sign+'" in: '+line);}
textPointer++;}}
return patches;};diff_match_patch.patch_obj=function(){this.diffs=[];this.start1=null;this.start2=null;this.length1=0;this.length2=0;};diff_match_patch.patch_obj.prototype.toString=function(){var coords1,coords2;if(this.length1===0){coords1=this.start1+',0';}else if(this.length1==1){coords1=this.start1+1;}else{coords1=(this.start1+1)+','+this.length1;}
if(this.length2===0){coords2=this.start2+',0';}else if(this.length2==1){coords2=this.start2+1;}else{coords2=(this.start2+1)+','+this.length2;}
var text=['@@ -'+coords1+' +'+coords2+' @@\n'];var op;for(var x=0;x<this.diffs.length;x++){switch(this.diffs[x][0]){case DIFF_INSERT:op='+';break;case DIFF_DELETE:op='-';break;case DIFF_EQUAL:op=' ';break;}
text[x+1]=op+encodeURI(this.diffs[x][1])+'\n';}
return text.join('').replace(/%20/g,' ');};this['diff_match_patch']=diff_match_patch;this['DIFF_DELETE']=DIFF_DELETE;this['DIFF_INSERT']=DIFF_INSERT;this['DIFF_EQUAL']=DIFF_EQUAL;(function($,len,createRange,duplicate){$.fn.caret=function(options,opt2){var start,end,t=this[0];if(typeof options==="object"&&typeof options.start==="number"&&typeof options.end==="number"){start=options.start;end=options.end;}else if(typeof options==="number"&&typeof opt2==="number"){start=options;end=opt2;}else if(typeof options==="string"){if((start=t.value.indexOf(options))>-1)end=start+options[len];else start=null;}else if(Object.prototype.toString.call(options)==="[object RegExp]"){var re=options.exec(t.value);if(re!=null){start=re.index;end=start+re[0][len];}}
if(typeof start!="undefined"){this[0].selectionStart=start;this[0].selectionEnd=end;this[0].focus();return this}else{var s=t.selectionStart,e=t.selectionEnd;var te=t.value.substring(s,e);return{start:s,end:e,text:te,replace:function(st){return t.value.substring(0,s)+st+t.value.substring(e,t.value[len])}}}}})(jQuery,"length","createRange","duplicate");(function($){$.fn.highlightRegex=function(regex){if(regex==undefined||regex.source==''){$(this).find('span.highlight').each(function(){$(this).replaceWith($(this).text());$(this).parent().each(function(){node=$(this).get(0);if(node.normalize)node.normalize();});});}else{$(this).each(function(){elt=$(this).get(0)
elt.normalize();$.each($.makeArray(elt.childNodes),function(i,node){if(node.nodeType==3){var searchnode=node
while((pos=searchnode.data.search(regex))>=0){match=searchnode.data.slice(pos).match(regex)[0];if(match.length==0)break;var spannode=document.createElement('span');spannode.className='highlight';var middlebit=searchnode.splitText(pos);var searchnode=middlebit.splitText(match.length);var middleclone=middlebit.cloneNode(true);spannode.appendChild(middleclone);searchnode.parentNode.replaceChild(spannode,middlebit);}}else{$(node).highlightRegex(regex);}})})}
return $(this);}})(jQuery);(function($){function noop(){}
function genericCallback(data){lastValue=[data];}
function callIfDefined(method,object,parameters){return method&&method.apply&&method.apply(object.context||object,parameters);}
function qMarkOrAmp(url){return/\?/.test(url)?"&":"?";}
var
STR_ASYNC="async",STR_CHARSET="charset",STR_EMPTY="",STR_ERROR="error",STR_INSERT_BEFORE="insertBefore",STR_JQUERY_JSONP="_jqjsp",STR_ON="on",STR_ON_CLICK=STR_ON+"click",STR_ON_ERROR=STR_ON+STR_ERROR,STR_ON_LOAD=STR_ON+"load",STR_ON_READY_STATE_CHANGE=STR_ON+"readystatechange",STR_READY_STATE="readyState",STR_REMOVE_CHILD="removeChild",STR_SCRIPT_TAG="<script>",STR_SUCCESS="success",STR_TIMEOUT="timeout",win=window,Deferred=$.Deferred,head=$("head")[0]||document.documentElement,pageCache={},count=0,lastValue,xOptionsDefaults={callback:STR_JQUERY_JSONP,url:location.href},opera=win.opera,oldIE=!!$("<div>").html("<!--[if IE]><i><![endif]-->").find("i").length;function jsonp(xOptions){xOptions=$.extend({},xOptionsDefaults,xOptions);var successCallback=xOptions.success,errorCallback=xOptions.error,completeCallback=xOptions.complete,dataFilter=xOptions.dataFilter,callbackParameter=xOptions.callbackParameter,successCallbackName=xOptions.callback,cacheFlag=xOptions.cache,pageCacheFlag=xOptions.pageCache,charset=xOptions.charset,url=xOptions.url,data=xOptions.data,timeout=xOptions.timeout,pageCached,done=0,cleanUp=noop,supportOnload,supportOnreadystatechange,firstChild,script,scriptAfter,timeoutTimer;Deferred&&Deferred(function(defer){defer.done(successCallback).fail(errorCallback);successCallback=defer.resolve;errorCallback=defer.reject;}).promise(xOptions);xOptions.abort=function(){!(done++)&&cleanUp();};if(callIfDefined(xOptions.beforeSend,xOptions,[xOptions])===!1||done){return xOptions;}
url=url||STR_EMPTY;data=data?((typeof data)=="string"?data:$.param(data,xOptions.traditional)):STR_EMPTY;url+=data?(qMarkOrAmp(url)+data):STR_EMPTY;callbackParameter&&(url+=qMarkOrAmp(url)+encodeURIComponent(callbackParameter)+"=?");!cacheFlag&&!pageCacheFlag&&(url+=qMarkOrAmp(url)+"_"+(new Date()).getTime()+"=");url=url.replace(/=\?(&|$)/,"="+successCallbackName+"$1");function notifySuccess(json){if(!(done++)){cleanUp();pageCacheFlag&&(pageCache[url]={s:[json]});dataFilter&&(json=dataFilter.apply(xOptions,[json]));callIfDefined(successCallback,xOptions,[json,STR_SUCCESS,xOptions]);callIfDefined(completeCallback,xOptions,[xOptions,STR_SUCCESS]);}}
function notifyError(type){if(!(done++)){cleanUp();pageCacheFlag&&type!=STR_TIMEOUT&&(pageCache[url]=type);callIfDefined(errorCallback,xOptions,[xOptions,type]);callIfDefined(completeCallback,xOptions,[xOptions,type]);}}
if(pageCacheFlag&&(pageCached=pageCache[url])){pageCached.s?notifySuccess(pageCached.s[0]):notifyError(pageCached);}else{win[successCallbackName]=genericCallback;script=$(STR_SCRIPT_TAG)[0];script.id=STR_JQUERY_JSONP+count++;if(charset){script[STR_CHARSET]=charset;}
opera&&opera.version()<11.60?((scriptAfter=$(STR_SCRIPT_TAG)[0]).text="document.getElementById('"+script.id+"')."+STR_ON_ERROR+"()"):(script[STR_ASYNC]=STR_ASYNC);if(oldIE){script.htmlFor=script.id;script.event=STR_ON_CLICK;}
script[STR_ON_LOAD]=script[STR_ON_ERROR]=script[STR_ON_READY_STATE_CHANGE]=function(result){if(!script[STR_READY_STATE]||!/i/.test(script[STR_READY_STATE])){try{script[STR_ON_CLICK]&&script[STR_ON_CLICK]();}catch(_){}
result=lastValue;lastValue=0;result?notifySuccess(result[0]):notifyError(STR_ERROR);}};script.src=url;cleanUp=function(i){timeoutTimer&&clearTimeout(timeoutTimer);script[STR_ON_READY_STATE_CHANGE]=script[STR_ON_LOAD]=script[STR_ON_ERROR]=null;head[STR_REMOVE_CHILD](script);scriptAfter&&head[STR_REMOVE_CHILD](scriptAfter);};head[STR_INSERT_BEFORE](script,(firstChild=head.firstChild));scriptAfter&&head[STR_INSERT_BEFORE](scriptAfter,firstChild);timeoutTimer=timeout>0&&setTimeout(function(){notifyError(STR_TIMEOUT);},timeout);}
return xOptions;}
jsonp.setup=function(xOptions){$.extend(xOptionsDefaults,xOptions);};$.jsonp=jsonp;})(jQuery);(function(Date,undefined){var origParse=Date.parse,numericKeys=[1,4,5,6,7,10,11];Date.parse=function(date){var timestamp,struct,minutesOffset=0;if((struct=/^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))){for(var i=0,k;(k=numericKeys[i]);++i){struct[k]=+struct[k]||0;}
struct[2]=(+struct[2]||1)-1;struct[3]=+struct[3]||1;if(struct[8]!=='Z'&&struct[9]!==undefined){minutesOffset=struct[10]*60+struct[11];if(struct[9]==='+'){minutesOffset=0-minutesOffset;}}
timestamp=Date.UTC(struct[1],struct[2],struct[3],struct[4],struct[5]+minutesOffset,struct[6],struct[7]);}
else{timestamp=origParse?origParse(date):NaN;}
return timestamp;};}(Date));(function(){var root=this;var previousUnderscore=root._;var breaker={};var ArrayProto=Array.prototype,ObjProto=Object.prototype,FuncProto=Function.prototype;var
push=ArrayProto.push,slice=ArrayProto.slice,concat=ArrayProto.concat,toString=ObjProto.toString,hasOwnProperty=ObjProto.hasOwnProperty;var
nativeForEach=ArrayProto.forEach,nativeMap=ArrayProto.map,nativeReduce=ArrayProto.reduce,nativeReduceRight=ArrayProto.reduceRight,nativeFilter=ArrayProto.filter,nativeEvery=ArrayProto.every,nativeSome=ArrayProto.some,nativeIndexOf=ArrayProto.indexOf,nativeLastIndexOf=ArrayProto.lastIndexOf,nativeIsArray=Array.isArray,nativeKeys=Object.keys,nativeBind=FuncProto.bind;var _=function(obj){if(obj instanceof _)return obj;if(!(this instanceof _))return new _(obj);this._wrapped=obj;};if(typeof exports!=='undefined'){if(typeof module!=='undefined'&&module.exports){exports=module.exports=_;}
exports._=_;}else{root._=_;}
_.VERSION='1.6.0';var each=_.each=_.forEach=function(obj,iterator,context){if(obj==null)return obj;if(nativeForEach&&obj.forEach===nativeForEach){obj.forEach(iterator,context);}else if(obj.length===+obj.length){for(var i=0,length=obj.length;i<length;i++){if(iterator.call(context,obj[i],i,obj)===breaker)return;}}else{var keys=_.keys(obj);for(var i=0,length=keys.length;i<length;i++){if(iterator.call(context,obj[keys[i]],keys[i],obj)===breaker)return;}}
return obj;};_.map=_.collect=function(obj,iterator,context){var results=[];if(obj==null)return results;if(nativeMap&&obj.map===nativeMap)return obj.map(iterator,context);each(obj,function(value,index,list){results.push(iterator.call(context,value,index,list));});return results;};var reduceError='Reduce of empty array with no initial value';_.reduce=_.foldl=_.inject=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduce&&obj.reduce===nativeReduce){if(context)iterator=_.bind(iterator,context);return initial?obj.reduce(iterator,memo):obj.reduce(iterator);}
each(obj,function(value,index,list){if(!initial){memo=value;initial=true;}else{memo=iterator.call(context,memo,value,index,list);}});if(!initial)throw new TypeError(reduceError);return memo;};_.reduceRight=_.foldr=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduceRight&&obj.reduceRight===nativeReduceRight){if(context)iterator=_.bind(iterator,context);return initial?obj.reduceRight(iterator,memo):obj.reduceRight(iterator);}
var length=obj.length;if(length!==+length){var keys=_.keys(obj);length=keys.length;}
each(obj,function(value,index,list){index=keys?keys[--length]:--length;if(!initial){memo=obj[index];initial=true;}else{memo=iterator.call(context,memo,obj[index],index,list);}});if(!initial)throw new TypeError(reduceError);return memo;};_.find=_.detect=function(obj,predicate,context){var result;any(obj,function(value,index,list){if(predicate.call(context,value,index,list)){result=value;return true;}});return result;};_.filter=_.select=function(obj,predicate,context){var results=[];if(obj==null)return results;if(nativeFilter&&obj.filter===nativeFilter)return obj.filter(predicate,context);each(obj,function(value,index,list){if(predicate.call(context,value,index,list))results.push(value);});return results;};_.reject=function(obj,predicate,context){return _.filter(obj,function(value,index,list){return!predicate.call(context,value,index,list);},context);};_.every=_.all=function(obj,predicate,context){predicate||(predicate=_.identity);var result=true;if(obj==null)return result;if(nativeEvery&&obj.every===nativeEvery)return obj.every(predicate,context);each(obj,function(value,index,list){if(!(result=result&&predicate.call(context,value,index,list)))return breaker;});return!!result;};var any=_.some=_.any=function(obj,predicate,context){predicate||(predicate=_.identity);var result=false;if(obj==null)return result;if(nativeSome&&obj.some===nativeSome)return obj.some(predicate,context);each(obj,function(value,index,list){if(result||(result=predicate.call(context,value,index,list)))return breaker;});return!!result;};_.contains=_.include=function(obj,target){if(obj==null)return false;if(nativeIndexOf&&obj.indexOf===nativeIndexOf)return obj.indexOf(target)!=-1;return any(obj,function(value){return value===target;});};_.invoke=function(obj,method){var args=slice.call(arguments,2);var isFunc=_.isFunction(method);return _.map(obj,function(value){return(isFunc?method:value[method]).apply(value,args);});};_.pluck=function(obj,key){return _.map(obj,_.property(key));};_.where=function(obj,attrs){return _.filter(obj,_.matches(attrs));};_.findWhere=function(obj,attrs){return _.find(obj,_.matches(attrs));};_.max=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.max.apply(Math,obj);}
var result=-Infinity,lastComputed=-Infinity;each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;if(computed>lastComputed){result=value;lastComputed=computed;}});return result;};_.min=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.min.apply(Math,obj);}
var result=Infinity,lastComputed=Infinity;each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;if(computed<lastComputed){result=value;lastComputed=computed;}});return result;};_.shuffle=function(obj){var rand;var index=0;var shuffled=[];each(obj,function(value){rand=_.random(index++);shuffled[index-1]=shuffled[rand];shuffled[rand]=value;});return shuffled;};_.sample=function(obj,n,guard){if(n==null||guard){if(obj.length!==+obj.length)obj=_.values(obj);return obj[_.random(obj.length-1)];}
return _.shuffle(obj).slice(0,Math.max(0,n));};var lookupIterator=function(value){if(value==null)return _.identity;if(_.isFunction(value))return value;return _.property(value);};_.sortBy=function(obj,iterator,context){iterator=lookupIterator(iterator);return _.pluck(_.map(obj,function(value,index,list){return{value:value,index:index,criteria:iterator.call(context,value,index,list)};}).sort(function(left,right){var a=left.criteria;var b=right.criteria;if(a!==b){if(a>b||a===void 0)return 1;if(a<b||b===void 0)return-1;}
return left.index-right.index;}),'value');};var group=function(behavior){return function(obj,iterator,context){var result={};iterator=lookupIterator(iterator);each(obj,function(value,index){var key=iterator.call(context,value,index,obj);behavior(result,key,value);});return result;};};_.groupBy=group(function(result,key,value){_.has(result,key)?result[key].push(value):result[key]=[value];});_.indexBy=group(function(result,key,value){result[key]=value;});_.countBy=group(function(result,key){_.has(result,key)?result[key]++:result[key]=1;});_.sortedIndex=function(array,obj,iterator,context){iterator=lookupIterator(iterator);var value=iterator.call(context,obj);var low=0,high=array.length;while(low<high){var mid=(low+high)>>>1;iterator.call(context,array[mid])<value?low=mid+1:high=mid;}
return low;};_.toArray=function(obj){if(!obj)return[];if(_.isArray(obj))return slice.call(obj);if(obj.length===+obj.length)return _.map(obj,_.identity);return _.values(obj);};_.size=function(obj){if(obj==null)return 0;return(obj.length===+obj.length)?obj.length:_.keys(obj).length;};_.first=_.head=_.take=function(array,n,guard){if(array==null)return void 0;if((n==null)||guard)return array[0];if(n<0)return[];return slice.call(array,0,n);};_.initial=function(array,n,guard){return slice.call(array,0,array.length-((n==null)||guard?1:n));};_.last=function(array,n,guard){if(array==null)return void 0;if((n==null)||guard)return array[array.length-1];return slice.call(array,Math.max(array.length-n,0));};_.rest=_.tail=_.drop=function(array,n,guard){return slice.call(array,(n==null)||guard?1:n);};_.compact=function(array){return _.filter(array,_.identity);};var flatten=function(input,shallow,output){if(shallow&&_.every(input,_.isArray)){return concat.apply(output,input);}
each(input,function(value){if(_.isArray(value)||_.isArguments(value)){shallow?push.apply(output,value):flatten(value,shallow,output);}else{output.push(value);}});return output;};_.flatten=function(array,shallow){return flatten(array,shallow,[]);};_.without=function(array){return _.difference(array,slice.call(arguments,1));};_.partition=function(array,predicate){var pass=[],fail=[];each(array,function(elem){(predicate(elem)?pass:fail).push(elem);});return[pass,fail];};_.uniq=_.unique=function(array,isSorted,iterator,context){if(_.isFunction(isSorted)){context=iterator;iterator=isSorted;isSorted=false;}
var initial=iterator?_.map(array,iterator,context):array;var results=[];var seen=[];each(initial,function(value,index){if(isSorted?(!index||seen[seen.length-1]!==value):!_.contains(seen,value)){seen.push(value);results.push(array[index]);}});return results;};_.union=function(){return _.uniq(_.flatten(arguments,true));};_.intersection=function(array){var rest=slice.call(arguments,1);return _.filter(_.uniq(array),function(item){return _.every(rest,function(other){return _.contains(other,item);});});};_.difference=function(array){var rest=concat.apply(ArrayProto,slice.call(arguments,1));return _.filter(array,function(value){return!_.contains(rest,value);});};_.zip=function(){var length=_.max(_.pluck(arguments,'length').concat(0));var results=new Array(length);for(var i=0;i<length;i++){results[i]=_.pluck(arguments,''+i);}
return results;};_.object=function(list,values){if(list==null)return{};var result={};for(var i=0,length=list.length;i<length;i++){if(values){result[list[i]]=values[i];}else{result[list[i][0]]=list[i][1];}}
return result;};_.indexOf=function(array,item,isSorted){if(array==null)return-1;var i=0,length=array.length;if(isSorted){if(typeof isSorted=='number'){i=(isSorted<0?Math.max(0,length+isSorted):isSorted);}else{i=_.sortedIndex(array,item);return array[i]===item?i:-1;}}
if(nativeIndexOf&&array.indexOf===nativeIndexOf)return array.indexOf(item,isSorted);for(;i<length;i++)if(array[i]===item)return i;return-1;};_.lastIndexOf=function(array,item,from){if(array==null)return-1;var hasIndex=from!=null;if(nativeLastIndexOf&&array.lastIndexOf===nativeLastIndexOf){return hasIndex?array.lastIndexOf(item,from):array.lastIndexOf(item);}
var i=(hasIndex?from:array.length);while(i--)if(array[i]===item)return i;return-1;};_.range=function(start,stop,step){if(arguments.length<=1){stop=start||0;start=0;}
step=arguments[2]||1;var length=Math.max(Math.ceil((stop-start)/step),0);var idx=0;var range=new Array(length);while(idx<length){range[idx++]=start;start+=step;}
return range;};var ctor=function(){};_.bind=function(func,context){var args,bound;if(nativeBind&&func.bind===nativeBind)return nativeBind.apply(func,slice.call(arguments,1));if(!_.isFunction(func))throw new TypeError;args=slice.call(arguments,2);return bound=function(){if(!(this instanceof bound))return func.apply(context,args.concat(slice.call(arguments)));ctor.prototype=func.prototype;var self=new ctor;ctor.prototype=null;var result=func.apply(self,args.concat(slice.call(arguments)));if(Object(result)===result)return result;return self;};};_.partial=function(func){var boundArgs=slice.call(arguments,1);return function(){var position=0;var args=boundArgs.slice();for(var i=0,length=args.length;i<length;i++){if(args[i]===_)args[i]=arguments[position++];}
while(position<arguments.length)args.push(arguments[position++]);return func.apply(this,args);};};_.bindAll=function(obj){var funcs=slice.call(arguments,1);if(funcs.length===0)throw new Error('bindAll must be passed function names');each(funcs,function(f){obj[f]=_.bind(obj[f],obj);});return obj;};_.memoize=function(func,hasher){var memo={};hasher||(hasher=_.identity);return function(){var key=hasher.apply(this,arguments);return _.has(memo,key)?memo[key]:(memo[key]=func.apply(this,arguments));};};_.delay=function(func,wait){var args=slice.call(arguments,2);return setTimeout(function(){return func.apply(null,args);},wait);};_.defer=function(func){return _.delay.apply(_,[func,1].concat(slice.call(arguments,1)));};_.throttle=function(func,wait,options){var context,args,result;var timeout=null;var previous=0;options||(options={});var later=function(){previous=options.leading===false?0:_.now();timeout=null;result=func.apply(context,args);context=args=null;};return function(){var now=_.now();if(!previous&&options.leading===false)previous=now;var remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0){clearTimeout(timeout);timeout=null;previous=now;result=func.apply(context,args);context=args=null;}else if(!timeout&&options.trailing!==false){timeout=setTimeout(later,remaining);}
return result;};};_.debounce=function(func,wait,immediate){var timeout,args,context,timestamp,result;var later=function(){var last=_.now()-timestamp;if(last<wait){timeout=setTimeout(later,wait-last);}else{timeout=null;if(!immediate){result=func.apply(context,args);context=args=null;}}};return function(){context=this;args=arguments;timestamp=_.now();var callNow=immediate&&!timeout;if(!timeout){timeout=setTimeout(later,wait);}
if(callNow){result=func.apply(context,args);context=args=null;}
return result;};};_.once=function(func){var ran=false,memo;return function(){if(ran)return memo;ran=true;memo=func.apply(this,arguments);func=null;return memo;};};_.wrap=function(func,wrapper){return _.partial(wrapper,func);};_.compose=function(){var funcs=arguments;return function(){var args=arguments;for(var i=funcs.length-1;i>=0;i--){args=[funcs[i].apply(this,args)];}
return args[0];};};_.after=function(times,func){return function(){if(--times<1){return func.apply(this,arguments);}};};_.keys=function(obj){if(!_.isObject(obj))return[];if(nativeKeys)return nativeKeys(obj);var keys=[];for(var key in obj)if(_.has(obj,key))keys.push(key);return keys;};_.values=function(obj){var keys=_.keys(obj);var length=keys.length;var values=new Array(length);for(var i=0;i<length;i++){values[i]=obj[keys[i]];}
return values;};_.pairs=function(obj){var keys=_.keys(obj);var length=keys.length;var pairs=new Array(length);for(var i=0;i<length;i++){pairs[i]=[keys[i],obj[keys[i]]];}
return pairs;};_.invert=function(obj){var result={};var keys=_.keys(obj);for(var i=0,length=keys.length;i<length;i++){result[obj[keys[i]]]=keys[i];}
return result;};_.functions=_.methods=function(obj){var names=[];for(var key in obj){if(_.isFunction(obj[key]))names.push(key);}
return names.sort();};_.extend=function(obj){each(slice.call(arguments,1),function(source){if(source){for(var prop in source){obj[prop]=source[prop];}}});return obj;};_.pick=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));each(keys,function(key){if(key in obj)copy[key]=obj[key];});return copy;};_.omit=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));for(var key in obj){if(!_.contains(keys,key))copy[key]=obj[key];}
return copy;};_.defaults=function(obj){each(slice.call(arguments,1),function(source){if(source){for(var prop in source){if(obj[prop]===void 0)obj[prop]=source[prop];}}});return obj;};_.clone=function(obj){if(!_.isObject(obj))return obj;return _.isArray(obj)?obj.slice():_.extend({},obj);};_.tap=function(obj,interceptor){interceptor(obj);return obj;};var eq=function(a,b,aStack,bStack){if(a===b)return a!==0||1/a==1/b;if(a==null||b==null)return a===b;if(a instanceof _)a=a._wrapped;if(b instanceof _)b=b._wrapped;var className=toString.call(a);if(className!=toString.call(b))return false;switch(className){case'[object String]':return a==String(b);case'[object Number]':return a!=+a?b!=+b:(a==0?1/a==1/b:a==+b);case'[object Date]':case'[object Boolean]':return+a==+b;case'[object RegExp]':return a.source==b.source&&a.global==b.global&&a.multiline==b.multiline&&a.ignoreCase==b.ignoreCase;}
if(typeof a!='object'||typeof b!='object')return false;var length=aStack.length;while(length--){if(aStack[length]==a)return bStack[length]==b;}
var aCtor=a.constructor,bCtor=b.constructor;if(aCtor!==bCtor&&!(_.isFunction(aCtor)&&(aCtor instanceof aCtor)&&_.isFunction(bCtor)&&(bCtor instanceof bCtor))&&('constructor'in a&&'constructor'in b)){return false;}
aStack.push(a);bStack.push(b);var size=0,result=true;if(className=='[object Array]'){size=a.length;result=size==b.length;if(result){while(size--){if(!(result=eq(a[size],b[size],aStack,bStack)))break;}}}else{for(var key in a){if(_.has(a,key)){size++;if(!(result=_.has(b,key)&&eq(a[key],b[key],aStack,bStack)))break;}}
if(result){for(key in b){if(_.has(b,key)&&!(size--))break;}
result=!size;}}
aStack.pop();bStack.pop();return result;};_.isEqual=function(a,b){return eq(a,b,[],[]);};_.isEmpty=function(obj){if(obj==null)return true;if(_.isArray(obj)||_.isString(obj))return obj.length===0;for(var key in obj)if(_.has(obj,key))return false;return true;};_.isElement=function(obj){return!!(obj&&obj.nodeType===1);};_.isArray=nativeIsArray||function(obj){return toString.call(obj)=='[object Array]';};_.isObject=function(obj){return obj===Object(obj);};each(['Arguments','Function','String','Number','Date','RegExp'],function(name){_['is'+name]=function(obj){return toString.call(obj)=='[object '+name+']';};});if(!_.isArguments(arguments)){_.isArguments=function(obj){return!!(obj&&_.has(obj,'callee'));};}
if(typeof(/./)!=='function'){_.isFunction=function(obj){return typeof obj==='function';};}
_.isFinite=function(obj){return isFinite(obj)&&!isNaN(parseFloat(obj));};_.isNaN=function(obj){return _.isNumber(obj)&&obj!=+obj;};_.isBoolean=function(obj){return obj===true||obj===false||toString.call(obj)=='[object Boolean]';};_.isNull=function(obj){return obj===null;};_.isUndefined=function(obj){return obj===void 0;};_.has=function(obj,key){return hasOwnProperty.call(obj,key);};_.noConflict=function(){root._=previousUnderscore;return this;};_.identity=function(value){return value;};_.constant=function(value){return function(){return value;};};_.property=function(key){return function(obj){return obj[key];};};_.matches=function(attrs){return function(obj){if(obj===attrs)return true;for(var key in attrs){if(attrs[key]!==obj[key])
return false;}
return true;}};_.times=function(n,iterator,context){var accum=Array(Math.max(0,n));for(var i=0;i<n;i++)accum[i]=iterator.call(context,i);return accum;};_.random=function(min,max){if(max==null){max=min;min=0;}
return min+Math.floor(Math.random()*(max-min+1));};_.now=Date.now||function(){return new Date().getTime();};var entityMap={escape:{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#x27;'}};entityMap.unescape=_.invert(entityMap.escape);var entityRegexes={escape:new RegExp('['+_.keys(entityMap.escape).join('')+']','g'),unescape:new RegExp('('+_.keys(entityMap.unescape).join('|')+')','g')};_.each(['escape','unescape'],function(method){_[method]=function(string){if(string==null)return'';return(''+string).replace(entityRegexes[method],function(match){return entityMap[method][match];});};});_.result=function(object,property){if(object==null)return void 0;var value=object[property];return _.isFunction(value)?value.call(object):value;};_.mixin=function(obj){each(_.functions(obj),function(name){var func=_[name]=obj[name];_.prototype[name]=function(){var args=[this._wrapped];push.apply(args,arguments);return result.call(this,func.apply(_,args));};});};var idCounter=0;_.uniqueId=function(prefix){var id=++idCounter+'';return prefix?prefix+id:id;};_.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var noMatch=/(.)^/;var escapes={"'":"'",'\\':'\\','\r':'r','\n':'n','\t':'t','\u2028':'u2028','\u2029':'u2029'};var escaper=/\\|'|\r|\n|\t|\u2028|\u2029/g;_.template=function(text,data,settings){var render;settings=_.defaults({},settings,_.templateSettings);var matcher=new RegExp([(settings.escape||noMatch).source,(settings.interpolate||noMatch).source,(settings.evaluate||noMatch).source].join('|')+'|$','g');var index=0;var source="__p+='";text.replace(matcher,function(match,escape,interpolate,evaluate,offset){source+=text.slice(index,offset).replace(escaper,function(match){return'\\'+escapes[match];});if(escape){source+="'+\n((__t=("+escape+"))==null?'':_.escape(__t))+\n'";}
if(interpolate){source+="'+\n((__t=("+interpolate+"))==null?'':__t)+\n'";}
if(evaluate){source+="';\n"+evaluate+"\n__p+='";}
index=offset+match.length;return match;});source+="';\n";if(!settings.variable)source='with(obj||{}){\n'+source+'}\n';source="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+
source+"return __p;\n";try{render=new Function(settings.variable||'obj','_',source);}catch(e){e.source=source;throw e;}
if(data)return render(data,_);var template=function(data){return render.call(this,data,_);};template.source='function('+(settings.variable||'obj')+'){\n'+source+'}';return template;};_.chain=function(obj){return _(obj).chain();};var result=function(obj){return this._chain?_(obj).chain():obj;};_.mixin(_);each(['pop','push','reverse','shift','sort','splice','unshift'],function(name){var method=ArrayProto[name];_.prototype[name]=function(){var obj=this._wrapped;method.apply(obj,arguments);if((name=='shift'||name=='splice')&&obj.length===0)delete obj[0];return result.call(this,obj);};});each(['concat','join','slice'],function(name){var method=ArrayProto[name];_.prototype[name]=function(){return result.call(this,method.apply(this._wrapped,arguments));};});_.extend(_.prototype,{chain:function(){this._chain=true;return this;},value:function(){return this._wrapped;}});if(typeof define==='function'&&define.amd){define('underscore',[],function(){return _;});}}).call(this);(function(root,factory){if(typeof define==='function'&&define.amd){define(['underscore','jquery','exports'],function(_,$,exports){root.Backbone=factory(root,exports,_,$);});}else if(typeof exports!=='undefined'){var _=require('underscore');factory(root,exports,_);}else{root.Backbone=factory(root,{},root._,(root.jQuery||root.Zepto||root.ender||root.$));}}(this,function(root,Backbone,_,$){var previousBackbone=root.Backbone;var array=[];var push=array.push;var slice=array.slice;var splice=array.splice;Backbone.VERSION='1.1.2';Backbone.$=$;Backbone.noConflict=function(){root.Backbone=previousBackbone;return this;};Backbone.emulateHTTP=false;Backbone.emulateJSON=false;var Events=Backbone.Events={on:function(name,callback,context){if(!eventsApi(this,'on',name,[callback,context])||!callback)return this;this._events||(this._events={});var events=this._events[name]||(this._events[name]=[]);events.push({callback:callback,context:context,ctx:context||this});return this;},once:function(name,callback,context){if(!eventsApi(this,'once',name,[callback,context])||!callback)return this;var self=this;var once=_.once(function(){self.off(name,once);callback.apply(this,arguments);});once._callback=callback;return this.on(name,once,context);},off:function(name,callback,context){var retain,ev,events,names,i,l,j,k;if(!this._events||!eventsApi(this,'off',name,[callback,context]))return this;if(!name&&!callback&&!context){this._events=void 0;return this;}
names=name?[name]:_.keys(this._events);for(i=0,l=names.length;i<l;i++){name=names[i];if(events=this._events[name]){this._events[name]=retain=[];if(callback||context){for(j=0,k=events.length;j<k;j++){ev=events[j];if((callback&&callback!==ev.callback&&callback!==ev.callback._callback)||(context&&context!==ev.context)){retain.push(ev);}}}
if(!retain.length)delete this._events[name];}}
return this;},trigger:function(name){if(!this._events)return this;var args=slice.call(arguments,1);if(!eventsApi(this,'trigger',name,args))return this;var events=this._events[name];var allEvents=this._events.all;if(events)triggerEvents(events,args);if(allEvents)triggerEvents(allEvents,arguments);return this;},stopListening:function(obj,name,callback){var listeningTo=this._listeningTo;if(!listeningTo)return this;var remove=!name&&!callback;if(!callback&&typeof name==='object')callback=this;if(obj)(listeningTo={})[obj._listenId]=obj;for(var id in listeningTo){obj=listeningTo[id];obj.off(name,callback,this);if(remove||_.isEmpty(obj._events))delete this._listeningTo[id];}
return this;}};var eventSplitter=/\s+/;var eventsApi=function(obj,action,name,rest){if(!name)return true;if(typeof name==='object'){for(var key in name){obj[action].apply(obj,[key,name[key]].concat(rest));}
return false;}
if(eventSplitter.test(name)){var names=name.split(eventSplitter);for(var i=0,l=names.length;i<l;i++){obj[action].apply(obj,[names[i]].concat(rest));}
return false;}
return true;};var triggerEvents=function(events,args){var ev,i=-1,l=events.length,a1=args[0],a2=args[1],a3=args[2];switch(args.length){case 0:while(++i<l)(ev=events[i]).callback.call(ev.ctx);return;case 1:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1);return;case 2:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2);return;case 3:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2,a3);return;default:while(++i<l)(ev=events[i]).callback.apply(ev.ctx,args);return;}};var listenMethods={listenTo:'on',listenToOnce:'once'};_.each(listenMethods,function(implementation,method){Events[method]=function(obj,name,callback){var listeningTo=this._listeningTo||(this._listeningTo={});var id=obj._listenId||(obj._listenId=_.uniqueId('l'));listeningTo[id]=obj;if(!callback&&typeof name==='object')callback=this;obj[implementation](name,callback,this);return this;};});Events.bind=Events.on;Events.unbind=Events.off;_.extend(Backbone,Events);var Model=Backbone.Model=function(attributes,options){var attrs=attributes||{};options||(options={});this.cid=_.uniqueId('c');this.attributes={};if(options.collection)this.collection=options.collection;if(options.parse)attrs=this.parse(attrs,options)||{};attrs=_.defaults({},attrs,_.result(this,'defaults'));this.set(attrs,options);this.changed={};this.initialize.apply(this,arguments);};_.extend(Model.prototype,Events,{changed:null,validationError:null,idAttribute:'id',initialize:function(){},toJSON:function(options){return _.clone(this.attributes);},sync:function(){return Backbone.sync.apply(this,arguments);},get:function(attr){return this.attributes[attr];},escape:function(attr){return _.escape(this.get(attr));},has:function(attr){return this.get(attr)!=null;},set:function(key,val,options){var attr,attrs,unset,changes,silent,changing,prev,current;if(key==null)return this;if(typeof key==='object'){attrs=key;options=val;}else{(attrs={})[key]=val;}
options||(options={});if(!this._validate(attrs,options))return false;unset=options.unset;silent=options.silent;changes=[];changing=this._changing;this._changing=true;if(!changing){this._previousAttributes=_.clone(this.attributes);this.changed={};}
current=this.attributes,prev=this._previousAttributes;if(this.idAttribute in attrs)this.id=attrs[this.idAttribute];for(attr in attrs){val=attrs[attr];if(!_.isEqual(current[attr],val))changes.push(attr);if(!_.isEqual(prev[attr],val)){this.changed[attr]=val;}else{delete this.changed[attr];}
unset?delete current[attr]:current[attr]=val;}
if(!silent){if(changes.length)this._pending=options;for(var i=0,l=changes.length;i<l;i++){this.trigger('change:'+changes[i],this,current[changes[i]],options);}}
if(changing)return this;if(!silent){while(this._pending){options=this._pending;this._pending=false;this.trigger('change',this,options);}}
this._pending=false;this._changing=false;return this;},unset:function(attr,options){return this.set(attr,void 0,_.extend({},options,{unset:true}));},clear:function(options){var attrs={};for(var key in this.attributes)attrs[key]=void 0;return this.set(attrs,_.extend({},options,{unset:true}));},hasChanged:function(attr){if(attr==null)return!_.isEmpty(this.changed);return _.has(this.changed,attr);},changedAttributes:function(diff){if(!diff)return this.hasChanged()?_.clone(this.changed):false;var val,changed=false;var old=this._changing?this._previousAttributes:this.attributes;for(var attr in diff){if(_.isEqual(old[attr],(val=diff[attr])))continue;(changed||(changed={}))[attr]=val;}
return changed;},previous:function(attr){if(attr==null||!this._previousAttributes)return null;return this._previousAttributes[attr];},previousAttributes:function(){return _.clone(this._previousAttributes);},fetch:function(options){options=options?_.clone(options):{};if(options.parse===void 0)options.parse=true;var model=this;var success=options.success;options.success=function(resp){if(!model.set(model.parse(resp,options),options))return false;if(success)success(model,resp,options);model.trigger('sync',model,resp,options);};wrapError(this,options);return this.sync('read',this,options);},save:function(key,val,options){var attrs,method,xhr,attributes=this.attributes;if(key==null||typeof key==='object'){attrs=key;options=val;}else{(attrs={})[key]=val;}
options=_.extend({validate:true},options);if(attrs&&!options.wait){if(!this.set(attrs,options))return false;}else{if(!this._validate(attrs,options))return false;}
if(attrs&&options.wait){this.attributes=_.extend({},attributes,attrs);}
if(options.parse===void 0)options.parse=true;var model=this;var success=options.success;options.success=function(resp){model.attributes=attributes;var serverAttrs=model.parse(resp,options);if(options.wait)serverAttrs=_.extend(attrs||{},serverAttrs);if(_.isObject(serverAttrs)&&!model.set(serverAttrs,options)){return false;}
if(success)success(model,resp,options);model.trigger('sync',model,resp,options);};wrapError(this,options);method=this.isNew()?'create':(options.patch?'patch':'update');if(method==='patch')options.attrs=attrs;xhr=this.sync(method,this,options);if(attrs&&options.wait)this.attributes=attributes;return xhr;},destroy:function(options){options=options?_.clone(options):{};var model=this;var success=options.success;var destroy=function(){model.trigger('destroy',model,model.collection,options);};options.success=function(resp){if(options.wait||model.isNew())destroy();if(success)success(model,resp,options);if(!model.isNew())model.trigger('sync',model,resp,options);};if(this.isNew()){options.success();return false;}
wrapError(this,options);var xhr=this.sync('delete',this,options);if(!options.wait)destroy();return xhr;},url:function(){var base=_.result(this,'urlRoot')||_.result(this.collection,'url')||urlError();if(this.isNew())return base;return base.replace(/([^\/])$/,'$1/')+encodeURIComponent(this.id);},parse:function(resp,options){return resp;},clone:function(){return new this.constructor(this.attributes);},isNew:function(){return!this.has(this.idAttribute);},isValid:function(options){return this._validate({},_.extend(options||{},{validate:true}));},_validate:function(attrs,options){if(!options.validate||!this.validate)return true;attrs=_.extend({},this.attributes,attrs);var error=this.validationError=this.validate(attrs,options)||null;if(!error)return true;this.trigger('invalid',this,error,_.extend(options,{validationError:error}));return false;}});var modelMethods=['keys','values','pairs','invert','pick','omit'];_.each(modelMethods,function(method){Model.prototype[method]=function(){var args=slice.call(arguments);args.unshift(this.attributes);return _[method].apply(_,args);};});var Collection=Backbone.Collection=function(models,options){options||(options={});if(options.model)this.model=options.model;if(options.comparator!==void 0)this.comparator=options.comparator;this._reset();this.initialize.apply(this,arguments);if(models)this.reset(models,_.extend({silent:true},options));};var setOptions={add:true,remove:true,merge:true};var addOptions={add:true,remove:false};_.extend(Collection.prototype,Events,{model:Model,initialize:function(){},toJSON:function(options){return this.map(function(model){return model.toJSON(options);});},sync:function(){return Backbone.sync.apply(this,arguments);},add:function(models,options){return this.set(models,_.extend({merge:false},options,addOptions));},remove:function(models,options){var singular=!_.isArray(models);models=singular?[models]:_.clone(models);options||(options={});var i,l,index,model;for(i=0,l=models.length;i<l;i++){model=models[i]=this.get(models[i]);if(!model)continue;delete this._byId[model.id];delete this._byId[model.cid];index=this.indexOf(model);this.models.splice(index,1);this.length--;if(!options.silent){options.index=index;model.trigger('remove',model,this,options);}
this._removeReference(model,options);}
return singular?models[0]:models;},set:function(models,options){options=_.defaults({},options,setOptions);if(options.parse)models=this.parse(models,options);var singular=!_.isArray(models);models=singular?(models?[models]:[]):_.clone(models);var i,l,id,model,attrs,existing,sort;var at=options.at;var targetModel=this.model;var sortable=this.comparator&&(at==null)&&options.sort!==false;var sortAttr=_.isString(this.comparator)?this.comparator:null;var toAdd=[],toRemove=[],modelMap={};var add=options.add,merge=options.merge,remove=options.remove;var order=!sortable&&add&&remove?[]:false;for(i=0,l=models.length;i<l;i++){attrs=models[i]||{};if(attrs instanceof Model){id=model=attrs;}else{id=attrs[targetModel.prototype.idAttribute||'id'];}
if(existing=this.get(id)){if(remove)modelMap[existing.cid]=true;if(merge){attrs=attrs===model?model.attributes:attrs;if(options.parse)attrs=existing.parse(attrs,options);existing.set(attrs,options);if(sortable&&!sort&&existing.hasChanged(sortAttr))sort=true;}
models[i]=existing;}else if(add){model=models[i]=this._prepareModel(attrs,options);if(!model)continue;toAdd.push(model);this._addReference(model,options);}
model=existing||model;if(order&&(model.isNew()||!modelMap[model.id]))order.push(model);modelMap[model.id]=true;}
if(remove){for(i=0,l=this.length;i<l;++i){if(!modelMap[(model=this.models[i]).cid])toRemove.push(model);}
if(toRemove.length)this.remove(toRemove,options);}
if(toAdd.length||(order&&order.length)){if(sortable)sort=true;this.length+=toAdd.length;if(at!=null){for(i=0,l=toAdd.length;i<l;i++){this.models.splice(at+i,0,toAdd[i]);}}else{if(order)this.models.length=0;var orderedModels=order||toAdd;for(i=0,l=orderedModels.length;i<l;i++){this.models.push(orderedModels[i]);}}}
if(sort)this.sort({silent:true});if(!options.silent){for(i=0,l=toAdd.length;i<l;i++){(model=toAdd[i]).trigger('add',model,this,options);}
if(sort||(order&&order.length))this.trigger('sort',this,options);}
return singular?models[0]:models;},reset:function(models,options){options||(options={});for(var i=0,l=this.models.length;i<l;i++){this._removeReference(this.models[i],options);}
options.previousModels=this.models;this._reset();models=this.add(models,_.extend({silent:true},options));if(!options.silent)this.trigger('reset',this,options);return models;},push:function(model,options){return this.add(model,_.extend({at:this.length},options));},pop:function(options){var model=this.at(this.length-1);this.remove(model,options);return model;},unshift:function(model,options){return this.add(model,_.extend({at:0},options));},shift:function(options){var model=this.at(0);this.remove(model,options);return model;},slice:function(){return slice.apply(this.models,arguments);},get:function(obj){if(obj==null)return void 0;return this._byId[obj]||this._byId[obj.id]||this._byId[obj.cid];},at:function(index){return this.models[index];},where:function(attrs,first){if(_.isEmpty(attrs))return first?void 0:[];return this[first?'find':'filter'](function(model){for(var key in attrs){if(attrs[key]!==model.get(key))return false;}
return true;});},findWhere:function(attrs){return this.where(attrs,true);},sort:function(options){if(!this.comparator)throw new Error('Cannot sort a set without a comparator');options||(options={});if(_.isString(this.comparator)||this.comparator.length===1){this.models=this.sortBy(this.comparator,this);}else{this.models.sort(_.bind(this.comparator,this));}
if(!options.silent)this.trigger('sort',this,options);return this;},pluck:function(attr){return _.invoke(this.models,'get',attr);},fetch:function(options){options=options?_.clone(options):{};if(options.parse===void 0)options.parse=true;var success=options.success;var collection=this;options.success=function(resp){var method=options.reset?'reset':'set';collection[method](resp,options);if(success)success(collection,resp,options);collection.trigger('sync',collection,resp,options);};wrapError(this,options);return this.sync('read',this,options);},create:function(model,options){options=options?_.clone(options):{};if(!(model=this._prepareModel(model,options)))return false;if(!options.wait)this.add(model,options);var collection=this;var success=options.success;options.success=function(model,resp){if(options.wait)collection.add(model,options);if(success)success(model,resp,options);};model.save(null,options);return model;},parse:function(resp,options){return resp;},clone:function(){return new this.constructor(this.models);},_reset:function(){this.length=0;this.models=[];this._byId={};},_prepareModel:function(attrs,options){if(attrs instanceof Model)return attrs;options=options?_.clone(options):{};options.collection=this;var model=new this.model(attrs,options);if(!model.validationError)return model;this.trigger('invalid',this,model.validationError,options);return false;},_addReference:function(model,options){this._byId[model.cid]=model;if(model.id!=null)this._byId[model.id]=model;if(!model.collection)model.collection=this;model.on('all',this._onModelEvent,this);},_removeReference:function(model,options){if(this===model.collection)delete model.collection;model.off('all',this._onModelEvent,this);},_onModelEvent:function(event,model,collection,options){if((event==='add'||event==='remove')&&collection!==this)return;if(event==='destroy')this.remove(model,options);if(model&&event==='change:'+model.idAttribute){delete this._byId[model.previous(model.idAttribute)];if(model.id!=null)this._byId[model.id]=model;}
this.trigger.apply(this,arguments);}});var methods=['forEach','each','map','collect','reduce','foldl','inject','reduceRight','foldr','find','detect','filter','select','reject','every','all','some','any','include','contains','invoke','max','min','toArray','size','first','head','take','initial','rest','tail','drop','last','without','difference','indexOf','shuffle','lastIndexOf','isEmpty','chain','sample'];_.each(methods,function(method){Collection.prototype[method]=function(){var args=slice.call(arguments);args.unshift(this.models);return _[method].apply(_,args);};});var attributeMethods=['groupBy','countBy','sortBy','indexBy'];_.each(attributeMethods,function(method){Collection.prototype[method]=function(value,context){var iterator=_.isFunction(value)?value:function(model){return model.get(value);};return _[method](this.models,iterator,context);};});var View=Backbone.View=function(options){this.cid=_.uniqueId('view');options||(options={});_.extend(this,_.pick(options,viewOptions));this._ensureElement();this.initialize.apply(this,arguments);this.delegateEvents();};var delegateEventSplitter=/^(\S+)\s*(.*)$/;var viewOptions=['model','collection','el','id','attributes','className','tagName','events'];_.extend(View.prototype,Events,{tagName:'div',$:function(selector){return this.$el.find(selector);},initialize:function(){},render:function(){return this;},remove:function(){this.$el.remove();this.stopListening();return this;},setElement:function(element,delegate){if(this.$el)this.undelegateEvents();this.$el=element instanceof Backbone.$?element:Backbone.$(element);this.el=this.$el[0];if(delegate!==false)this.delegateEvents();return this;},delegateEvents:function(events){if(!(events||(events=_.result(this,'events'))))return this;this.undelegateEvents();for(var key in events){var method=events[key];if(!_.isFunction(method))method=this[events[key]];if(!method)continue;var match=key.match(delegateEventSplitter);var eventName=match[1],selector=match[2];method=_.bind(method,this);eventName+='.delegateEvents'+this.cid;if(selector===''){this.$el.on(eventName,method);}else{this.$el.on(eventName,selector,method);}}
return this;},undelegateEvents:function(){this.$el.off('.delegateEvents'+this.cid);return this;},_ensureElement:function(){if(!this.el){var attrs=_.extend({},_.result(this,'attributes'));if(this.id)attrs.id=_.result(this,'id');if(this.className)attrs['class']=_.result(this,'className');var $el=Backbone.$('<'+_.result(this,'tagName')+'>').attr(attrs);this.setElement($el,false);}else{this.setElement(_.result(this,'el'),false);}}});Backbone.sync=function(method,model,options){var type=methodMap[method];_.defaults(options||(options={}),{emulateHTTP:Backbone.emulateHTTP,emulateJSON:Backbone.emulateJSON});var params={type:type,dataType:'json'};if(!options.url){params.url=_.result(model,'url')||urlError();}
if(options.data==null&&model&&(method==='create'||method==='update'||method==='patch')){params.contentType='application/json';params.data=JSON.stringify(options.attrs||model.toJSON(options));}
if(options.emulateJSON){params.contentType='application/x-www-form-urlencoded';params.data=params.data?{model:params.data}:{};}
if(options.emulateHTTP&&(type==='PUT'||type==='DELETE'||type==='PATCH')){params.type='POST';if(options.emulateJSON)params.data._method=type;var beforeSend=options.beforeSend;options.beforeSend=function(xhr){xhr.setRequestHeader('X-HTTP-Method-Override',type);if(beforeSend)return beforeSend.apply(this,arguments);};}
if(params.type!=='GET'&&!options.emulateJSON){params.processData=false;}
if(params.type==='PATCH'&&noXhrPatch){params.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP");};}
var xhr=options.xhr=Backbone.ajax(_.extend(params,options));model.trigger('request',model,xhr,options);return xhr;};var noXhrPatch=typeof window!=='undefined'&&!!window.ActiveXObject&&!(window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent);var methodMap={'create':'POST','update':'PUT','patch':'PATCH','delete':'DELETE','read':'GET'};Backbone.ajax=function(){return Backbone.$.ajax.apply(Backbone.$,arguments);};var Router=Backbone.Router=function(options){options||(options={});if(options.routes)this.routes=options.routes;this._bindRoutes();this.initialize.apply(this,arguments);};var optionalParam=/\((.*?)\)/g;var namedParam=/(\(\?)?:\w+/g;var splatParam=/\*\w+/g;var escapeRegExp=/[\-{}\[\]+?.,\\\^$|#\s]/g;_.extend(Router.prototype,Events,{initialize:function(){},route:function(route,name,callback){if(!_.isRegExp(route))route=this._routeToRegExp(route);if(_.isFunction(name)){callback=name;name='';}
if(!callback)callback=this[name];var router=this;Backbone.history.route(route,function(fragment){var args=router._extractParameters(route,fragment);router.execute(callback,args);router.trigger.apply(router,['route:'+name].concat(args));router.trigger('route',name,args);Backbone.history.trigger('route',router,name,args);});return this;},execute:function(callback,args){if(callback)callback.apply(this,args);},navigate:function(fragment,options){Backbone.history.navigate(fragment,options);return this;},_bindRoutes:function(){if(!this.routes)return;this.routes=_.result(this,'routes');var route,routes=_.keys(this.routes);while((route=routes.pop())!=null){this.route(route,this.routes[route]);}},_routeToRegExp:function(route){route=route.replace(escapeRegExp,'\\$&').replace(optionalParam,'(?:$1)?').replace(namedParam,function(match,optional){return optional?match:'([^/?]+)';}).replace(splatParam,'([^?]*?)');return new RegExp('^'+route+'(?:\\?([\\s\\S]*))?$');},_extractParameters:function(route,fragment){var params=route.exec(fragment).slice(1);return _.map(params,function(param,i){if(i===params.length-1)return param||null;return param?decodeURIComponent(param):null;});}});var History=Backbone.History=function(){this.handlers=[];_.bindAll(this,'checkUrl');if(typeof window!=='undefined'){this.location=window.location;this.history=window.history;}};var routeStripper=/^[#\/]|\s+$/g;var rootStripper=/^\/+|\/+$/g;var isExplorer=/msie [\w.]+/;var trailingSlash=/\/$/;var pathStripper=/#.*$/;History.started=false;_.extend(History.prototype,Events,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,'$&/')===this.root;},getHash:function(window){var match=(window||this).location.href.match(/#(.*)$/);return match?match[1]:'';},getFragment:function(fragment,forcePushState){if(fragment==null){if(this._hasPushState||!this._wantsHashChange||forcePushState){fragment=decodeURI(this.location.pathname+this.location.search);var root=this.root.replace(trailingSlash,'');if(!fragment.indexOf(root))fragment=fragment.slice(root.length);}else{fragment=this.getHash();}}
return fragment.replace(routeStripper,'');},start:function(options){if(History.started)throw new Error("Backbone.history has already been started");History.started=true;this.options=_.extend({root:'/'},this.options,options);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var fragment=this.getFragment();var docMode=document.documentMode;var oldIE=(isExplorer.exec(navigator.userAgent.toLowerCase())&&(!docMode||docMode<=7));this.root=('/'+this.root+'/').replace(rootStripper,'/');if(oldIE&&this._wantsHashChange){var frame=Backbone.$('<iframe src="javascript:0" tabindex="-1">');this.iframe=frame.hide().appendTo('body')[0].contentWindow;this.navigate(fragment);}
if(this._hasPushState){Backbone.$(window).on('popstate',this.checkUrl);}else if(this._wantsHashChange&&('onhashchange'in window)&&!oldIE){Backbone.$(window).on('hashchange',this.checkUrl);}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval);}
this.fragment=fragment;var loc=this.location;if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){this.fragment=this.getFragment(null,true);this.location.replace(this.root+'#'+this.fragment);return true;}else if(this._hasPushState&&this.atRoot()&&loc.hash){this.fragment=this.getHash().replace(routeStripper,'');this.history.replaceState({},document.title,this.root+this.fragment);}}
if(!this.options.silent)return this.loadUrl();},stop:function(){Backbone.$(window).off('popstate',this.checkUrl).off('hashchange',this.checkUrl);if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);History.started=false;},route:function(route,callback){this.handlers.unshift({route:route,callback:callback});},checkUrl:function(e){var current=this.getFragment();if(current===this.fragment&&this.iframe){current=this.getFragment(this.getHash(this.iframe));}
if(current===this.fragment)return false;if(this.iframe)this.navigate(current);this.loadUrl();},loadUrl:function(fragment){fragment=this.fragment=this.getFragment(fragment);return _.any(this.handlers,function(handler){if(handler.route.test(fragment)){handler.callback(fragment);return true;}});},navigate:function(fragment,options){if(!History.started)return false;if(!options||options===true)options={trigger:!!options};var url=this.root+(fragment=this.getFragment(fragment||''));fragment=fragment.replace(pathStripper,'');if(this.fragment===fragment)return;this.fragment=fragment;if(fragment===''&&url!=='/')url=url.slice(0,-1);if(this._hasPushState){this.history[options.replace?'replaceState':'pushState']({},document.title,url);}else if(this._wantsHashChange){this._updateHash(this.location,fragment,options.replace);if(this.iframe&&(fragment!==this.getFragment(this.getHash(this.iframe)))){if(!options.replace)this.iframe.document.open().close();this._updateHash(this.iframe.location,fragment,options.replace);}}else{return this.location.assign(url);}
if(options.trigger)return this.loadUrl(fragment);},_updateHash:function(location,fragment,replace){if(replace){var href=location.href.replace(/(javascript:|#).*$/,'');location.replace(href+'#'+fragment);}else{location.hash='#'+fragment;}}});Backbone.history=new History;var extend=function(protoProps,staticProps){var parent=this;var child;if(protoProps&&_.has(protoProps,'constructor')){child=protoProps.constructor;}else{child=function(){return parent.apply(this,arguments);};}
_.extend(child,parent,staticProps);var Surrogate=function(){this.constructor=child;};Surrogate.prototype=parent.prototype;child.prototype=new Surrogate;if(protoProps)_.extend(child.prototype,protoProps);child.__super__=parent.prototype;return child;};Model.extend=Collection.extend=Router.extend=View.extend=History.extend=extend;var urlError=function(){throw new Error('A "url" property or function must be specified');};var wrapError=function(model,options){var error=options.error;options.error=function(resp){if(error)error(model,resp,options);model.trigger('error',model,resp,options);};};return Backbone;}));(function(root,factory){if(typeof define==='function'&&define.amd){define(['exports','backbone','underscore'],factory);}
else if(typeof exports!=='undefined'){factory(exports,require('backbone'),require('underscore'));}
else{factory(root,root.Backbone,root._);}}(this,function(exports,Backbone,_){"use strict";Backbone.Relational={showWarnings:true};Backbone.Semaphore={_permitsAvailable:null,_permitsUsed:0,acquire:function(){if(this._permitsAvailable&&this._permitsUsed>=this._permitsAvailable){throw new Error('Max permits acquired');}
else{this._permitsUsed++;}},release:function(){if(this._permitsUsed===0){throw new Error('All permits released');}
else{this._permitsUsed--;}},isLocked:function(){return this._permitsUsed>0;},setAvailablePermits:function(amount){if(this._permitsUsed>amount){throw new Error('Available permits cannot be less than used permits');}
this._permitsAvailable=amount;}};Backbone.BlockingQueue=function(){this._queue=[];};_.extend(Backbone.BlockingQueue.prototype,Backbone.Semaphore,{_queue:null,add:function(func){if(this.isBlocked()){this._queue.push(func);}
else{func();}},process:function(){var queue=this._queue;this._queue=[];while(queue&&queue.length){queue.shift()();}},block:function(){this.acquire();},unblock:function(){this.release();if(!this.isBlocked()){this.process();}},isBlocked:function(){return this.isLocked();}});Backbone.Relational.eventQueue=new Backbone.BlockingQueue();Backbone.Store=function(){this._collections=[];this._reverseRelations=[];this._orphanRelations=[];this._subModels=[];this._modelScopes=[exports];};_.extend(Backbone.Store.prototype,Backbone.Events,{initializeRelation:function(model,relation,options){var type=!_.isString(relation.type)?relation.type:Backbone[relation.type]||this.getObjectByName(relation.type);if(type&&type.prototype instanceof Backbone.Relation){new type(model,relation,options);}
else{Backbone.Relational.showWarnings&&typeof console!=='undefined'&&console.warn('Relation=%o; missing or invalid relation type!',relation);}},addModelScope:function(scope){this._modelScopes.push(scope);},removeModelScope:function(scope){this._modelScopes=_.without(this._modelScopes,scope);},addSubModels:function(subModelTypes,superModelType){this._subModels.push({'superModelType':superModelType,'subModels':subModelTypes});},setupSuperModel:function(modelType){_.find(this._subModels,function(subModelDef){return _.filter(subModelDef.subModels||[],function(subModelTypeName,typeValue){var subModelType=this.getObjectByName(subModelTypeName);if(modelType===subModelType){subModelDef.superModelType._subModels[typeValue]=modelType;modelType._superModel=subModelDef.superModelType;modelType._subModelTypeValue=typeValue;modelType._subModelTypeAttribute=subModelDef.superModelType.prototype.subModelTypeAttribute;return true;}},this).length;},this);},addReverseRelation:function(relation){var exists=_.any(this._reverseRelations,function(rel){return _.all(relation||[],function(val,key){return val===rel[key];});});if(!exists&&relation.model&&relation.type){this._reverseRelations.push(relation);this._addRelation(relation.model,relation);this.retroFitRelation(relation);}},addOrphanRelation:function(relation){var exists=_.any(this._orphanRelations,function(rel){return _.all(relation||[],function(val,key){return val===rel[key];});});if(!exists&&relation.model&&relation.type){this._orphanRelations.push(relation);}},processOrphanRelations:function(){_.each(this._orphanRelations.slice(0),function(rel){var relatedModel=Backbone.Relational.store.getObjectByName(rel.relatedModel);if(relatedModel){this.initializeRelation(null,rel);this._orphanRelations=_.without(this._orphanRelations,rel);}},this);},_addRelation:function(type,relation){if(!type.prototype.relations){type.prototype.relations=[];}
type.prototype.relations.push(relation);_.each(type._subModels||[],function(subModel){this._addRelation(subModel,relation);},this);},retroFitRelation:function(relation){var coll=this.getCollection(relation.model,false);coll&&coll.each(function(model){if(!(model instanceof relation.model)){return;}
new relation.type(model,relation);},this);},getCollection:function(type,create){if(type instanceof Backbone.RelationalModel){type=type.constructor;}
var rootModel=type;while(rootModel._superModel){rootModel=rootModel._superModel;}
var coll=_.find(this._collections,function(item){return item.model===rootModel;});if(!coll&&create!==false){coll=this._createCollection(rootModel);}
return coll;},getObjectByName:function(name){var parts=name.split('.'),type=null;_.find(this._modelScopes,function(scope){type=_.reduce(parts||[],function(memo,val){return memo?memo[val]:undefined;},scope);if(type&&type!==scope){return true;}},this);return type;},_createCollection:function(type){var coll;if(type instanceof Backbone.RelationalModel){type=type.constructor;}
if(type.prototype instanceof Backbone.RelationalModel){coll=new Backbone.Collection();coll.model=type;this._collections.push(coll);}
return coll;},resolveIdForItem:function(type,item){var id=_.isString(item)||_.isNumber(item)?item:null;if(id===null){if(item instanceof Backbone.RelationalModel){id=item.id;}
else if(_.isObject(item)){id=item[type.prototype.idAttribute];}}
if(!id&&id!==0){id=null;}
return id;},find:function(type,item){var id=this.resolveIdForItem(type,item),coll=this.getCollection(type);if(coll){var obj=coll.get(id);if(obj instanceof type){return obj;}}
return null;},register:function(model){var coll=this.getCollection(model);if(coll){var modelColl=model.collection;coll.add(model);model.collection=modelColl;}},checkId:function(model,id){var coll=this.getCollection(model),duplicate=coll&&coll.get(id);if(duplicate&&model!==duplicate){if(Backbone.Relational.showWarnings&&typeof console!=='undefined'){console.warn('Duplicate id! Old RelationalModel=%o, new RelationalModel=%o',duplicate,model);}
throw new Error("Cannot instantiate more than one Backbone.RelationalModel with the same id per type!");}},update:function(model){var coll=this.getCollection(model);if(!coll.contains(model)){this.register(model);}
coll._onModelEvent('change:'+model.idAttribute,model,coll);model.trigger('relational:change:id',model,coll);},unregister:function(type){var coll,models;if(type instanceof Backbone.Model){coll=this.getCollection(type);models=[type];}
else if(type instanceof Backbone.Collection){coll=this.getCollection(type.model);models=_.clone(type.models);}
else{coll=this.getCollection(type);models=_.clone(coll.models);}
_.each(models,function(model){this.stopListening(model);_.invoke(model.getRelations(),'stopListening');},this);if(_.contains(this._collections,type)){coll.reset([]);}
else{_.each(models,function(model){if(coll.get(model)){coll.remove(model);}
else{coll.trigger('relational:remove',model,coll);}},this);}},reset:function(){this.stopListening();_.each(this._collections,function(coll){this.unregister(coll);},this);this._collections=[];this._subModels=[];this._modelScopes=[exports];}});Backbone.Relational.store=new Backbone.Store();Backbone.Relation=function(instance,options,opts){this.instance=instance;options=_.isObject(options)?options:{};this.reverseRelation=_.defaults(options.reverseRelation||{},this.options.reverseRelation);this.options=_.defaults(options,this.options,Backbone.Relation.prototype.options);this.reverseRelation.type=!_.isString(this.reverseRelation.type)?this.reverseRelation.type:Backbone[this.reverseRelation.type]||Backbone.Relational.store.getObjectByName(this.reverseRelation.type);this.key=this.options.key;this.keySource=this.options.keySource||this.key;this.keyDestination=this.options.keyDestination||this.keySource||this.key;this.model=this.options.model||this.instance.constructor;this.relatedModel=this.options.relatedModel;if(_.isFunction(this.relatedModel)&&!(this.relatedModel.prototype instanceof Backbone.RelationalModel)){this.relatedModel=_.result(this,'relatedModel');}
if(_.isString(this.relatedModel)){this.relatedModel=Backbone.Relational.store.getObjectByName(this.relatedModel);}
if(!this.checkPreconditions()){return;}
if(!this.options.isAutoRelation&&this.reverseRelation.type&&this.reverseRelation.key){Backbone.Relational.store.addReverseRelation(_.defaults({isAutoRelation:true,model:this.relatedModel,relatedModel:this.model,reverseRelation:this.options},this.reverseRelation));}
if(instance){var contentKey=this.keySource;if(contentKey!==this.key&&typeof this.instance.get(this.key)==='object'){contentKey=this.key;}
this.setKeyContents(this.instance.get(contentKey));this.relatedCollection=Backbone.Relational.store.getCollection(this.relatedModel);if(this.keySource!==this.key){delete this.instance.attributes[this.keySource];}
this.instance._relations[this.key]=this;this.initialize(opts);if(this.options.autoFetch){this.instance.fetchRelated(this.key,_.isObject(this.options.autoFetch)?this.options.autoFetch:{});}
this.listenTo(this.instance,'destroy',this.destroy).listenTo(this.relatedCollection,'relational:add relational:change:id',this.tryAddRelated).listenTo(this.relatedCollection,'relational:remove',this.removeRelated)}};Backbone.Relation.extend=Backbone.Model.extend;_.extend(Backbone.Relation.prototype,Backbone.Events,Backbone.Semaphore,{options:{createModels:true,includeInJSON:true,isAutoRelation:false,autoFetch:false,parse:false},instance:null,key:null,keyContents:null,relatedModel:null,relatedCollection:null,reverseRelation:null,related:null,checkPreconditions:function(){var i=this.instance,k=this.key,m=this.model,rm=this.relatedModel,warn=Backbone.Relational.showWarnings&&typeof console!=='undefined';if(!m||!k||!rm){warn&&console.warn('Relation=%o: missing model, key or relatedModel (%o, %o, %o).',this,m,k,rm);return false;}
if(!(m.prototype instanceof Backbone.RelationalModel)){warn&&console.warn('Relation=%o: model does not inherit from Backbone.RelationalModel (%o).',this,i);return false;}
if(!(rm.prototype instanceof Backbone.RelationalModel)){warn&&console.warn('Relation=%o: relatedModel does not inherit from Backbone.RelationalModel (%o).',this,rm);return false;}
if(this instanceof Backbone.HasMany&&this.reverseRelation.type===Backbone.HasMany){warn&&console.warn('Relation=%o: relation is a HasMany, and the reverseRelation is HasMany as well.',this);return false;}
if(i&&_.keys(i._relations).length){var existing=_.find(i._relations,function(rel){return rel.key===k;},this);if(existing){warn&&console.warn('Cannot create relation=%o on %o for model=%o: already taken by relation=%o.',this,k,i,existing);return false;}}
return true;},setRelated:function(related){this.related=related;this.instance.attributes[this.key]=related;},_isReverseRelation:function(relation){return relation.instance instanceof this.relatedModel&&this.reverseRelation.key===relation.key&&this.key===relation.reverseRelation.key;},getReverseRelations:function(model){var reverseRelations=[];var models=!_.isUndefined(model)?[model]:this.related&&(this.related.models||[this.related]);_.each(models||[],function(related){_.each(related.getRelations()||[],function(relation){if(this._isReverseRelation(relation)){reverseRelations.push(relation);}},this);},this);return reverseRelations;},destroy:function(){this.stopListening();if(this instanceof Backbone.HasOne){this.setRelated(null);}
else if(this instanceof Backbone.HasMany){this.setRelated(this._prepareCollection());}
_.each(this.getReverseRelations(),function(relation){relation.removeRelated(this.instance);},this);}});Backbone.HasOne=Backbone.Relation.extend({options:{reverseRelation:{type:'HasMany'}},initialize:function(opts){this.listenTo(this.instance,'relational:change:'+this.key,this.onChange);var related=this.findRelated(opts);this.setRelated(related);_.each(this.getReverseRelations(),function(relation){relation.addRelated(this.instance,opts);},this);},findRelated:function(options){var related=null;options=_.defaults({parse:this.options.parse},options);if(this.keyContents instanceof this.relatedModel){related=this.keyContents;}
else if(this.keyContents||this.keyContents===0){var opts=_.defaults({create:this.options.createModels},options);related=this.relatedModel.findOrCreate(this.keyContents,opts);}
if(related){this.keyId=null;}
return related;},setKeyContents:function(keyContents){this.keyContents=keyContents;this.keyId=Backbone.Relational.store.resolveIdForItem(this.relatedModel,this.keyContents);},onChange:function(model,attr,options){if(this.isLocked()){return;}
this.acquire();options=options?_.clone(options):{};var changed=_.isUndefined(options.__related),oldRelated=changed?this.related:options.__related;if(changed){this.setKeyContents(attr);var related=this.findRelated(options);this.setRelated(related);}
if(oldRelated&&this.related!==oldRelated){_.each(this.getReverseRelations(oldRelated),function(relation){relation.removeRelated(this.instance,null,options);},this);}
_.each(this.getReverseRelations(),function(relation){relation.addRelated(this.instance,options);},this);if(!options.silent&&this.related!==oldRelated){var dit=this;this.changed=true;Backbone.Relational.eventQueue.add(function(){dit.instance.trigger('change:'+dit.key,dit.instance,dit.related,options,true);dit.changed=false;});}
this.release();},tryAddRelated:function(model,coll,options){if((this.keyId||this.keyId===0)&&model.id===this.keyId){this.addRelated(model,options);this.keyId=null;}},addRelated:function(model,options){var dit=this;model.queue(function(){if(model!==dit.related){var oldRelated=dit.related||null;dit.setRelated(model);dit.onChange(dit.instance,model,_.defaults({__related:oldRelated},options));}});},removeRelated:function(model,coll,options){if(!this.related){return;}
if(model===this.related){var oldRelated=this.related||null;this.setRelated(null);this.onChange(this.instance,model,_.defaults({__related:oldRelated},options));}}});Backbone.HasMany=Backbone.Relation.extend({collectionType:null,options:{reverseRelation:{type:'HasOne'},collectionType:Backbone.Collection,collectionKey:true,collectionOptions:{}},initialize:function(opts){this.listenTo(this.instance,'relational:change:'+this.key,this.onChange);this.collectionType=this.options.collectionType;if(_.isFunction(this.collectionType)&&this.collectionType!==Backbone.Collection&&!(this.collectionType.prototype instanceof Backbone.Collection)){this.collectionType=_.result(this,'collectionType');}
if(_.isString(this.collectionType)){this.collectionType=Backbone.Relational.store.getObjectByName(this.collectionType);}
if(this.collectionType!==Backbone.Collection&&!(this.collectionType.prototype instanceof Backbone.Collection)){throw new Error('`collectionType` must inherit from Backbone.Collection');}
var related=this.findRelated(opts);this.setRelated(related);},_prepareCollection:function(collection){if(this.related){this.stopListening(this.related);}
if(!collection||!(collection instanceof Backbone.Collection)){var options=_.isFunction(this.options.collectionOptions)?this.options.collectionOptions(this.instance):this.options.collectionOptions;collection=new this.collectionType(null,options);}
collection.model=this.relatedModel;if(this.options.collectionKey){var key=this.options.collectionKey===true?this.options.reverseRelation.key:this.options.collectionKey;if(collection[key]&&collection[key]!==this.instance){if(Backbone.Relational.showWarnings&&typeof console!=='undefined'){console.warn('Relation=%o; collectionKey=%s already exists on collection=%o',this,key,this.options.collectionKey);}}
else if(key){collection[key]=this.instance;}}
this.listenTo(collection,'relational:add',this.handleAddition).listenTo(collection,'relational:remove',this.handleRemoval).listenTo(collection,'relational:reset',this.handleReset);return collection;},findRelated:function(options){var related=null;options=_.defaults({parse:this.options.parse},options);if(this.keyContents instanceof Backbone.Collection){this._prepareCollection(this.keyContents);related=this.keyContents;}
else{var toAdd=[];_.each(this.keyContents,function(attributes){if(attributes instanceof this.relatedModel){var model=attributes;}
else{model=this.relatedModel.findOrCreate(attributes,_.extend({merge:true},options,{create:this.options.createModels}));}
model&&toAdd.push(model);},this);if(this.related instanceof Backbone.Collection){related=this.related;}
else{related=this._prepareCollection();}
related.set(toAdd,_.defaults({merge:false,parse:false},options));}
this.keyIds=_.difference(this.keyIds,_.pluck(related.models,'id'));return related;},setKeyContents:function(keyContents){this.keyContents=keyContents instanceof Backbone.Collection?keyContents:null;this.keyIds=[];if(!this.keyContents&&(keyContents||keyContents===0)){this.keyContents=_.isArray(keyContents)?keyContents:[keyContents];_.each(this.keyContents,function(item){var itemId=Backbone.Relational.store.resolveIdForItem(this.relatedModel,item);if(itemId||itemId===0){this.keyIds.push(itemId);}},this);}},onChange:function(model,attr,options){options=options?_.clone(options):{};this.setKeyContents(attr);this.changed=false;var related=this.findRelated(options);this.setRelated(related);if(!options.silent){var dit=this;Backbone.Relational.eventQueue.add(function(){if(dit.changed){dit.instance.trigger('change:'+dit.key,dit.instance,dit.related,options,true);dit.changed=false;}});}},handleAddition:function(model,coll,options){options=options?_.clone(options):{};this.changed=true;_.each(this.getReverseRelations(model),function(relation){relation.addRelated(this.instance,options);},this);var dit=this;!options.silent&&Backbone.Relational.eventQueue.add(function(){dit.instance.trigger('add:'+dit.key,model,dit.related,options);});},handleRemoval:function(model,coll,options){options=options?_.clone(options):{};this.changed=true;_.each(this.getReverseRelations(model),function(relation){relation.removeRelated(this.instance,null,options);},this);var dit=this;!options.silent&&Backbone.Relational.eventQueue.add(function(){dit.instance.trigger('remove:'+dit.key,model,dit.related,options);});},handleReset:function(coll,options){var dit=this;options=options?_.clone(options):{};!options.silent&&Backbone.Relational.eventQueue.add(function(){dit.instance.trigger('reset:'+dit.key,dit.related,options);});},tryAddRelated:function(model,coll,options){var item=_.contains(this.keyIds,model.id);if(item){this.addRelated(model,options);this.keyIds=_.without(this.keyIds,model.id);}},addRelated:function(model,options){var dit=this;model.queue(function(){if(dit.related&&!dit.related.get(model)){dit.related.add(model,_.defaults({parse:false},options));}});},removeRelated:function(model,coll,options){if(this.related.get(model)){this.related.remove(model,options);}}});Backbone.RelationalModel=Backbone.Model.extend({relations:null,_relations:null,_isInitialized:false,_deferProcessing:false,_queue:null,_attributeChangeFired:false,subModelTypeAttribute:'type',subModelTypes:null,constructor:function(attributes,options){if(options&&options.collection){var dit=this,collection=this.collection=options.collection;delete options.collection;this._deferProcessing=true;var processQueue=function(model){if(model===dit){dit._deferProcessing=false;dit.processQueue();collection.off('relational:add',processQueue);}};collection.on('relational:add',processQueue);_.defer(function(){processQueue(dit);});}
Backbone.Relational.store.processOrphanRelations();Backbone.Relational.store.listenTo(this,'relational:unregister',Backbone.Relational.store.unregister);this._queue=new Backbone.BlockingQueue();this._queue.block();Backbone.Relational.eventQueue.block();try{Backbone.Model.apply(this,arguments);}
finally{Backbone.Relational.eventQueue.unblock();}},trigger:function(eventName){if(eventName.length>5&&eventName.indexOf('change')===0){var dit=this,args=arguments;if(!Backbone.Relational.eventQueue.isLocked()){Backbone.Model.prototype.trigger.apply(dit,args);}
else{Backbone.Relational.eventQueue.add(function(){var changed=true;if(eventName==='change'){changed=dit.hasChanged()||dit._attributeChangeFired;dit._attributeChangeFired=false;}
else{var attr=eventName.slice(7),rel=dit.getRelation(attr);if(rel){changed=(args[4]===true);if(changed){dit.changed[attr]=args[2];}
else if(!rel.changed){delete dit.changed[attr];}}
else if(changed){dit._attributeChangeFired=true;}}
changed&&Backbone.Model.prototype.trigger.apply(dit,args);});}}
else if(eventName==='destroy'){Backbone.Model.prototype.trigger.apply(this,arguments);Backbone.Relational.store.unregister(this);}
else{Backbone.Model.prototype.trigger.apply(this,arguments);}
return this;},initializeRelations:function(options){this.acquire();this._relations={};_.each(this.relations||[],function(rel){Backbone.Relational.store.initializeRelation(this,rel,options);},this);this._isInitialized=true;this.release();this.processQueue();},updateRelations:function(changedAttrs,options){if(this._isInitialized&&!this.isLocked()){_.each(this._relations,function(rel){if(!changedAttrs||(rel.keySource in changedAttrs||rel.key in changedAttrs)){var value=this.attributes[rel.keySource]||this.attributes[rel.key],attr=changedAttrs&&(changedAttrs[rel.keySource]||changedAttrs[rel.key]);if(rel.related!==value||(value===null&&attr===null)){this.trigger('relational:change:'+rel.key,this,value,options||{});}}
if(rel.keySource!==rel.key){delete this.attributes[rel.keySource];}},this);}},queue:function(func){this._queue.add(func);},processQueue:function(){if(this._isInitialized&&!this._deferProcessing&&this._queue.isBlocked()){this._queue.unblock();}},getRelation:function(key){return this._relations[key];},getRelations:function(){return _.values(this._relations);},fetchRelated:function(key,options,refresh){options=_.extend({update:true,remove:false},options);var models,setUrl,requests=[],rel=this.getRelation(key),idsToFetch=rel&&((rel.keyIds&&rel.keyIds.slice(0))||((rel.keyId||rel.keyId===0)?[rel.keyId]:[]));if(refresh){models=rel.related instanceof Backbone.Collection?rel.related.models:[rel.related];_.each(models,function(model){if(model.id||model.id===0){idsToFetch.push(model.id);}});}
if(idsToFetch&&idsToFetch.length){var created=[];models=_.map(idsToFetch,function(id){var model=rel.relatedModel.findModel(id);if(!model){var attrs={};attrs[rel.relatedModel.prototype.idAttribute]=id;model=rel.relatedModel.findOrCreate(attrs,options);created.push(model);}
return model;},this);if(rel.related instanceof Backbone.Collection&&_.isFunction(rel.related.url)){setUrl=rel.related.url(models);}
if(setUrl&&setUrl!==rel.related.url()){var opts=_.defaults({error:function(){var args=arguments;_.each(created,function(model){model.trigger('destroy',model,model.collection,options);options.error&&options.error.apply(model,args);});},url:setUrl},options);requests=[rel.related.fetch(opts)];}
else{requests=_.map(models,function(model){var opts=_.defaults({error:function(){if(_.contains(created,model)){model.trigger('destroy',model,model.collection,options);options.error&&options.error.apply(model,arguments);}}},options);return model.fetch(opts);},this);}}
return requests;},get:function(attr){var originalResult=Backbone.Model.prototype.get.call(this,attr);if(!this.dotNotation||attr.indexOf('.')===-1){return originalResult;}
var splits=attr.split('.');var result=_.reduce(splits,function(model,split){if(_.isNull(model)||_.isUndefined(model)){return undefined;}
else if(model instanceof Backbone.Model){return Backbone.Model.prototype.get.call(model,split);}
else if(model instanceof Backbone.Collection){return Backbone.Collection.prototype.at.call(model,split)}
else{throw new Error('Attribute must be an instanceof Backbone.Model or Backbone.Collection. Is: '+model+', currentSplit: '+split);}},this);if(originalResult!==undefined&&result!==undefined){throw new Error("Ambiguous result for '"+attr+"'. direct result: "+originalResult+", dotNotation: "+result);}
return originalResult||result;},set:function(key,value,options){Backbone.Relational.eventQueue.block();var attributes;if(_.isObject(key)||key==null){attributes=key;options=value;}
else{attributes={};attributes[key]=value;}
try{var id=this.id,newId=attributes&&this.idAttribute in attributes&&attributes[this.idAttribute];Backbone.Relational.store.checkId(this,newId);var result=Backbone.Model.prototype.set.apply(this,arguments);if(!this._isInitialized&&!this.isLocked()){this.constructor.initializeModelHierarchy();if(newId||newId===0){Backbone.Relational.store.register(this);}
this.initializeRelations(options);}
else if(newId&&newId!==id){Backbone.Relational.store.update(this);}
if(attributes){this.updateRelations(attributes,options);}}
finally{Backbone.Relational.eventQueue.unblock();}
return result;},clone:function(){var attributes=_.clone(this.attributes);if(!_.isUndefined(attributes[this.idAttribute])){attributes[this.idAttribute]=null;}
_.each(this.getRelations(),function(rel){delete attributes[rel.key];});return new this.constructor(attributes);},toJSON:function(options){if(this.isLocked()){return this.id;}
this.acquire();var json=Backbone.Model.prototype.toJSON.call(this,options);if(this.constructor._superModel&&!(this.constructor._subModelTypeAttribute in json)){json[this.constructor._subModelTypeAttribute]=this.constructor._subModelTypeValue;}
_.each(this._relations,function(rel){var related=json[rel.key],includeInJSON=rel.options.includeInJSON,value=null;if(includeInJSON===true){if(related&&_.isFunction(related.toJSON)){value=related.toJSON(options);}}
else if(_.isString(includeInJSON)){if(related instanceof Backbone.Collection){value=related.pluck(includeInJSON);}
else if(related instanceof Backbone.Model){value=related.get(includeInJSON);}
if(includeInJSON===rel.relatedModel.prototype.idAttribute){if(rel instanceof Backbone.HasMany){value=value.concat(rel.keyIds);}
else if(rel instanceof Backbone.HasOne){value=value||rel.keyId;if(!value&&!_.isObject(rel.keyContents)){value=rel.keyContents||null;}}}}
else if(_.isArray(includeInJSON)){if(related instanceof Backbone.Collection){value=[];related.each(function(model){var curJson={};_.each(includeInJSON,function(key){curJson[key]=model.get(key);});value.push(curJson);});}
else if(related instanceof Backbone.Model){value={};_.each(includeInJSON,function(key){value[key]=related.get(key);});}}
else{delete json[rel.key];}
if(includeInJSON){json[rel.keyDestination]=value;}
if(rel.keyDestination!==rel.key){delete json[rel.key];}});this.release();return json;}},{setup:function(superModel){this.prototype.relations=(this.prototype.relations||[]).slice(0);this._subModels={};this._superModel=null;if(this.prototype.hasOwnProperty('subModelTypes')){Backbone.Relational.store.addSubModels(this.prototype.subModelTypes,this);}
else{this.prototype.subModelTypes=null;}
_.each(this.prototype.relations||[],function(rel){if(!rel.model){rel.model=this;}
if(rel.reverseRelation&&rel.model===this){var preInitialize=true;if(_.isString(rel.relatedModel)){var relatedModel=Backbone.Relational.store.getObjectByName(rel.relatedModel);preInitialize=relatedModel&&(relatedModel.prototype instanceof Backbone.RelationalModel);}
if(preInitialize){Backbone.Relational.store.initializeRelation(null,rel);}
else if(_.isString(rel.relatedModel)){Backbone.Relational.store.addOrphanRelation(rel);}}},this);return this;},build:function(attributes,options){this.initializeModelHierarchy();var model=this._findSubModelType(this,attributes)||this;return new model(attributes,options);},_findSubModelType:function(type,attributes){if(type._subModels&&type.prototype.subModelTypeAttribute in attributes){var subModelTypeAttribute=attributes[type.prototype.subModelTypeAttribute];var subModelType=type._subModels[subModelTypeAttribute];if(subModelType){return subModelType;}
else{for(subModelTypeAttribute in type._subModels){subModelType=this._findSubModelType(type._subModels[subModelTypeAttribute],attributes);if(subModelType){return subModelType;}}}}
return null;},initializeModelHierarchy:function(){this.inheritRelations();if(this.prototype.subModelTypes){var resolvedSubModels=_.keys(this._subModels);var unresolvedSubModels=_.omit(this.prototype.subModelTypes,resolvedSubModels);_.each(unresolvedSubModels,function(subModelTypeName){var subModelType=Backbone.Relational.store.getObjectByName(subModelTypeName);subModelType&&subModelType.initializeModelHierarchy();});}},inheritRelations:function(){if(!_.isUndefined(this._superModel)&&!_.isNull(this._superModel)){return;}
Backbone.Relational.store.setupSuperModel(this);if(this._superModel){this._superModel.inheritRelations();if(this._superModel.prototype.relations){var inheritedRelations=_.filter(this._superModel.prototype.relations||[],function(superRel){return!_.any(this.prototype.relations||[],function(rel){return superRel.relatedModel===rel.relatedModel&&superRel.key===rel.key;},this);},this);this.prototype.relations=inheritedRelations.concat(this.prototype.relations);}}
else{this._superModel=false;}},findOrCreate:function(attributes,options){options||(options={});var parsedAttributes=(_.isObject(attributes)&&options.parse&&this.prototype.parse)?this.prototype.parse(_.clone(attributes)):attributes;var model=this.findModel(parsedAttributes);if(_.isObject(attributes)){if(model&&options.merge!==false){delete options.collection;delete options.url;model.set(parsedAttributes,options);}
else if(!model&&options.create!==false){model=this.build(parsedAttributes,_.defaults({parse:false},options));}}
return model;},find:function(attributes,options){options||(options={});options.create=false;return this.findOrCreate(attributes,options);},findModel:function(attributes){return Backbone.Relational.store.find(this,attributes);}});_.extend(Backbone.RelationalModel.prototype,Backbone.Semaphore);Backbone.Collection.prototype.__prepareModel=Backbone.Collection.prototype._prepareModel;Backbone.Collection.prototype._prepareModel=function(attrs,options){var model;if(attrs instanceof Backbone.Model){if(!attrs.collection){attrs.collection=this;}
model=attrs;}
else{options=options?_.clone(options):{};options.collection=this;if(typeof this.model.findOrCreate!=='undefined'){model=this.model.findOrCreate(attrs,options);}
else{model=new this.model(attrs,options);}
if(model&&model.validationError){this.trigger('invalid',this,attrs,options);model=false;}}
return model;};var set=Backbone.Collection.prototype.__set=Backbone.Collection.prototype.set;Backbone.Collection.prototype.set=function(models,options){if(!(this.model.prototype instanceof Backbone.RelationalModel)){return set.apply(this,arguments);}
if(options&&options.parse){models=this.parse(models,options);}
var singular=!_.isArray(models),newModels=[],toAdd=[];models=singular?(models?[models]:[]):_.clone(models);_.each(models,function(model){if(!(model instanceof Backbone.Model)){model=Backbone.Collection.prototype._prepareModel.call(this,model,options);}
if(model){toAdd.push(model);if(!(this.get(model)||this.get(model.cid))){newModels.push(model);}
else if(model.id!=null){this._byId[model.id]=model;}}},this);toAdd=singular?(toAdd.length?toAdd[0]:null):toAdd;var result=set.call(this,toAdd,_.defaults({parse:false},options));_.each(newModels,function(model){if(this.get(model)||this.get(model.cid)){this.trigger('relational:add',model,this,options);}},this);return result;};var remove=Backbone.Collection.prototype.__remove=Backbone.Collection.prototype.remove;Backbone.Collection.prototype.remove=function(models,options){if(!(this.model.prototype instanceof Backbone.RelationalModel)){return remove.apply(this,arguments);}
var singular=!_.isArray(models),toRemove=[];models=singular?(models?[models]:[]):_.clone(models);options||(options={});_.each(models,function(model){model=this.get(model)||(model&&this.get(model.cid));model&&toRemove.push(model);},this);var result=remove.call(this,singular?(toRemove.length?toRemove[0]:null):toRemove,options);_.each(toRemove,function(model){this.trigger('relational:remove',model,this,options);},this);return result;};var reset=Backbone.Collection.prototype.__reset=Backbone.Collection.prototype.reset;Backbone.Collection.prototype.reset=function(models,options){options=_.extend({merge:true},options);var result=reset.call(this,models,options);if(this.model.prototype instanceof Backbone.RelationalModel){this.trigger('relational:reset',this,options);}
return result;};var sort=Backbone.Collection.prototype.__sort=Backbone.Collection.prototype.sort;Backbone.Collection.prototype.sort=function(options){var result=sort.call(this,options);if(this.model.prototype instanceof Backbone.RelationalModel){this.trigger('relational:reset',this,options);}
return result;};var trigger=Backbone.Collection.prototype.__trigger=Backbone.Collection.prototype.trigger;Backbone.Collection.prototype.trigger=function(eventName){if(!(this.model.prototype instanceof Backbone.RelationalModel)){return trigger.apply(this,arguments);}
if(eventName==='add'||eventName==='remove'||eventName==='reset'||eventName==='sort'){var dit=this,args=arguments;if(_.isObject(args[3])){args=_.toArray(args);args[3]=_.clone(args[3]);}
Backbone.Relational.eventQueue.add(function(){trigger.apply(dit,args);});}
else{trigger.apply(this,arguments);}
return this;};Backbone.RelationalModel.extend=function(protoProps,classProps){var child=Backbone.Model.extend.apply(this,arguments);child.setup(this);return child;};}));window.PTL=window.PTL||{};PTL.models=PTL.models||{};(function(models,utils){models.Unit=Backbone.RelationalModel.extend({relations:[{type:'HasOne',key:'store',relatedModel:'PTL.models.Store',reverseRelation:{key:'units'}}],setTranslation:function(value){if(!_.isArray(value)){value=[value];}
this.set('target',_.map(value,function(item){return utils.cleanEscape(item);}));}});models.Store=Backbone.RelationalModel.extend({});}(PTL.models,PTL.utils));window.PTL=window.PTL||{};PTL.collections=PTL.collections||{};(function(collections,models){collections.UnitSet=Backbone.Collection.extend({model:models.Unit,initialize:function(model,opts){this.chunkSize=opts.chunkSize;this.uIds=[];this.total=0;},comparator:function(unit){return this.uIds.indexOf(unit.id);},getCurrent:function(){return this.activeUnit;},setCurrent:function(unit){this.activeUnit=unit instanceof this.model?unit:this.get(unit);},setFirstAsCurrent:function(){this.setCurrent(this.at(0));},fetchedIds:function(){return this.map(function(unit){return unit.id;});},next:function(){var index=this.indexOf(this.getCurrent());return(index+1===this.length)?null:this.at(index+1);},hasNext:function(){return this.next()!==null;},prev:function(){var index=this.indexOf(this.getCurrent());return(index===0)?null:this.at(index-1);},hasPrev:function(){return this.prev()!==null;}});}(PTL.collections,PTL.models));(function($){window.PTL=window.PTL||{};PTL.editor={init:function(options){this.settings={mt:[]};options&&$.extend(this.settings,options);this.units=new PTL.collections.UnitSet([],{chunkSize:this.settings.chunkSize});this.filter='all';this.checks=[];this.user=null;this.ctxGap=0;this.ctxQty=parseInt($.cookie('ctxQty'),10)||1;this.ctxStep=1;this.preventNavigation=false;this.isLoading=true;this.showActivity();this.searchFields=[];this.searchOptions=[];this.cpRE=/^(<[^>]+>|\[n\|t]|\W$^\n)*(\b|$)/gm;this.timelineReq=null;this.tmLocalReq=null;this.tmRemoteReq=null;this.differencer=new diff_match_patch();this.tmpl={vUnit:_.template($('#view_unit').html()),tm:_.template($('#tm_suggestions').html()),editCtx:_.template($('#editCtx').html())};PTL.search.init({onSubmit:this.search});$(document).on('input','.js-translation-area',this.onTextareaChange.bind(this));$(document).on('change','input.fuzzycheck',this.onStateChange.bind(this));$(document).on('click','input.fuzzycheck',this.onStateClick.bind(this));$(document).on('click','.switch-suggest-mode a',this.toggleSuggestMode.bind(this));$(document).on('focus','.focusthis',function(e){PTL.editor.focused=e.target;});$(document).on('click','.js-editor-copytext',this.copyText);$(document).on('click','.js-copyoriginal',function(){PTL.editor.copyOriginal($(this).parents('.source-language').find('.translation-text'));});$(document).on('click','div.suggestion',function(){if(PTL.editor.getSelectedText()){return;}
if($('.js-translation-area').attr('disabled')){return;}
PTL.editor.copyOriginal($('.suggestion-translation',this));});$(document).on('editor_ready','table.translate-table',this.ready);$(document).on('noResults','table.translate-table',this.noResults);$(document).on('mouseup','tr.view-row, tr.ctx-row',this.gotoUnit);$(document).on('keypress','#item-number',function(e){if(e.which===13){PTL.editor.gotoIndex(parseInt($('#item-number').val(),10));}});$(document).on('click','input.submit',this.submit);$(document).on('click','input.suggest',this.suggest);$(document).on('click','#js-nav-prev',this.gotoPrev.bind(this));$(document).on('click','#js-nav-next',this.gotoNext.bind(this));$(document).on('click','.js-suggestion-reject',this.rejectSuggestion);$(document).on('click','.js-suggestion-accept',this.acceptSuggestion);$(document).on('click','#js-show-timeline',this.showTimeline);$(document).on('click','#js-hide-timeline',this.hideTimeline);$(document).on('click','.js-toggle-check',this.toggleCheck);$("#filter-checks").hide();$(document).on('change','#filter-status select',this.filterStatus);$(document).on('change','#filter-checks select',this.filterChecks);$(document).on('click','.js-more-ctx',function(){PTL.editor.moreContext(false);});$(document).on('click','.js-less-ctx',this.lessContext);$(document).on('click','.js-show-ctx',this.showContext);$(document).on('click','.js-hide-ctx',this.hideContext);$(document).on('click','.js-editor-comment',function(e){e.preventDefault();$('#editor-comment').slideToggle('fast');});$(document).on('submit','#js-comment-form',this.comment);$(document).on('click','.js-editor-msg-hide',this.hideMsg);shortcut.add('ctrl+return',function(){if(PTL.editor.isSuggestMode()){$('input.suggest').trigger('click');}else{$('input.submit').trigger('click');}});shortcut.add('ctrl+j',this.jumpToPreviousPlaceable);shortcut.add('ctrl+k',this.jumpToNextPlaceable);shortcut.add('ctrl+l',this.insertSelectedPlaceable);shortcut.add('ctrl+space',this.toggleState.bind(this));shortcut.add('ctrl+shift+space',this.toggleSuggestMode.bind(this));shortcut.add('ctrl+up',this.gotoPrev.bind(this));shortcut.add('ctrl+,',this.gotoPrev.bind(this));shortcut.add('ctrl+down',this.gotoNext.bind(this,false));shortcut.add('ctrl+.',this.gotoNext.bind(this,false));if(navigator.platform.toUpperCase().indexOf('MAC')>=0){$('#js-nav-next').attr('title',gettext(['Go to the next string (Ctrl+.)','','Also:','Next page: Ctrl+Shift+.','Last page: Ctrl+Shift+End'].join('<br/>')));$('#js-nav-prev').attr('title',gettext(['Go to the previous string (Ctrl+,)','','Also:','Previous page: Ctrl+Shift+,','First page: Ctrl+Shift+Home'].join('<br/>')));}
shortcut.add('ctrl+shift+n',function(){$('#item-number').focus().select();});$(document).ajaxStart(function(){clearTimeout(PTL.editor.delayedActivityTimer);PTL.editor.delayedActivityTimer=setTimeout(function(){PTL.editor.showActivity();},3000);});$(document).ajaxStop(function(){clearTimeout(PTL.editor.delayedActivityTimer);if(!PTL.editor.isLoading){PTL.editor.hideActivity();}});$.each(this.settings.mt,function(){var backend=this.name,key=this.key;$.ajax({url:s(['js/mt/',backend,'.js'].join('')),async:false,dataType:'script',cache:'true',success:function(){setTimeout(function(){PTL.editor.mt[backend].init(key);},0);$(document).on('mt_ready','table.translate-table',PTL.editor.mt[backend].ready);}});});$.each(this.settings.lookup,function(){var backend=this;$.ajax({url:s(['js/lookup/',backend,'.js'].join('')),async:false,dataType:'script',cache:'true',success:function(){setTimeout(function(){PTL.editor.lookup[backend].init();},0);$(document).on('lookup_ready','table.translate-table',PTL.editor.lookup[backend].ready);}});});setInterval(PTL.common.updateRelativeDates,6e4);setTimeout(function(){$.history.init(function(hash){var params=PTL.utils.getParsedHash(hash),isInitial=true,uId=0;if(params['unit']){var uIdParam=parseInt(params['unit'],10);if(uIdParam&&!isNaN(uIdParam)){var current=PTL.editor.units.getCurrent(),newUnit=PTL.editor.units.get(uIdParam);if(newUnit&&newUnit!==current){PTL.editor.units.setCurrent(newUnit);PTL.editor.displayEditUnit();return;}else{uId=uIdParam;isInitial=!PTL.editor.units.length;}}}
PTL.editor.filter='all';if('filter'in params){var filterName=params['filter'];PTL.editor.filter=filterName;if(filterName==='checks'&&'checks'in params){PTL.editor.checks=params['checks'].split(',');}else{PTL.editor.checks=[];}}
if('user'in params&&PTL.editor.filter.indexOf('user-')===0){var user;PTL.editor.user=user=params['user'];var newOpts=[],values={'user-suggestions':interpolate(gettext("%s's pending suggestions"),[user]),'user-suggestions-accepted':interpolate(gettext("%s's accepted suggestions"),[user]),'user-suggestions-rejected':interpolate(gettext("%s's rejected suggestions"),[user]),'user-submissions':interpolate(gettext("%s's submissions"),[user]),'user-submissions-overwritten':interpolate(gettext("%s's overwritten submissions"),[user]),};for(var key in values){newOpts.push(['<option value="',key,'" data-user="',user,'" class="','js-user-filter','">',values[key],'</option>'].join(''));}
$(".js-user-filter").remove();$('#filter-status select').append(newOpts.join(''))}
if('search'in params){PTL.editor.filter="search";PTL.editor.searchText=params['search'];if('sfields'in params){PTL.editor.searchFields=params['sfields'].split(',');}
PTL.editor.searchOptions=[];if('soptions'in params){PTL.editor.searchOptions=params['soptions'].split(',');}}
PTL.editor.preventNavigation=true;$('#filter-status select').select2('val',PTL.editor.filter);if(PTL.editor.filter=="checks"){if($("#filter-checks").is(':hidden')){PTL.editor.filterStatus();}
$('#filter-checks select').select2('val',PTL.editor.checks[0]);}
if(PTL.editor.filter=="search"){$("#id_search").val(PTL.editor.searchText);$("#id_search").trigger('focus');if(!PTL.editor.searchFields.length){PTL.editor.searchFields=["source","target"];}
$(".js-search-fields input").each(function(){if($.inArray($(this).val(),PTL.editor.searchFields)>=0){$(this).attr("checked","checked");}else{$(this).removeAttr("checked");}});$(".js-search-options input").each(function(){if($.inArray($(this).val(),PTL.editor.searchOptions)>=0){$(this).attr("checked","checked");}else{$(this).removeAttr("checked");}});$('#filter-checks').remove();}
PTL.editor.preventNavigation=false;PTL.editor.fetchUnits({initial:isInitial,uId:uId,success:function(){if(uId>0){PTL.editor.units.setCurrent(uId);}else{PTL.editor.units.setFirstAsCurrent();}
PTL.editor.displayEditUnit();}});},{'unescape':true});},1);},jumpToPreviousPlaceable:function(){var $selectedPlaceable=$('#js-selected-placeable');if(!$selectedPlaceable.length){$('div.original .js-placeable:last').attr('id','js-selected-placeable');}else{$selectedPlaceable.removeAttr('id');if(!$('div.original .js-placeable:first').is($selectedPlaceable)){$selectedPlaceable.prev('div.original .js-placeable').attr('id','js-selected-placeable');};};},jumpToNextPlaceable:function(){var $selectedPlaceable=$('#js-selected-placeable');if(!$selectedPlaceable.length){$('div.original .js-placeable:first').attr('id','js-selected-placeable');}else{$selectedPlaceable.removeAttr('id');if(!$('div.original .js-placeable:last').is($selectedPlaceable)){$selectedPlaceable.next('div.original .js-placeable').attr('id','js-selected-placeable');};};},insertSelectedPlaceable:function(){var $selectedPlaceable=$('#js-selected-placeable');if($selectedPlaceable.length){$selectedPlaceable.trigger('click');PTL.editor.jumpToNextPlaceable();};},ready:function(){var maxheight=$(window).height()*0.3;$('textarea.expanding').TextAreaExpander('10',maxheight);$('.extra-item-comment').filter(':not([dir])').bidi();$('.suggestion-translation-body').filter(':not([dir])').bidi();var firstArea=$('.focusthis')[0];if(firstArea){firstArea.focus();}
PTL.editor.settings.targetLang=PTL.editor.normalizeCode($('.js-translation-area').attr('lang'));PTL.editor.hlSearch();PTL.editor.setupAutocomplete();if(PTL.editor.settings.tmUrl!=''){PTL.editor.getTMUnits();}
$("table.translate-table").trigger("mt_ready");$("table.translate-table").trigger("lookup_ready");PTL.editor.keepState=false;PTL.editor.isLoading=false;PTL.editor.hideActivity();PTL.editor.updateExportLink();PTL.common.updateRelativeDates();clearTimeout(PTL.editor.delayedActivityTimer);},noResults:function(){PTL.editor.displayMsg(gettext("No results."));PTL.editor.reDraw(false);},escapeUnsafeRegexSymbols:function(s){return s.replace(/[!$&(-+\-.:<-?\[-^{-}]/g,'\\$&');},makeRegexForMultipleWords:function(s){return['(',PTL.editor.escapeUnsafeRegexSymbols(s).trim().replace(/ +/g,'|'),')'].join('');},hlSearch:function(){var hl=PTL.editor.filter=="search"?PTL.editor.searchText:"",sel=[],selMap={notes:'div.developer-comments',locations:'div.translate-locations',source:'td.translate-original, div.original div.translation-text',target:'td.translate-translation'},hlRegex;$.each(PTL.editor.searchFields,function(i,field){sel.push("tr.edit-row "+selMap[field]);sel.push("tr.view-row "+selMap[field]);});if(PTL.editor.searchOptions.indexOf('exact')>=0){hlRegex=new RegExp(['(',PTL.editor.escapeUnsafeRegexSymbols(hl),')'].join(''));}else{hlRegex=new RegExp(PTL.editor.makeRegexForMultipleWords(hl),"i");}
$(sel.join(", ")).highlightRegex(hlRegex);},setupAutocomplete:function(){var searchFunc=function(term,callback){var $placeables=$("div.original .js-placeable");var matching=$.map($placeables,function(placeable){var text=$(placeable).text(),html=$(placeable).html();if(term.length!==0&&text.indexOf(term)===0){return html;}else{return null;}});callback(matching);};var replaceFunc=function(value){var text=$('<div/>').html(value).text();return text;};$("textarea.translation").textcomplete([{match:/(\S*)$/,search:searchFunc,replace:replaceFunc,index:1,}]);},copyText:function(e){var selector,text,element,start,action=$(this).data('action');selector=$(".tm-translation",this).ifExists()||$(".suggestion-translation",this).ifExists()||$(this);text=selector.data('entity')||selector.text();element=$(PTL.editor.focused);if(action==="overwrite"){element.val(text).trigger('input');start=text.length;}else{start=element.caret().start+text.length;element.val(element.caret().replace(text)).trigger('input');}
element.caret(start,start);},copyOriginal:function(sources){var cleanSources=[];$.each(sources,function(i){cleanSources[i]=$(this).text();});var targets=$('.js-translation-area');if(targets.length){var i,active,max=cleanSources.length-1;for(var i=0;i<targets.length;i++){var newval=cleanSources[i]||cleanSources[max];$(targets.get(i)).val(newval).trigger('input');}
active=$(targets)[0];active.focus();PTL.editor.goFuzzy();PTL.editor.cpRE.exec($(active).val());i=PTL.editor.cpRE.lastIndex;$(active).caret(i,i);PTL.editor.cpRE.lastIndex=0;}},getSelectedText:function(){var t='';if(window.getSelection){t=window.getSelection();}else if(document.getSelection){t=document.getSelection();}else if(document.selection){t=document.selection.createRange().text;}
return t;},doDiff:function(a,b){var d,op,text,textDiff="",removed="",diff=this.differencer.diff_main(a,b);this.differencer.diff_cleanupSemantic(diff);$.each(diff,function(k,v){op=v[0];text=v[1];if(op===0){if(removed){textDiff+='<span class="diff-delete">'+PTL.utils.fancyEscape(removed)+'</span>'
removed="";}
textDiff+=PTL.utils.fancyEscape(text);}else if(op===1){if(removed){textDiff+='<span class="diff-replace">'+PTL.utils.fancyEscape(text)+'</span>';removed="";}else{textDiff+='<span class="diff-insert">'+PTL.utils.fancyEscape(text)+'</span>';}}else if(op===-1){removed=text;}});if(removed){textDiff+='<span class="diff-delete">'+PTL.utils.fancyEscape(removed)+'</span>';}
return textDiff;},doFuzzyStyle:function(){$("tr.edit-row").addClass("fuzzy-unit");},undoFuzzyStyle:function(){$("tr.edit-row").removeClass("fuzzy-unit");},doFuzzyBox:function(){var $checkbox=$('input.fuzzycheck');$checkbox.prop('checked',true);if(!this.settings.isAdmin){$('.js-fuzzy-block').show();$checkbox[0].defaultChecked=true;}
$checkbox.trigger('change');},undoFuzzyBox:function(){var $checkbox=$('input.fuzzycheck');$checkbox.prop('checked',false);$checkbox.trigger('change');},goFuzzy:function(){if(!this.isFuzzy()){this.doFuzzyStyle();this.doFuzzyBox();}},ungoFuzzy:function(){if(this.isFuzzy()){this.undoFuzzyStyle();this.undoFuzzyBox();}},isFuzzy:function(){return $('input.fuzzycheck').prop('checked');},toggleFuzzyStyle:function(){if(this.isFuzzy()){this.doFuzzyStyle();}else{this.undoFuzzyStyle();}},toggleState:function(){$('input.fuzzycheck').blur().click();},handleTranslationChange:function(){var $submit=$('.js-submit'),translations=$('.js-translation-area').get(),checkbox=$('#id_state')[0],stateChanged=checkbox.defaultChecked!==checkbox.checked,areaChanged=false,needsReview=false,area,i;if(!this.settings.isAdmin){needsReview=checkbox.checked===true;}
for(i=0;i<translations.length&&!areaChanged;i++){area=translations[i];areaChanged=area.defaultValue!==area.value;}
var disableSubmit=!(stateChanged||areaChanged)||needsReview;$submit.each(function(){this.disabled=disableSubmit;});},onStateChange:function(){this.handleTranslationChange();this.toggleFuzzyStyle();},onStateClick:function(){this.keepState=true;},onTextareaChange:function(e){this.handleTranslationChange();var el=e.target,hasChanged=el.defaultValue!==el.value;if(hasChanged&&!this.keepState){this.ungoFuzzy();}},doSuggestMode:function(){$("table.translate-table").addClass("suggest-mode");},undoSuggestMode:function(){$("table.translate-table").removeClass("suggest-mode");},isSuggestMode:function(){return $("table.translate-table").hasClass("suggest-mode");},toggleSuggestMode:function(e){e.preventDefault();if(this.isSuggestMode()){this.undoSuggestMode();}else{this.doSuggestMode();}},updateExportLink:function(){var urlStr=window.location.href.replace('/translate/','/export-view/').replace('#','?'),exportLink=['<a href="',l(urlStr),'">',gettext('Export View'),'</a>'].join('');$("#js-editor-export").html(exportLink);},showActivity:function(force){this.hideMsg();$("#js-editor-act").spin().fadeIn(300);},hideActivity:function(){$("#js-editor-act").spin(false).fadeOut(300);},displayMsg:function(msg){this.hideActivity();PTL.common.fixSidebarHeight();$("#js-editor-msg").show().find("span").html(msg).fadeIn(300);},hideMsg:function(msg){if($("#js-editor-msg").is(":visible")){$("#js-editor-msg").fadeOut(300);}},displayError:function(msg){if(msg){this.hideActivity();$("#js-editor-error span").text(msg).parent().parent().stop(true,true).fadeIn(300).delay(2000).fadeOut(3500);}},error:function(xhr,s){var msg="";if(s=="abort"){return;}
if(xhr.status==0){msg=gettext("Error while connecting to the server");}else if(xhr.status==402){PTL.captcha.onError(xhr,'PTL.editor.error');}else if(xhr.status==404){msg=gettext("Not found");}else if(xhr.status==500){msg=gettext("Server error");}else if(s=="timeout"){msg=gettext("The server seems down. Try again later.");}else{if(xhr.hasOwnProperty('responseText')){msg=$.parseJSON(xhr.responseText).msg;}else{msg=gettext("Unknown error");}}
PTL.editor.displayError(msg);},getReqData:function(){var reqData={};switch(this.filter){case"checks":reqData.filter=this.filter;if(this.checks.length){reqData.checks=this.checks.join(",");}
break;case"search":reqData.search=this.searchText;reqData.sfields=this.searchFields;reqData.soptions=this.searchOptions;break;case"all":break;default:reqData.filter=this.filter;break;}
if(this.user){reqData.user=this.user;}
return reqData;},buildRow:function(unit){return['<tr id="row',unit.id,'" class="view-row">',this.tmpl.vUnit({unit:unit.toJSON()}),'</tr>'].join('');},buildRows:function(){var unitGroups=this.getUnitGroups(),groupSize=_.size(unitGroups),currentUnit=this.units.getCurrent(),rows=[],i,unit;_.each(unitGroups,function(unitGroup,key){if(groupSize!==1){rows.push(['<tr class="delimiter-row"><td colspan="2">','<div class="hd"><h2>',key,'</h2></div>','</td></tr>'].join(''));}
for(i=0;i<unitGroup.length;i++){unit=unitGroup[i];if(unit.id===currentUnit.id){rows.push(this.getEditUnit());}else{rows.push(this.buildRow(unit));}}},this);return rows.join('');},buildCtxRows:function(units,extraCls){var i,unit,currentUnit=this.units.getCurrent(),rows='';for(i=0;i<units.length;i++){unit=units[i];unit=$.extend({},currentUnit.toJSON(),unit);rows+='<tr id="ctx'+unit.id+'" class="ctx-row '+extraCls+'">';rows+=this.tmpl.vUnit({unit:unit});rows+='</tr>';}
return rows;},getUnitGroups:function(){var limit=parseInt(((this.units.chunkSize-1)/2),10),unitCount=this.units.length,currentUnit=this.units.getCurrent(),curIndex=this.units.indexOf(currentUnit),begin=curIndex-limit,end=curIndex+1+limit;if(begin<0){end=end+-begin;begin=0;}else if(end>unitCount){if(begin>end-unitCount){begin=begin+-(end-unitCount);}else{begin=0;}
end=unitCount;}
return _.groupBy(this.units.slice(begin,end),function(unit){return unit.get('store').get('pootlePath');},this);},displayEditUnit:function(){if(PTL.editor.units.length){this.fetchUnits();this.hideMsg();this.reDraw(this.buildRows());this.updateNavButtons();}},reDraw:function(newTbody){var tTable=$("table.translate-table"),where=$("tbody",tTable),oldRows=$("tr",where);oldRows.remove();if(newTbody!==false){where.append(newTbody);$(tTable).trigger("editor_ready");}},updateNavButton:function(selector,disable){var $el=$(selector);if($el.is(':disabled')&&disable||$el.is(':enabled')&&!disable){return;}
if(disable){$el.data('title',$el.attr('title'));$el.removeAttr('title');}else{$el.attr('title',$el.data('title'));}
$el.prop('disabled',disable);},updateNavButtons:function(){this.updateNavButton('#js-nav-prev',!this.units.hasPrev());this.updateNavButton('#js-nav-next',!this.units.hasNext());},fetchUnits:function(opts){var defaults={initial:false,uId:0},viewUrl=l('/xhr/units/'),reqData={path:this.settings.pootlePath};opts=$.extend({},defaults,opts);if(opts.initial){reqData.initial=opts.initial;if(opts.uId>0){reqData.uids=opts.uId;}}else{var fetchedIds=this.units.fetchedIds(),offset=this.units.chunkSize,curUId=opts.uId>0?opts.uId:this.units.getCurrent().id,uIndex=this.units.uIds.indexOf(curUId),uIds,begin,end;begin=Math.max(uIndex-offset,0);end=Math.min(uIndex+offset+1,this.units.total);if(opts.uId===0){if(fetchedIds.indexOf(this.units.uIds[begin])===-1){begin=Math.max(begin-offset,0);}
if(fetchedIds.indexOf(this.units.uIds[end-1])===-1){end=Math.min(end+offset+1,this.units.total);}}
uIds=this.units.uIds.slice(begin,end);uIds=_.difference(uIds,fetchedIds);if(!uIds.length){return;}
reqData.uids=uIds.join(',');}
$.extend(reqData,this.getReqData());$.ajax({url:viewUrl,data:reqData,dataType:'json',cache:false,success:function(data){if(data.uIds){PTL.editor.units.reset();PTL.editor.units.uIds=data.uIds;PTL.editor.units.total=data.uIds.length;}
if(data.unitGroups.length){var i,unitGroup;for(i=0;i<data.unitGroups.length;i++){unitGroup=data.unitGroups[i];$.each(unitGroup,function(pootlePath,group){var storeData=$.extend({pootlePath:pootlePath},group.meta),units=_.map(group.units,function(unit){return $.extend(unit,{store:storeData});});PTL.editor.units.set(units,{remove:false});});}
if(opts.success&&$.isFunction(opts.success)){opts.success();}}else{$("table.translate-table").trigger("noResults");}},error:PTL.editor.error});},updateNav:function(){$("#items-count").text(this.units.total);var currentUnit=PTL.editor.units.getCurrent();if(currentUnit!==undefined){var uIndex=this.units.uIds.indexOf(currentUnit.id)+1;$("#item-number").val(uIndex);}},getEditUnit:function(){var editUnit,editCtxRowBefore,editCtxRowAfter,editCtxWidgets,hasData,eClass="edit-row",currentUnit=this.units.getCurrent(),uid=currentUnit.id,editUrl=l(['/xhr/units/',uid,'/edit/'].join('')),widget='',ctx={before:[],after:[]};$.ajax({url:editUrl,async:false,dataType:'json',success:function(data){widget=data['editor'];PTL.editor.updateNav();if(data.ctx){PTL.editor.ctxGap=Math.max(data.ctx.before.length,data.ctx.after.length);ctx.before=data.ctx.before;ctx.after=data.ctx.after;}},error:PTL.editor.error});eClass+=currentUnit.get('isfuzzy')?" fuzzy-unit":"";eClass+=PTL.editor.filter!=='all'?" with-ctx":"";hasData=ctx.before.length||ctx.after.length;editCtxWidgets=this.editCtxUI({hasData:hasData});editCtxRowBefore=editCtxWidgets[0];editCtxRowAfter=editCtxWidgets[1];editUnit=(PTL.editor.filter!=='all'?editCtxRowBefore+this.buildCtxRows(ctx.before,"before"):'')+'<tr id="row'+uid+'" class="'+eClass+'">'+
widget+'</tr>'+
(PTL.editor.filter!=='all'?this.buildCtxRows(ctx.after,"after")+editCtxRowAfter:'');return editUnit;},submit:function(e){e.preventDefault();var el=e.target,uId=PTL.editor.units.getCurrent().id,submitUrl=l(['/xhr/units/',uId].join('')),reqData=$('#translate').serializeObject(),captchaCallbacks={sfn:'PTL.editor.processSubmission',efn:'PTL.editor.error'};$.extend(reqData,PTL.editor.getReqData(),captchaCallbacks);el.disabled=true;$('.js-translation-area').each(function(){this.defaultValue=this.value;});var checkbox=$('#id_state')[0];checkbox.defaultChecked=checkbox.checked;$.ajax({url:submitUrl,type:'POST',data:reqData,dataType:'json',success:PTL.editor.processSubmission,error:PTL.editor.error});},processSubmission:function(data){var translations=$('.js-translation-area').map(function(i,el){return $(el).val();}).get();var unit=PTL.editor.units.getCurrent();unit.setTranslation(translations);unit.set('isfuzzy',PTL.editor.isFuzzy());$('.translate-container').toggleClass('error',!!data.checks);if(data.checks){var $checks=$('.js-unit-checks'),focusedArea=$('.focusthis')[0];$checks.html(data.checks).show();var blinkClass=function(elem,className,n,delay){elem.toggleClass(className);if(n>1){setTimeout(function(){blinkClass(elem,className,n-1,delay);},delay);}};blinkClass($checks,'blink',4,200);focusedArea.focus();}else{PTL.editor.gotoNext();}},suggest:function(e){e.preventDefault();var uId=PTL.editor.units.getCurrent().id,suggestUrl=l(['/xhr/units/',uId,'/suggestions/'].join('')),reqData=$('#translate').serializeObject(),captchaCallbacks={sfn:'PTL.editor.processSuggestion',efn:'PTL.editor.error'};$.extend(reqData,PTL.editor.getReqData(),captchaCallbacks);$.ajax({url:suggestUrl,type:'POST',data:reqData,dataType:'json',success:PTL.editor.processSuggestion,error:PTL.editor.error});},processSuggestion:function(){PTL.editor.gotoNext();},gotoPrev:function(){var newUnit=this.units.prev();if(newUnit){var newHash=PTL.utils.updateHashPart('unit',newUnit.id);$.history.load(newHash);}},gotoNext:function(isSubmission){if(isSubmission===undefined){isSubmission=true;};var newUnit=this.units.next();if(newUnit){var newHash=PTL.utils.updateHashPart('unit',newUnit.id);$.history.load(newHash);}else if(isSubmission){var backLink=$('.js-back-to-browser').attr('href');window.location.href=[backLink,'finished'].join('?');}},gotoUnit:function(e){e.preventDefault();if(e.ctrlKey||e.altKey||e.metaKey||e.which===2){var $el=e.target.nodeName!=='TD'?$(e.target).parents('td'):$(e.target);window.open($el.data('target'),'_blank');return;}
if(PTL.editor.getSelectedText()!=""){return;}
var m=this.id.match(/(row|ctx)([0-9]+)/);if(m){var newHash,type=m[1],uid=parseInt(m[2],10);if(type==='row'){newHash=PTL.utils.updateHashPart("unit",uid);}else{newHash=['unit=',encodeURIComponent(uid)].join('');}
$.history.load(newHash);}},gotoIndex:function(index){if(index&&!isNaN(index)&&index>0&&index<=PTL.editor.units.total){var uId=PTL.editor.units.uIds[index-1],newHash=PTL.utils.updateHashPart('unit',uId);$.history.load(newHash);}},getCheckOptions:function(options){var checksUrl=l('/xhr/stats/checks/'),reqData={path:this.settings.pootlePath};$.ajax({url:checksUrl,data:reqData,dataType:'json',success:options.success,error:PTL.editor.error});},filterChecks:function(){if(PTL.editor.preventNavigation){return;}
var filterBy=$("option:selected",this).val();if(filterBy!="none"){var newHash="filter=checks&checks="+encodeURIComponent(filterBy);$.history.load(newHash);}},appendChecks:function(checks){if(Object.keys(checks).length){$("#filter-checks").show();$("#filter-checks").find('optgroup').each(function(e){var empty=true,$gr=$(this);$gr.find('option').each(function(e){var $opt=$(this),value=$opt.attr('value');if(value in checks){empty=false;$opt.text($opt.data('title')+'('+checks[value]+')');}else{$opt.remove();}});if(empty){$gr.hide();}});$("#filter-checks").show();$("#js-select2-filter-checks").select2({width:"resolve"});}else{PTL.editor.displayMsg(gettext("No results."));$('#filter-status select').select2('val',PTL.editor.filter);}},filterStatus:function(){var $selected=$("#filter-status option:selected"),filterBy=$selected.val(),isUserFilter=$selected.data('user');if(filterBy=="checks"){PTL.editor.getCheckOptions({success:PTL.editor.appendChecks});}else{$("#filter-checks").hide();if(!PTL.editor.preventNavigation){var newHash="filter="+filterBy;if(PTL.editor.user&&isUserFilter){newHash+='&user='+PTL.editor.user;}else{PTL.editor.user=null;$(".js-user-filter").remove();}
$.history.load(newHash);}}},editCtxUI:function(opts){var defaults={hasData:false,replace:false};opts=$.extend({},defaults,opts);var editCtxRowBefore=PTL.editor.tmpl.editCtx({hasData:opts.hasData,extraCls:'before'});var editCtxRowAfter=PTL.editor.tmpl.editCtx({hasData:opts.hasData,extraCls:'after'});if(opts.replace){$("tr.edit-ctx.before").replaceWith(editCtxRowBefore);$("tr.edit-ctx.after").replaceWith(editCtxRowAfter);}
return[editCtxRowBefore,editCtxRowAfter];},moreContext:function(initial){var ctxUrl=l(['/xhr/units/',PTL.editor.units.getCurrent().id,'/context/'].join('')),reqData={gap:PTL.editor.ctxGap};reqData.qty=initial?PTL.editor.ctxQty:PTL.editor.ctxStep;if(initial&&reqData.qty===0){return;}
$.ajax({url:ctxUrl,async:false,dataType:'json',data:reqData,success:function(data){if(data.ctx.before.length||data.ctx.after.length){if(initial){PTL.editor.ctxGap=Math.max(data.ctx.before.length,data.ctx.after.length);}else{PTL.editor.ctxGap+=Math.max(data.ctx.before.length,data.ctx.after.length);}
$.cookie('ctxQty',PTL.editor.ctxGap,{path:'/'});var before=PTL.editor.buildCtxRows(data.ctx.before,"before"),after=PTL.editor.buildCtxRows(data.ctx.after,"after");var editCtxRows=$("tr.edit-ctx");editCtxRows.first().after(before);editCtxRows.last().before(after);}},error:PTL.editor.error});},lessContext:function(){var before=$(".ctx-row.before"),after=$(".ctx-row.after");if(before.length||after.length){if(before.length===PTL.editor.ctxGap){before.slice(0,PTL.editor.ctxStep).remove();}
if(after.length===PTL.editor.ctxGap){after.slice(-PTL.editor.ctxStep).remove();}
PTL.editor.ctxGap-=PTL.editor.ctxStep;if(PTL.editor.ctxGap>=0){if(PTL.editor.ctxGap==0){PTL.editor.editCtxUI({hasData:false,replace:true});$.cookie('ctxShow',false,{path:'/'});}
$.cookie('ctxQty',PTL.editor.ctxGap,{path:'/'});}}},showContext:function(){var editCtxRowBefore,editCtxRowAfter,before=$(".ctx-row.before"),after=$(".ctx-row.after");if(before.length||after.length){before.show();after.show();}else{PTL.editor.moreContext(true);}
PTL.editor.editCtxUI({hasData:true,replace:true});$.cookie('ctxShow',true,{path:'/'});},hideContext:function(){var editCtxRowBefore,editCtxRowAfter,before=$(".ctx-row.before"),after=$(".ctx-row.after");before.hide();after.hide();PTL.editor.editCtxUI({hasData:false,replace:true});$.cookie('ctxShow',false,{path:'/'});},search:function(e){e.preventDefault();var newHash,text=$("#id_search").val();if(text){var remember=true,queryString=PTL.search.buildSearchQuery(text,remember);newHash="search="+queryString;}else{newHash=PTL.utils.updateHashPart("filter","all",["search","sfields","soptions"]);}
$.history.load(newHash);},comment:function(e){e.preventDefault();var url=$(this).attr('action'),reqData=$(this).serializeObject();$.ajax({url:url,type:'POST',data:reqData,success:function(data){$("#editor-comment").fadeOut(200);if($("#translator-comment").length){$(data.comment).hide().prependTo("#translator-comment").delay(200).animate({height:'show'},1000,'easeOutQuad');}else{var commentHtml='<div id="translator-comment">'+data.comment
+'</div>';$(commentHtml).prependTo("#extras-container").delay(200).hide().animate({height:'show'},1000,'easeOutQuad');}
PTL.common.updateRelativeDates();},error:PTL.editor.error});return false;},showTimeline:function(e){e.preventDefault();if($("#timeline-results").length){$("#js-hide-timeline").show();$("#timeline-results").slideDown(1000,'easeOutQuad');$("#js-show-timeline").hide();return;}
var uid=PTL.editor.units.getCurrent().id,node=$(".translate-container"),timelineUrl=l(['/xhr/units/',uid,'/timeline/'].join(''));node.spin();if(PTL.editor.timelineReq!=null){PTL.editor.timelineReq.abort();}
PTL.editor.timelineReq=$.ajax({url:timelineUrl,dataType:'json',success:function(data){var uid=data.uid;if(data.timeline&&uid===PTL.editor.units.getCurrent().id){if($("#translator-comment").length){$(data.timeline).hide().insertAfter("#translator-comment").slideDown(1000,'easeOutQuad');}else{$(data.timeline).hide().prependTo("#extras-container").slideDown(1000,'easeOutQuad');}
PTL.common.updateRelativeDates();$('.timeline-field-body').filter(':not([dir])').bidi();$("#js-show-timeline").hide();$("#js-hide-timeline").show();}},complete:function(){node.spin(false);},error:PTL.editor.error});},hideTimeline:function(e){$("#js-hide-timeline").hide();$("#timeline-results").slideUp(1000,'easeOutQuad');$("#js-show-timeline").show();},filterTMResults:function(results){var source=$("[id^=id_source_f_]").first().val(),filtered=[],quality;for(var i=0;i<results.length&&i<3;i++){results[i].source=this.doDiff(source,results[i].source);results[i].target=PTL.utils.fancyHl(results[i].target);quality=Math.round(results[i].quality);results[i].qTitle=interpolate(gettext('%s% match'),[quality]);filtered.push(results[i]);}
return filtered;},appendTMResults:function(uid,data,store){if(uid==PTL.editor.units.getCurrent().id&&data.length){var firstResult=true,container="#extras-container";if($("#tm-results").length>0){firstResult=false;container="#tm-results";}
var filtered=PTL.editor.filterTMResults(data),name=gettext("Similar translations"),tm=PTL.editor.tmpl.tm({store:store.toJSON(),suggs:filtered,name:name,firstResult:firstResult});$(tm).hide().appendTo(container).slideDown(1000,'easeOutQuad');}},getRemoteTMUnits:function(){var unit=this.units.getCurrent(),store=unit.get('store'),src=store.get('source_lang'),tgt=store.get('target_lang'),sText=unit.get('source')[0],pStyle=store.get('project_style'),tmUrl=this.settings.tmUrl+src+"/"+tgt+"/unit/?source="+encodeURIComponent(sText)+"&jsoncallback=?";if(!sText.length){return;}
if(pStyle.length&&pStyle!="standard"){tmUrl+='&style='+pStyle;}
if(this.tmRemoteReq!=null){this.tmRemoteReq.abort();}
this.tmRemoteReq=$.jsonp({url:tmUrl,callback:'_jsonp'+PTL.editor.units.getCurrent().id,dataType:'jsonp',cache:true,success:function(data){var uid=this.callback.slice(6);PTL.editor.appendTMResults(uid,data,store);},error:PTL.editor.error});},getTMUnits:function(){this.getRemoteTMUnits();},rejectSuggestion:function(e){e.stopPropagation();var suggId=$(this).data("sugg-id"),element=$("#suggestion-"+suggId);uid=$('.translate-container #id_id').val(),url=l(['/xhr/units/',uid,'/suggestions/',suggId,'/reject/'].join(''));$.post(url,{'reject':1},function(data){element.fadeOut(200,function(){$(this).remove();if(!$("#suggestions div[id^=suggestion]").length){PTL.editor.gotoNext();}});},"json");},acceptSuggestion:function(e){e.stopPropagation();var suggId=$(this).data("sugg-id"),element=$("#suggestion-"+suggId),unit=PTL.editor.units.getCurrent(),url=l(['/xhr/units/',unit.id,'/suggestions/',suggId,'/accept/'].join('')),translations;$.post(url,{'accept':1},function(data){$.each(data.newtargets,function(i,target){$("#id_target_f_"+i).val(target).focus();});$.each(data.newdiffs,function(suggId,sugg){$.each(sugg,function(i,target){$("#suggdiff-"+suggId+"-"+i).html(target);});});translations=$('.js-translation-area').map(function(i,el){return $(el).val();}).get();unit.setTranslation(translations);unit.set('isfuzzy',false);element.fadeOut(200,function(){$(this).remove();if(!$("#suggestions div[id^=suggestion]").length){PTL.editor.gotoNext();}});},"json");},toggleCheck:function(){var check=$(this).parent(),checkId=$(this).data("check-id"),uid=$('.translate-container #id_id').val(),url=l(['/xhr/units/',uid,'/checks/',checkId,'/toggle/'].join('')),falsePositive=!check.hasClass('false-positive'),post={},error;if(falsePositive){post.mute=1;}
$.post(url,post,function(data){check.toggleClass('false-positive',falsePositive);error=$('#translate-checks-block .check').not('.false-positive').size()>0;$('.translate-container').toggleClass('error',error);},"json");},isSupportedSource:function(pairs,source){for(var i in pairs){if(source==pairs[i].source){return true;}}
return false;},isSupportedTarget:function(pairs,target){for(var i in pairs){if(target==pairs[i].target){return true;}}
return false;},isSupportedPair:function(pairs,source,target){for(var i in pairs){if(source==pairs[i].source&&target==pairs[i].target){return true;}}
return false;},addMTButton:function(container,aClass,tooltip){var btn='<a class="translate-mt '+aClass+'">';btn+='<i class="icon-'+aClass+'" title="'+tooltip+'"><i/></a>';$(container).first().prepend(btn);},addMTButtons:function(provider){if(this.isSupportedTarget(provider.pairs,PTL.editor.settings.targetLang)){var that=this,$sources=$(".translate-toolbar"),ok;$sources.each(function(){var source=that.normalizeCode($(this).parents('.source-language').find('.translation-text').attr("lang"));if(provider.validatePairs){ok=that.isSupportedPair(provider.pairs,source,PTL.editor.settings.targetLang);}else{ok=that.isSupportedSource(provider.pairs,source);}
if(ok){that.addMTButton($(this).find('.js-toolbar-buttons'),provider.buttonClassName,provider.hint+' ('+source.toUpperCase()+'&rarr;'+PTL.editor.settings.targetLang.toUpperCase()+')');}});}},normalizeCode:function(locale){if(locale){var clean=locale.replace('_','-')
var atIndex=locale.indexOf('@');if(atIndex!==-1){clean=clean.slice(0,atIndex);}
return clean;}
return locale;},collectArguments:function(s){this.argSubs[this.argPos]=s;return"["+(this.argPos++)+"]";},translate:function(linkObject,providerCallback){var that=this,$areas=$('.js-translation-area'),$sources=$(linkObject).parents('.source-language').find('.translation-text'),langFrom=PTL.editor.normalizeCode($sources[0].lang),langTo=PTL.editor.normalizeCode($areas[0].lang);var htmlPat=/<[\/]?\w+.*?>/g,cPrintfPat=/%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g,csharpStrPat=/{\d+(,\d+)?(:[a-zA-Z ]+)?}/g,percentNumberPat=/%\d+/g,pos=0;$sources.each(function(j){that.argSubs=[];that.argPos=0;var sourceText=$(this).text().replace(htmlPat,that.collectArguments.bind(that)).replace(cPrintfPat,that.collectArguments.bind(that)).replace(csharpStrPat,that.collectArguments.bind(that)).replace(percentNumberPat,that.collectArguments.bind(that));providerCallback(sourceText,langFrom,langTo,function(opts){var translation=opts.translation,msg=opts.msg,$area=$areas.eq(j),i,value;if(translation===undefined&&msg){PTL.editor.displayError(msg);return;}
for(i=0;i<that.argSubs.length;i++){if(sourceText.match(new RegExp("\\["+i+"\\][^\\s]"))){translation=translation.replace(new RegExp("\\["+i+"\\]\\s+"),"["+i+"]");}
if(sourceText.match(new RegExp("[^\\s]\\["+i+"\\]"))){translation=translation.replace(new RegExp("\\s+\\["+i+"\\]"),"["+i+"]");}}
for(i=0;i<that.argSubs.length;i++){value=that.argSubs[i].replace(/\&/g,'&amp;').replace(/\</g,'&lt;').replace(/\>/g,'&gt;');translation=translation.replace("["+i+"]",value);}
$area.val($('<div />').html(translation).text());});});$areas.eq(0).trigger('input').focus();PTL.editor.goFuzzy();return false;},addLookupButton:function(container,aClass,tooltip){$(container).first().prepend(['<a class="translate-lookup iframe ',aClass,'"><i class="icon-',aClass,'" title="',tooltip,'"></i></a>'].join(''));},addLookupButtons:function(provider){var _this=this;var sources=$(".translate-toolbar");$(sources).each(function(){var source=_this.normalizeCode($(this).parent().parent().find('.translation-text').attr("lang"));_this.addLookupButton(this,provider.buttonClassName,[provider.hint,' (',source.toUpperCase(),')'].join(''));});},lookup:function(linkObject,providerCallback){var areas=$("[id^=id_target_f_]");var sources=$(linkObject).parent().parent().parent().find('.translation-text');var langFrom=PTL.editor.normalizeCode(sources.eq(0).attr("lang"));var langTo=PTL.editor.normalizeCode(areas.eq(0).attr("lang"));var lookupText=PTL.editor.getSelectedText().toString();if(!lookupText){lookupText=sources.eq(0).text();}
var url=providerCallback(lookupText,langFrom,langTo);$.magnificPopup.open({items:{src:url,type:'iframe'},});linkObject.href=url;return false;}};}(jQuery));