(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.iframeTimer={_appState:undefined,_init:function(){var current_hash=locationWrapper.get();self._appState=current_hash;iframeWrapper.init().put(current_hash);self.callback(current_hash);setInterval(self.check,100);},check:function(){var iframe_hash=iframeWrapper.get(),location_hash=locationWrapper.get();if(location_hash!=iframe_hash){if(location_hash==self._appState){self._appState=iframe_hash;locationWrapper.put(iframe_hash);self.callback(iframe_hash);}else{self._appState=location_hash;iframeWrapper.put(location_hash);self.callback(location_hash);}}},load:function(hash){if(hash!=self._appState){locationWrapper.put(hash);iframeWrapper.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($.browser.msie&&($.browser.version<8||document.documentMode<8)){self.type='iframeTimer';}else 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){var hCheck=!($.browser.msie||$.browser.opera);function ResizeTextarea(e){e=e.target||e;var vlen=e.value.length,ewidth=e.offsetWidth;if(vlen!=e.valLength||ewidth!=e.boxWidth){if(hCheck&&(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 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(){var fieldSelection={getSelection:function(){var e=this.jquery?this[0]:this;return(('selectionStart'in e&&function(){var l=e.selectionEnd-e.selectionStart;return{start:e.selectionStart,end:e.selectionEnd,length:l,text:e.value.substr(e.selectionStart,l)};})||(document.selection&&function(){e.focus();var r=document.selection.createRange();if(r==null){return{start:0,end:e.value.length,length:0}}
var re=e.createTextRange();var rc=re.duplicate();re.moveToBookmark(r.getBookmark());rc.setEndPoint('EndToStart',re);return{start:rc.text.length,end:rc.text.length+r.text.length,length:r.text.length,text:r.text};})||function(){return{start:0,end:e.value.length,length:0};})();},replaceSelection:function(){var e=this.jquery?this[0]:this;var text=arguments[0]||'';return(('selectionStart'in e&&function(){e.value=e.value.substr(0,e.selectionStart)+text+e.value.substr(e.selectionEnd,e.value.length);return this;})||(document.selection&&function(){e.focus();document.selection.createRange().text=text;return this;})||function(){e.value+=text;return this;})();}};jQuery.each(fieldSelection,function(i){jQuery.fn[i]=this;});})();﻿(function($,len,createRange,duplicate){$.fn.caret=function(options,opt2){var start,end,t=this[0],browser=$.browser.msie;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"){if(browser){var selRange=this[0].createTextRange();selRange.collapse(true);selRange.moveStart('character',start);selRange.moveEnd('character',end-start);selRange.select();}else{this[0].selectionStart=start;this[0].selectionEnd=end;}
this[0].focus();return this}else{if(browser){var selection=document.selection;if(this[0].tagName.toLowerCase()!="textarea"){var val=this.val(),range=selection[createRange]()[duplicate]();range.moveEnd("character",val[len]);var s=(range.text==""?val[len]:val.lastIndexOf(range.text));range=selection[createRange]()[duplicate]();range.moveStart("character",-val[len]);var e=range.text[len];}else{var range=selection[createRange](),stored_range=range[duplicate]();stored_range.moveToElementText(this[0]);stored_range.setEndPoint('EndToEnd',range);var s=stored_range.text[len]-range.text[len],e=s+range.text[len]}}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));if(!this.JSON){this.JSON={};}
(function(){"use strict";function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}());(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.4.4';var each=_.each=_.forEach=function(obj,iterator,context){if(obj==null)return;if(nativeForEach&&obj.forEach===nativeForEach){obj.forEach(iterator,context);}else if(obj.length===+obj.length){for(var i=0,l=obj.length;i<l;i++){if(iterator.call(context,obj[i],i,obj)===breaker)return;}}else{for(var key in obj){if(_.has(obj,key)){if(iterator.call(context,obj[key],key,obj)===breaker)return;}}}};_.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[results.length]=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,iterator,context){var result;any(obj,function(value,index,list){if(iterator.call(context,value,index,list)){result=value;return true;}});return result;};_.filter=_.select=function(obj,iterator,context){var results=[];if(obj==null)return results;if(nativeFilter&&obj.filter===nativeFilter)return obj.filter(iterator,context);each(obj,function(value,index,list){if(iterator.call(context,value,index,list))results[results.length]=value;});return results;};_.reject=function(obj,iterator,context){return _.filter(obj,function(value,index,list){return!iterator.call(context,value,index,list);},context);};_.every=_.all=function(obj,iterator,context){iterator||(iterator=_.identity);var result=true;if(obj==null)return result;if(nativeEvery&&obj.every===nativeEvery)return obj.every(iterator,context);each(obj,function(value,index,list){if(!(result=result&&iterator.call(context,value,index,list)))return breaker;});return!!result;};var any=_.some=_.any=function(obj,iterator,context){iterator||(iterator=_.identity);var result=false;if(obj==null)return result;if(nativeSome&&obj.some===nativeSome)return obj.some(iterator,context);each(obj,function(value,index,list){if(result||(result=iterator.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,function(value){return value[key];});};_.where=function(obj,attrs,first){if(_.isEmpty(attrs))return first?null:[];return _[first?'find':'filter'](obj,function(value){for(var key in attrs){if(attrs[key]!==value[key])return false;}
return true;});};_.findWhere=function(obj,attrs){return _.where(obj,attrs,true);};_.max=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.max.apply(Math,obj);}
if(!iterator&&_.isEmpty(obj))return-Infinity;var result={computed:-Infinity,value:-Infinity};each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;computed>=result.computed&&(result={value:value,computed:computed});});return result.value;};_.min=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.min.apply(Math,obj);}
if(!iterator&&_.isEmpty(obj))return Infinity;var result={computed:Infinity,value:Infinity};each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;computed<result.computed&&(result={value:value,computed:computed});});return result.value;};_.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;};var lookupIterator=function(value){return _.isFunction(value)?value:function(obj){return obj[value];};};_.sortBy=function(obj,value,context){var iterator=lookupIterator(value);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?-1:1;}),'value');};var group=function(obj,value,context,behavior){var result={};var iterator=lookupIterator(value||_.identity);each(obj,function(value,index){var key=iterator.call(context,value,index,obj);behavior(result,key,value);});return result;};_.groupBy=function(obj,value,context){return group(obj,value,context,function(result,key,value){(_.has(result,key)?result[key]:(result[key]=[])).push(value);});};_.countBy=function(obj,value,context){return group(obj,value,context,function(result,key){if(!_.has(result,key))result[key]=0;result[key]++;});};_.sortedIndex=function(array,obj,iterator,context){iterator=iterator==null?_.identity: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;return(n!=null)&&!guard?slice.call(array,0,n):array[0];};_.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 slice.call(array,Math.max(array.length-n,0));}else{return array[array.length-1];}};_.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){each(input,function(value){if(_.isArray(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));};_.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(concat.apply(ArrayProto,arguments));};_.intersection=function(array){var rest=slice.call(arguments,1);return _.filter(_.uniq(array),function(item){return _.every(rest,function(other){return _.indexOf(other,item)>=0;});});};_.difference=function(array){var rest=concat.apply(ArrayProto,slice.call(arguments,1));return _.filter(array,function(value){return!_.contains(rest,value);});};_.zip=function(){var args=slice.call(arguments);var length=_.max(_.pluck(args,'length'));var results=new Array(length);for(var i=0;i<length;i++){results[i]=_.pluck(args,""+i);}
return results;};_.object=function(list,values){if(list==null)return{};var result={};for(var i=0,l=list.length;i<l;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,l=array.length;if(isSorted){if(typeof isSorted=='number'){i=(isSorted<0?Math.max(0,l+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<l;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 len=Math.max(Math.ceil((stop-start)/step),0);var idx=0;var range=new Array(len);while(idx<len){range[idx++]=start;start+=step;}
return range;};_.bind=function(func,context){if(func.bind===nativeBind&&nativeBind)return nativeBind.apply(func,slice.call(arguments,1));var args=slice.call(arguments,2);return function(){return func.apply(context,args.concat(slice.call(arguments)));};};_.partial=function(func){var args=slice.call(arguments,1);return function(){return func.apply(this,args.concat(slice.call(arguments)));};};_.bindAll=function(obj){var funcs=slice.call(arguments,1);if(funcs.length===0)funcs=_.functions(obj);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){var context,args,timeout,result;var previous=0;var later=function(){previous=new Date;timeout=null;result=func.apply(context,args);};return function(){var now=new Date;var remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0){clearTimeout(timeout);timeout=null;previous=now;result=func.apply(context,args);}else if(!timeout){timeout=setTimeout(later,remaining);}
return result;};};_.debounce=function(func,wait,immediate){var timeout,result;return function(){var context=this,args=arguments;var later=function(){timeout=null;if(!immediate)result=func.apply(context,args);};var callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow)result=func.apply(context,args);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 function(){var args=[func];push.apply(args,arguments);return wrapper.apply(this,args);};};_.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){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments);}};};_.keys=nativeKeys||function(obj){if(obj!==Object(obj))throw new TypeError('Invalid object');var keys=[];for(var key in obj)if(_.has(obj,key))keys[keys.length]=key;return keys;};_.values=function(obj){var values=[];for(var key in obj)if(_.has(obj,key))values.push(obj[key]);return values;};_.pairs=function(obj){var pairs=[];for(var key in obj)if(_.has(obj,key))pairs.push([key,obj[key]]);return pairs;};_.invert=function(obj){var result={};for(var key in obj)if(_.has(obj,key))result[obj[key]]=key;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]==null)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;}
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{var aCtor=a.constructor,bCtor=b.constructor;if(aCtor!==bCtor&&!(_.isFunction(aCtor)&&(aCtor instanceof aCtor)&&_.isFunction(bCtor)&&(bCtor instanceof bCtor))){return false;}
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;};_.times=function(n,iterator,context){var accum=Array(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));};var entityMap={escape:{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#x27;','/':'&#x2F;'}};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 null;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;}});}).call(this);(function(){var root=this;var previousBackbone=root.Backbone;var array=[];var push=array.push;var slice=array.slice;var splice=array.splice;var Backbone;if(typeof exports!=='undefined'){Backbone=exports;}else{Backbone=root.Backbone={};}
Backbone.VERSION='1.0.0';var _=root._;if(!_&&(typeof require!=='undefined'))_=require('underscore');Backbone.$=root.jQuery||root.Zepto||root.ender||root.$;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={};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 listeners=this._listeners;if(!listeners)return this;var deleteListener=!name&&!callback;if(typeof name==='object')callback=this;if(obj)(listeners={})[obj._listenerId]=obj;for(var id in listeners){listeners[id].off(name,callback,this);if(deleteListener)delete this._listeners[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);}};var listenMethods={listenTo:'on',listenToOnce:'once'};_.each(listenMethods,function(implementation,method){Events[method]=function(obj,name,callback){var listeners=this._listeners||(this._listeners={});var id=obj._listenerId||(obj._listenerId=_.uniqueId('l'));listeners[id]=obj;if(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 defaults;var attrs=attributes||{};options||(options={});this.cid=_.uniqueId('c');this.attributes={};_.extend(this,_.pick(options,modelOptions));if(options.parse)attrs=this.parse(attrs,options)||{};if(defaults=_.result(this,'defaults')){attrs=_.defaults({},attrs,defaults);}
this.set(attrs,options);this.changed={};this.initialize.apply(this,arguments);};var modelOptions=['url','urlRoot','collection'];_.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=true;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){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;}
if(attrs&&(!options||!options.wait)&&!this.set(attrs,options))return false;options=_.extend({validate:true},options);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+(base.charAt(base.length-1)==='/'?'':'/')+encodeURIComponent(this.id);},parse:function(resp,options){return resp;},clone:function(){return new this.constructor(this.attributes);},isNew:function(){return this.id==null;},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.url)this.url=options.url;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,merge:false,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,_.defaults(options||{},addOptions));},remove:function(models,options){models=_.isArray(models)?models.slice():[models];options||(options={});var i,l,index,model;for(i=0,l=models.length;i<l;i++){model=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);}
return this;},set:function(models,options){options=_.defaults(options||{},setOptions);if(options.parse)models=this.parse(models,options);if(!_.isArray(models))models=models?[models]:[];var i,l,model,attrs,existing,sort;var at=options.at;var sortable=this.comparator&&(at==null)&&options.sort!==false;var sortAttr=_.isString(this.comparator)?this.comparator:null;var toAdd=[],toRemove=[],modelMap={};for(i=0,l=models.length;i<l;i++){if(!(model=this._prepareModel(models[i],options)))continue;if(existing=this.get(model)){if(options.remove)modelMap[existing.cid]=true;if(options.merge){existing.set(model.attributes,options);if(sortable&&!sort&&existing.hasChanged(sortAttr))sort=true;}}else if(options.add){toAdd.push(model);model.on('all',this._onModelEvent,this);this._byId[model.cid]=model;if(model.id!=null)this._byId[model.id]=model;}}
if(options.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){if(sortable)sort=true;this.length+=toAdd.length;if(at!=null){splice.apply(this.models,[at,0].concat(toAdd));}else{push.apply(this.models,toAdd);}}
if(sort)this.sort({silent:true});if(options.silent)return this;for(i=0,l=toAdd.length;i<l;i++){(model=toAdd[i]).trigger('add',model,this,options);}
if(sort)this.trigger('sort',this,options);return this;},reset:function(models,options){options||(options={});for(var i=0,l=this.models.length;i<l;i++){this._removeReference(this.models[i]);}
options.previousModels=this.models;this._reset();this.add(models,_.extend({silent:true},options));if(!options.silent)this.trigger('reset',this,options);return this;},push:function(model,options){model=this._prepareModel(model,options);this.add(model,_.extend({at:this.length},options));return model;},pop:function(options){var model=this.at(this.length-1);this.remove(model,options);return model;},unshift:function(model,options){model=this._prepareModel(model,options);this.add(model,_.extend({at:0},options));return model;},shift:function(options){var model=this.at(0);this.remove(model,options);return model;},slice:function(begin,end){return this.models.slice(begin,end);},get:function(obj){if(obj==null)return void 0;return this._byId[obj.id!=null?obj.id:obj.cid||obj];},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;},sortedIndex:function(model,value,context){value||(value=this.comparator);var iterator=_.isFunction(value)?value:function(model){return model.get(value);};return _.sortedIndex(this.models,model,iterator,context);},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(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){if(!attrs.collection)attrs.collection=this;return attrs;}
options||(options={});options.collection=this;var model=new this.model(attrs,options);if(!model._validate(attrs,options)){this.trigger('invalid',this,attrs,options);return false;}
return model;},_removeReference:function(model){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','indexOf','shuffle','lastIndexOf','isEmpty','chain'];_.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'];_.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');this._configure(options||{});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;},_configure:function(options){if(this.options)options=_.extend({},_.result(this,'options'),options);_.extend(this,_.pick(options,viewOptions));this.options=options;},_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'&&window.ActiveXObject&&!(window.external&&window.external.msActiveXFilteringEnabled)){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 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);callback&&callback.apply(router,args);router.trigger.apply(router,['route:'+name].concat(args));router.trigger('route',name,args);Backbone.history.trigger('route',router,name,args);});return this;},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+'$');},_extractParameters:function(route,fragment){var params=route.exec(fragment).slice(1);return _.map(params,function(param){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=/\/$/;History.started=false;_.extend(History.prototype,Events,{interval:50,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=this.location.pathname;var root=this.root.replace(trailingSlash,'');if(!fragment.indexOf(root))fragment=fragment.substr(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){this.iframe=Backbone.$('<iframe src="javascript:0" tabindex="-1" />').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;var atRoot=loc.pathname.replace(/[^\/]$/,'$&/')===this.root;if(this._wantsHashChange&&this._wantsPushState&&!this._hasPushState&&!atRoot){this.fragment=this.getFragment(null,true);this.location.replace(this.root+this.location.search+'#'+this.fragment);return true;}else if(this._wantsPushState&&this._hasPushState&&atRoot&&loc.hash){this.fragment=this.getHash().replace(routeStripper,'');this.history.replaceState({},document.title,this.root+this.fragment+loc.search);}
if(!this.options.silent)return this.loadUrl();},stop:function(){Backbone.$(window).off('popstate',this.checkUrl).off('hashchange',this.checkUrl);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()||this.loadUrl(this.getHash());},loadUrl:function(fragmentOverride){var fragment=this.fragment=this.getFragment(fragmentOverride);var matched=_.any(this.handlers,function(handler){if(handler.route.test(fragment)){handler.callback(fragment);return true;}});return matched;},navigate:function(fragment,options){if(!History.started)return false;if(!options||options===true)options={trigger:options};fragment=this.getFragment(fragment||'');if(this.fragment===fragment)return;this.fragment=fragment;var url=this.root+fragment;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)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);};};}).call(this);(function(undefined){"use strict";var _,Backbone,exports;if(typeof window==='undefined'){_=require('underscore');Backbone=require('backbone');exports=module.exports=Backbone;}
else{_=window._;Backbone=window.Backbone;exports=window;}
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(){while(this._queue&&this._queue.length){this._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 _.find(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);},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=_.findWhere(this._collections,{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);var 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);this.listenTo(model,'destroy',this.unregister,this);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);coll._onModelEvent('change:'+model.idAttribute,model,coll);model.trigger('relational:change:id',model,coll);},unregister:function(model){this.stopListening(model,'destroy',this.unregister);var coll=this.getCollection(model);coll&&coll.remove(model);},reset:function(){this.stopListening();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(_.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){this.instance.unset(this.keySource,{silent:true});}
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.acquire();this.instance.attributes[this.key]=related;this.instance.release();},_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(this.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(_.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,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();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;Backbone.Relational.eventQueue.add(function(){if(!dit._isInitialized){return;}
var changed=true;if(eventName==='change'){changed=dit.hasChanged();}
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];}}}
changed&&Backbone.Model.prototype.trigger.apply(dit,args);});}
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(options){if(this._isInitialized&&!this.isLocked()){_.each(this._relations,function(rel){var val=this.attributes[rel.keySource]||this.attributes[rel.key];if(rel.related!==val){this.trigger('relational:change:'+rel.key,this,val,options||{});}},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 setUrl,requests=[],rel=this.getRelation(key),idsToFetch=rel&&(rel.keyIds||((rel.keyId||rel.keyId===0)?[rel.keyId]:[]));if(refresh){var 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=Backbone.Relational.store.find(rel.relatedModel,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(!(model instanceof Backbone.Model)){throw new Error('Attribute must be an instanceof Backbone.Model. Is: '+model+', currentSplit: '+split);}
return Backbone.Model.prototype.get.call(model,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();Backbone.Relational.store.register(this);this.initializeRelations(options);}
else if(newId&&newId!==id){Backbone.Relational.store.update(this);}
if(attributes){this.updateRelations(options);}}
finally{Backbone.Relational.eventQueue.unblock();}
return result;},unset:function(attribute,options){Backbone.Relational.eventQueue.block();var result=Backbone.Model.prototype.unset.apply(this,arguments);this.updateRelations(options);Backbone.Relational.eventQueue.unblock();return result;},clear:function(options){Backbone.Relational.eventQueue.block();var result=Backbone.Model.prototype.clear.apply(this,arguments);this.updateRelations(options);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;}}}
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){var model=this;this.initializeModelHierarchy();if(this._subModels&&this.prototype.subModelTypeAttribute in attributes){var subModelTypeAttribute=attributes[this.prototype.subModelTypeAttribute];var subModelType=this._subModels[subModelTypeAttribute];if(subModelType){model=subModelType;}}
return new model(attributes,options);},initializeModelHierarchy:function(){if(_.isUndefined(this._superModel)||_.isNull(this._superModel)){Backbone.Relational.store.setupSuperModel(this);if(this._superModel&&this._superModel.prototype.relations){var inheritedRelations=_.select(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;}}
if(this.prototype.subModelTypes&&_.keys(this.prototype.subModelTypes).length!==_.keys(this._subModels).length){_.each(this.prototype.subModelTypes||[],function(subModelTypeName){var subModelType=Backbone.Relational.store.getObjectByName(subModelTypeName);subModelType&&subModelType.initializeModelHierarchy();});}},findOrCreate:function(attributes,options){options||(options={});var parsedAttributes=(_.isObject(attributes)&&options.parse&&this.prototype.parse)?this.prototype.parse(attributes):attributes;var model=Backbone.Relational.store.find(this,parsedAttributes);if(_.isObject(attributes)){if(model&&options.merge!==false){delete options.collection;model.set(parsedAttributes,options);}
else if(!model&&options.create!==false){model=this.build(attributes,options);}}
return model;}});_.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={});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.isNew()&&!model._validate(attrs,options)){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);}
if(!_.isArray(models)){models=models?[models]:[];}
var newModels=[],toAdd=[];_.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);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 this;};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);}
models=_.isArray(models)?models.slice():[models];options||(options={});var toRemove=[];_.each(models,function(model){model=this.get(model)||this.get(model.cid);model&&toRemove.push(model);},this);if(toRemove.length){remove.call(this,toRemove,options);_.each(toRemove,function(model){this.trigger('relational:remove',model,this,options);},this);}
return this;};var reset=Backbone.Collection.prototype.__reset=Backbone.Collection.prototype.reset;Backbone.Collection.prototype.reset=function(models,options){options=_.extend({merge:true},options);reset.call(this,models,options);if(this.model.prototype instanceof Backbone.RelationalModel){this.trigger('relational:reset',this,options);}
return this;};var sort=Backbone.Collection.prototype.__sort=Backbone.Collection.prototype.sort;Backbone.Collection.prototype.sort=function(options){sort.call(this,options);if(this.model.prototype instanceof Backbone.RelationalModel){this.trigger('relational:reset',this,options);}
return this;};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'){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.UnitCollection=Backbone.Collection.extend({model:models.Unit,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));},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.UnitCollection;this.pager={current:1};this.pagesGot={};this.filter='all';this.checks=[];this.goal=null;this.user=null;this.ctxGap=0;this.ctxQty=parseInt($.cookie('ctxQty'),10)||1;this.ctxStep=1;this.keepState=false;this.preventNavigation=false;this.isLoading=true;this.showActivity();this.searchFields=[];this.searchOptions=[];this.cpRE=/^(<[^>]+>|\[n\|t]|\W$^\n)*(\b|$)/gm;this.timelineReq=null;this.tmReq=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('submit','#captcha',function(e){e.preventDefault();var fn=$(this).data('js-action');PTL.editor[fn](e);$.magnificPopup.close();});$(document).on('keyup blur','textarea.translation',function(){if(!PTL.editor.keepState&&$(this).prop('defaultValue')!==$(this).val()){PTL.editor.ungoFuzzy();}});$(document).on('click','input.fuzzycheck',function(){if(PTL.editor.isFuzzy()){PTL.editor.doFuzzyArea();}else{PTL.editor.undoFuzzyArea();}});$(document).on('click','.switch-suggest-mode a',function(){PTL.editor.toggleSuggestMode();return false;});$(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($('.translation-text',$(this).parent().parent().parent()));});$(document).on('click','div.suggestion',function(){if(PTL.editor.getSelectedText()){return;}
if($('#id_target_f_0').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, #js-nav-next',this.gotoPrevNext);$(document).on('click','.js-suggestion-reject',this.rejectSuggestion);$(document).on('click','.js-suggestion-accept',this.acceptSuggestion);$(document).on('click','.js-vote-clear',this.clearVote);$(document).on('click','.js-vote-up',this.voteUp);$(document).on('click','#js-show-timeline',this.showTimeline);$(document).on('click','#js-hide-timeline',this.hideTimeline);$(document).on('click','#translate-checks-block .js-reject-check',this.rejectCheck);$(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','#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+space',function(e){if(e&&e.preventDefault){e.preventDefault();}
PTL.editor.keepState=true;if(PTL.editor.isFuzzy()){PTL.editor.ungoFuzzy();}else{PTL.editor.goFuzzy();}});shortcut.add('ctrl+shift+space',function(){PTL.editor.toggleSuggestMode();});shortcut.add('ctrl+up',function(){$('#js-nav-prev').trigger('click');});shortcut.add('ctrl+,',function(){$('#js-nav-prev').trigger('click');});shortcut.add('ctrl+down',function(){$('#js-nav-next').trigger('click');});shortcut.add('ctrl+.',function(){$('#js-nav-next').trigger('click');});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',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',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),withUid=0,tmpParamValue;if(params['unit']){tmpParamValue=parseInt(params['unit'],10);if(tmpParamValue&&!isNaN(tmpParamValue)){var current=PTL.editor.units.getCurrent(),newUnit=PTL.editor.units.get(tmpParamValue);if(newUnit&&newUnit!==current){PTL.editor.units.setCurrent(newUnit);PTL.editor.displayEditUnit();return;}else{withUid=tmpParamValue;}}}
PTL.editor.pager.current=1;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=[];}}
PTL.editor.goal=null;if('goal'in params){PTL.editor.goal=params['goal'];}
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").length){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.getViewUnits({pager:true,withUid:withUid});if(PTL.editor.hasResults){PTL.editor.fetchPages({async:false});if(PTL.editor.units.getCurrent()===undefined){PTL.editor.units.setFirstAsCurrent();}
PTL.editor.displayEditUnit();}},{'unescape':true});},1);},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();if($(".focusthis").get(0)){$(".focusthis").get(0).focus();}
PTL.editor.hlSearch();if(PTL.editor.settings.tmUrl!=''){PTL.editor.getTMUnits();}
$("table.translate-table").trigger("mt_ready");$("table.translate-table").trigger("lookup_ready");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);},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);start=text.length;}else{start=element.caret().start+text.length;element.val(element.caret().replace(text));}
element.caret(start,start);},copyOriginal:function(sources){var cleanSources=[];$.each(sources,function(i){cleanSources[i]=$(this).text();});var targets=$("[id^=id_target_f_]");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);}
active=$(targets).get(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;},doFuzzyArea:function(){$("tr.edit-row").addClass("fuzzy-unit");},undoFuzzyArea:function(){$("tr.edit-row").removeClass("fuzzy-unit");},doFuzzyBox:function(){$("input.fuzzycheck").attr("checked","checked");},undoFuzzyBox:function(){$("input.fuzzycheck").removeAttr("checked");},goFuzzy:function(){if(!this.isFuzzy()){this.keepState=true;this.doFuzzyArea();this.doFuzzyBox();}},ungoFuzzy:function(){if(this.isFuzzy()){this.keepState=true;this.undoFuzzyArea();this.undoFuzzyBox();}},isFuzzy:function(){return $("input.fuzzycheck").attr("checked");},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(){if(this.isSuggestMode()){this.undoSuggestMode();}else{this.doSuggestMode();}},updateExportLink:function(){var unit=this.units.getCurrent(),store=unit.get('store'),urlStr=['',store.get('target_lang'),store.get('project_code'),'export-view',this.resourcePath].join('/'),urlStr=[urlStr,$.param(this.getReqData())].join('?'),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();$("#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==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;}
if(this.goal){reqData.goal=this.goal;}
return reqData;},getViewUnits:function(opts){var extraData,reqData,defaults={async:false,page:this.pager.current,pager:false,withUid:0},viewUrl=l('/xhr/units/');opts=$.extend({},defaults,opts);extraData={page:opts.page,path:this.settings.pootlePath};if(opts.pager){extraData.pager=opts.pager;}
if(opts.withUid>0){extraData.uid=opts.withUid;delete extraData.page}
reqData=$.extend(extraData,this.getReqData());$.ajax({url:viewUrl,data:reqData,dataType:'json',async:opts.async,success:function(data){if(opts.pager&&data.pager){PTL.editor.hasResults=true;PTL.editor.pagesGot={};PTL.editor.units.reset();PTL.editor.pager=data.pager;}
if(data.unit_groups.length){if(data.pager){var page=data.pager.current;}else{var page=opts.page;}
PTL.editor.pagesGot[page]=[];var pages=$.map(PTL.editor.pagesGot,function(value,key){return parseInt(key,10);}).sort(PTL.utils.numberCmp),pageIndex=pages.indexOf(page),at=PTL.editor.pager.perPage*pageIndex;var urlStr=[PTL.editor.settings.ctxPath,'translate/',PTL.editor.settings.resourcePath,'#unit=',].join('');var i,j,unit,unitGroup;for(i=0;i<data.unit_groups.length;i++){unitGroup=data.unit_groups[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,{at:at,remove:false});at+=group.units.length;for(j=0;j<group.units.length;j++){unit=PTL.editor.units.get(group.units[j].id);unit.set('url',l(urlStr+unit.id));PTL.editor.pagesGot[page].push(unit.id);}});}
if(opts.withUid){PTL.editor.units.setCurrent(opts.withUid);}else if(data.pager){var firstInPage=PTL.editor.pagesGot[data.pager.current][0];PTL.editor.units.setCurrent(firstInPage);}
PTL.editor.hasResults=true;}else{PTL.editor.hasResults=false;$("table.translate-table").trigger("noResults");}},error:PTL.editor.error});},buildRow:function(unit,cls){return['<tr id="row',unit.id,'" class="view-row ',cls,'">',this.tmpl.vUnit({unit:unit.toJSON()}),'</tr>'].join('');},buildRows:function(){var unitGroups=this.getUnitGroups(),groupSize=_.size(unitGroups),currentUnit=this.units.getCurrent(),cls="even",even=true,rows=[],i,unit;_.each(unitGroups,function(unitGroup){if(groupSize!==1){rows.push('<tr class="delimiter-row"><td colspan="2"></td></tr>');}
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,cls));}
cls=even?"odd":"even";even=!even;}},this);return rows.join('');},buildCtxRows:function(units,extraCls){var i,unit,currentUnit=this.units.getCurrent(),cls="even",even=true,rows="",urlStr=[PTL.editor.settings.ctxPath,'translate/',PTL.editor.settings.resourcePath,'#unit=',].join('');for(i=0;i<units.length;i++){unit=units[i];unit['url']=l(urlStr+unit.id);unit=$.extend({},currentUnit.toJSON(),unit);rows+='<tr id="ctx'+unit.id+'" class="ctx-row '+extraCls+' '+cls+'">';rows+=this.tmpl.vUnit({unit:unit});rows+='</tr>';cls=even?"odd":"even";even=!even;}
return rows;},getUnitGroups:function(){var limit=parseInt(((this.pager.perPage-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.hasResults){this.fetchPages();this.hideMsg();this.reDraw(this.buildRows());this.updateNavButtons();}},reDraw:function(newTbody){var tTable=$("table.translate-table"),where=$("tbody",tTable),oldRows=$("tr",where);oldRows.remove();$('.tipsy').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());},fetchPages:function(opts){var defaults={async:true,page:this.pager.current};opts=$.extend({},defaults,opts);var current=opts.page,candidates=[current,current+1,current-1],pages=[],i;for(i=0;i<candidates.length;i++){if(candidates[i]<=this.pager.numPages&&candidates[i]>0&&!(candidates[i]in this.pagesGot)){pages.push(candidates[i]);}}
for(i=0;i<pages.length;i++){this.getViewUnits({async:opts.async,page:pages[i]});}},updatePager:function(){var pager=this.pager;$("#items-count").text(pager.count);var currentUnit=PTL.editor.units.getCurrent();if(currentUnit!==undefined){var uId=currentUnit.id,uIndexInPage=PTL.editor.pagesGot[pager.current].indexOf(uId)+1,uIndex=(pager.current-1)*pager.perPage+uIndexInPage;$("#item-number").val(uIndex);}},createPager:function(uid){var newPager=this.pager;if($.inArray(uid,this.pagesGot[this.pager.current])==-1){var newPageNumber,i=this.pager.current,j=this.pager.current+1,found=false;while(!found&&(i>0||j<=this.pager.numPages)){if(i>0&&$.inArray(uid,this.pagesGot[i])!=-1){newPageNumber=i;found=true;}else if($.inArray(uid,this.pagesGot[j])!=-1){newPageNumber=j;found=true;}
i--;j++;}
if(found){newPager.current=newPageNumber;}}
return newPager;},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('')),reqData=this.getReqData(),widget='',ctx={before:[],after:[]};$.ajax({url:editUrl,async:false,data:reqData,dataType:'json',success:function(data){widget=data['editor'];PTL.editor.pager=PTL.editor.createPager(uid);PTL.editor.updatePager();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":"";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 reqData,submitUrl,translations,unit=PTL.editor.units.getCurrent(),form=$("#captcha").ifExists()||$("#translate");submitUrl=l(['/xhr/units/',unit.id].join(''));reqData=form.serializeObject();$.extend(reqData,PTL.editor.getReqData());$.ajax({url:submitUrl,type:'POST',data:reqData,dataType:'json',success:function(data){if(data.captcha){$.magnificPopup.open({items:{src:data.captcha,type:'inline'},focus:'#id_captcha_answer'});}else{translations=$("textarea[id^=id_target_f_]").map(function(i,el){return $(el).val();}).get();unit.setTranslation(translations);unit.set('isfuzzy',PTL.editor.isFuzzy());PTL.editor.gotoNext();}},error:PTL.editor.error});},suggest:function(e){e.preventDefault();var reqData,suggestUrl,uid=PTL.editor.units.getCurrent().id,form=$("#captcha").ifExists()||$("#translate");suggestUrl=l(['/xhr/units/',uid,'/suggestions/'].join(''));reqData=form.serializeObject();$.extend(reqData,PTL.editor.getReqData());$.ajax({url:suggestUrl,type:'POST',data:reqData,dataType:'json',success:function(data){if(data.captcha){$.magnificPopup.open({items:{src:data.captcha,type:'inline'},focus:'#id_captcha_answer'});}else{PTL.editor.gotoNext();}},error:PTL.editor.error});},gotoNext:function(){PTL.editor.gotoPrevNext($.Event('click',{target:'#js-nav-next'}));},gotoPrevNext:function(e){e.preventDefault();var prevNextMap={'js-nav-prev':'prev','js-nav-next':'next'},elementId=e.target.id||$(e.target)[0].id,newUnit=PTL.editor.units[prevNextMap[elementId]]();if(newUnit){var newHash=PTL.utils.updateHashPart("unit",newUnit.id);$.history.load(newHash);}else{if(elementId==='js-nav-prev'){PTL.editor.displayMsg(gettext("You reached the beginning of the list"));}else{PTL.editor.displayMsg([gettext("You reached the end of the list."),'<br /><a href="',l(PTL.editor.settings.pootlePath),'">',gettext('Return to the overview page.'),'</a>'].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.pager.count){var preceding=index-1,page=parseInt(preceding/PTL.editor.pager.perPage+1,10)||1,uIndexInPage=preceding%PTL.editor.pager.perPage,uId;if(!(page in PTL.editor.pagesGot)){PTL.editor.fetchPages({async:false,page:page});}
uId=PTL.editor.pagesGot[page][uIndexInPage];var newHash=PTL.utils.updateHashPart("unit",uId);$.history.load(newHash);}},getCheckOptions:function(){var checksUrl=l('/xhr/checks/'),reqData={path:this.settings.pootlePath,goal:this.goal},opts;$.ajax({url:checksUrl,async:false,data:reqData,dataType:'json',success:function(data){opts=data;},error:PTL.editor.error});return opts;},filterChecks:function(){if(PTL.editor.preventNavigation){return;}
var filterBy=$("option:selected",this).val();if(filterBy!="none"){var newHash="filter=checks&checks="+encodeURIComponent(filterBy);if(PTL.editor.goal){newHash+='&goal='+PTL.editor.goal;}
$.history.load(newHash);}},filterStatus:function(){var $selected=$("#filter-status option:selected"),filterBy=$selected.val(),isUserFilter=$selected.data('user');if(filterBy=="checks"){var optGroups=PTL.editor.getCheckOptions();if(optGroups.length){var dropdown=['<div id="filter-checks">','<select id="js-select2-filter-checks" ','class="select2-filter-checks" name="filter-checks">','<option selected="selected" value="none">------</option>']
$.each(optGroups,function(){dropdown.push(['<optgroup label="',this.display_name,'">'].join(''));$.each(this.checks,function(){dropdown.push(['<option value="',this.name,'">',this.display_name,' (',this.count,')</option>'].join(''));});dropdown.push('</optgroup>');});dropdown.push('</select></div>');$("#filter-status").first().after(dropdown.join(''));$("#js-select2-filter-checks").select2({width:"resolve"});}else{PTL.editor.displayMsg(gettext("No results."));$('#filter-status select').select2('val',PTL.editor.filter);}}else{$("#filter-checks").remove();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();}
if(PTL.editor.goal){newHash+='&goal='+PTL.editor.goal;}
$.history.load(newHash);}}},editCtxUI:function(opts){var defaults={hasData:false,replace:false};opts=$.extend({},defaults,opts);editCtxRowBefore=PTL.editor.tmpl.editCtx({hasData:opts.hasData,extraCls:'before'});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"]);}
if(PTL.editor.goal){newHash+='&goal='+PTL.editor.goal;}
$.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=$("#extras-container"),timelineUrl=l(['/xhr/units/',uid,'/timeline/'].join(''));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();}},beforeSend:function(){node.spin();},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;},getTMUnits: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.tmReq!=null){this.tmReq.abort();}
this.tmReq=$.jsonp({url:tmUrl,callback:'_jsonp'+PTL.editor.units.getCurrent().id,dataType:'jsonp',cache:true,success:function(data){var uid=this.callback.slice(6);if(uid==PTL.editor.units.getCurrent().id&&data.length){var filtered=PTL.editor.filterTMResults(data),name=gettext("Similar translations"),tm=PTL.editor.tmpl.tm({store:store.toJSON(),suggs:filtered,name:name});$(tm).hide().appendTo("#extras-container").slideDown(1000,'easeOutQuad');}},error:PTL.editor.error});},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=$("textarea[id^=id_target_f_]").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");},clearVote:function(e){e.stopPropagation();var element=$(this),voteId=element.data("vote-id"),url=l(['/xhr/votes/',voteId,'/clear/'].join(''));element.fadeTo(200,0.01);$.ajax({url:url,type:'POST',data:{'clear':1},dataType:'json',success:function(data){element.hide();element.siblings(".js-vote-up").fadeTo(200,1);},error:function(xhr,s){PTL.editor.error(xhr,s);element.delay(3000).fadeTo(2000,1);}});},voteUp:function(e){e.stopPropagation();var element=$(this),suggId=element.siblings("[data-sugg-id]").data("sugg-id"),url=l(['/xhr/units/',PTL.editor.units.getCurrent().id,'/suggestions/',suggId,'/votes/'].join(''));element.fadeTo(200,0.01);$.ajax({url:url,type:'POST',data:{'up':1},dataType:'json',success:function(data){element.siblings("[data-vote-id]").data("vote-id",data.voteid);element.hide();element.siblings(".js-vote-clear").fadeTo(200,1);},error:function(xhr,s){PTL.editor.error(xhr,s);element.delay(3000).fadeTo(2000,1);}});},rejectCheck:function(){var element=$(this).parent(),checkId=$(this).data("check-id"),uid=$('.translate-container #id_id').val(),url=l(['/xhr/units/',uid,'/checks/',checkId,'/reject/'].join(''));$.post(url,{'reject':1},function(data){if(element.siblings().size()==0){element=$('#translate-checks-block');}
element.fadeOut(200,function(){$(this).remove();$('.tipsy').remove();});},"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,provider.targetLang)){var _this=this;var sources=$(".translate-toolbar");$(sources).each(function(){var source=_this.normalizeCode($(this).parent().parent().find('.translation-text').attr("lang"));var ok;if(provider.validatePairs){ok=_this.isSupportedPair(provider.pairs,source,provider.targetLang);}else{ok=_this.isSupportedSource(provider.pairs,source);}
if(ok){_this.addMTButton(this,provider.buttonClassName,provider.hint+' ('+source.toUpperCase()+'&rarr;'+provider.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 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 htmlPat=/<[\/]?\w+.*?>/g;var cPrintfPat=/%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;var csharpStrPat=/{\d+(,\d+)?(:[a-zA-Z ]+)?}/g;var percentNumberPat=/%\d+/g;var pos=0;var _this=this;$(sources).each(function(j){var sourceText=$(this).text();_this.argSubs=new Array();_this.argPos=0;sourceText=sourceText.replace(htmlPat,function(s){return _this.collectArguments(s)});sourceText=sourceText.replace(cPrintfPat,function(s){return _this.collectArguments(s)});sourceText=sourceText.replace(csharpStrPat,function(s){return _this.collectArguments(s)});sourceText=sourceText.replace(percentNumberPat,function(s){return _this.collectArguments(s)});var result=providerCallback(sourceText,langFrom,langTo,function(translation,message){if(translation===false){PTL.editor.displayError(message);return;}
for(var i=0;i<_this.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(var i=0;i<_this.argSubs.length;i++){var value=_this.argSubs[i].replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;");translation=translation.replace("["+i+"]",value);}
areas.eq(j).val($('<div />').html(translation).text());areas.eq(j).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));