-
Notifications
You must be signed in to change notification settings - Fork 52
/
jgabc.js
3 lines (3 loc) · 66.9 KB
/
jgabc.js
1
2
3
function encode_utf8(e){return utf8_bom+unescape(encodeURIComponent(e))}function decode_utf8(e){return decodeURIComponent(escape(e))}function Header(e){"string"!=typeof e&&(e=""),this.comments=[],this.cValues={},this.original="";var t=e.match(regexHeaderEnd);if(t)for(var n=this.original=e.slice(0,t.index+t[0].length),a=n.split(/\r?\n/g),i=0;i<a.length;++i){var s=a[i],t=regexHeaderLine.exec(s);if(t)if(this[t[1]]){var r=t[1]+"Array";this[r]||(this[r]=[this[t[1]]]),this[r].push(t[2])}else this[t[1]]=t[2];else(t=regexHeaderComment.exec(s))&&"%%"!=s&&(t=regexHeaderLine.exec(s.slice(1)),t?this.cValues[t[1]]=t[2]:this.comments[i]=s)}}function getHeaderLen(e){var t=e.match(regexHeaderEnd);return t?t.index+t[0].length:0}function getHeader(e){return new Header(e)}function updateLinks(e){var t=getHeader(e);t?e=e.slice(t.original.length):t="%%\n",linkSelector&&$(linkSelector).attr("href","http://gregorio.gabrielmass.com/cgi/process.pl?gregtext="+window.escape(t+e)+"&gregfontselect=17&gregtextfontselect=12&greginitialselect=43&gregspaceselect=7mm&gregredselect=N&greglinethickselect=10&gregpaperselect=letterpaper&gregfaceselect=libertine&gregcropselect=N");try{if(linkDownloadSelector){var n=encode_utf8(t+e),a="data:text/plain;charset=utf8;base64,"+btoa(n),i=t.name||"Untitled";i.match(/\.gabc$/)||(i+=".gabc"),$(linkDownloadSelector).attr("charset","UTF-8").attr("href",a).attr("data-downloadurl","text/plain:"+i+":"+a)}}catch(s){}return[t,e]}function updateChant(e,t,n){var a=t,i=$(t);if(i.is("svg")||(i=i.find("svg"),i.length||(i=$(_svg).clone().appendTo(t)),t=i[0]),t!=_svg&&otherElements.indexOf(t)<0&&a&&otherElements.push(a),!dontUpdateChant&&e){var s=updateLinks(e);if(_timeoutGabcUpdate&&clearTimeout(_timeoutGabcUpdate),!n){var r=gabcProcessTime+100;return void(_timeoutGabcUpdate=setTimeout(function(){updateChant(e,t,!0)},r))}_nextUpdate=(new Date).getTime()+100+gabcProcessTime;var l=new Date;e=s,_timeoutGabcUpdate=null;var o=$(t).find(">g")[0];if(o){var c=[0],f=getChant(e,t,o,c),d=f.getBBox().height+c[0]+_heightCorrection-_defText.getExtentOfChar("q").height;$(t).height(d),t.parentNode.tagName.match(/span/i)&&$(t).css("width",f.getBBox().width),gabcProcessTime=new Date-l,console.info("Update chant time: "+gabcProcessTime),gabcProcessTime>3e3&&(gabcProcessTime=3e3)}}}function make(e,t,n){var i=document.createElementNS(svgns,e);if(t&&i.appendChild(document.createTextNode(t)),n)switch(typeof n){case"string":i.setAttribute("class",n);break;case"object":for(a in n)i.setAttribute(a,n[a])}return i}function textWidth(e,t,n){var a=0,i=void 0;if(0===e.length)return 0;if("number"==typeof t&&"number"==typeof n&&(a=t,i=n,t="goudy",n=void 0,0===i))return 0;var s=n?_defText:defText;if($.isArray(e)){var r,l;if(1!=e.length||0!=e[0].tags.length){if(0==a&&!i&&(l=JSON.stringify(e))&&(r=_txtWidths[l]))return r;$(s).empty();var o=0,c=0;return e.forEach(function(e){var t=e.span();s.appendChild(t);var n=Math.max(a,c),r=t.textContent.length,l=Math.min(c+r,a+(i||1e6))-n;n-=c,c+=r;try{l>0&&n>=0&&(o+=t.getSubStringLength(n,l))}catch(f){console.warn(f)}}),l&&(_txtWidths[l]=o||s.getComputedTextLength()),o}if(e=e[0].text,0==e.length)return 0;if(void 0==t&&(t=""),0==a&&!i&&(l=t+","+e)&&(r=_txtWidths[l]))return r}else if("object"==typeof e){if(1==e.childNodes.length){var f=e.firstChild,l=$(f).attr("class").replace(new RegExp("(?:^|\\s)"+fontclass+"(?:\\s|$)|\\s+$","g"),"")+","+f.textContent,r=_txtWidths[l];if(r)return r}$(s).empty().append($(e).clone());var o=s.getComputedTextLength();return l&&(_txtWidths[l]=o),o}t&&s.setAttribute("class",t),$(s).text(e.replace(/ /g," "));var o=s.getSubStringLength(a,i||e.length);return l&&(_txtWidths[l]=o),o}function useWidth(e,t,n){if(e.tagName.match(/^use$/i)&&(e=document.getElementById(e.getAttribute("href").slice(1))),"undefined"==typeof t)return getChantWidth(e.textContent);for(var a=0,i="",s="",r=[],l=0;l<e.childNodes.length;++l){var o=e.childNodes[l];if(a>=t){if(0==r.length&&getChantWidth(o.textContent)<=2?i=i.slice(0,0-s.length):s="",r.push(getChantWidth(i)),2==r.length)return r;i=s,t+=n}i+=o.textContent,s=o.textContent,a+=1}return r.push(getChantWidth(i)),r}function getChantWidth(e){return defChant.textContent=e,defChant.getComputedTextLength()}function selectGabc(e,t,n){var a=$("#"+$(n).parent().attr("for"));if(0==a.length&&(a=$("#editor")),e+=getHeaderLen(a.val()),a.is(":visible"))a=a[0];else{a=$("#hymngabc")[0];var i,s=0;for(i in _hymnGabcMap)if(_hymGabcMap.hasOwnProperty(i)){if(i>e)break;s=_hymnGabcMap[i]+e-i}e=s}if(-1==t){var r=$(a).val().slice(e).match(/^[^) ]*/);t=r[0].length}a.select(e,t),a.selectionStart=e,a.selectionEnd=e+t}function getTagsFrom(e){for(var t,n=[];t=regexTag.exec(e);){n.push(t[2]);var a=t.index+t[0].length;e=0==t.index?e.slice(t[0].length):e.slice(0,t.index)+e.slice(a)}return n}function tagsForText(e,t){"string"==typeof e&&(e=[e]);var n=[],a=e[0];t||(t=[]);for(var i;i=regexTag.exec(a);){var s=a.slice(0,i.index);if(s.length>0&&n.push(new TagInfo(s,t)),"/"!=i[1])t.indexOf(i[2])<0&&t.push(i[2]);else{var r=t.indexOf(i[2]);r>=0&&t.splice(r,1)}var l=i.index+i[0].length;a=a.slice(l)}return e[0]=a,n}function TagInfo(e,t){if(this.tags=$.merge([],t||[]),this.text=e.replace(/ /g," "),t&&t.indexOf("v")>=0){this.span=this.spanV,this.spans=[];for(var e="",n=this.text.match(/\\[^\\\s]*|[^\\]+/g),a=0;a<n.length;++a){var i=n[a];if("\\"==i[0]){i=i.slice(1);var s=vCodes[i];if(s){this.spans.push({txt:s}),e+=s;continue}}this.spans.push(i),e+=i}this.text=e}}function relayoutChant(e,t){t=svgWidth=t||e.parentNode.clientWidth;var n,a,i,s,r,l,o,c,f,d,u,h=$(e),g=h.children("g"),m=h.find("#commentary"),p=0,v=0,x=0,b=0,y=h.find("#system"+x),T=y[0],w=y[0].info,C=h.find("defs")[0],S=w.y,A=[],k=[],N=t-w.x-spaceBetweenNeumes;for(tagsBetweenText=[],e=h[0],w.ltone=3,w.htone=10,m.length&&m.attr("x",t-m[0].getComputedTextLength());;){l=r,o=a,n=g.find("#neume"+b),a=g.find("#neumetext"+b),i=g.find("#neumetrans"+b),r=n[0]?n[0].neume:a[0]?a[0].neume:{match:{}},delete r.custos;var I=g.find("#neumemask"+b);s=$().add(n).add(a).add(i).add(I),d=s.toArray(),u=n.toArray().concat(I.toArray());var O=!1;for(H in r.ledgers)if(r.ledgers.hasOwnProperty(H)){O=!0;break}if(f=r.offset||0,0==s.length)break;v+=Math.min(0,f),r.wChant>0&&(v>p||!a.length)?p=v:l.lastOnLineHyphen&&($(l.lastOnLineHyphen).remove(),delete l.lastOnLineHyphen);var L=a.length?p+r.wText+Math.max(Math.floor(f),0):L||0;r.match[7]&&r.match.index>0&&(L+=5);var _=p+r.wChant+(r.spaceBeforeNextNeume||spaceBetweenNeumes)-Math.min(f,0);if(r.x=p,Math.max(L,_)>N){var P=lastClefBeforeNeume(b,e),E=P?P.wChant:0;!o.length||l.lastOnLineHyphen||o.text().slice(-1).match(/-|\s/)||(l.lastOnLineHyphen=new TagInfo("-").span(),o.append(l.lastOnLineHyphen)),L-=p,_-=p,p=0,v=E+(r.spaceBeforeNextNeume||spaceBetweenNeumes)+f,r.wChant>0&&v>p&&(p=v),L+=p,_+=p,r.x=p,++x,A.length&&(k.push(A),A=[]),T.words=k,k=[],tagsBetweenText=[],c=T,trimStaff(T,t-w.x);var M=finishStaff(T);if(y=h.find("#system"+x),y.length)T=y[0],T.info.htone=10,T.info.ltone=3;else{var G=staffoffset+M+verticalSpace+w.y;T=addStaff(e,T.parentNode,0,G,x,null,C),T.info.vOffset=T.info.y,y=$(T)}w=T.info,N=t-w.x-(r.spaceBeforeNextNeume||spaceBetweenNeumes)}if(A=A.concat(d),n.length&&(w.ltone=Math.min(w.ltone,r.info.ltone),w.htone=Math.max(w.htone,r.info.htone),y.append(n),c&&!r.gabc.match(/^[,;:]+$/)&&(addCustos(c,r),c=null)),i.length&&(i[0].neume=r),a.length){$(w.eText).append(a),$(w.eTrans).append(i);var D=tagsBetweenText.length-1;if(0>=D)tagsBetweenText[0]=u;else{var B=tagsBetweenText[0][0],W=B.neume.x+B.neume.wChant;W+=r.transformX||0;var F=p;0>f&&(F-=f);for(var U=0,H=1;D>=H;++H)U+=tagsBetweenText[H][0].neume.wChant;var j=F-W-U;j/=D+1;for(var K=W+j,H=1;D>=H;++H){for(var R=0;R<tagsBetweenText[H].length;++R)tagsBetweenText[H][R].neume.x=K;K+=j+tagsBetweenText[H][0].neume.wChant}tagsBetweenText=[u]}}else tagsBetweenText.length>0&&!r.info.ftone&&(tagsBetweenText.push(u),(1==A.length&&A[0]==n[0]||2==A.length&&A[0]==n[0]&&A[1]==I[0])&&(k.push(A),A=[]));O&&processLedger(r,n[0],A),r.match[7]&&(k.push(A),A=[]),p=L,v=_,++b}for(A.length&&k.push(A),T.words=k,justifyLine(T,!0,!0),T.custos&&($(T.custos).remove(),T.custos=void 0),T.custosLedger&&($(T.custosLedger).remove(),T.custosLedger=void 0),trimStaff(T,t-w.x),finishStaff(T),trimStaff(T);y.length;)++x,y=h.find("#system"+x+",.system"+x),y.remove();var z=h.children("g")[0].getBBox().height+S+_heightCorrection-_defText.getExtentOfChar("q").height;e.setAttribute("height",z),h.height(z)}function getChant(e,t,n,a){a||(a=[]);var i=e[0];e=e[1];var s=e.match(/[\r\n]\s*[-\w]+:[^;]+;\s*[\r\n]/);s&&(e=e.slice(0,s.index));var r=t.parentNode.getAttribute("for"),l=$("#"+r);l.is("textarea")||(r=l=null);var o=t?t.parentNode&&("chant-preview"==t.parentNode.id||r):!1,c=$(t).find("defs")[0];c||(c=_defs);var f,d=0,u=0;n?$(n).empty():(n=make("g"),n.setAttribute("transform","translate(0,"+staffoffset+")"),n.setAttribute("class","caeciliae")),t.clefs=[],t.accidentals=[],o&&(t.tones=[],syllableOffsetCorrection={});var h=$(t.parentNode).width(),g=i["user-notes"],m=i.commentary,p=String(i.cValues.timing||"").split(" ")||[],v=String(i.cValues.volume||"").split(" ")||[],x=0;if("string"==typeof g&&g.length>0){var b=make("text",g);b.setAttribute("id","userNotes"),b.setAttribute("class",fontclass+" i"),b.setAttribute("y",16-staffoffset),n.appendChild(b),x=20}if("string"==typeof m&&m.length>0){var b=make("text",m);b.setAttribute("id","commentary"),b.setAttribute("class",fontclass+" i"),b.setAttribute("y",16-staffoffset),n.appendChild(b),b.setAttribute("x",h-b.getComputedTextLength()),x=20}a[0]=x,regexOuter.lastIndex=0;var y,T,w,C,S,A,k,N,I,O,L=0,_=0,P=null,E=0,M=!0,G=0,D=[],B=[],W=[],F=!1,U=fontclass,H=[],j=addStaff(t,n,0,x,G,null,c),K=j.info;try{var R=$(t.parentNode).css("padding-left");R&&(h-=parseFloat(R))}catch(z){}for(svgWidth=h;gmatch=regexOuter.exec(e);)for(var q,V=gmatch[5]?gmatch[5].match(/(?:\[[^\]]*\]?|[^[\/,;:]+\/*|\/+)+|[`,;:]+/g):[""],Z=gmatch.index,X=0;X<V.length;++X){var f=1==V.length?gmatch:0==X?gmatch.slice(0,6):X==V.length-1?gmatch.slice(4):["",""];5==f.length&&f.splice(0,0,"","","",""),f.index=Z+=f[1].length;var Y=V[X];Z+=Y.length;var J=Y.match(/\/+$/);if(J?(J=J[0].length,Y=Y.slice(0,-J),q=J*slashSpace):q=spaceBetweenNeumes,"z0"!=Y){var Q={index:f.index,match:f,ledgers:{},wChant:0,wText:0,spaceBeforeNextNeume:q},et=[];Q.gabc=Y,Q.info=getChantFragment(Q.gabc||"/",c),k=Q.info.clef||k,Q.info.clef&&(t.clefs[d]=I=Q,I.clefs=[],t.accidentals[u]=3==k.length?-1:null),o&&(t.tones=t.tones.concat(Q.info.tones));for(var tt=Q.info.def.textContent,nt=0;nt<Q.info.tones.length;++nt){var at=Q.info.tones[nt];at.choralSign&&(tt=tt.replace(at.choralSign,""))}Q.wChant=getChantWidth(tt),Q.gabc==k&&(N=Q.wChant),B.length>0&&O&&(O[7]||O[8])&&(D.push(B),B=[]);var it=f[7]||f[8],b=f[3]||it,st=regexSqBrackets.exec(b);st&&(b=b.slice(0,st.index)+b.slice(st.index+st[0].length),st=st[1]);var rt=b;f[3]&&it&&(b+=it),Q.txt=b,Q.translation=st;var lt=0;if(b){if(M&&f[3]&&(M=!1,"0"!=i["initial-style"])){var ot=b[0];b=b.slice(1),0==b.replace(/[{}]/g,"").length&&(b="-");var ct=K.txtInitial=make("text",ot);ct.setAttribute("transform","translate(0,"+K.vOffset+")"),o&&d==selectedNeume?ct.setAttribute("class","greinitial selectable selected neume"+d+" "+fontclass):ct.setAttribute("class","greinitial "+(o?"selectable ":"")+"neume"+d+" "+fontclass),n.appendChild(ct);var ft=ct.getComputedTextLength(),dt=i.annotation;if("string"==typeof dt&&dt.length>0){var s=/([a-g]\d?\*?\s*)$/.exec(dt),ut="</sc>";s&&(dt=dt.slice(0,s.index),ut+=s[0]),dt=dt.replace(/\b[A-Z\d]+\b/,function(e){return e.toLowerCase()})+ut;for(var ht=K.txtAnnotation=make("text"),gt=tagsForText("<sc><v>"+dt+"</v></sc>"),nt=0;nt<gt.length;++nt)ht.appendChild(gt[nt].span());ht.setAttribute("class","greannotation"),ht.setAttribute("y",K.vOffset-25),n.appendChild(ht);var mt=ht.getComputedTextLength(),pt=Math.max(mt,ft)/2;ht.setAttribute("x",pt-mt/2),ct.setAttribute("x",pt-ft/2),E=Math.max(mt,ft)+5}else E=ft+5;K.eText.setAttribute("transform","translate("+E+","+K.vOffset+")"),K.eTrans.setAttribute("transform","translate("+E+","+K.vOffset+")"),K.x=E;var vt=$(j).find("use[href=#staff]")[0];vt.setAttribute("transform","scale("+(h-E)+",1)")}b=b.replace(/^\s+/,"").replace(/\r\n/g," ").replace(/\n/g," ").replace(/<v>(?:\\greheightstar|\$\\star\$)<\/v>/g,"*").replaceSpTags();var xt=[b];et=tagsForText(xt,W),b=xt[0];var bt="";if(et.length>0&&et.forEach(function(e){bt+=e.text}),b.length>0){var yt=b.replace(/[{}]/g,"");yt.length>0&&et.push(new TagInfo(yt,W))}if(b=bt+b,Q.wText=textWidth(et),b){var Tt,wt=b.indexOf("{"),Ct=b.indexOf("}");if(wt>=0&&Ct>wt){var St=b.slice(wt+1,Ct);b=b.slice(0,wt)+St+b.slice(Ct+1),--Ct,Tt={index:wt,0:St,1:St}}else Tt=/^english$/i.exec(i["centering-scheme"])?{index:0,0:b.replace(/[,.:;\s]*$/,""),1:b.replace(/[,.:;\s]*$/,"")}:regexVowel.exec(b);Tt||(Tt={index:0,0:b.trimRight(),1:b.trimRight()});try{var At=Tt.index+Tt[0].length-Tt[1].length;lt-=textWidth(et,0,At),lt-=textWidth(et,At,Tt[1].length)/2}catch(z){}lt+=notewidth/2}}var $t=Q.info.startsWithAccidental?getChantWidth("b-"):0;lt+=$t,Q.offset=lt,_+=Math.min(0,lt),Q.wChant>0&&(_>L||!b)&&(L=_);var kt=b?L+Q.wText+Math.max(Math.floor(lt),0):kt||0;f[7]&&f.index>0&&(kt+=5);var Nt=Math.max(L,_)+Q.wChant+q-Math.min(lt,0),It=0==Q.wText?Math.max(It||0,L):Math.max(kt,Nt);if(C||It>=h-E-q-Q.wChant){F=j,F.justify=C?C.justify:!0,F.justify||(S=L),C=void 0,H=[],P&&b&&"-"!=$(P).text().slice(-1)&&P.appendChild(Q.lastOnLineHyphen=new TagInfo("-").span()),B.length>0&&(D.push(B),B=[]),j.words=D,D=[];var Ot=finishStaff(j),Lt=staffoffset+Ot+verticalSpace+K.y;if(j=addStaff(t,n,0,Lt,++G,null,c),j.info.vOffset=j.info.y,K=j.info,K.eText.setAttribute("transform","translate(0,"+K.vOffset+")"),K.eTrans.setAttribute("transform","translate(0,"+K.vOffset+")"),It-=L,kt-=L,Nt-=L,k){var y=make("use");y.setAttribute("class","clef"),y.setAttributeNS(xlinkns,"href","#"+k),y.setAttribute("x",0),y.setAttribute("y",0),j.appendChild(y),I&&I.clefs&&I.clefs.push(y),L=0,_=N+q+lt,Q.wChant>0&&_>L&&(L=_),It+=L,kt+=L,Nt+=L}else L=0}if(C=Q.gabc&&Q.gabc.match(/z(?!0)/i),C&&(C.justify=Q.gabc.match(/z/)),Q.gabc||""===Q.gabc){if(F&&!Q.gabc.match(/^[`,;:]+$/)&&(addCustos(F,Q,F.justify,S),F=!1,E=0),Q.info.mask?(T=make("use"),T.setAttributeNS(xlinkns,"href","#"+Q.info.mask),T.setAttribute("id","neumemask"+d),T.setAttribute("class","caeciliae"),T.setAttribute("x",L),T.setAttribute("y",0),B.push(T),masks[G].firstChild.appendChild(T)):T=null,K.ltone=Math.min(K.ltone,Q.info.ltone),K.htone=Math.max(K.htone,Q.info.htone),o?y=$(Q.info.def).clone()[0]:(y=make("use"),y.setAttributeNS(xlinkns,"href","#"+Q.gabc)),y.setAttribute("id","neume"+d),y.setAttribute("x",L),y.setAttribute("y",0),y.neume=Q,o){if(d==selectedNeume){selectedNeumeTag=y;var _t=$(y).children().last();syllableGabcOriginalLength=""==Q.gabc?0:parseInt(_t.attr("offset"))+parseInt(_t.attr("len"))}u=setUpPunctaIn(y,u,t)}if(it){var St=k&&3==k.length?-1:null;t.accidentals[t.accidentals.length-1]!=St&&(t.accidentals[u]=St)}if(j.appendChild(y),B.push(y),currentUse=[y],T&¤tUse.push(T),b){var Pt=H.length-1;if(0>=Pt)H[0]=currentUse;else{var Et=H[0][0],Mt=parseFloat(Et.getAttribute("x"))+Et.neume.wChant,Gt=Et.getAttribute("transform");if(Gt){var s=regexTranslate.exec(Gt);Mt+=parseFloat(s[1])}var Dt=L;0>lt&&(Dt-=lt);for(var Bt=0,nt=1;Pt>=nt;++nt)Bt+=H[nt][0].neume.wChant;var Wt=Dt-Mt-Bt;Wt/=Pt+1;for(var Ft=Mt+Wt,nt=1;Pt>=nt;++nt)$(H[nt]).attr("x",Ft),Ft+=Wt+H[nt][0].neume.wChant;H=[currentUse]}}else H.length>0&&!Q.info.ftone?(H.push(currentUse),(1==B.length&&B[0]==y||2==B.length&&B[0]==T&&B[1]==y)&&(D.push(B),B=[])):Q.info.ftone&&(H=[])}else y=T=null;if(b){A=P,pneume=w,P=make("tspan"),w=Q;var Ut=L;if(y&&(Q.transform="translate("+-lt+")",Q.transformX=-lt,lt>0?Ut-lt>=_?(Q.wText-=lt,y.setAttribute("transform",Q.transform),T&&T.setAttribute("transform",Q.transform)):(Ut+=lt,Q.wText+=lt):(y.setAttribute("transform",Q.transform),T&&T.setAttribute("transform",Q.transform))),A){var Ht=parseFloat(A.getAttribute("x"),10),jt=Ht+textWidth(A);if(Ut>jt&&"-"!=$(A).text().slice(-1)&&(A.appendChild(new TagInfo("-").span()),pneume.wText=textWidth(A),jt=Ht+pneume.wText,jt>Ut)){var Kt=jt-Ut;Ut=jt,y&&(y.setAttribute("x",L+Kt),T&&T.setAttribute("x",L+Kt)),kt+=Kt,Nt+=Kt}}P.setAttribute("id","neumetext"+d),P.setAttribute("x",Ut);var Rt=rt.length;if(P.setAttribute("selectIndex",Q.index-1-Rt),P.setAttribute("selectLen",Rt),o&&d==selectedNeume?(syllableTextOriginalLength=Rt,P.setAttribute("class",U+" selectable selected"),selectedNeumeTextTag=$(P)):P.setAttribute("class",U+(o?" selectable":"")),P.neume=Q,L=kt,_=Nt,et.forEach(function(e){P.appendChild(e.span())}),st){var zt=new TagInfo(st,["i","trans"]).span();zt.setAttribute("id","neumetrans"+d),zt.setAttribute("x",Ut),B.push(zt),K.eTrans.appendChild(zt)}B.push(P),K.eText.appendChild(P)}else y?(_=Math.max(_,L+getChantWidth(Q.info.def.textContent)+q),L=kt):_=Math.max(_,L);d++,O=f,it&&(P=null),processLedger(Q,y,B)}}if(finishStaff(j),gabcSettings.trimStaff&&trimStaff(j),o){selectedNeumeTag&&$("#txtSyllableGabc,#txtSyllable").trigger("autoSizeInput");for(var qt=[],Vt=[],Zt=100,Xt=0,Yt=0;Xt+Yt<t.tones.length;Xt++){for(;!(t.tones[Xt+Yt].isPlayable()||(++Yt,Xt+Yt>=t.tones.length)););if(Xt+Yt>=t.tones.length)break;var Jt=v[Xt],Qt=p[Xt]?/(\d+(?:\.\d+)?)(?:\:(\d+(?:\.\d+)?))?/.exec(p[Xt]):null;if(Zt=Jt&&parseInt(Jt)||Zt,qt[Xt+Yt]=Zt,Qt&&Qt.length){var Rt=parseFloat(Qt[1]);Rt>20&&(Rt/=400),Vt[Xt+Yt]={length:Rt},Qt[2]&&(Vt[Xt+Yt].restAfter=parseFloat(Qt[2]))}}t.volumes=qt,t.timings=Vt}return n}function processLedger(e,t,n){for(i in e.ledgers)e.ledgers.hasOwnProperty(i)&&$(e.ledgers[i]).remove();if(e.ledgers={},e.info.ledgerA&&(e.info.ledgerA.length||e.info.ledgerB.length)&&t){var a=t.parentNode,s=[];processLedgerHelper(e.info.ledgerA,s,!0),processLedgerHelper(e.info.ledgerB,s,!1),s.forEach(function(i){var s=insertLedger(i,a,t);e.ledgers[i.above]=s,n&&n.push(s)})}}function processLedgerHelper(e,t,n){var i=null,s=0;for(a in e)if(e.hasOwnProperty(a)){var r=e[a];r-1==i?++s:r-2==i?s+=2:(s>0&&t.push({i:i,len:s,above:n}),i=r,s=1)}s>0&&t.push({i:i,len:s,above:n})}function insertLedger(e,t,n,a){var i=0,s=1;"object"==typeof e&&(i=e.i,s=e.len,e=e.above);var r=make("use");r.setAttributeNS(xlinkns,"href",e?"#ledgera":"#ledgerb"),r.setAttribute("y",n.getAttribute("y"));var l=n.getAttribute("transform"),o=parseFloat(n.getAttribute("x"));if(l)for(;m=regexTranslateG.exec(l);)o+=parseFloat(m[1]);var c=useWidth(n,i,s);return o+=c[0],c=c[1],a?(o-=.25*notewidth,r.setAttribute("transform","translate("+o+") scale("+(c+.25*notewidth)+",1)")):(o-=.75*notewidth,r.setAttribute("transform","translate("+o+") scale("+(c+1.5*notewidth)+",1)")),n?t.insertBefore(r,n):t.appendChild(r),r}function addStaff(e,t,n,a,i,s,r){var l,o="staffmask"+i,c="staff"+i,f="system"+i;if(masks[i]){for(var d=masks[i].firstChild;d.childElementCount>1;)d.removeChild(d.childNodes[1]);l=d.firstChild}else{var u,h,g=masks[i];g&&g.parentNode!=r&&(g=$(r).find("#"+o)[0]),g?(u=g,h=u.firstChild,l=$(h).find(">rect")[0]):(u=make("mask"),u.setAttribute("maskUnits","objectBoundingBox"),u.setAttribute("id",o),h=make("g"),h.setAttribute("class","caeciliae"),u.appendChild(h),l=make("rect"),h.appendChild(l),r.appendChild(u)),masks[i]=u,u.setAttribute("transform","translate(0,"+a+")")}l.setAttribute("y",-staffheight),l.setAttribute("width","10000"),l.setAttribute("height",1+staffheight),l.setAttribute("fill","white");var m=make("g"),p=m.info={ltone:3,htone:10,vOffset:0,x:0,y:parseInt(a),eText:make("text"),eTrans:make("text")};p.eText.setAttribute("class",fontclass),p.eTrans.setAttribute("class",fontclass);var v=make("g");m.setAttribute("id",f),v.setAttribute("id",c),v.setAttribute("mask","url(#"+o+")");var x=make("use");return x.setAttributeNS(xlinkns,"href","#staff"),s||(s=$(e.parentNode).width()),x.setAttribute("transform","translate("+n+") scale("+s+",1)"),v.appendChild(x),m.appendChild(v),t.appendChild(m),m}function setGradient(e,t){var n=0==t?"RedBlack":"BlackRed",a=e.parentNode,i=$(e).index(),s=useWidth(a,i,1),r=a.neume.wChant||useWidth(a),l="grad"+n+s.join("_")+"_"+r;if(!(l in gradients)){var o=$(gradients[n]).clone(),c=o.find("stop");o.attr("id",l),$(c[0]).attr("offset",(s[0]+.25*s[1])/r),$(c[1]).attr("offset",(s[0]+.75*s[1])/r),_defs.appendChild(o[0]),gradients[l]=o[0]}e.setAttribute("style","fill:url(#"+l+")")}function setUpPunctaIn(e,t,n){var a=0,i=t,s=e.neume.info.tones,r=n.clefs;return $(e).children().each(function(){var e=s[a];e.match[rtg.accidental]?n.accidentals[t]=e.match[rtg.flat]?e.index-r[r.length-1].info.clefTone:null:e.match[rtg.whitespace]&&e.match[rtg.whitespace].match(/[,;:]/)&&(n.accidentals[t]=r.length&&3==r[r.length-1].gabc.length?-1:null),this.setAttribute("id","punctum"+t),this.tone=e;var l=parseInt(this.getAttribute("count"))||1;2==l?t==selectedPunctum?(selectedPunctumTag=this,this.setAttribute("class","selectable selected-1"),setGradient(this,0)):t+1==selectedPunctum?(selectedPunctumTag=this,this.setAttribute("class","selectable selected-2"),setGradient(this,1)):this.setAttribute("class","selectable"):t==selectedPunctum?(selectedPunctumTag=this,this.setAttribute("class","selectable selected")):this.setAttribute("class","selectable"),a+=parseInt(this.getAttribute("count"))||1,t=i+a}),t}function gabcEditorKeyDown(e){var t=$(this),n=t.val(),a=this.selectionStart,i=this.selectionEnd;switch(e.which){case 66:(e.ctrlKey||e.altKey)&&(e.preventDefault(),s=n.indexOf(" ",this.selectionEnd),0>=s&&(s=n.length),t.val(n.slice(0,s)+" ()"+n.slice(s)),this.selectionEnd=this.selectionStart=s+2);break;case 83:a==i&&(e.ctrlKey||e.altKey)&&"("!=n[a-1]&&")"!=n[a]&&(e.preventDefault(),t.val(n.slice(0,a)+"()"+n.slice(a)),this.selectionEnd=this.selectionStart=a+1);break;case 9:var s,r,l;if(e.preventDefault(),e.shiftKey)s=this.selectionStart,l=n.lastIndexOf("\n%%\n",s-1),s=n.lastIndexOf(")",s-1),l>=s&&(s=n.lastIndexOf(")")),s>=0&&(r=s,s=n.lastIndexOf("(",s));else{s=this.selectionEnd;var o=/(\()|(-(?!\())|(\s+(?![:;!.]))|([^)\s]$)/g;o.lastIndex=s;for(var c;(c=o.exec(n))&&(c[2]||c[3]);)if(!c[3]||0!=c.index&&")"!=n[c.index-1]){s=c.index;var f=n.lastIndexOf("\n",s-1)+1,d=n.indexOf("\n",s);0>d&&(d=n.length),"\r"==n[d]&&d--;var u=n.slice(f,d);if(!u.match(/^(?:\s*(?:%.*|[-\w]+:[^;]+;)\s*|%%)$/))break}c?c[1]?s=c.index:c[2]||c[3]||c[4]?((c[2]||c[4])&&(s=c.index+1),n=n.slice(0,s)+"()"+n.slice(s),t.val(n)):s=n.indexOf("("):s=n.indexOf("("),s=n.indexOf("(",s),s>=0&&(r=n.indexOf(")",s))}s>=0&&r>=0&&(this.selectionStart=s+1,this.selectionEnd=r);break;case 57:if(e.shiftKey){var h=this.value.slice(i),g=h.indexOf(")"),m=h.indexOf("(");if(0>g||m>=0&&g>m)return this.value=this.value.slice(0,this.selectionStart)+"()"+this.value.slice(i),this.selectionStart=this.selectionEnd=a+1,void e.preventDefault()}break;case 48:e.shiftKey&&a==i&&")"==n[a]&&(e.preventDefault(),this.selectionStart=this.selectionEnd=a+1);break;case 8:var i=this.selectionEnd;i==this.selectionStart&&i>0&&")"==this.value[i]&&"("==this.value[i-1]&&(e.preventDefault(),this.value=this.value.slice(0,this.selectionStart-1)+this.value.slice(i+1),this.selectionStart=this.selectionEnd=i-1)}}String.prototype.repeat=function(e){return new Array(e+1).join(this)},String.prototype.reverse=function(){return this.split("").reverse().join("")},HTMLTextAreaElement.prototype.selectAndScroll=function(e,t,n){var a=this.value,i=this;setTimeout(function(){if(a==i.value){var s=i.scrollTop,r="";if(n){var l=$(i),o=parseFloat(l.css("line-height"));isNaN(o)&&(o=1.2*parseFloat(l.css("font-size")));var c=Math.floor(l.height()/o);r="\n".repeat(c-1)}i.value=a.slice(0,t)+r,i.scrollTop=i.scrollHeight,i.value=a,i.setSelectionRange(e,t),(i.scrollTop-s)*(n?-1:1)<0&&(i.scrollTop=s)}})},String.prototype.trimRight||(String.prototype.trimRight=function(){return this.replace(/\s+$/,"")});var gabcSettings={trimStaff:!0,showSyllableEditorOnHover:!0,showSyllableEditorOnClick:!0},uuid,_indicesChar={flat:[57585,58176,57586,58177,57587,58178,57588,58179,57589,58180,57590,58181,57591],natural:[57593,58182,57594,58183,57595,58184,57596,58185,57597,58186,57598,58187,57599],flat_line:58176,natural_line:58182,punctum:57603,diamond:57619,virga:57635,v:57635,leftVirga:57651,quilisma:57667,w:57667,bottomPartPodatus:57684,topPartPodatus:57699,podatus:[null,57715,57731,57748,57763],o:57779,O:57795,diamond_tilde:57811,">":57827,"<":57843,upper_tilde:57859,lower_tilde:57875,porrectus:[null,57891,57907,57923,57939],r:57971,s:57987,custos:58019,"+":58019,dot:58035,apos:58050,ictus:58050,ictus_above:58053,ictus_below:58050,underscore:58066,episema:58066,episema_below:58066,episema_above:58069,underscore_longer:58082,episema_longer:58082,clivis:[null,58115,58131,58147,58163],accent_above_staff:58188,connecting_line:[void 0,void 0,59139,59155,59171,59187],decorative_line:[void 0,59203,59219,59235,59251,59267]},vCodes={Abar:"a",Vbar:"v",Rbar:"r"},fontclass="goudy",_neumeChar=function(e,t){if(arguments.length<2)return"";var e,t,n=e;return e=parseInt(t),t=0,"object"==typeof n&&(arguments.length>2&&(t=parseInt(arguments[2])),n=n[Math.abs(t-e)],2==arguments.length&&(e=0)),String.fromCharCode(n+e)},_clefSpanChar=function(e,t){var n,a,i=parseInt(e.clef.slice(-1),10),s=0;return 2==e.index?(a="d-",s=2-i):(a="f-",s=3-i),3==e.clef.length&&(a+=neume(indices.flat,4)+"-"),s*=spaceheight,t[0]=Math.min(t[0],s),n=make("tspan",a),n.setAttribute("dy",s),n},_ci=["B","A","0","1","2","3","4","5","6","7","8","9","Z"],staffheight=48,spaceheight=staffheight/4,notewidth=staffheight/6,spaceBetweenNeumes=notewidth,slashSpace=staffheight/20,verticalSpace=staffheight/4,fontsize=3*spaceheight/2,spaceWidth=3*spaceheight/4,staffoffset=Math.ceil(staffheight-spaceheight/2),svgns="http://www.w3.org/2000/svg",xlinkns="http://www.w3.org/1999/xlink",staffInFont=!1,fontExt="ttf",fontExtS="svg#webfont",fontFormat="truetype",fontFormatS="svg",filenameCaeciliae="Caeciliae-"+(staffInFont?"Regular.":"Staffless.")+fontExt,filenameCaeciliaeS="Caeciliae-"+(staffInFont?"Regular.":"Staffless.")+fontExtS,filenameCaeciliaePrint="Caeciliae-"+(staffInFont?"Regular":"Staffless")+"-Print."+fontExt,localCaeciliae="Caeciliae"+(staffInFont?"":" Staffless"),familyCaeciliae="Caeciliae"+(staffInFont?"":" Staffless"),styleCaeciliae="font-family: '"+familyCaeciliae+"'; font-size:"+staffheight+"px;",styleCaeciliaeSvg="font-family: '"+familyCaeciliae+" SVG'; font-size:"+staffheight+"px;",styleGoudy="font-family: 'Crimson Text'; font-size: "+fontsize+"px;",styleFont="@font-face {font-family: '"+familyCaeciliae+"'; font-weight: normal; font-style: normal;src: local('"+localCaeciliae+"'); src: url('"+filenameCaeciliae+"') format('"+fontFormat+"')}@font-face {font-family: '"+familyCaeciliae+" SVG'; font-weight: normal; font-style: normal;src: url('"+filenameCaeciliaeS+"') format('"+fontFormatS+"')}@font-face {font-family: '"+familyCaeciliae+" Print'; font-weight: normal; font-style: normal;src: url('"+filenameCaeciliaePrint+"') format('"+fontFormat+"')}@font-face { font-family: 'Crimson Text'; src: url('fonts/crimson-bold-webfont.woff2') format('woff2'), url('fonts/crimson-bold-webfont.woff') format('woff'); font-weight: bold; font-style: normal; }@font-face { font-family: 'Crimson Text'; src: url('fonts/crimson-italic-webfont.woff2') format('woff2'), url('fonts/crimson-italic-webfont.woff') format('woff'); font- weight: normal; font-style: italic; }@font-face { font-family: 'Crimson Text'; src: url('fonts/crimson-roman-webfont.woff2') format('woff2'), url('fonts/crimson-roman-webfont.woff') format('woff'); font- weight: normal; font-style: normal; }",svgWidth,_svg,svg,textElem,codea="a".charCodeAt(0),codem=codea+12,codeA="A".charCodeAt(0),codeM=codeA+12,regexLatinLongPenult=/([ao]e|au|[aeiouyāēīōūȳăĕĭŏŭäëïöüÿ])(?!([bcdgkpt][rl]|qu|[bcdfghjklmnprstvy])[aeiouyāēīōūȳăĕĭŏŭäëïöüÿ])((?:[bcdfghjklmnprstvy]{2,}|[xz])(?:[ao]e|au|[aeiouyāēīōūȳăĕĭŏŭäëïöüÿ])[bcdfghjklmnprstvxyz]*)$/i,regexTranslate=/translate\((-?\d+(?:\.\d+)?)(?:[,\s]\s*(-?\d+(?:.\d+)?))?\)/,regexTranslateG=/translate\((-?\d+(?:\.\d+)?)(?:[,\s]\s*(-?\d+(?:.\d+)?))?\)/g,regexHeaderEnd=/(?:^|\n)%%\s?\n/,regexOuter=/((([^\(\r\n]+)($|\())|\()([^\)]*)($|\))(?:(\s+)|(?=(?:\([^\)]*\))+(\s*))|)/g,regexTag=/<(\/)?(\w+)>/i,regexSqBrackets=/\[([^\]]*)(?:\]|$)/,regexTags=/(<\w+>)(.*?)(?:(<\/\1>)|$)/i,regexTagsSp=/<sp>([^<]*)<\/sp>/gi,spSubstitutions={"'ae":"ǽ","'æ":"ǽ",ae:"æ",oe:"œ","'œ":"œ","'oe":"œ",AE:"Æ",OE:"Œ",Ae:"Æ",Oe:"Œ","V/":"V","R/":"R","A/":"A"};String.prototype.replaceSpTags=function(){return this.replace(regexTagsSp,function(e){var t=e.slice(4,-5);return spSubstitutions[t]||t})};var regexInner=/[!\/ ,;:`]+|(([^\)!\/ ,;:`\[]+)(\[[^\]]*(?:$|\]))?)+/g,rog={syl:3,gabc:5,whitespace:7},linkSelector="",linkDownloadSelector="",setPdfLinkSelector=function(e){linkSelector=e},onDragStart=function(e){console.info(e),e.originalEvent.dataTransfer.setData("DownloadURL",this.getAttribute("data-downloadurl"))},setGabcLinkSelector=function(e){linkDownloadSelector=e,$(e).bind("dragstart",onDragStart)},regexToneModifiers=/(')|(\.{1,2})|(_{1,4}0?)/g,regexTones=new RegExp("([/ ,;:`]+)|((?:[fF]|[cC][bB]?)[1-4])|(?:(-)?(([A-M])|([a-m]))(([Vv]{1,3})|(s{1,3})|((<)|(>)|(~))|(w)|(o)|(O)|((x)|(y))|(q)|((R)|(r0)|(r(?![1-5])))|(r[1-5])|(\\+))?((?:"+regexToneModifiers.source.replace(/\((?!\?:)/g,"(?:")+")*)(?:\\[([^\\]]*)(?:]|$))?|(z0))","g"),regexTonesSpliceIndex=27,regexToneModifiersCount=4,rtg={whitespace:1,clef:2,initioDebilis:3,tone:4,toneUpper:5,toneLower:6,noteType:7,virga:8,stropha:9,liquescentia:10,ascendingLiquescentia:11,descendingLiquescentia:12,diminutiveLiquescentia:13,quilisma:14,oriscus:15,oriscusReverse:16,accidental:17,flat:18,natural:19,q:20,lineaPunctum:22,lineaPunctumCavum:23,punctumCavum:24,rNumber:25,custos:26,ictus:27,dot:28,episema:29,bracketed:30,autoCustos:31},regexVowel=/(?:[cgq]u|[iy])?([aeiouyáäąéëęíïóöúüýÿǽæœ́œ]+)/i,transforms=[["/"," ",",",";",":","`",""],["'","_","+",";","|",",",""],[/\//g,/ /g,/,/g,/;/g,/:/g,/`/g,/!/g]],abcs={},_defs=null,defText=null,_defText=null,defChant=null,masks=[],selectedPunctum=-1,selectedNeume=-1,selectedPunctumTag=null,selectedNeumeTag=null,selectedNeumeTextTag=null,syllableGabcIndex=-1,syllableGabcPrefix="",syllableGabcSuffix="",syllableGabcOriginalLength=0,syllableTextIndex=-1,syllableTextPrefix="",syllableTextSuffix="",syllableTextOriginalLength=0,syllableTextTag=null,syllableOffsetCorrection={},_timeoutGabcUpdate=null,_minUpdateInterval=1700,_heightCorrection=0,utf8_bom=String.fromCharCode(239)+String.fromCharCode(187)+String.fromCharCode(191);Header.prototype.toString=function(){var e=[];for(key in this)if("length"!=key&&"original"!=key&&"comments"!=key&&"cValues"!=key&&"string"==typeof this[key]){var t=this[key+"Array"];if(t)for(var n=0;n<t.length;++n)e.push(key+": "+t[n]+";");else e.push(key+": "+this[key]+";")}for(key in this.cValues)0!=key.length&&this.cValues.hasOwnProperty(key)&&e.push("%"+key+": "+this.cValues[key]+";");for(n in this.comments)if(this.comments.hasOwnProperty(n))try{e.splice(n,0,this.comments[n])}catch(a){}return e.join("\n")+"\n%%\n"};var regexHeaderLine=/^([\w-_]+):\s*([^;\r\n]*)(?:;|$)/i,regexHeaderComment=/^%.*/,gabcProcessTime=0,_nextUpdate=(new Date).getTime(),dontUpdateChant=!1,otherElements=[],_txtWidths={};TagInfo.prototype.span=function(){var e=make("tspan",this.text,fontclass+" "+this.tags.join(" "));return e},TagInfo.prototype.spanV=function(){for(var e=fontclass+" "+this.tags.join(" "),t=make("tspan","",e),n=0;n<this.spans.length;++n){var a=this.spans[n];switch(typeof a){case"object":t.appendChild(make("tspan",a.txt,"versiculum"));break;case"string":t.appendChild(document.createTextNode(a))}}return t};var finishStaff=function(e){var t=e.parentNode,n=parseInt(e.id.match(/\d+$/)[0]),a=e.info,i=a.ltone,s=a.htone;i=3-i,i=0>=i?0:i*spaceheight/2,s-=9,s=0>=s?0:s*spaceheight/2;var r=Math.ceil(.1*staffheight+fontsize+i+s);if(a.vOffset=a.y,a.txtInitial&&a.txtInitial.setAttribute("y",r+a.y),a.txtAnnotation&&a.txtAnnotation.setAttribute("y",a.y+Math.ceil(s)-25),a.eText.setAttribute("y",r),a.eTrans.setAttribute("y",r+fontsize),a.eText.setAttribute("transform","translate("+a.x+","+a.vOffset+")"),a.eText.setAttribute("class","system"+n),a.eTrans.setAttribute("transform","translate("+a.x+","+a.vOffset+")"),a.eTrans.setAttribute("class","system"+n),t){var l=$(t);
l.append(l.children("text")),t.appendChild(a.eText),t.appendChild(a.eTrans)}if(a.eTrans.childNodes.length>0&&(r+=fontsize),s>0){if(a.vOffset+=s,0==n){var o=0;$(e).children("[id^=neume]").each(function(){o=Math.min(o,this.neume.info.mindy)}),_heightCorrection=o+s}e.setAttribute("transform","translate("+a.x+", "+(a.y+s)+")")}return r},trimStaff=function(e,t){var n,a=$(e).find("use[href=#staff]");if(t)n=t;else{var i=$(e).find("[id^=neume]:last"),s=$(e.parentNode).find("[id^=neumetext]:last");if(href=i.attr("href")){if(!/\:$/.exec(href))return}else if(!/\|$/.exec(i.text()))return;var r=/\d+$/.exec(i.prop("id"))[0],l=/\d+$/.exec(s.prop("id"))[0];if(l>r)return;n=parseFloat(i.attr("x"));var o=i.attr("transform"),c=regexTranslate.exec(o);c&&c[1]&&(n+=parseFloat(c[1])),n+=i[0].neume.wChant}var f="scale("+n+",1)";a.attr("transform",function(e,t){return t.replace(/scale\([^\)]*\)/,f)})},justifyLine=function(e,t,n){var a=0,i=0,s=e.words;if(!n){var r=2*spaceBetweenNeumes;i=svgWidth-e.info.x-r;for(var l,o,c=s.length-1;c>=0&&(!l||!o);)for(var f=s[c--],d=f.length-1;d>=0&&(!l||!o);){var u=f[d--];!l&&u.tagName.match(/^use|text$/i)&&u.neume?l=u:o||!u.tagName.match(/^tspan$/i)||(o=u)}if(l){if(t)a=l.neume.x+(l.neume.transformX||0);else{a=parseFloat($(l).attr("x"));var h=t?l.neume.transform:$(l).attr("transform"),g=regexTranslate.exec(h);g&&g[1]&&(a+=parseFloat(g[1]))}a+=l.neume.wChant}if(o){var m;t&&o.neume?m=o.neume.x:(m=parseFloat($(o).attr("x")),m+=textWidth(o)-r),a=Math.max(a,m)}}if(n||a>0){var p=i-a,v=s.length-1,x=p/v;if(n||p>0)for(;v>=0;)s[v].forEach(function(e){e.neume&&(e.neume.justifyOffset=Math.round(p)),$(e).attr("transform")?(t&&e.neume&&$(e).attr("x",e.neume.x),$(e).attr("transform",function(){return"translate("+Math.round(p+(e.neume&&e.neume.transformX||0))+")"})):$(e).attr("x",function(n,a){return(t?e.neume.x:a?parseFloat(a):0)+Math.round(p)})}),p-=x,--v}},addCustos=function(e,t,n,a){var i=t.info.ftone,s=neume(indices.custos,i),r=e.custos;if(r){if(r.textContent=s,e.custosLedger)try{e.removeChild(e.custosLedger),delete e.custosLedger}catch(l){}}else r=make("text",s),r.setAttribute("class",defChant.getAttribute("class")),r.setAttribute("y",0);(n||"undefined"==typeof n)&&(justifyLine(e,"undefined"!=typeof t.x),n=!0);var o=n?svgWidth-e.info.x-staffheight/15:a;r.setAttribute("x",o),e.appendChild(r),e.custos=t.custos=r;var c=i>10,f=2>i;(c||f)&&(e.custosLedger=t.custosLedger=insertLedger(c,e,r,!0))},boolArray=[!0,!1],ToneInfo=function(e){for(i in e)e.hasOwnProperty(i)&&(this[i]=e[i])};!function(){var e,t,n,a,i,s,r,l=!1;getChantFragment=function(l,c){if(void 0!=abcs[l]){var f=abcs[l];return 0==$(c).find("[id='"+l.replace(/\'/g,"\\'")+"']").length&&(c.appendChild($.clone(f.def)),f.mask&&getChantFragment(f.mask,c)),f}var d=void 0;l.indexOf("r")>-1&&(d=l.replace(/r/g,"!"),getChantFragment(d,c)),t=make("text"),i=3,a=0,t.setAttribute("id",l);var u,h,g,m=null,p=0;ledgerA=[],ledgerB=[],n=0,regexInner.lastMatch=0;var v=[];for(s=0,r=0;u=regexInner.exec(l);){e=[];var x=-1;chant=u[0],regexTones.exec("");for(var b;b=regexTones.exec(chant);){++p;var y=[];if(b[regexTonesSpliceIndex])for(var T,w=b[regexTonesSpliceIndex];T=regexToneModifiers.exec(w);){if(T[3]){var C=T[3].match(/0/)?-1:0,S=T[3].length+C-1;T[3]=T[3].slice(C-1);for(var A=1,k=e.length;S>=A&&k>=A;){var N=e[k-A];N.match[rtg.episema]||(N.match[rtg.episema]=T[3],N.episemaLoc=C),++A}}if(T[2]){var S=T[2].length;if(S>1){var N=e[e.length-1];N.match[rtg.dot]||(N.match[rtg.dot]=".")}}$.extend(y,T)}else y=new Array(regexToneModifiersCount);var I=b.index;if(b=b.splice(0,regexTonesSpliceIndex).concat(y.splice(1,y.length-1)).concat(b.splice(1,b.length-1)),b.index=I+u.index,b[rtg.clef]&&(h=b[rtg.clef],g="f"==h[0]?5:1,g+=2*parseInt(h.slice(-1))),tone=b[0],b[rtg.whitespace]){for(var A=0;A<transforms[0].length;++A)tone=tone.replace(transforms[2][A],transforms[1][A]);var O=make("tspan",tone);O.setAttribute("offset",b.index),O.setAttribute("len",b[0].length),s&&(O.setAttribute("dx",s),s=0),r&&(O.setAttribute("dy",r),r=0),t.appendChild(O),a=Math.max(a,/[`,]/.exec(b[rtg.whitespace])&&9.5||0),v.push(O=new ToneInfo({match:[]})),O.match[rtg.whitespace]=b[rtg.whitespace]}else{var L=parseInt(b[rtg.tone]||b[rtg.clef]&&b[rtg.clef].slice(0,1),23)-10,_=null;b[rtg.tone]&&1==b[rtg.tone].length?(i=Math.min(i,L),a=Math.max(a,L),null!=m||b[rtg.accidental]||(m=L)):a=Math.max(a,b[rtg.clef]&&2*parseInt(b[rtg.clef].slice(-1))+2||0);var P=/^cs\:([^\]]+)/.exec(b[rtg.bracketed]);P&&(_=P[1]),L>10?ledgerA.push(p-1):2>L&&ledgerB.push(p-1);var O=new ToneInfo({match:b,index:L,relativeTone:0>x?0:L-x,modifiers:b[rtg.noteType],clef:b[rtg.clef],episemaLoc:b[rtg.episema]&&b[rtg.episema].match(/0/)?-1:0,diamond:b[rtg.toneUpper]?!0:!1,markings:b[rtg.ictus]||b[rtg.dot]||b[rtg.episema],liq:b[rtg.diminutiveLiquescentia],accidental:b[rtg.accidental],choralSign:_});e.push(O),v.push(O),x=L}}for(var A=0;A<e.length;++A)A=o(A)}return c.appendChild(t),abcs[l]={ltone:i,htone:a,ftone:m,tones:v,startsWithAccidental:v.length>0&&v[0].match[rtg.accidental]?!0:!1,mask:d,clef:h,clefTone:g,mindy:n,ledgerA:ledgerA,ledgerB:ledgerB,def:t}};var o=function(o){var c=function(e,t,n){n||(n=t),-1==e?(h+=neume(indices.episema_below,t),i=Math.min(i,t-1)):(h+=neume(indices.episema_above,n),a=Math.max(a,n+1))},f=function(e,t){1==e?(h+=neume(indices.ictus_above,t),a=Math.max(a,t+1)):(h+=neume(indices.ictus_below,t),i=Math.min(i,t-1))},d=function(e,t,n){var a=e.choralSign,i=e.index,l=make("tspan",a),o=textWidth(a,"choral-sign"),c=getChantWidth($(n).text());e.match[rtg.episema]&&-1!=e.episemaLoc&&(i+=2,i%2&&--i);var f=t?1:c>2*notewidth?-c+(notewidth-o)/2:(-o-notewidth)/2,d=-3+(1-Math.floor(i/2)+(t?1:0))*(staffheight/4);i%2==1&&(d-=2),f+=s,d+=r,l.setAttribute("class","choral-sign"),l.setAttribute("dx",f),l.setAttribute("dy",d),s-=o+f,r-=d,t&&l.setAttribute("transform","translate("+notewidth+",0)"),n.appendChild(l)},u=function(e){if(e&&h&&0!=h.length){var n=make("tspan",h);n.setAttribute("offset",e.match.index),n.setAttribute("len",e.match[0].length),s&&(n.setAttribute("dx",s),s=0),r&&(n.setAttribute("dy",r),r=0);for(var a=1;a<arguments.length;++a)n.setAttribute("len"+a,arguments[a].match[0].length);arguments.length>1&&n.setAttribute("count",arguments.length),t.appendChild(n);for(var a=0;a<arguments.length;++a){var e=arguments[a];e.choralSign&&d(e,1==a||l,n)}h="",l=!1}},h="",g=1,m=1,p="",v=e[o],x=e.length>o+1?e[o+1]:null,b=e.length>o+2?e[o+2]:null,y=e.length>o+3?e[o+3]:null,T=o>0?e[o-1]:null,w=indices.punctum;if(o>0&&0==v.relativeTone&&(h+="'"),v.diamond){w=v.liq?indices.diamond_tilde:indices.diamond;var C=Math.abs(v.relativeTone);T&&T.diamond&&2==C&&(h+="'"),x&&!x.diamond&&(p="-")}else{if(v.clef){var S=[n];return t.appendChild(makeClefSpan(v,S)),n=S[0],o}if(v.modifiers){if(v.match[rtg.accidental]){0==o&&(startsWithAccidental=!0);var A=v.match[rtg.flat]?"flat":"natural";return h+=neume(indices[A],v.index)+"-",u(v),o}v.match[rtg.virga]?(w=indices.v,m=v.match[rtg.virga].length,p="'"):v.match[rtg.stropha]?(w=indices.s,m=v.match[rtg.stropha].length,p="'"):indices[v.modifiers[0]]&&(w=indices[v.modifiers[0]],x&&x.relativeTone>0&&x.relativeTone<=5&&"w"==v.modifiers&&(!b||b.relativeTone>=0)&&(h+=neume(w,v.index),v.match[rtg.ictus]&&f(-1,v.index),v.match[rtg.episema]&&c(-1,v.index),u(v),x.relativeTone>1&&(h+=neume(indices.connecting_line,v.index,x.index)),++o,w=indices.topPartPodatus,v=x,v.episemaLoc=1))}else if(x&&!x.diamond&&(!x.modifiers||x.liq))if(x.relativeTone>0&&x.relativeTone<=5){if(b&&!b.diamond&&(!b.modifiers||"~"==b.modifiers)&&b.relativeTone<0&&b.relativeTone>=-4)if(w=indices.punctum,!b.modifiers&&y&&y.relativeTone>=1&&y.relativeTone<=5)--o,v.episemaLoc=0,x.episemaLoc=0;else{h+=neume(w,v.index);var k=x.index,N=Math.min(v.index,b.index);v.match[rtg.episema]&&c(v.episemaLoc,N,k),v.match[rtg.ictus]&&(f(v.episemaLoc,v.index),v.match[rtg.ictus]=void 0),u(v),x.relativeTone>1&&(h+=neume(indices.connecting_line,v.index,x.index)),"~"==b.modifiers?(--o,w=void 0):(h+=neume(w,x.index),x.match[rtg.episema]&&c(v.episemaLoc,N,k),x.match[rtg.ictus]&&(f(x.episemaLoc,x.index),x.match[rtg.ictus]=void 0),u(x),b.relativeTone<-1&&(h+=neume(indices.connecting_line,b.index,x.index)),v=b,b.match[rtg.episema]&&(v.episemaTone=-1==b.episemaLoc?N:k),"~"==b.modifiers&&(w=indices.lower_tilde),g=3,++o)}else if(x.relativeTone<=5){v.episemaLoc=-1,x.episemaLoc=1,w=indices.topPartPodatus,g=2,b&&b.relativeTone<=0&&(p="-"),x.liq?(h+=neume(indices["<"],v.index),w=indices.upper_tilde):(h+=neume(indices.bottomPartPodatus,v.index),l=!0),u(v),x.relativeTone>1&&(h+=neume(indices.connecting_line,v.index,x.index));var I=v;v=x,x=I}++o}else if(x.relativeTone<0&&x.relativeTone>=-5){if(!v.markings&&b&&!b.diamond&&(!b.modifiers||"~"==b.modifiers)&&b.relativeTone>=1&&b.relativeTone<=4&&x.relativeTone>=-4){if(v.relativeTone>=2&&v.relativeTone<=5)h+=neume(indices.connecting_line,v.index-v.relativeTone,v.index);else if(v.relativeTone<1){var O=Math.max(-x.relativeTone,1);h+=(t.childNodes.length>0?"-":"")+neume(indices.decorative_line,v.index-O,v.index)}"~"==b.modifiers?(--o,h+=neume(w,v.index),u(v),h+=neume(indices.connecting_line,x.index,v.index),w=void 0):(h+=neume(indices.porrectus,v.index,x.index),u(v,x),h+=neume(indices.decorative_line,x.index,b.index),x.episemaLoc=-1,!y||y.relativeTone>=0||y.relativeTone<-5?(w=indices.topPartPodatus,b.episeamLoc=1,v=b,g=3,++o):(w=void 0,b.connectingLine=!0,g=2))}else{if(g=2,x.liq){var O=Math.min(-x.relativeTone,2);h+=neume(indices.decorative_line,v.index-O,v.index),h+=neume(indices[">"],v.index),u(v),w=indices.lower_tilde}else v.relativeTone>0&&v.relativeTone<=5&&("w"==T.modifiers||v.connectingLine)?v.relativeTone>1&&(h+=neume(indices.connecting_line,T.index,v.index)):h+=neume(indices.decorative_line,x.index,v.index),h+=neume(indices.punctum,v.index),v.match[rtg.episema]&&(c(v.episemaLoc,x.index,v.index),g=1),v.match[rtg.ictus]&&(f(v.episemaLoc,v.index),v.match[rtg.ictus]=void 0),x.match[rtg.episema]&&(I=-1==x.episemaLoc?N:k,v.episemaTone=1,-1!=x.episemaLoc&&(x.episemaTone=v.index)),v.match[rtg.dot]&&(x.match[rtg.dot]?1==x.match[rtg.dot].length&&(x.match[rtg.dot]=".."):(h+=neume(indices.dot,v.index),g=1)),u(v);x.relativeTone<-1&&(h+=neume(indices.connecting_line,x.index,v.index));var I=v;v=x,x=I}++o}}var I=neume(w,v.index);if(m>1&&(I=(I+"'").repeat(m).slice(0,-1)),h+=I,v.match[rtg.ictus]&&f(v.episemaLoc,v.index),v.match[rtg.episema]){var I=v.episemaTone||v.index;c(v.episemaLoc,I)}g>1&&(x.match[rtg.ictus]&&f(x.episemaLoc,x.index),x.match[rtg.episema]&&!v.episemaTone&&c(x.episemaLoc,x.index));var L,_;g>1&&(L=Math.min(x.index,v.index),_=Math.max(x.index,v.index),(_-L>=2||L%2==0)&&(L=void 0));var I=v.match[rtg.dot];return I?(h+=v.index==L?neume(indices.dot,L-1):neume(indices.dot,v.index),I=I.length):I=0,x&&(I>1||g>1&&(I=x.match[rtg.dot]))&&(h+=x.index==L?neume(indices.dot,L-1):neume(indices.dot,x.index)),I&&e[o+1]&&(p+="--"),h+=p,w&&u(v),o}}();var gradients={},playTone=function(){console.warn("Audiolet library not loaded.")},playScore=playTone,stopScore=playTone,baseFreq=370;$(function(){$.fn.autoSizeInput=function(e){return e=$.extend({maxWidth:1e3,minWidth:0,comfortZone:0},e),this.filter("input:text").each(function(){var t=e.minWidth||$(this).width(),n="",a=$(this),i=$("<tester/>").css({position:"absolute",top:-9999,left:-9999,width:"auto",fontSize:a.css("fontSize"),fontFamily:a.css("fontFamily"),fontWeight:a.css("fontWeight"),letterSpacing:a.css("letterSpacing"),whiteSpace:"nowrap"}),s=function(){if(n!==(n=a.val())){var s=n.replace(/&/g,"&").replace(/\s/g," ").replace(/</g,"<").replace(/>/g,">");i.html(s);var r=i.width(),l=r+e.comfortZone>=t?r+e.comfortZone:t,o=a.width(),c=o>l&&l>=t||l>t&&l<e.maxWidth;c&&(a.width(l),a.trigger("autoSizeInput"))}};i.insertAfter(a),$(this).bind("keyup blur update",s).bind("keydown",function(e){window.setTimeout(function(){s.apply(this,[e])},1)})}),this};var t=function(){try{var e=new Audiolet,t=function(t,n,a){AudioletGroup.apply(this,[e,0,1]),this.sine=new Sine(e,t),this.gain=new Gain(e,.01*a),this.env=new PercussiveEnvelope(e,1,.3,.3*(n||1),function(){this.audiolet.scheduler.addRelative(0,this.remove.bind(this))}.bind(this)),this.envMulAdd=new Multiply(e,.002*a,0),this.sine.connect(this.gain),this.gain.connect(this.outputs[0]),this.env.connect(this.envMulAdd),this.envMulAdd.connect(this.gain,0,1)};extend(t,AudioletGroup);var n=function(n,a,i){var s=new t(n,a,i);s.connect(e.output)},a={0:0,1:2,2:4,3:5,4:7,5:9,6:11};playTone=function(e,t,i,s){var r=baseFreq;for(t=e==t;0>e;)e+=7,r/=2;for(;e>=7;)e-=7,r*=2;e>0&&(r*=Math.pow(2,(a[e]-(t?1:0))/12)),n(r,i,s)};var i=!1;tempo=150,setTempo=function(e){tempo=e||150},setRelativeTempo=function(e){tempo+=e,0>=tempo&&(tempo=150)};var s;playScore=function(t){for(var n=b,a=t?0:selectedPunctum||0;s&&s.next(););s=new PSequence(n.tones,1,a),i=!0,e.scheduler.setTempo(tempo),e.scheduler.play([s],1,function(t){for(var r;!(i=i&&a<n.tones.length)||!(r=t.play(a));)if(++a,!(t=s.next()))return w(-1),void(i=!1);w(a,!0),r&&e.scheduler.setTempo(tempo/r),++a})},stopScore=function(){i=!1}}catch(r){console.warn(r)}},n=function(){if("function"==typeof Audiolet)try{t()}catch(e){}else $.getScript("audiolet.js",t)};"function"==typeof Sink?n():$.getScript("sink.js",n),0==$("link[href=style\\.css]").length&&$(document.head).append($('<link rel="stylesheet" type="text/css" href="style.css">'));var a=$("#tbl");if(a)for(var i=57568;65535>i;i+=16){var s=document.createElement("row"),r=document.createElement("td"),l=document.createElement("td");r.innerText="0x"+i.toString(16);for(var o="",c=0;16>c;++c)o+=String.fromCharCode(i+c)+"_";l.innerText=o,l.className="caeciliae",s.appendChild(r),s.appendChild(l),a.append(s)}if("function"==typeof document.createElementNS){_svg=svg=document.createElementNS(svgns,"svg"),svg.setAttribute("style","width:100%;height:0"),setPrintFont=function(e){$(svg).find(".caeciliae,.caeciliae-print").attr("class",e?"caeciliae-print":"caeciliae")},_defs=document.createElementNS(svgns,"defs"),defText=make("text",""),defText.setAttribute("class","goudy"),_defs.appendChild(defText),_defText=make("text",""),_defText.setAttribute("class","goudy"),_defs.appendChild(_defText),defChant=make("text","p"),defChant.setAttribute("class","caeciliae"),_defs.appendChild(defChant),defChantSvg=make("text","p"),defChantSvg.setAttribute("class","caeciliaeSvg"),_defs.appendChild(defChantSvg);var f=make("linearGradient");f.setAttribute("gradientUnits","objectBoundingBox"),f.setAttribute("id","gradRedBlack");var d=make("stop");d.setAttribute("offset","0"),d.setAttribute("stop-color","#e22"),f.appendChild(d),d=make("stop"),d.setAttribute("offset","100"),d.setAttribute("stop-color","#000"),f.appendChild(d),gradients.RedBlack=f,f=make("linearGradient"),f.setAttribute("gradientUnits","objectBoundingBox"),f.setAttribute("id","gradBlackRed");var d=make("stop");d.setAttribute("offset","0"),d.setAttribute("stop-color","#000"),f.appendChild(d),d=make("stop"),d.setAttribute("offset","100"),d.setAttribute("stop-color","#e22"),f.appendChild(d),gradients.BlackRed=f;var u;if(staffInFont)u=document.createElementNS(svgns,"text"),u.textContent="'",u.setAttribute("transform","scale(0.5,1)");else{u=document.createElementNS(svgns,"g");var h=1,g=document.createElementNS(svgns,"path"),m="h1v"+h+"h-1zm0 -"+spaceheight;g.setAttribute("d","M0 0"+m.repeat(4)),u.appendChild(g);var p=document.createElementNS(svgns,"g");g=document.createElementNS(svgns,"path"),g.setAttribute("d","M0 "+spaceheight+m),p.appendChild(g),p.setAttribute("id","ledgerb"),_defs.appendChild(p),p=document.createElementNS(svgns,"g"),g=document.createElementNS(svgns,"path"),g.setAttribute("d","M0 "+4*-spaceheight+m),p.appendChild(g),p.setAttribute("id","ledgera"),_defs.appendChild(p)}u.setAttribute("id","staff"),_defs.appendChild(u),svg.appendChild(_defs),textElem=document.createElementNS(svgns,"g"),textElem.setAttribute("transform","translate(0,"+staffoffset+")"),textElem.setAttribute("class","caeciliae"),svg.appendChild(textElem),window.lastClefBeforeNeume=function(e,t){var n,a={clefTone:9};for(n in t.clefs)if(t.clefs.hasOwnProperty(n)){if(!(e>n))break;a=t.clefs[n]}return a},window.lastClefBeforePunctum=function(e,t){var n,a={clefTone:9};for(n in t.clefs)if(t.clefs.hasOwnProperty(n))try{var i=parseInt($(t).find("#neume"+n).children()[0].id.match(/\d+$/)[0]);if(!(e>i))break;a=t.clefs[n].info}catch(s){}return a},window.isPunctumFlat=function(e,t){var n,a=null;for(n in t.accidentals)if(t.accidentals.hasOwnProperty(n)){if(!(e>=n))break;a=t.accidentals[n]}return a};var v=$("#chant-preview,[id$=-preview][for]");if(0==v.length)$(document.body).append(svg);else{v.append(svg),v.append('<input type="text" id="txtSyllableGabc" style="display:none;position:absolute;padding:2px;width:5px;font-family:monospace;font-size:11pt;border:1px solid #aaa" spellcheck="false">'),v.append('<input type="text" id="txtSyllable" class="goudy" style="display:none;position:absolute;padding:2px;width:5px;border:1px solid #aaa" spellcheck="false">'),ToneInfo.prototype.isPlayable=function(){return!this.clef&&!this.accidental&&"number"==typeof this.index},ToneInfo.prototype.play=function(e){var t=b,n=t.timings,a=t.volumes;if(clefIndex=lastClefBeforePunctum(e,t).clefTone,setDuration=n&&n[e],volume=a[e]||100,duration=setDuration||this.match&&(this.match[rtg.dot]||this.match[rtg.episema])?2:(this.match[rtg.virga]||"v").length,longDuration=0,setDuration)duration=setDuration.length,longDuration=duration+(setDuration.restAfter||0);else{if(1==duration){var i=$(t).find("[id=punctum"+(1+e)+"]");i.length&&(i=i[0].tone,i&&i.match[rtg.quilisma]&&(duration=2))}longDuration=duration}return this.clef||this.accidental||"number"!=typeof this.index?!1:(playTone(this.index-clefIndex,isPunctumFlat(e,t),duration,volume),longDuration)};var x=function(e){var t=selectedPunctumTag,n=b,a=$("#"+$(n).parent().attr("for"));if(0==a.length&&(a=$("#editor")),t){var i=t.parentNode,s=selectedPunctum-/^punctum(\d+)$/.exec(i.childNodes[0].id)[1],r=i.neume,l=r.info.tones[s];if(l&&l.match){var o,c,f=l.match[rtg.tone];if(f){var d=l.index+e;if(0>d?d=0:d>12&&(d=12),e=d-l.index,0==e)return;o=String.fromCharCode(f.charCodeAt(0)+e)}else{c=l.match[rtg.clef],f=parseInt(c.slice(-1));var o=f+e;if(1>o?o=1:o>4&&(o=4),e=o-f,0==e)return;c=c.slice(0,-1)+o}var u=a.val(),h=getHeaderLen(u);h+=r.index;var g=u.slice(0,h);u=u.slice(h),h=T(!0);var m=h+l.match[0].length,p=u.slice(0,h);p+=u.slice(h,m).replace(f,o),h=r.gabc.length,p+=u.slice(m,h),u=g+p+u.slice(h),r.gabc=p;var v=r.info,x=r.info=getChantFragment(p,$(n).find("defs")[0]);if(c)for(O in n.clefs[selectedNeume].clefs)if(n.clefs[selectedNeume].clefs.hasOwnProperty(O)){var y=n.clefs[selectedNeume].clefs[O];y.setAttributeNS(xlinkns,"href","#"+c)}stopScore(),x.tones[s].play(selectedPunctum);var w=$(x.def).clone()[0];w.neume=r,w.setAttribute("id",i.id),w.setAttribute("x",i.getAttribute("x")),w.setAttribute("y",i.getAttribute("y")),w.setAttribute("transform",i.getAttribute("transform")),$(i).replaceWith(w),r.wChant=useWidth(w),processLedger(r,w),relayoutChant(n),0==s&&r.custos&&addCustos(r.custos.parentNode,r);var C=w.parentNode,S=C.info.htone,A=C.info.ltone;v.htone<=r.info.htone?C.info.htone=Math.max(C.info.htone,r.info.htone):(C.info.htone=10,$(C).find("[id^=neume]").each(function(){C.info.htone=Math.max(C.info.htone,this.neume.info.htone)})),v.ltone>=r.info.ltone?C.info.ltone=Math.min(C.info.ltone,r.info.ltone):(C.info.ltone=3,$(C).find("[id^=neume]").each(function(){C.info.ltone=Math.min(C.info.ltone,this.neume.info.ltone)}));var k=$(C.parentNode).children("#system0")[0].info.y;if(c||S!=C.info.htone||A!=C.info.ltone)for(var N=finishStaff(C),I=staffoffset+N+verticalSpace+C.info.y,O=parseInt(C.id.match(/\d+$/)[0])+1;C=$(C).siblings("#system"+O)[0];)C.info.y=I,N=finishStaff(C),I=staffoffset+N+verticalSpace+C.info.y,++O;n.setAttribute("height",$(n).children("g")[0].getBBox().height+k+_heightCorrection-_defText.getExtentOfChar("q").height),s=selectedPunctum-s,selectedPunctumTag=null,s=setUpPunctaIn(w,s,n),selectedNeumeTag=w,a.val(u)}}},b=svg,y=function(e){var t=e.firstElementChild,n=t&&parseInt(t.getAttribute("offset"))||0;return e.neume.index+n},T=function(e){if(null!=selectedPunctum&&selectedPunctumTag){var t=selectedPunctumTag,n=selectedPunctum-t.id.match(/^punctum(\d+)$/)[1],a=t.parentNode,i=parseInt(t.getAttribute("offset"))||0,s=parseInt(t.getAttribute("len"))||3;return n&&(i+=s,s=parseInt(t.getAttribute("len1"))),e?i:void selectGabc(a.neume.index+i,s,b)}},w=function(e,t,n){if(n?b=n:n=b,e=parseInt(e),0>e&&(e=-1),e!=selectedPunctum){var a,i=0;if(0>e)t=!0,a=$();else if(a=$(n).find("#punctum"+e),0==a.length&&(i=1,--e,a=$(n).find("#punctum"+e),0==a.length||2!=a.attr("count")))return void(selectedPunctumTag=null);selectedPunctum=e+i,selectedPunctumTag=a[0];var s=a.parent().attr("id");if(s&&(s=/neume(\d+)/i.exec(s)),selectedNeume=s?parseInt(s[1]):-1,selectedNeumeTag=selectedPunctumTag&&selectedPunctumTag.parentNode,selectedNeumeTextTag=$(n).find("#neumetext"+selectedNeume),$(n).find(".selectable").attr("style","").attr("class",function(e,t){return t.replace(/(^|\s+)selected(?=\s+|$)/g,"")}),$(n).find(".neume"+selectedNeume).attr("class",function(e,t){return t+" selected"}),a.attr("class","selectable selected"+(2==a.attr("count")?"-"+(1+i):"")),selectedNeumeTextTag.attr("class","selectable selected"),2==a.attr("count")&&setGradient(a[0],i),!t){stopScore();var r=selectedPunctum-/^punctum(\d+)$/.exec(selectedNeumeTag.childNodes[0].id)[1];selectedNeumeTag.neume.info.tones[r].play(selectedPunctum)}}},C=function(e){var t=$(b).find("#neume"+e+">tspan");return punctumToSelect=/punctum(\d+)/i.exec(t.attr("id")),punctumToSelect?(w(parseInt(punctumToSelect[1]),!0),!0):(selectedNeume=parseInt(e),selectedNeumeTag=$(b).find("#neume"+e).get(0),selectedNeumeTextTag=$(b).find("#neumetext"+e),$(b).find(".selectable").attr("style","").attr("class",function(e,t){return t.replace(/(^|\s+)selected(?=\s+|$)/g,"")}),$(b).find(".neume"+selectedNeume).attr("class",function(e,t){return t+" selected"}),selectedNeumeTextTag.attr("class","selectable selected"),selectedNeumeTag)},S=function(){syllableGabcIndex=-1,syllableGabcPrefix="",syllableGabcSuffix="",syllableGabcOriginalLength=0,$("#txtSyllableGabc").hide()},A=function(){syllableTextIndex=-1,syllableTextPrefix="",syllableTextSuffix="",syllableTextOriginalLength=0,$("#txtSyllable").hide()},k=function(){var e={my:"center bottom",at:"center top",of:selectedNeumeTag,collision:"fit"},t=selectedNeumeTag.neume.info.htone<8.5?8:selectedNeumeTag.neume.info.htone,n=5+(12-t)*staffheight/8;$.ui.version.match(/^1\.8/)?e.offset="0 "+n:e.my+="+"+n,$("#txtSyllableGabc").position(e)},N=function(){var e=syllableTextTag||selectedNeumeTextTag;if(e&&e.length){var t=$("#txtSyllable"),n=t.val(),a=e.text(),i=e.parent(),s=i.offset(),r=parseFloat(i.children().first().attr("x")),l={top:s.top-4,left:s.left-r-3+e.get(0).x.baseVal.getItem(0).value};if(a.slice(0,n.length)!=n){var o=e.children().last(),c=o.text(),f=t.width(),d="-"==c?o.width():textWidth(c.match(/\s*$/)[0]),u=e.width()-d;l.left+=u-f+1}t.offset(l)}},I=function(e){var t,n,a={my:"center bottom",at:"center top",collision:"fit"};if(1==e){a.of=selectedNeumeTag,a.my="left bottom",a.at="right top";var i;$("#txtSyllableGabc").is(":visible")?(syllableGabcPrefix+=$("#txtSyllableGabc").val(),i=syllableGabcSuffix):(syllableGabcPrefix=syllableTextPrefix+$("#txtSyllable").val(),i=syllableTextSuffix);var s=1+i.indexOf(")");0>=s&&(s=i.length),syllableGabcPrefix+=i.slice(0,s)+" (",syllableGabcSuffix=")"+i.slice(s),n="",++selectedNeume,$("#editor").val(syllableGabcPrefix+syllableGabcSuffix).keyup()}else{var r=e||selectedNeumeTag;a.of=r,syllableGabcIndex=y(r),syllableOffsetCorrection&&syllableOffsetCorrection.afterNeume<=selectedNeume&&(syllableGabcIndex+=syllableOffsetCorrection.offset),t=$("#editor").val(),syllableGabcIndex+=getHeaderLen(t);var l=$(r).children().last();if(syllableGabcOriginalLength=r.neume&&""==r.neume.gabc?0:parseInt(l.attr("offset"))+parseInt(l.attr("len")),isNaN(syllableGabcOriginalLength)){var o=/^([^\)]*)\)/.exec(t.slice(syllableGabcIndex));syllableGabcOriginalLength=o?o[1].length:0}n=t.slice(syllableGabcIndex,syllableGabcIndex+syllableGabcOriginalLength),syllableGabcPrefix=t.slice(0,syllableGabcIndex),syllableGabcSuffix=t.slice(syllableGabcIndex+syllableGabcOriginalLength)}tone=a.of.neume.info.htone<8.5?8:a.of.neume.info.htone,a.my+="+"+(5+(12-tone)*staffheight/8),$("#txtSyllableGabc").show().val(n).position(a).trigger("update").select()},O=function(e){var t=e||selectedNeumeTextTag,n=t.get(0),a=$("#txtSyllable");syllableTextIndex=parseInt(n.getAttribute("selectIndex")),syllableOffsetCorrection&&syllableOffsetCorrection.afterNeume<selectedNeume&&(syllableTextIndex+=syllableOffsetCorrection.offset);var i=parseInt(n.getAttribute("selectLen")),s=$("#editor").val();syllableTextIndex+=getHeaderLen(s);var r=s.slice(syllableTextIndex,syllableTextIndex+i);syllableTextPrefix=s.slice(0,syllableTextIndex),syllableTextSuffix=s.slice(syllableTextIndex+i),syllableTextOriginalLength=i,a.show().val(r).trigger("update"),e?syllableTextTag=e:a.select(),N()},L=function(){var e=this.value.length-syllableGabcOriginalLength;syllableOffsetCorrection=0==e?{}:{afterNeume:selectedNeume+.5,offset:e}},_=function(){var e=this.value.length-syllableTextOriginalLength;syllableOffsetCorrection=0==e?{}:{afterNeume:selectedNeume,offset:e}};$(document).on("click","tspan.selectable[id^=punctum]",function(e){w(/punctum(\d+)/i.exec(this.id)[1],!1,$(e.target).parents("svg")[0],!e.altKey),e.altKey&&I()}).on("dblclick","tspan.selectable[id^=punctum]",function(e){w(/punctum(\d+)/i.exec(this.id)[1],!1,$(e.target).parents("svg")[0],!1),I()}).on("mousedown","tspan.selectable[id^=punctum]",function(e){2==e.which&&(w(/punctum(\d+)/i.exec(this.id)[1],!1,$(e.target).parents("svg")[0],!0),I(),e.preventDefault())}).on("click","tspan.selectable[id^=neumetext]",function(){C(/neumetext(\d+)/i.exec(this.id)[1]),gabcSettings.showSyllableEditorOnClick&&O()}).on("mouseenter","tspan.selectable[id^=neumetext]",function(){(gabcSettings.showSyllableEditorOnHover&&!$("#txtSyllable").is(":visible")||syllableTextTag)&&O($(this))}),$("#txtSyllableGabc").on("blur",S).keyup(function(){var e=syllableGabcPrefix+$(this).val()+syllableGabcSuffix;$("#editor").val(e).keyup()}).keydown(function(e){switch(e.which){case 27:this.blur();break;case 40:O(),e.preventDefault();break;case 66:(e.ctrlKey||e.altKey)&&(e.preventDefault(),I(1));break;case 37:this.selectionStart==this.selectionEnd&&0==this.selectionStart&&(C(selectedNeume-1),I(),this.selectionStart=this.value.length,e.preventDefault());break;case 39:this.selectionStart==this.selectionEnd&&this.selectionStart==this.value.length&&(C(selectedNeume+1),I(),this.selectionStart=this.selectionEnd=0,e.preventDefault());break;case 9:C(selectedNeume+(e.shiftKey?-1:1)),I(),e.preventDefault()}}).on("autoSizeInput",k).keydown(function(){var e=this;window.setTimeout(function(){L.apply(e)},1)}).autoSizeInput();var P=function(e,t){selectedNeumeTextTag=[];for(var n=1;n>=0&&0==selectedNeumeTextTag.length&&selectedNeumeTag;)if(n=selectedNeume+e,!C(n)){var a=$("#txtSyllable");return syllableTextPrefix=$("#editor").val()+(t?" ":""),syllableTextSuffix="()",syllableTextOriginalLength=0,void a.show().val("").trigger("update").select()}O()};$("#txtSyllable").on("mouseleave",function(){syllableTextTag&&(syllableTextTag=null,$(this).hide())}).on("blur",A).click(function(){syllableTextTag&&(C(/neumetext(\d+)/i.exec(syllableTextTag.get(0).id)[1]),syllableTextTag=null)}).keydown(internationalTextBoxKeyDown).keyup(function(){var e=syllableTextPrefix+$(this).val()+syllableTextSuffix;$("#editor").val(e).keyup()}).keydown(function(e){switch(e.which){case 27:this.blur();break;case 38:I(),e.preventDefault();break;case 66:(e.ctrlKey||e.altKey)&&I(1);break;case 37:this.selectionStart==this.selectionEnd&&0==this.selectionStart&&(P(-1),this.selectionStart=this.value.length,e.preventDefault());break;case 39:this.selectionStart==this.selectionEnd&&this.selectionStart==this.value.length&&(P(1),this.selectionStart=this.selectionEnd=0,e.preventDefault());break;case 32:this.selectionStart==this.selectionEnd&&this.selectionStart==this.value.length&&(e.preventDefault(),P(1,!0));break;case 9:P(e.shiftKey?-1:1),e.preventDefault()}}).on("autoSizeInput",N).keydown(function(){var t=this;window.setTimeout(function(){_.apply(t,[e])},1)}).autoSizeInput({comfortZone:1});var E=function(e){if(27==e.which)return stopScore(),void S();if(e.target.tagName.match(/textarea|input|select/i))return void("txtSyllableGabc"!=e.target.id&&"txtSyllable"!=e.target.id&&w(-1));var t=selectedPunctum;if(e.ctrlKey){var n=selectedNeume;switch(e.which){case 37:--n;break;case 39:++n;break;case 38:return x(2),void e.preventDefault();case 40:return x(-2),void e.preventDefault();case 13:return void H();case 32:return void playScore();case 107:return void setRelativeTempo(1);case 109:return void setRelativeTempo(-1);default:return}C(n)}else{switch(e.which){case 37:--t;break;case 39:++t;break;case 38:return x(1),void e.preventDefault();case 40:return x(-1),void e.preventDefault();case 13:return I(),void e.preventDefault();case 32:return playScore(!0),void e.preventDefault();case 107:return setRelativeTempo(10),void e.preventDefault();case 109:return setRelativeTempo(-10),void e.preventDefault();default:return}w(t)}};$(document).keydown(E)}var M=[],G=0,D=0;window.updateGabc=updateGabc=function(){var e=$(".jgabc:visible");e.each(function(e,t){var n=$(t),a=n.clone().toggleClass("jgabc jgabc-svg").text("");n.hide(),$(svg).clone().appendTo(a),n.after(a);var i=n.attr("src");i&&(X=200,++G,$.get(i,function(e){n.html(e),++D==G&&(X=0,Y(),F(0,!0,!0))}))}),M=$(".jgabc"),M.length&&setTimeout(Y,500)};var B=null,W=null,F=function(e,t,n){if(H(),B&&clearTimeout(B),!t){var a=500;return void(B=setTimeout(function(){F(null,!0)},a))}B=null,$.each(M,function(e,t){var a=$(t).next(".jgabc-svg").find("svg")[0];a&&(t.innerHTML.match(/^\s*$/)||n&&t.hasSvg||(updateChant(t.innerHTML,a,!0),t.hasSvg=!0))})},U=function(e){if(W&&clearTimeout(W),!e){var t=500;return void(W=setTimeout(function(){U(!0)},t))}W=null;try{relayoutChant(svg)}catch(n){}var a=[];$.each(M,function(e,t){var n=$(t).next(".jgabc-svg").find("svg");0!=n.length&&(n.data("width",n[0].parentNode.clientWidth),a.push(n))}),$.each(a,function(e,t){var n=new Date;relayoutChant(t,t.data("width"));var a=new Date-n;console.info("Relayout chant time: "+a),t.trigger("relayout")})};updateAllChantWidth=navigator.userAgent.match(/\bChrome\b/)?function(){U(!0)}:function(){U()};var H=function(){updateChant($("#editor").val(),svg)};forceUpdateChant=function(){updateChant($("#editor").val(),svg,!0)};var j=function(e){return e.stopPropagation(),e.preventDefault(),!1},K=function(e){return e?(e^16*Math.random()>>e/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,K)},R=function(e){e.stopPropagation(),e.preventDefault();var t,n=$(this),a=e.originalEvent.dataTransfer.files.length,i=uuid&&uuid.v4?uuid.v4():K();for(t=0;a>t;++t){var s=e.originalEvent.dataTransfer.files[t],r=new FileReader;r.onload=function(e){var t=processDraggedFile(e.target.result);1==a&&n.val(t).keyup(),"function"==typeof processGabc&&processGabc(t,i,a)},r.readAsText(s)}};$("#editor").keyup(H).bind("dragover",j).bind("drop",R),$(window).resize(updateAllChantWidth);var z=0,q=0,V=0,Z=0,X=0,Y=function(){svg&&(svg.parentNode&&0==svg.parentNode.clientWidth?setTimeout(Y,100):(z=textWidth("abcdefghijklmnopqrstuvwxyz",fontclass,!0),notewidth=getChantWidth("p"),V=getChantWidth("p p p p p p p p p p p p p p p"),z!=q&&(_txtWidths={},q=z,forceUpdateChant(),F()),V!=Z&&(Z=V,forceUpdateChant(),F()),++X<100&&setTimeout(Y,300)))};setTimeout(Y,100),updateGabc()}});var processDraggedFile=function(e){return e};window.updateChant=updateChant;var neume=_neumeChar,indices=_indicesChar,makeClefSpan=_clefSpanChar,makeInternationalTextBoxKeyDown=function(e){var t={222:{"false":{a:"á",e:"é",i:"í",o:"ó",u:"ú",y:"ý",A:"Á",E:"É",I:"Í",O:"Ó",U:"Ú",Y:"Ý",æ:"ǽ",œ:"oé",Æ:"Ǽ",Œ:"Oé"},"true":{a:"ä",e:"ë",i:"ï",o:"ö",u:"ü",y:"ÿ",A:"Ä",E:"Ë",I:"Ï",O:"Ö",U:"Ü",æ:"aë",œ:"oë",Æ:"Aë",Œ:"Oë"}},69:{"false":{a:"æ",o:"œ",A:"Æ",O:"Œ"},"true":{a:"æ",o:"œ",A:"Æ",O:"Œ"}},8:{"false":{"†":"+",æ:"ae",œ:"oe",Æ:"Ae",Œ:"Oe",á:"a",é:"e",í:"i",ó:"o",ú:"u",ý:"y",Á:"A",É:"E",Í:"I",Ó:"O",Ú:"U",Ý:"Y",ä:"a",ë:"e",ï:"i",ö:"o",ü:"u",ÿ:"y",Ä:"A",Ë:"E",Ï:"I",Ö:"O",Ü:"U",Ǽ:"Aé",ǽ:"aé"},"true":{}}},n={á:"a",é:"e",í:"i",ó:"o",ú:"u",ý:"y",Á:"A",É:"E",Í:"I",Ó:"O",Ú:"U",Ý:"Y",Ǽ:"Æ",ǽ:"æ",áu:"au",oé:"oe",aé:"ae"},a=function(e,a){word="";
for(var i=0;i<e.length;++i)word=a==i?e[i].replace(/((?:[gq]u|i|[^aeiouyáéíóúýæœ])*)([ao][eé]|[aá]u|[aeiouyáéíóúýǽæœ])(?=[^aeiouyáéëíóúýǽæœ]|$)/,function(e,n,a){if(2==a.length){if("u"==a[1])return n+"áu";n+=a[0],a=a[1]}return n+(t[222]["false"][a]||a)})+word:e[i].replace(/((?:[gq]u|i|[^aeiouyáéíóúýæœ])*)(ae|au|oe|[aeiouyáéíóúýǽæœ])(?=[^aeiouyáéëíóúýǽæœ]|$)/,function(e,t,a){return t+(n[a]||a)})+word;return word};return function(n){if("function"==typeof getHeaderLen&&getHeaderLen(this.value)>0){var i=this.value.lastIndexOf("(",this.selectionStart-1),s=this.value.lastIndexOf(")",this.selectionStart-1);if(i>s)return}if(e&&187==n.which&&n.shiftKey){var r=this.selectionStart,l=1;return this.value=this.value.slice(0,r)+"†"+this.value.slice(this.selectionEnd),this.selectionStart=this.selectionEnd=r+l,void n.preventDefault()}var o=$("#cbEnglish")[0]&&cbEnglish.checked;if(49==n.which||50==n.which||51==n.which&&o){var c=2-(n.which-49),f=this.selectionStart,d=this.selectionEnd,u=this.value.lastIndexOf(" ",f)+1,h=this.value.indexOf(" ",d);if(0>h&&(h=this.value.length),o){var g=this.value.slice(u,d).replace(/\*/g,""),m=Syl.syllabify(g),c=m.length-1-c;if(0>c)return;var p=m[c];return g=g.slice(0,p.index)+p.sylnospace+"*"+g.slice(g.indexOf(p.sylnospace,p.index)+p.sylnospace.length),this.value=this.value.slice(0,u)+g+this.value.slice(d),this.selectAndScroll(f,f+g.length,n.shiftKey),void n.preventDefault()}var v=this.value.slice(f,d),m=v.match(regexLatin);m.length>2&&(m=m.reverse(),v=a(m,c),this.value=this.value.slice(0,f)+v+this.value.slice(d),this.selectAndScroll(f,d,n.shiftKey),n.preventDefault())}if(9==n.which||!o&&(49==n.which||50==n.which)){if(o){var x=this.selectionEnd;this.selectionEnd==this.selectionStart&&(x=0,this.scrollTop=0);var b,y,T;if(n.shiftKey){if(b=this.value.slice(0,this.selectionStart),y=splitSentences(b),y.length<2)return;T=y.slice(-2)[0],T&&(x=b.lastIndexOf(T))}else b=this.value.slice(x),y=splitSentences(b),T=y[0],T&&T.length<4&&(T=y[1]),T&&(x+=b.indexOf(T));if(!T)return;var m=Syl.syllabify(T);if(m.length<3)return;var w=m.slice(-1)[0],C=m.slice(-3);if(T.indexOf("*",C[0].index)<0){var S=1==w.word.length?w:C[1];S.separator="*";var A=S.index+S.sylnospace.length;T=T.slice(0,A)+"*"+T.slice(A),this.value=this.value.slice(0,x)+T+this.value.slice(x+T.length-1)}return this.selectAndScroll(x+m.slice(-3)[0].index,x+T.indexOf(w.sylnospace,w.index)+w.sylnospace.length+(w.separator&&w.separator.length||0),n.shiftKey),void n.preventDefault()}var A=n.shiftKey?this.selectionStart:this.selectionEnd;9==n.which&&this.selectionEnd==this.selectionStart&&(A=n.shiftKey?this.value.length:0);for(;;){var k=n.shiftKey?this.value.slice(0,A).reverse():this.value.slice(A),N=k.match(/[a-zæœ]{3,}(?=$|[\s,.;!\?])/i),v=N&&N[0]||"";n.shiftKey&&(v=v.reverse()),n.shiftKey?A-=N.index+v.length:A+=N.index;var m=v.match(regexLatin);if(!m||m.length<=2)n.shiftKey||(A+=v.length);else{var I=v.match(regexLatinLongPenult);if(!I){this.selectAndScroll(A,A+v.length,n.shiftKey),n.preventDefault();break}this.value=this.value.slice(0,A)+a(m.reverse(),1)+this.value.slice(A+=v.length),this.selectAndScroll(A-v.length,A,n.shiftKey)}}}var O=t[n.which];if(O&&this.selectionStart==this.selectionEnd&&this.selectionStart>0){var L=this.value[this.selectionStart-1],_=O[n.shiftKey][L];if(_){var P=this.selectionEnd,l=_.length-1;return this.value=this.value.slice(0,--this.selectionStart)+_+this.value.slice(P),this.selectionStart=this.selectionEnd=P+l,void n.preventDefault()}}}},internationalTextBoxKeyDown=makeInternationalTextBoxKeyDown(!0);