PageSourceSearch

https://miaprep.com/generated/js/website-js.js

js miaprep.com collected 2026-10-07 20:53:19 UTC 407,128 bytes, 145 lines download raw bytes

1function ColorScheme(){this.SecondaryColor="#BEBEBE",this.ContentBackground="white",this.ControlTextColor="white",this.ControlButton="#383838",this.ActiveButton="#66CCCC"}activeDrag={NO:0,YES:1},currentMode={DRAWPOINT:0,FILLSHAPE:1,STAMP:2,LETTER:3,ERASE:4},colorscheme=new ColorScheme;var nativeCreateLinearGradient=CanvasRenderingContext2D.prototype.createLinearGradient;CanvasRenderingContext2D.prototype.createLinearGradient=function(x0,y0,x1,y1){var newGradient=nativeCreateLinearGradient.apply(this,arguments);return newGradient.gradientType=0,newGradient.x0=x0,newGradient.y0=y0,newGradient.x1=x1,newGradient.y1=y1,newGradient.colorStops=[],newGradient};var nativeCreateRadialGradient=CanvasRenderingContext2D.prototype.createRadialGradient;CanvasRenderingContext2D.prototype.createRadialGradient=function(x0,y0,r0,x1,y1,r1){var newGradient=nativeCreateRadialGradient.apply(this,arguments);return newGradient.gradientType=1,newGradient.x0=x0,newGradient.y0=y0,newGradient.x1=x1,newGradient.y1=y1,newGradient.r0=r0,newGradient.r1=r1,newGradient.colorStops=[],newGradient};var dummyContext=document.createElement("canvas").getContext("2d"),nativeAddColorStop=CanvasGradient.prototype.addColorStop;function DesignstudioEditorData(constructionParameters,svgContent){var itemCanvas=document.getElementById("freestyle"),control=document.getElementsByClassName("designstudioEditorControlDiv")[0];if(this.svgContent=svgContent,this.controlWidth=window.getComputedStyle(control,null).getPropertyValue("width").slice(0,-2),this.controlHeight=window.getComputedStyle(control,null).getPropertyValue("height").slice(0,-2),this.paintingWidth=window.getComputedStyle(itemCanvas,null).getPropertyValue("width").slice(0,-2),this.paintingHeight=window.getComputedStyle(itemCanvas,null).getPropertyValue("height").slice(0,-2),this.XScale=1,this.YScale=1,this.paintAllFirstTime=!0,this.saveAjaxUrl=constructionParameters.saveAjaxUrl,this.saveDraftAjaxUrl=constructionParameters.saveDraftAjaxUrl,this.loadDraft=constructionParameters.loadDraft,"true"==this.loadDraft){var tmp=JSON.parse(constructionParameters.draft);this.draft=tmp}this.onSaveRedirectUrl=constructionParameters.onSaveRedirectUrl,this.memberOwnsAShop=constructionParameters.memberOwnsAShop,this.shapeId=constructionParameters.shapeId,this.productionCosts=constructionParameters.productionCosts,this.highestAllowedPrice=constructionParameters.highestAllowedPrice,this.defaultItemName=constructionParameters.defaultItemName,this.emptyPriceMessage=constructionParameters.emptyPriceMessage,this.isSavingInProcess=!1,this.picker=JSON.parse(constructionParameters.picker),this.cursor=new function(constructionParameters){this.eraser=constructionParameters.eraserCursor,this.bucket=constructionParameters.bucketCursor,this.brush=constructionParameters.brushCursor,this.stamp=constructionParameters.stampCursor}(constructionParameters),this.buttonimg=new function(){this.brushButton=constructionParameters.brushButton,this.eraserButton=constructionParameters.eraserButton,this.bucketButton=constructionParameters.bucketButton,this.letterButton=constructionParameters.letterButton,this.stampButton=constructionParameters.stampButton,this.undoButton=constructionParameters.undoButton,this.undoDisabledButton=constructionParameters.undoDisabledButton}}function resizeCanvas(){var canvasWidth=designData.paintingWidth,canvasHeight=designData.paintingHeight,canvaslist=[];canvaslist.push(backgroundCanvas,freestyleCanvas,toppingCanvas,objecthoverCanvas,clicklayer,finalCanvasTmp),designData.XScale=designData.YScale=Math.min(designData.paintingWidth/designitem.width,designData.paintingHeight/designitem.height);for(var i=0;i<canvaslist.length;++i)canvaslist[i].width=canvasWidth,canvaslist[i].height=canvasHeight,canvaslist[i].style.webkitUserSelect="none",canvaslist[i].style.webkitTapHighlightColor="rgba(0,0,0,0)",canvaslist[i].getContext("2d").scale(designData.XScale,designData.YScale);controlCanvas.width=designData.controlWidth,controlCanvas.height=designData.controlHeight,controlCanvas.style.webkitUserSelect="none",finalCanvas.width=designitem.width*designData.XScale,finalCanvas.height=designitem.height*designData.YScale}function styleGradx(){gradX("#gradX",{code_shown:!1,sliders:[{color:"red",position:20},{color:"green",position:50},{color:"blue",position:80}],change:function(stops,styles){1===styles.length&&(document.getElementById("gradXtarget2").style.background=styles[0]);var gradxAddSlider=document.getElementById("gradx_add_slider");stops.length>=controlpanel.maxNumberOfStops?(gradxAddSlider.style.pointerEvents="none",gradxAddSlider.classList.add("disabled"),stops=stops.slice(0,controlpanel.maxNumberOfStops)):(gradxAddSlider.style.pointerEvents="auto",gradxAddSlider.classList.remove("disabled")),controlpanel.chosenColor.colorpickerstatus=[stops,styles]},targets:["#gradXtarget2"]}),document.getElementById("gradx_show_code").classList.add("hidden"),document.getElementById("gradXtable").classList.add("hidden");var x=document.getElementsByClassName("gradx");for(i=0;i<x.length;i++)x[i].style.background=colorscheme.PrimaryColor,x[i].style.border=0;var subtype2=document.getElementById("gradx_gradient_subtype2"),parent=subtype2.parentNode;parent.removeChild(subtype2);var newchild=document.createElement("div");newchild.setAttribute("id","gradx_gradient_subtype2"),newchild.style.width="0px",newc
1hild.style.visibility="hidden",newchild.style.height="0px",parent.appendChild(newchild);var addslider=document.getElementById("gradx_add_slider");addslider.style.background=colorscheme.SecondaryColor,addslider.style.borderColor=colorscheme.SecondaryColor,addslider.style.borderBottomColor=colorscheme.SecondaryColor,addslider.style.color="white";x=document.getElementsByClassName("gradx_gradient_type");for(i=0;i<x.length;i++)x[i].style.background=colorscheme.SecondaryColor,x[i].style.color="white";var i;x=document.getElementsByClassName("gradx_slider");for(i=0;i<x.length;i++)x[i].style.width=20,x[i].style.height=20}CanvasGradient.prototype.addColorStop=function(offset,color){return offset=+offset,dummyContext.fillStyle=color,color=dummyContext.fillStyle,this.colorStops.push([offset,color]),nativeAddColorStop.call(this,offset,color),this},initializeDesignStudio=function(constructionParameters,svgContent){if(document.removeEventListener("DOMContentLoaded",arguments.callee,!1),designData=new DesignstudioEditorData(constructionParameters,svgContent),designitem=new Item,designitem.init(),controlpanel=new ControlPanel,designEventHandler=new DesignstudioEventHandler,finalCanvas=document.getElementById("final"),finalCanvasTmp=document.getElementById("finaltmp"),backgroundCanvas=document.getElementById("background"),freestyleCanvas=document.getElementById("freestyle"),toppingCanvas=document.getElementById("topping"),controlCanvas=document.getElementById("control"),objecthoverCanvas=document.getElementById("objecthover"),clicklayer=document.getElementById("clicklayer"),document.getElementById("clicklayer").style.cursor="url("+designData.cursor.brush+"), auto",document.getElementById("contentcontent_designstudioeditor").style.borderSpacing="0px",document.getElementById("contentcontent_tditem").style.borderTopRightRadius="0px",document.getElementById("contentcontent_tditem").style.borderBottomRightRadius="0px",document.getElementById("contentcontent_tdcontrol").style.borderTopLeftRadius="0px",document.getElementById("contentcontent_tdcontrol").style.borderBottomLeftRadius="0px",activePaint=!1,controlCanvas.addEventListener("mousedown",designEventHandler.control_getPosition,!0),clicklayer.addEventListener("mousedown",designEventHandler.getPosition,!0),clicklayer.addEventListener("mousedown",designEventHandler.letterPosition,!0),clicklayer.addEventListener("mousedown",designEventHandler.objectPositionImage,!0),clicklayer.addEventListener("touchend",designEventHandler.objectPositionImage,!0),clicklayer.addEventListener("touchend",designEventHandler.letterPosition,!0),clicklayer.addEventListener("mousemove",designEventHandler.handlerMousemove,!0),clicklayer.addEventListener("touchmove",designEventHandler.handlerTouchmove,!0),document.addEventListener("mouseup",designEventHandler.paintDeactivate,!1),document.addEventListener("touchend",designEventHandler.paintDeactivate,!1),document.addEventListener("keydown",designEventHandler.selectLetter,!0),(new DesignstudioSaveDialog).initialize(),window.jQuery){for(var $=document,currentDomain=window.location.protocol+"//"+window.location.host+"/",files=["gradx.css"],a=0;a<files.length;++a){var head=$.getElementsByTagName("head")[0],link=$.createElement("link");link.rel="stylesheet",link.type="text/css",link.href=currentDomain.concat("generated/css/",files[a]),link.media="all",head.appendChild(link)}styleGradx(),designEventHandler.importColorFromColorPicker()}if("true"==designData.loadDraft){for(var i=0;i<designData.draft.colors.length;++i)if("object"==typeof designData.draft.colors[i]){var gradient;gradient=0==designData.draft.colors[i].gradientType?dummyContext.createLinearGradient(designData.draft.colors[i].x0,designData.draft.colors[i].y0,designData.draft.colors[i].x1,designData.draft.colors[i].y1):dummyContext.createRadialGradient(designData.draft.colors[i].x0,designData.draft.colors[i].y0,designData.draft.colors[i].r0,designData.draft.colors[i].x1,designData.draft.colors[i].y1,designData.draft.colors[i].r1);for(var c=0;c<designData.draft.colors[i].colorStops.length;++c)gradient.addColorStop(designData.draft.colors[i].colorStops[c][0],designData.draft.colors[i].colorStops[c][1]);designData.draft.colors[i]=gradient}designitem.draft_stash(designData.draft),designitem.draft_pop()}paintAll(),document.getElementById("clicklayer").style.cursor="url("+designData.cursor.brush+"), auto"};
2function DesignstudioSaveDialog(){function createFinalImage(){var ctxFinal=finalCanvas.getContext("2d");ctxFinal.clearRect(0,0,designData.paintingWidth,designData.paintingHeight),ctxFinal.drawImage(backgroundCanvas,0,0),ctxFinal.globalCompositeOperation="source-atop",ctxFinal.drawImage(freestyleCanvas,0,0),designitem.paintShape("finaltmp"),ctxFinal.globalCompositeOperation="source-over",ctxFinal.drawImage(document.getElementById("finaltmp"),0,0)}function saveFreestyleAsImage(name,price,offerItemInShop){if(!designData.isSavingInProcess){designData.isSavingInProcess=!0,createFinalImage(),designitem.draft_stash();var item=designitem.draft_last(),dataUrl=finalCanvas.toDataURL("image/png"),dict2={shapeId:designData.shapeId,imagedataurl:dataUrl,name:name,price:price,draft:JSON.stringify(item),offerItemInShop:offerItemInShop};axios(designData.saveAjaxUrl,{method:"post",headers:{"content-type":"application/x-www-form-urlencoded"},data:dict2}).then((response=>{var data=response.data;data.success&&window.location.replace(designData.onSaveRedirectUrl),designData.isSavingInProcess=!1;var message=data.message;if(message){var inputId=data.inputId;inputId?showError(message,inputId,data.errorElementId):confirmAI(message,(function(){}),(function(){}),!1,!0)}})).finally((()=>{designData.isSavingInProcess=!1}))}}function onConfirmationDialogSave(event){event.preventDefault(),jQuery("#offerInShopCheckBox").is(":checked")?(jQuery("#saveConfirmation").hide(),jQuery("#shopdetails").show(),jQuery("#itemname").focus()):saveFreestyleAsImage("",0,!1)}function onShowSaveDraftOptions(event){event.preventDefault(),jQuery("#saveConfirmation").hide(),jQuery("#draftdetails").show(),jQuery("#draftname").focus()}function onConfirmationDialogSaveDraft(event){event.preventDefault(),createFinalImage(),function(status){if(designitem.draft_stash(),item=designitem.draft_last(),!designData.isSavingInProcess){var params={draft:JSON.stringify(item),shapeid:designData.shapeId,name:jQuery("#draftname").val(),status:status,image:finalCanvas.toDataURL("image/png")};axios(designData.saveDraftAjaxUrl,{method:"post",headers:{"content-type":"application/x-www-form-urlencoded"},data:params}).then((response=>{var data=response.data;if(data.success)window.location.replace(designData.onSaveRedirectUrl);else{designData.isSavingInProcess=!1;var message=data.message;message&&confirmAI(message,(function(){}),(function(){}),!1,!0)}}))}}("USERDRAFT")}function onConfirmationDialogCancel(event){event.preventDefault(),jQuery("#savedialog").modal("hide")}function onShopDialogSave(event){event.preventDefault();var name=jQuery("#itemname").val().trim()||designData.defaultItemName,price=jQuery("#itemprice").val();price.trim()?saveFreestyleAsImage(name,price,!0):showError(designData.emptyPriceMessage,"itemprice","itemPriceError")}function showError(message,inputId,errorElementId){var input=jQuery("#"+inputId),errorElement=jQuery("#"+errorElementId);errorElement.text(message).show(),input.addClass("invalid").on("input.validation",(function(){errorElement.text("").hide(),input.removeClass("invalid").off("input.validation")}))}function onShopDialogCancel(event){event.preventDefault(),jQuery("#saveConfirmation").show(),jQuery("#shopdetails").hide(),jQuery("#savedialog").modal("hide")}this.initialize=function(){jQuery("#confirmationSaveButton").click(onConfirmationDialogSave.bind()),jQuery("#confirmationCancelButton").click(onConfirmationDialogCancel.bind()),jQuery("#showSaveDraftOptionsButton").click(onShowSaveDraftOptions.bind()),jQuery("#confirmationSaveDraftButton").click(onConfirmationDialogSaveDraft.bind()),jQuery("#saveDraftCancelButton").click(onConfirmationDialogCancel.bind()),designData.memberOwnsAShop&&(jQuery("#shopSaveButton").click(onShopDialogSave.bind()),jQuery("#shopCancelButton").click(onShopDialogCancel.bind()))}}
3function ItemDraft(){this.colors=[],this.freepng=null}function Item(){var svgstring="",tmp="",paths=[],colors=[];this.freePoints=[];var draft_history=[];this.clearColors=function(){for(var i=0;i<colors.length;++i)colors[i]="white"},this.extractPathsFromSvg=function(){for(;-1!=tmp.search("<path");){var path=(tmp=tmp.substring(tmp.search("<path"),tmp.length)).substring(0,tmp.search("/>"))+"/>";tmp=tmp.substring(tmp.search("/>")+2,tmp.length),paths.push(path),colors.push("white")}},this.svg_adapt_stroke_width=function(contents,desired_stroke_width){return contents=(contents=(contents=(contents=contents.replace(/stroke-width: ?[^;\"]+/g,"")).replace(/stroke: ?[^;\"]+/g,"stroke:#000000;stroke-width:"+desired_stroke_width.toString())).replace(/stroke-width=\"[^\"]+\"/g,"")).replace(/stroke=\"[^\"]+\"/g,'stroke="#000000" stroke-width="'+desired_stroke_width.toString()+'"')},this.cleanpaths=function(){for(var idx=0;idx<paths.length;++idx)paths[idx]=paths[idx].replace(new RegExp('sodipodi:nodetypes="([c]*)"'),""),paths[idx]=paths[idx].replace(new RegExp('inkscape:connect([^ ]*)="([^ ])"'),"")};this.extractTransformFromSvg=function(){var start=svgstring.search("transform="),tmp=svgstring.substr(start+21,15);this.transform=[],this.transform.push(parseFloat(tmp)),tmp=-1!=tmp.search(",")?tmp.substr(tmp.search(",")+1,20):-1!=tmp.search(" ")?tmp.substr(tmp.search(" ")+1,20):tmp.substr(tmp.substr(1,19).search("-")+1,20),this.transform.push(parseFloat(tmp))},this.width=0,this.height=0,this.extractSizeFromSvg=function(){var start=svgstring.search("width="),stroketest=svgstring.substr(start-7,6);if(-1==start||"stroke"==stroketest)start=svgstring.search("viewB
3ox"),tmp=svgstring.substr(start+13,20),this.width=parseFloat(tmp),tmp=tmp.substr(tmp.search(" "),10),this.height=parseFloat(tmp);else{"mm"==(tmp=(tmp=svgstring.substr(start+7,20)).substring(0,tmp.search('"'))).substr(tmp.length-2,2)?this.width=3.54*parseFloat(tmp):this.width=parseFloat(tmp);var tmp;start=svgstring.search("height=");"mm"==(tmp=(tmp=svgstring.substr(start+8,20)).substring(0,tmp.search('"'))).substr(tmp.length-2,2)?this.height=3.54*parseFloat(tmp):this.height=parseFloat(tmp)}},this.init=function(){svgstring=designData.svgContent,tmp=svgstring,this.extractSizeFromSvg();var desired_stroke_width=3*Math.max(this.width/designData.paintingWidth,this.height/designData.paintingHeight);tmp=this.svg_adapt_stroke_width(tmp,desired_stroke_width),this.extractPathsFromSvg(),this.cleanpaths(),this.extractTransformFromSvg()},this.paintOnCanvas=function(canvasId,x,y,fillNewShapeFlag,newcolor){null==x&&(x=-1),null==y&&(y=-1),null==fillNewShapeFlag&&(fillNewShapeFlag=!1),null==newcolor&&(newcolor="white");var ctx=document.getElementById(canvasId).getContext("2d");ctx.setTransform(designData.XScale,0,0,designData.YScale,designData.XScale*this.transform[0],designData.YScale*this.transform[1]);for(var draft=this.create_draft(),updated=!1,idx=0;idx<paths.length;++idx)canvg(canvasId,paths[idx],{ignoreMouse:!0,ignoreAnimation:!0,ignoreClear:!0}),fillNewShapeFlag&&ctx.isPointInPath(x,y)&&(colors[idx]=controlpanel.chosenColor.getPositioned(x,y),"erase"==colors[idx]&&(colors[idx]="white"),updated=!0),ctx.save(),ctx.setTransform(designData.XScale,0,0,designData.YScale,0,0),ctx.fillStyle=colors[idx],ctx.fill(),ctx.restore();updated&&this.draft_stash(draft)},this.paintShape=function(canvasId){var ctxtop=document.getElementById(canvasId).getContext("2d");ctxtop.setTransform(designData.XScale,0,0,designData.YScale,designData.XScale*this.transform[0],designData.YScale*this.transform[1]),ctxtop.fillStyle="finaltmp"==canvasId?"rgba(0,0,0,0)":"#BEBEBE",ctxtop.fillRect(0,0,designData.paintingWidth/designData.XScale,designData.paintingHeight/designData.YScale);for(var idx=0;idx<paths.length;++idx)ctxtop.globalCompositeOperation="destination-out",canvg(canvasId,paths[idx],{ignoreMouse:!0,ignoreAnimation:!0,ignoreClear:!0}),ctxtop.fill(),ctxtop.globalCompositeOperation="source-over",canvg(canvasId,paths[idx],{ignoreMouse:!0,ignoreAnimation:!0,ignoreClear:!0})},this.create_draft=function(){var draft=new ItemDraft;return draft.colors=colors.slice(),draft.freepng=freestyleCanvas.toDataURL("image/png"),draft},this.draft_history_size=function(){return draft_history.length},this.draft_history_clear=function(){draft_history=[]},this.draft_stash=function(draft){for(draft=void 0!==draft?draft:this.create_draft();draft_history.length>50;)draft_history.shift();draft_history.push(draft),1==this.draft_history_size()&&controlpanel.paintAllControlElements(-1,-1)},this.draft_pop=function(){if(0!=draft_history.length){controlpanel.clearClickHandler(),draft=draft_history.pop(),colors=draft.colors;var freeimg=new Image;freestyleCanvas.getContext("2d").clearRect(0,0,freestyleCanvas.width,freestyleCanvas.height),freeimg.onload=function(){freestyleCanvas.getContext("2d").drawImage(freeimg,0,0,designData.paintingWidth/designData.XScale,designData.paintingHeight/designData.YScale)},freeimg.src=draft.freepng,paintAll()}},this.draft_last=function(){if(0!=draft_history.length)return draft_history[draft_history.length-1]}}
4function DesignstudioEventHandler(){function setClickXandY(event,canvas){var rect,scale=parseFloat(document.getElementById("contentcontent_designstudioeditor").style.transform.substring(6,13));"control"==canvas?(rect=controlCanvas.getBoundingClientRect(),clickcoords={ctrl_x:(event.clientX-rect.left)/scale,ctrl_y:(event.clientY-rect.top)/scale,item_x:-1,item_y:-1}):"item"==canvas&&(rect=clicklayer.getBoundingClientRect(),clickcoords={ctrl_x:-1,ctrl_y:-1,item_x:(event.clientX-rect.left)/designData.XScale/scale,item_y:(event.clientY-rect.top)/designData.YScale/scale},"touchend"==event.type&&(clickcoords.item_x=(event.changedTouches[0].clientX-rect.left)/designData.XScale/scale,clickcoords.item_y=(event.changedTouches[0].clientY-rect.top)/designData.YScale/scale))}function paintMove(event){if(ctx=objecthoverCanvas.getContext("2d"),ctx.clearRect(0,0,designitem.width,designitem.height),setClickXandY(event,"item"),activePaint)addFreePoint(clickcoords.item_x,clickcoords.item_y,!0),paintFreePoints(freestyleCanvas.getContext("2d"),"source-over");else if(controlpanel.letterDrag==activeDrag.YES)repaintItemArea(),ctx=objecthoverCanvas.getContext("2d"),ctx.clearRect(0,0,designitem.width,designitem.height),ctx.fillStyle=controlpanel.chosenColor.get(),ctx.font=(8*controlpanel.brushsize/designData.XScale).toString().concat("px Comic Sans MS"),ctx.fillText(controlpanel.letters[controlpanel.letterIdx],clickcoords.item_x,clickcoords.item_y);else if(controlpanel.imageDrag==activeDrag.YES){repaintItemArea(),ctx=objecthoverCanvas.getContext("2d"),ctx.clearRect(0,0,designitem.width,designitem.height);var img=controlpanel.chosenpicture;ctx.drawImage(img,clickcoords.item_x-8*controlpanel.brushsize/designData.XScale,clickcoords.item_y-8*controlpanel.brushsize/designData.YScale,16*controlpanel.brushsize/designData.XScale,16*controlpanel.brushsize/designData.YScale)}
4}this.letterPosition=function(event){if(controlpanel.letterDrag!=activeDrag.NO){setClickXandY(event,"item"),designitem.draft_stash();var ctx=freestyleCanvas.getContext("2d");ctx.fillStyle=controlpanel.chosenColor.get(),ctx.font=(8*controlpanel.brushsize/designData.XScale).toString().concat("px Comic Sans MS"),ctx.fillText(controlpanel.letters[controlpanel.letterIdx],clickcoords.item_x,clickcoords.item_y),controlpanel.letterDrag=activeDrag.NO,controlpanel.paintAllControlElements(-1,-1)}},this.objectPositionImage=function(event){if(controlpanel.imageDrag!=activeDrag.NO){setClickXandY(event,"item"),designitem.draft_stash();var ctx=freestyleCanvas.getContext("2d"),img=controlpanel.chosenpicture;ctx.drawImage(img,clickcoords.item_x-8*controlpanel.brushsize/designData.XScale,clickcoords.item_y-8*controlpanel.brushsize/designData.YScale,16*controlpanel.brushsize/designData.XScale,16*controlpanel.brushsize/designData.YScale)}},this.getPosition=function(event){setClickXandY(event,"item"),controlpanel.paintMode!=currentMode.DRAWPOINT&&controlpanel.paintMode!=currentMode.ERASE||controlpanel.imageDrag!=activeDrag.NO||controlpanel.letterDrag!=activeDrag.NO?paintAll(clickcoords):(designitem.draft_stash(),addFreePoint(clickcoords.item_x,clickcoords.item_y,!1),activePaint=!0,repaintItemArea())},this.control_getPosition=function(event){setClickXandY(event,"control"),paintAll(clickcoords)},this.importColorFromColorPicker=function(){controlpanel.chosenColor.chooseColorpickerGradient();var ctx=document.getElementById("gradXtarget2").getContext("2d"),width=designitem.width,height=designitem.height;controlpanel.chosenColor.createGradient(ctx,width/2,height/2,width,!1),controlpanel.paintAllControlElements(-1,-1)},this.paintDeactivate=function(event){activePaint=!1},this.selectLetter=function(event){var backup=controlpanel.letterIdx;controlpanel.letterIdx=controlpanel.letters.indexOf(String.fromCharCode(event.keyCode)),-1==controlpanel.letterIdx&&(controlpanel.letterIdx=backup),controlpanel.letterDrag=activeDrag.YES,paintAll()},this.handlerMousemove=function(event){paintMove(event)},this.handlerTouchmove=function(event){event.preventDefault(),event.clientX=event.touches[0].clientX,event.clientY=event.touches[0].clientY,setClickXandY(event,"item"),controlpanel.imageDrag!=activeDrag.NO||controlpanel.letterDrag!=activeDrag.NO||0!=activePaint||controlpanel.paintMode!=currentMode.DRAWPOINT&&controlpanel.paintMode!=currentMode.ERASE||(addFreePoint(clickcoords.item_x,clickcoords.item_y,!1),paintFreePoints(freestyleCanvas.getContext("2d"),"source-over"),activePaint=!0),paintMove(event)}}
5function paintAll(clickcoords){if(designData.paintAllFirstTime&&resizeCanvas(),void 0===clickcoords)clickcoords={ctrl_x:-1,ctrl_y:-1,item_x:-1,item_y:-1};controlpanel.paintAllControlElements(clickcoords.ctrl_x,clickcoords.ctrl_y),repaintItemArea();var fillNewShapeFlag=controlpanel.paintMode==currentMode.FILLSHAPE&&controlpanel.letterDrag==activeDrag.NO&&controlpanel.imageDrag==activeDrag.NO;designitem.paintOnCanvas("background",clickcoords.item_x*designData.XScale,clickcoords.item_y*designData.YScale,fillNewShapeFlag,controlpanel.chosenColor.get()),designData.paintAllFirstTime&&(designitem.paintShape("topping"),designData.paintAllFirstTime=!1)}function repaintItemArea(){if(void 0===clickcoords)var clickcoords={ctrl_x:-1,ctrl_y:-1,item_x:-1,item_y:-1};if(designData.paintAllFirstTime){var ctxtop=toppingCanvas.getContext("2d");ctxtop.fillStyle=colorscheme.ContentBackground,ctxtop.fillRect(0,0,toppingCanvas.width/designData.XScale,toppingCanvas.height/designData.YScale)}paintFreePoints(freestyleCanvas.getContext("2d"),"source-over");var fillNewShapeFlag=controlpanel.paintMode==currentMode.FILLSHAPE&&controlpanel.letterDrag==activeDrag.NO&&controlpanel.imageDrag==activeDrag.NO;designitem.paintOnCanvas("background",clickcoords.item_x*designData.XScale,clickcoords.item_y*designData.YScale,fillNewShapeFlag,controlpanel.chosenColor.get()),designData.paintAllFirstTime&&(designitem.paintShape("topping"),designData.paintAllFirstTime=!1)}function FreePoint(nx,ny,nColor,nDrag,nStrokeSize,nPainted){this.X=nx,this.Y=ny,this.Color=nColor,this.Drag=nDrag,this.StrokeSize=nStrokeSize,this.Painted=nPainted}function addFreePoint(x,y,drag){0==controlpanel.letterDrag&&designitem.freePoints.push(new FreePoint(x,y,controlpanel.chosenColor.get(),drag,controlpanel.brushsize,!1))}var freePointRedrawCache=0;function paintFreePoints(ctxFree,compositeDefault){ctxFree.lineJoin="round",ctxFree.lineWidth=controlpanel.brushsize;for(var idx=freePointRedrawCache;idx<designitem.freePoints.length;++idx)designitem.freePoints[idx].Painted||(designitem.freePoints[idx].Painted=!0,ctxFree.lineWidth=designitem.freePoints[idx].StrokeSize,ctxFree.beginPath(),idx>0&&designitem.freePoints[idx].Drag?ctxFree.moveTo(designitem.freePoints[idx-1].X,designitem.freePoints[idx-1].Y):ctxFree.moveTo(designitem.freePoints[idx].X-1,designitem.freePoints[idx].Y),"erase"==designitem.freePoints[idx].Color?ctxFree.globalCompositeOperation="destination-out":ctxFree.globalCompositeOperation=compositeDefault,ctxFree.strokeStyle=designitem.freePoints[idx].Color,ctxFree.lineTo(designitem.freePoints[idx].X,designitem.freePoints[idx].Y),ctxFree.closePath(),ctxFree.stroke()),++freePointRedrawCache;ctxFree.globalCompositeOperation=compositeDefault}function paintText(ctx,text,x,y,fontOverride){void 0===fontOverride?(ctx.fillStyle="black",ctx.font="10px Comic Sans MS"):ctx.font=fontOverride,ctx.fillText(text,x,y)}function roundRect(ctx,x,y,width,height,radius,fill,stroke){void 0===stroke&&(stroke=!0),void 0===radius&&(radius=5),ctx.beginPath(),ctx.moveTo(x+radius,y),ctx.lineTo(x+width-radius,y),ctx.quadraticCurveTo(x+width,y,x+width,y+radius),ctx.lineTo(x+width,y+height-radius),ctx.quadraticCurveTo(x+width,y+height,x+width-radius,y+height),ctx.lineTo(x+radius,y+height),ctx.quadraticCurveTo(x,y+height,x,y+height-radius),ctx.lineTo(x,y+radius),ctx.quadraticCurveTo(x,y,x+radius,y),ctx.closePath(),stroke&&ctx.stroke(),fill&&ctx.fill()}
6function ControlPanel(){this.controlCanvas=document.getElementById("control"),this.ctx=this.controlCanvas.getContext("2d"),this.width=designData.controlWidth,this.height=designData.paintingHeight,this.maxNumberOfStops=100;var colorPanel=["black","white","#909090","#CFCFCF","#EC654C","#E93F33","#F9DC43","#F29F33","#69D49B","#608C67","#68dede","#49a0a0","#45aff0","#2c82cd","#728ce0","#6463c8","#ec7ca4","#e94f81","#f7cfbf","#f19e8a"];this.letters=["A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z","0","1","2","3","4","5","6","7","8","9"],this.paintMode=currentMode.DRAWPOINT,this.letterIdx=0,this.letterDrag=activeDrag.NO,this.imageDrag=activeDrag.NO,this.imageIdx=[];for(var i=0;i<designData.picker.length;++i)this.imageIdx.push(0);this.chosenpicture=!1,this.brushsize=3,this.pickerImages=[];for(var p=0;p<designData.picker.length;++p){this.pickerImages[p]=[];for(var img=0;img<designData.picker[p].length;++img)this.pickerImages[p][img]=new Image,this.pickerImages[p][img].src=designData.picker[p][img]}this.firstColX=20,this.secondColX=130,this.thirdColX=250,this.brushButton=new ButtonWithImage(this.firstColX,20,90,90,designData.buttonimg.brushButton),this.eraserButton=new ButtonWithImage(this.firstColX,120,90,90,designData.buttonimg.eraserButton),this.bucketButton=new ButtonWithImage(this.firstColX,220,90,90,designData.buttonimg.bucketButton),this.letterButton=new ButtonWithImage(this.firstColX,320,90,90,designData.buttonimg.letterButton),this.stampButton=new ButtonWithImage(this.firstColX,420,90,90,designData.buttonimg.stampButton),this.colorpickerButton=new ButtonWithText(this.thirdColX,425,73,73,"","red"),this.colorpickerButtonText=new ButtonWithText(this.thirdColX,496,73,40,"Edit","#383838"),this.clearButton=new ButtonWithText(this.firstColX-20,550,120,50,"Clear","#383838"),this.undoButton=new ButtonWithImage(this.secondColX-10,550,60,50,designData.buttonimg.undoButton),this.undoDisabledButton=new ButtonWithImage(this.secondColX-10,550,60,50,designData.buttonimg.undoDisabledButton),this.saveButton=new ButtonWithText(this.secondColX+50,550,170,50,"Done","#2CD56D"),this.paintAllControlElements=function(x,y){var grd=this.ctx.createLinearGradient(200,0,200,550);if(grd.addColorStop(0,"#e6e6e6"),grd.addColorStop(1,"#e6e6e6"),this.ctx.fillStyle=grd,this.ctx.fillRect(0,0,this.width,this.height),this.clearButton.paint(this.ctx,x,y,this.clearClickHandler),this.saveButton.paint(this.ctx,x,y,this.saveClickHandler),designitem.draft_history_size()>0?this.undoButton.paint(this.ctx,x,y,this.undoClickHandler):this.undoDisabledButton.paint(this.ctx,x,y,this.undoClickHandler),this.eraserButton.paint(this.ctx,x,y,this.eraserClickHandler),this.bucketButton.paint(this.ctx,x,y,this.bucketClickHandler),this.brushButton.paint(this.ctx,x,y,this.brushClickHandler),this.letterButton.paint(this.ctx,x,y,this.letterClickHandler),this.stampButton.paint(this.ctx,x,y,this.stampClickHandler),this.paintMode!=currentMode.FILLSHAPE&&this.paintBrushsizeMenu(x,y),this.paintMode==currentMode.FILLSHAPE||this.paintMode==currentMode.DRAWPOINT||this.paintMode==currentMode.LETTER
6){this.paintColorMenu(x,y);var gradctx=document.getElementById("gradXtarget2").getContext("2d");if("string"!=typeof this.chosenColor.get()){this.chosenColor.save();var w=this.colorpickerButton.button.width;this.chosenColor.createGradient(gradctx,this.colorpickerButton.button.posx+w/2,this.colorpickerButton.button.posy+w/2,w,!0),this.colorpickerButton.paint(this.ctx,x,y,this.colorpickerClickHandler,this.chosenColor.get()),this.chosenColor.restore()}else this.colorpickerButton.paint(this.ctx,x,y,this.colorpickerClickHandler,this.chosenColor.get());this.colorpickerButtonText.paint(this.ctx,x,y,this.colorpickerClickHandler)}this.paintMode==currentMode.STAMP&&(this.paintImageSelector(0,130,320,x,y),this.paintImageSelector(1,250,320,x,y),this.paintImageSelector(2,250,170,x,y),this.paintImageSelector(3,250,20,x,y)),this.paintMode==currentMode.LETTER&&this.paintLetterBox(x,y),this.highlightActiveTool()},this.paintImageSelector=function(idx,posx,posy,x,y){this.paintImageSelectorBox(x,y,posx,posy,this.pickerImages[idx],idx)},this.highlightActiveTool=function(){this.ctx.save(),this.ctx.fillStyle=colorscheme.ActiveButton;var b=null;switch(this.paintMode){case currentMode.DRAWPOINT:b=this.brushButton;break;case currentMode.STAMP:b=this.stampButton;break;case currentMode.LETTER:b=this.letterButton;break;case currentMode.ERASE:b=this.eraserButton;break;case currentMode.FILLSHAPE:b=this.bucketButton}this.ctx.fillRect(b.button.posx-1,b.button.posy-1,b.button.width+2,b.button.height+2),b.paint(this.ctx,-1,-1,(function(){})),this.ctx.restore()},this.paintImageSelectorBox=function(x,y,posx,posy,imageCollection,ImageBoxId){activePaint=!1;imageCollection[0].onload=function(){controlpanel.ctx.drawImage(this,posx,posy,90,90)},this.paintSelectorBox(x,y,posx,posy,90,90,(function(){this.imageIdx[ImageBoxId]=(this.imageIdx[ImageBoxId]-1+imageCollection.length)%imageCollection.length}),(function(){this.imageIdx[ImageBoxId]=(this.imageIdx[ImageBoxId]+1+imageCollection.length)%imageCollection.length}),(function(){this.letterDrag=activeDrag.NO,this.imageDrag=activeDrag.YES,this.chosenpicture=imageCollection[this.imageIdx[ImageBoxId]]})),this.ctx.drawImage(imageCollection[this.imageIdx[ImageBoxId]],posx,posy,90,90)},this.paintSelectorBox=function(x,y,posx,posy,main_width,height,leftarrowclick,rightarrowclick,mainclick){var arrow_width=main_width/2,arrow_height=main_width/2;this.ctx.beginPath(),this.ctx.fillStyle=colorscheme.SecondaryColor,this.ctx.rect(posx,posy,main_width,height),this.ctx.fill(),this.ctx.isPointInPath(x,y)&&(mainclick.call(this),this.ctx.fillStyle=colorscheme.ContentBackground,this.ctx.rect(posx,posy,main_width,height),this.ctx.fill()),this.ctx.fillStyle=colorscheme.ControlButton,this.ctx.beginPath(),this.ctx.rect(posx,posy+height,arrow_width,arrow_height),this.ctx.fill(),this.ctx.isPointInPath(x,y)&&leftarrowclick.call(this),this.ctx.beginPath(),this.ctx.rect(posx+main_width/2,posy+height,arrow_width,arrow_height),this.ctx.isPointInPath(x,y)&&rightarrowclick.call(this),this.ctx.fill(),this.ctx.font="30px Trebuchet MS",this.ctx.fillStyle=colorscheme.ControlTextColor,this.ctx.fillText("<",posx+15,posy+height+35),this.ctx.fillText(">",posx+main_width/2+15,posy+height+35)},this.paintBrushsizeMenu=function(x,y){var allbrushsizes=[1,3,6,9,12],posx=this.secondColX;this.ctx.save(),this.ctx.fillStyle="#BEBEBE";this.ctx.fillRect(posx,20,90,250),this.ctx.restore(),paintBrush=function(idx,radd){var r=3+3*idx+radd,cx=posx+45,cy=35+18*idx+3*idx+6*idx*idx;this.ctx.beginPath(),this.ctx.rect(cx-45,cy-r,90,2*r),this.ctx.isPointInPath(x,y)&&(this.brushsize=allbrushsizes[idx]),this.ctx.beginPath(),this.ctx.arc(cx,cy,r,0,6.28),this.ctx.fill()}.bind(this);for(var idx=0;idx<allbrushsizes.length;++idx)this.ctx.fillStyle="white",paintBrush(idx,0);this.ctx.fillStyle="#66CCCC",paintBrush(allbrushsizes.indexOf(this.brushsize),6),this.ctx.fillStyle="white",paintBrush(allbrushsizes.indexOf(this.brushsize),0)},this.paintLetterBox=function(x,y){activePaint=!1;var posx=this.secondColX;this.paintSelectorBox(x,y,posx,290,90,90,(function(){this.letterIdx=(this.letterIdx-1+this.letters.length)%this.letters.length}),(function(){this.letterIdx=(this.letterIdx+1)%this.letters.length}),(function(){this.imageDrag=activeDrag.NO,this.letterDrag=activeDrag.YES})),this.ctx.save(),this.ctx.font="50px ABeZeh Mia",this.ctx.textAlign="center",this.ctx.shadowOffsetX=2,this.ctx.shadowOffsetY=2,this.ctx.shadowColor="#323232",this.ctx.fillStyle=this.chosenColor.get(),this.ctx.fillText(this.letters[this.letterIdx],posx+45,350),this.ctx.restore(
6)},this.chosenColor=new function(){this.colorpickerstatus=[],this.type="linear",this.direction="right",this.value="grey",this.valueBackup="grey",this.get=function(){return this.value},this.set=function(v){"erase"==v&&(this.valueBackup=this.value),this.value=v},this.save=function(){this.valueBackup=this.value},this.restore=function(){this.value=this.valueBackup},this.getPositioned=function(x,y){return-1!=colorPanel.indexOf(this.value)||this.createGradient(ctx,x,y),this.value};var colorstops=[];this.addColorStop=function(a,b){var pair=[a,b];colorstops.push(pair)},this.clearColorStops=function(){colorstops=[]},this.chooseColorpickerGradient=function(){this.clearColorStops();for(var i=0;i<this.colorpickerstatus[0].length;++i)this.addColorStop(1-this.colorpickerstatus[0][i][1]/100,this.colorpickerstatus[0][i][0]);var oLinearGradient=this.colorpickerstatus[1][3];oLinearGradient&&(-1!==oLinearGradient.indexOf("radial")?this.type="radial":(this.type="linear",-1!==oLinearGradient.indexOf("top")?this.direction="top":-1!==oLinearGradient.indexOf("right")?this.direction="right":-1!==oLinearGradient.indexOf("bottom")?this.direction="bottom":-1!==oLinearGradient.indexOf("left")&&(this.direction="left")))},this._dynamicGradient=function(x,y,width,tmpctx,scaleoverride){var usectx,gradient;usectx=void 0===tmpctx?ctx:tmpctx,void 0===width&&(width=200);var xScaled=scaleoverride?x:x/designData.XScale,yScaled=scaleoverride?y:y/designData.YScale;"linear"==this.type?("right"==this.direction&&(gradient=usectx.createLinearGradient(xScaled+width/2,0,xScaled-width/2,0)),"bottom"==this.direction&&(gradient=usectx.createLinearGradient(0,yScaled-width/2,0,yScaled+width/2)),"top"==this.direction&&(gradient=usectx.createLinearGradient(0,yScaled+width/2,0,yScaled-width/2)),"left"==this.direction&&(gradient=usectx.createLinearGradient(xScaled-width/2,0,xScaled+width/2,0))):gradient=usectx.createRadialGradient(xScaled,yScaled,0,xScaled,yScaled,width/2);for(var i=0;i<colorstops.length;++i)gradient.addColorStop(colorstops[i][0],colorstops[i][1]);return gradient},this.createGradient=function(tmpctx,x,y,width,scaleoverride){return void 0===tmpctx&&(tmpctx=document.getElementById("gradXtarget2").getContext("2d")),void 0===x&&(x=50),void 0===y&&(y=50),void 0===width&&(width=200),void 0===scaleoverride&&(scaleoverride=!1),this.value=this._dynamicGradient(x,y,width,tmpctx,scaleoverride),!1}},this.paintColorMenu=function(x,y){for(var posx=this.thirdColX,paintSelectorBox=function(idx,sadd){var square_posx=posx+idx%2*39,square_posy=20+(idx-idx%2)/2*39;this.ctx.beginPath(),this.ctx.rect(square_posx,square_posy,34,34),this.ctx.isPointInPath(x,y)&&this.chosenColor.set(colorPanel[idx]),this.ctx.fillRect(square_posx-sadd/2,square_posy-sadd/2,34+sadd,34+sadd)}.bind(this),idx=0;idx<colorPanel.length;++idx)this.ctx.fillStyle=colorPanel[idx],paintSelectorBox(idx,0);-1!=(idx=colorPanel.indexOf(this.chosenColor.get()))&&(this.ctx.fillStyle="#323232",paintSelectorBox(idx,10),this.ctx.fillStyle=colorPanel[idx],paintSelectorBox(idx,0))},this.eraserClickHandler=function(){controlpanel.letterDrag=activeDrag.NO,controlpanel.imageDrag=activeDrag.NO,controlpanel.chosenColor.set("erase"),document.getElementById("clicklayer").style.cursor="url("+designData.cursor.eraser+"),auto",controlpanel.paintMode=currentMode.ERASE},this.bucketClickHandler=function(){controlpanel.switchMode(currentMode.FILLSHAPE)},this.brushClickHandler=function(){controlpanel.switchMode(currentMode.DRAWPOINT)},this.stampClickHandler=function(){controlpanel.switchMode(currentMode.STAMP)},this.letterClickHandler=function(){controlpanel.switchMode(currentMode.LETTER)},this.clearClickHandler=function(){designitem.freePoints=[],designitem.clearColors(),ctxFree=freestyleCanvas.getContext("2d"),ctxFree.clearRect(0,0,designitem.width,designitem.height),freePointRedrawCache=0},this.undoClickHandler=function(){designitem.draft_pop()},this.saveClickHandler=function(){jQuery("#savedialog").modal("show")},this.colorpickerClickHandler=function(){document.getElementById("gradXtable").classList.remove("hidden")},this.switchMode=function(newMode){switch(this.letterDrag=activeDrag.NO,this.imageDrag=activeDrag.NO,this.paintMode==currentMode.ERASE&&this.chosenColor.restore(
6),this.paintMode=newMode,this.paintMode){case currentMode.ERASE:document.getElementById("clicklayer").style.cursor="url("+designData.cursor.eraser+"),auto";break;case currentMode.FILLSHAPE:document.getElementById("clicklayer").style.cursor="url("+designData.cursor.bucket+"),auto";break;case currentMode.DRAWPOINT:document.getElementById("clicklayer").style.cursor="url("+designData.cursor.brush+"),auto";break;case currentMode.LETTER:this.letterDrag=activeDrag.YES,document.getElementById("clicklayer").style.cursor="url("+designData.cursor.stamp+"),auto";break;case currentMode.STAMP:document.getElementById("clicklayer").style.cursor="url("+designData.cursor.stamp+"),auto"}}}function CanvasButton(_posx,_posy,_width,_height){this.posx=_posx,this.posy=_posy,this.width=_width,this.height=_height,this.paint=function(ctx,x,y,clickhandler){ctx.beginPath(),ctx.rect(this.posx,this.posy,this.width,this.height),ctx.isPointInPath(x,y)&&clickhandler()}}function ButtonWithImage(_posx,_posy,_width,_height,_filename){this.button=new CanvasButton(_posx,_posy,_width,_height),this.img=new Image,this.src=_filename,this.paint=function(ctx,x,y,clickhandler){this.img.src!=this.src?(this.img.onload=function(){ctx.drawImage(this.img,this.button.posx,this.button.posy,this.button.width,this.button.height)}.bind(this),this.img.src=this.src):ctx.drawImage(this.img,this.button.posx,this.button.posy,this.button.width,this.button.height),this.button.paint(ctx,x,y,clickhandler)}}function ButtonWithText(_posx,_posy,_width,_height,_heading,specialBackgroundColor){this.button=new CanvasButton(_posx,_posy,_width,_height),this.heading=_heading,this.backgroundColor=null==specialBackgroundColor?colorscheme.SecondaryColor:specialBackgroundColor,this.paint=function(ctx,x,y,clickhandler,specialBackgroundColor){null!=specialBackgroundColor&&(this.backgroundColor=specialBackgroundColor),ctx.save(),ctx.lineWidth=0,this.button.paint(ctx,x,y,clickhandler),this.paintText(ctx,this.heading,this.button.posx+this.button.width/2-25,this.button.posy+30),ctx.restore()},this.paintText=function(ctx,text,x,y){ctx.fillStyle=this.backgroundColor,roundRect(ctx,this.button.posx,this.button.posy,this.button.width,this.button.height,0,!0,0),ctx.fillStyle="white",ctx.font="14px ABeZeh Mia",ctx.textAlign="center",ctx.fillText(text,_posx+_width/2,_posy+_height/2+5)}}
7function scaleToContainerWidth(){jQuery(".mia-js-scaleToContainerWidth").each((function(index,element){var scalingFactor=(element=jQuery(element)).parent().width()/element.width();element.css({transform:"scale("+scalingFactor+")","transform-origin":"0 0","margin-bottom":element.height()*(scalingFactor-1)})}))}jQuery(document).ready(scaleToContainerWidth),jQuery(window).on("resize",scaleToContainerWidth),jQuery(window).on("orientationchange",scaleToContainerWidth);
8function scaleParentHeigthToMaximumOfChildrenHeights(event){var childHeight,parent=jQuery(event.data.blockForWhomChangeHeight),maxHeight=-1;if(jQuery(event&&event.data.searchRoot||parent).children(":visible").length)jQuery(event&&event.data.searchRoot||parent).children(":visible").each((function(index,element){jQuery(element).each((function(){(childHeight=this.getBoundingClientRect().height)>maxHeight&&(maxHeight=childHeight)}))})),-1!==maxHeight&&parent.height(maxHeight),showDataBelow();else var intervalId=setInterval((function(){jQuery(event&&event.data.searchRoot||parent).children(":visible").length&&(clearInterval(intervalId),trackAllScaleHeightToAbsoluteChildrenElements())}),50)}function trackAllScaleHeightToAbsoluteChildrenElements(){var elementsToChangeHeightFor=jQuery(".mia-js-scaleHeightToAbsoluteChildren");jQuery.each(elementsToChangeHeightFor,(function(index,value){scaleParentHeigthToMaximumOfChildrenHeights({data:value.dataset&&value.dataset.searchroot?{blockForWhomChangeHeight:value,searchRoot:value.dataset.searchroot}:{blockForWhomChangeHeight:value}})}))}function showDataBelow(){jQuery(".mia-u-initiallyHidden.mia-dataBelowDynamicallyComputedElement").show()}window.addEventListener("load",trackAllScaleHeightToAbsoluteChildrenElements),jQuery(window).on("resize",trackAllScaleHeightToAbsoluteChildrenElements);
9function encloseModalInWindow(windowClass){jQuery(".modal-backdrop").appendTo("."+windowClass);var bodyJQuery=jQuery("body");bodyJQuery.removeClass("modal-open"),bodyJQuery.css("padding-right",0)}function removeFocusFromModalInWindow(modalId){jQuery(".modal[modal-id='"+modalId+"']").on("shown.bs.modal",(function(){jQuery(document).off("focusin.modal")}))}
10!function($){$(document).ready((function(){new MobileDetect(window.navigator.userAgent).mobile()?$("body").addClass("mia-js-mobile"):$("body").addClass("mia-js-desktop")}))}(jQuery);
11var MiniworldHouseWall=function(name,canvas,polygon,upperLeft,allTextures,color,textureIndex){this.category="WALL",this.name=name,this.canvas=canvas,this.polygon=polygon,this.upperLeft=upperLeft,this.allTextures=allTextures,this.color=color,this.textureIndex=textureIndex,this.texture=this.allTextures[textureIndex],this.draw=function(){var context=this.canvas.getContext("2d");context.beginPath(),miniworldHouseCanvasHelper.moveToPoint(context,polygon[polygon.length-1]);for(var i=0;i!=polygon.length;++i)miniworldHouseCanvasHelper.lineToPoint(context,polygon[i]);context.fillStyle=this.color,context.fill(),context.closePath(),this.texture&&context.drawImage(this.texture,this.upperLeft.x,this.upperLeft.y,this.texture.width,this.texture.height)},this.setTexture=function(textureIndex){this.textureIndex=textureIndex,this.texture=this.allTextures[textureIndex]},this.doesAcceptInteraction=function(pointerX,pointerY){return miniworldHouseGeometry.polygonCheck({x:pointerX,y:pointerY},this.polygon)},this.colorMoveInteraction=function(pointerX,pointerY){if(this==miniworldHouseColorPicker.activeObject){var color=miniworldHouseColorPicker.getColor(pointerX,pointerY),textureIndex=miniworldHouseColorPicker.getTexture(pointerX,pointerY);null!==color&&(this.color=color),null!==textureIndex&&this.setTexture(textureIndex),this.draw(),miniworldHouseColorPicker.draw()}}};MiniworldHouseWall.textureNumbers={left:6,right:6,ceiling:0,floor:3,back:6},MiniworldHouseWall.loadRoomWalls=function(canvas,wallTextures,wallColors){var j,textures,texture,walls={};for(var wallName in wallTextures)if(wallTextures.hasOwnProperty(wallName)){for(textures=[null],j=1;j<=MiniworldHouseWall.textureNumbers[wallName];++j)texture=document.createElement("img"),textures.push(texture);var wall=new MiniworldHouseWall(wallName,canvas,miniworldHouseGeometry.wallPolygon[wallName],miniworldHouseGeometry.wallUpperLeft[wallName],textures,wallColors[wallName],wallTextures[wallName]);for(null!==textures[wallTextures[wallName]]?textures[wallTextures[wallName]].onload=wall.draw.bind(wall):wall.draw(),j=1;j<=MiniworldHouseImages.patterns[wallName].length;++j)textures[j].src=MiniworldHouseImages.patterns[wallName][j-1];walls[wallName]=wall}return walls},MiniworldHouseWall.serializeRoomWalls=function(walls){var colors={},textures={};for(var wallName in walls)walls.hasOwnProperty(wallName)&&(colors[wallName]=walls[wallName].color,textures[wallName]=walls[wallName].textureIndex);return{colors:colors,textures:textures}},MiniworldHouseWall.drawWallLines=function(canvas){var context=canvas.getContext("2d");context.clearRect(0,0,canvas.width,canvas.height),context.beginPath(),miniworldHouseCanvasHelper.moveToPoint(context,miniworldHouseGeometry.cornerTopLeft),miniworldHouseCanvasHelper.lineToPoint(context,miniworldHouseGeometry.topLeft),miniworldHouseCanvasHelper.lineToPoint(context,miniworldHouseGeometry.topRight),miniworldHouseCanvasHelper.lineToPoint(context,miniworldHouseGeometry.cornerTopRight),miniworldHouseCanvasHelper.moveToPoint(context,miniworldHouseGeometry.topRight),miniworldHouseCanvasHelper.lineToPoint(context,miniworldHouseGeometry.bottomRight),miniworldHouseCanvasHelper.lineToPoint(context,miniworldHouseGeometry.cornerBottomRight),miniworldHouseCanvasHelper.moveToPoint(context,miniworldHouseGeometry.bottomRight),miniworldHouseCanvasHelper.lineToPoint(context,miniworldHouseGeometry.bottomLeft),miniworldHouseCanvasHelper.lineToPoint(context,miniworldHouseGeometry.cornerBottomLeft),miniworldHouseCanvasHelper.moveToPoint(context,miniworldHouseGeometry.bottomLeft),miniworldHouseCanvasHelper.lineToPoint(context,miniworldHouseGeometry.topLeft),context.globalAlpha=.5,context.stroke(),context.globalAlpha=1,context.closePath();var shadowImage=document.createElement("img");shadowImage.onload=function(){context.drawImage(shadowImage,0,0,canvas.width,canvas.height)},shadowImage.src=MiniworldHouseImages.shadow};
12var MiniworldHouseSaveTimer=function(saveFunction){this.saveFunction=saveFunction,this.timer=null,this.timerInterval=2500,this.stopTimer=function(){null!==this.timer&&(window.clearTimeout(this.timer),this.timer=null)},this.saveNow=function(){this.stopTimer(),this.saveFunction()},this.saveAfterInterval=function(){this.stopTimer(),this.timer=window.setTimeout(this.saveNow.bind(this),this.timerInterval)}},miniworldHouseSaveTimer=null;
13var MiniworldHouseRoom=function(wallCanvasZIndex,zIndexOffset){this.wallCanvas=miniworldHouseCanvasHelper.createCanvas(null,wallC
13anvasZIndex),this.itemDiv=document.createElement("div"),MiniworldHouseRoom.zIndexOffset=zIndexOffset,this.id=null,this.name=null,this.editable=!1,this.itemManager=null,this.changedSinceSave=!1,this.state=MiniworldHouseRoom.interactionStates.NO_INTERACTION,this.load=function(response){var representation=response.data;this.id=representation.id,this.name=representation.name||representation.unnamed,this.unnamed=representation.unnamed,this.emptyRoomNameMessage=representation.emptyRoomNameMessage,this.editable=representation.editable,this.parentId=representation.parentId,this.itemManager=new MiniworldHouseItemManager(this.itemDiv,zIndexOffset,representation.level),this.itemManager.loadRoomItems(representation.items,representation.doors),this.walls=MiniworldHouseWall.loadRoomWalls(this.wallCanvas,representation.settings.textures,representation.settings.colors)},this.serialize=function(){var representation=this.itemManager.serializeRoomItems();return representation.settings=JSON.stringify(MiniworldHouseWall.serializeRoomWalls(this.walls)),representation.id=this.id,representation.name=this.name,representation},this.onShow=function(){this.state=MiniworldHouseRoom.interactionStates.NO_INTERACTION,MiniworldHouseRoom.zIndexBeforeCurrent=this.zIndexBefore.bind(this)},this.draggedItem=function(){return this.itemManager.draggedItem},this.startInteraction=function(pointerX,pointerY){switch(this.state){case MiniworldHouseRoom.interactionStates.NO_INTERACTION:null!==this.itemManager.tryToDragItem(pointerX,pointerY)&&(this.state=MiniworldHouseRoom.interactionStates.ITEM_INTERACTION);break;case MiniworldHouseRoom.interactionStates.PREVIEW_DOOR_INTERACTION:this.startToPlacePreviewDoor();break;case MiniworldHouseRoom.interactionStates.COLOR_INTERACTION:if(null===miniworldHouseColorPicker.activeObject){var draggedObject=this.itemManager.tryToDragItem(pointerX,pointerY);null==draggedObject?(draggedObject=this.getWallForInteraction(pointerX,pointerY),miniworldHouseColorPicker.activeObject=draggedObject,miniworldHouseColorPicker.drawPicker(pointerX,pointerY)):draggedObject.type===miniworldHouseItem.itemType.DOOR?(miniworldHouseColorPicker.activeObject=draggedObject,miniworldHouseColorPicker.drawPicker(pointerX,pointerY)):MiniworldHouseInstance.menu.colorMode.clickInteraction()}else miniworldHouseColorPicker.startInteraction(pointerX,pointerY)}},this.getWallForInteraction=function(pointerX,pointerY){for(var wallName in this.walls)if(this.walls.hasOwnProperty(wallName)){var wall=this.walls[wallName];if(wall.doesAcceptInteraction(pointerX,pointerY))return wall}},this.startToPlacePreviewDoor=function(){this.draggedItem().state=MiniworldHouseDoorItem.interactionStates.CLICKED},this.moveInteraction=function(pointerX,pointerY){switch(this.state){case MiniworldHouseRoom.interactionStates.ITEM_INTERACTION:this.changedSinceSave=!0,this.itemManager.moveInteraction(pointerX,pointerY);break;case MiniworldHouseRoom.interactionStates.PREVIEW_DOOR_INTERACTION:this.itemManager.moveInteraction(pointerX,pointerY);break;case MiniworldHouseRoom.interactionStates.COLOR_INTERACTION:miniworldHouseColorPicker.activated&&null!=miniworldHouseColorPicker.activeObject&&miniworldHouseColorPicker.activeObject.colorMoveInteraction(pointerX,pointerY)}},this.endInteraction=function(pointerX,pointerY){switch(this.state){case MiniworldHouseRoom.interactionStates.ITEM_INTERACTION:this.itemManager.placeItemInteraction(pointerX,pointerY);break;case MiniworldHouseRoom.interactionStates.PREVIEW_DOOR_INTERACTION:this.draggedItem().state!=MiniworldHouseDoorItem.interactionStates.PREVIEW&&this.tryToPlaceNewDoor();break;case MiniworldHouseRoom.interactionStates.COLOR_INTERACTION:miniworldHouseColorPicker.endInteraction(pointerX,pointerY),this.changedSinceSave=!0}this.changedSinceSave&&miniworldHouseSaveTimer.saveAfterInterval(),this.state!=MiniworldHouseRoom.interactionStates.PREVIEW_DOOR_INTERACTION&&this.state!=MiniworldHouseRoom.interactionStates.COLOR_INTERACTION&&(this.state=MiniworldHouseRoom.interactionStates.NO_INTERACTION)},this.tryToDeleteItem=function(){var tr,itemToDelete=this.draggedItem();tr=itemToDelete.type==miniworldHouseItem.itemType.DOOR?MiniworldHouseTR.tr_deleteRoom:MiniworldHouseTR.tr_deleteItem,confirmAI(tr,function(){itemToDelete.type==miniworldHouseItem.itemType.DOOR?miniworldHouseCommunication.deleteRoom(itemToDelete.linkedRoom):(console.log(itemToDelete),miniworldHouseCommunication.deleteItem(itemToDelete.instanceId)),this.itemManager.removeItemInteraction(),MiniworldHouseInstance.menu.deleteDoor.hide(),this.state=MiniworldHouseRoom.interactionStates.NO_INTERACTION}.bind(this),(function(){}),!0,!0)},this.tryToPlaceNewDoor=function(){this.draggedItem().isPlaceable()&&(miniworldHouseTryToBuyNewRoom(this.draggedItem().lastV
13alidX),this.itemManager.removeItemInteraction(),this.state=MiniworldHouseRoom.interactionStates.NO_INTERACTION)},this.placeItemFromInventory=function(item){var positionY,newItem=this.itemManager.loadItem(item),positionX=(miniworldHouseGeometry.frameBottomLeft.x+miniworldHouseGeometry.frameBottomRight.x)/2;positionY=newItem.type===miniworldHouseItem.itemType.FLOOR?miniworldHouseGeometry.bottomLeft.y+3*(miniworldHouseGeometry.frameBottomLeft.y-miniworldHouseGeometry.bottomLeft.y)/4:miniworldHouseGeometry.topLeft.y+(miniworldHouseGeometry.bottomLeft.y-miniworldHouseGeometry.topLeft.y)/2,item.positionx=newItem.lastValidX=newItem.posX=parseInt(positionX),item.positiony=newItem.lastValidY=newItem.posY=parseInt(positionY),newItem.draw(miniworldHouseItem.displayMode.DISPLAY,null,null),this.itemManager.resortLayers()},this.storeItemInInventory=function(){miniworldHouseCommunication.storeItemInInventory(this.draggedItem().instanceId),this.itemManager.removeItemInteraction(),this.state=MiniworldHouseRoom.interactionStates.NO_INTERACTION},this.zIndexBefore=function(){return this.itemManager.zIndexOffset+this.itemManager.layerOrder.length},this.switchColorState=function(){return this.state==MiniworldHouseRoom.interactionStates.NO_INTERACTION?(this.state=MiniworldHouseRoom.interactionStates.COLOR_INTERACTION,!0):(this.state=MiniworldHouseRoom.interactionStates.NO_INTERACTION,miniworldHouseColorPicker.hide(),!1)},miniworldHousePreviewDoor=function(){this.state=MiniworldHouseRoom.interactionStates.PREVIEW_DOOR_INTERACTION,this.itemManager.createPreviewDoor()}.bind(this),miniworldHouseAbortPreviewDoor=function(){this.itemManager.removeItemInteraction(),this.state=MiniworldHouseRoom.interactionStates.NO_INTERACTION}.bind(this)};MiniworldHouseRoom.interactionStates={NO_INTERACTION:"NOINTERACTION",COLOR_INTERACTION:"COLORINTERACTION",ITEM_INTERACTION:"ITEMINTERACTION",PREVIEW_DOOR_INTERACTION:"PREVIEWDOORINTERACTION"},MiniworldHouseRoom.zIndexOffset=0,MiniworldHouseRoom.zIndexBeforeCurrent=function(){return MiniworldHouseRoom.zIndexOffset};var miniworldHousePreviewDoor=function(){},miniworldHouseAbortPreviewDoor=function(){};
14var MiniworldHouseMenu=function(editableRoom,options){this.options=options,this.editableRoom=editableRoom,this.menu=[],this.menuCounter=0,this.addToMenu=function(element){this.menu[this.menuCounter]=element,this.menuCounter++},this.doorBack=new MiniworldHouseIcon("Exit-Icon",MiniworldHouseDoorBack,this.options),this.addToMenu(this.doorBack),this.editableRoom&&(this.doorAdd=new MiniworldHouseIcon("Add-Icon",MiniworldHouseDoorAdd,this.options),this.addToMenu(this.doorAdd),this.deleteDoor=new MiniworldHouseIcon("Delete-Icon",MiniworldHouseDeleteItem,this.options),this.deleteDoor.hide(),this.addToMenu(this.deleteDoor),this.colorMode=new MiniworldHouseIcon("ColorMode-Icon",MiniworldHouseColorMode,this.options),this.addToMenu(this.colorMode),this.inventory=new MiniworldHouseIcon("Inventory-Icon",MiniworldHouseInventory,this.options),this.addToMenu(this.inventory)),this.touchStartInteraction=function(event){for(var i=0;i<this.menu.length;i++)this.menu[i].touchStartInteraction(event)},this.touchMoveInteraction=function(event){for(var i=0;i<this.menu.length;i++)this.menu[i].touchMoveInteraction(event)},this.touchEndInteraction=function(event){for(var i=0;i<this.menu.length;i++)this.menu[i].touchEndInteraction(event)}};MiniworldHouseMenu.type={DOORBACK:"DOORBACK",DOORADD:"DOORADD",INVENTORY:"INVENTORY",DELETEDOOR:"DELETEDOOR",COLORMODE:"COLORMODE",NONE:"NONE"};
15var MiniworldHouseImages={},MiniworldHouseInstance=null,MiniworldHouse=function(canvasDivId,options){MiniworldHouseInstance=this,MiniworldHouseImages.patterns=JSON.parse(options.patterns),MiniworldHouseImages.shadow=options.shadowimage,MiniworldHouseImages.door=options.doorimage,MiniworldHouseImages.colorpickerspectrum=options.colorpickerspectrumimage,MiniworldHouseImages.closeicon=options.closeiconimage,MiniworldHouseImages.colorpickerwalltextures=JSON.parse(options.colorpickerwalltextures),MiniworldHouseImages.colorpickerfloortextures=JSON.parse(options.colorpickerfloortextures),this.canvasDiv=document.getElementById(canvasDivId),this.options=options,this.editableRoom=this.options.editable,this.editableRoom||(document.getElementById("Inventory-Icon").style.display="none",document.getElementById("Delete-Icon").style.display="none"),this.zIndexOffset=3,MiniworldHouseRoom.zIndexOffset=this.zIndexOffset,this.wallLinesCanvas=miniworldHouseCanvasHelper.createCanvas(this.canvasDiv,this.zIndexOffset-2),this.colorPickerCanvas=miniworldHouseCanvasHelper.createCanvas(this.canvasDiv,100),MiniworldHouseWall.drawWallLines(this.wallLinesCanvas),this.rooms={},this.getRoomFromResponse=function(response){var id=response.data.id,room=new MiniworldHouseRoom(this.zIndexOffset-3,this.zIndexOffset);return this.rooms[id]=room,room.load(response),room},this.loadRoomWithId=function(id,callBack){this.rooms.hasOwnProperty[id]||miniworldHouseCommunication.loadRoom(id,function(response){callBack(this.getRoomFromResponse(response)),scaleToContainerWidth()}.bind(this))},this.switchToRoom=function(room){room.onShow(),null===this.room?(this.canvasDiv.appendChild(room.wallCanvas),this.canvasDiv.appendChild(room.itemDiv),scaleToContainerWidth()):(this.canvasDiv.replaceChild(room.wallCanvas,this.room.wallCanvas),this.canvasDiv.replaceChild(room.itemDiv,this.room.itemDiv)),this.room=room,this.updateRoomName()},miniworldHouseSwitchToRoom=function(id){this.saveRooms(),this.loadRoomWithId(id,this.switchToRoom.bind(this))}.bind(this),this.room=null,miniworldHouseGetCurrentRoom=function(){return this.room}.bind(this);miniworldHouseCommunication.loadFirstRoom(this.options.ownerId,function(response){this.switchToRoom(this.getRoomFromResponse(response))}.bind(this)),this.saveRooms=function(){var onSuccessRoomSave=function(result){this.changedSinceSave=!1;var response=result.data;response.success||confirmAI(response.message,(function(){}),(function(){}),!1,!0)};for(var id in this.rooms)this.rooms.hasOwnProperty(id)&&this.rooms[id].changedSinceSave&&miniworldHouseCommunication.saveRoom(this.rooms[id].serialize(),onSuccessRoomSave.bind(this.rooms[id]),miniworldHouseSaveTimer.saveAfterInterval)},miniworldHouseSaveTimer=new MiniworldHouseSaveTimer(this.saveRooms.bind(this)),this.menu=new MiniworldHouseMenu(this.editableRoom,this.options),miniworldHouseColorPicker=new MiniworldHouseColorPicker(this.colorPickerCanvas),this.updateRoomName=function(){this.roomNameSpan.innerHTML=this.room.name},this.showRoomNameInputField=function(show){show?(this.roomNameSpan.classList.add("hidden"),this.roomNameInput.classList.remove("hidden"),this.editButton.classList.add("hidden"),this.saveButton.classList.remove("hidden")):(this.roomNameSpan.classList.remove("hidden"),this.roomNameInput.classList.add("hidden"),this.editButton.classList.remove("hidden"),this.saveButton.classList.add("hidden"))},this.editRoomName=function(e){e.preventDefault(),e.stopPropagation(),this.showRoomNameInputField(!0),this.room.name!==this.room.unnamed?this.roomNameInput.value=this.room.name:(this.roomNameInput.value="",this.roomNameInput.placeholder=this.room.unnamed)},this.saveRoomName=function(e){e.preventDefault(),e.stopPropagation(),this.roomNameInput.value.trim()?(this.showRoomNameInputField(!1),this.room.name=this.roomNameInput.value,this.room.changedSinceSave=!0,this.saveRooms(),this.updateRoomName()):confirmAI(this.room.emptyRoomNameMessage,(function(){}),function(){this.roomNameInput.focus()}.bind(this),!1,!0)},this.roomNameSpan=document.getElementsByClassName("house-roomName-name")[0],this.editableRoom&&(this.roomNameInput=document.getElementsByClassName("house-roomName-input")[0],this.editButton=document.getElementsByClassName("house-roomName-editBtn")[0],this.editButton.onclick=this.editRoomName.bind(this),this.saveButton=document.getElementsByClassName("house-roomName-saveBtn")[0],this.saveButton.onclick=this.saveRoomName.bind(this)),this.startInteraction=function(pointerX,pointerY){null!=this.room&&this.room.startInteraction(pointerX,pointerY)},this.moveInteraction=function(pointerX,pointerY){null!=this.room&&this.editableRoom&&this.room.moveInteraction(pointerX,pointerY)},this.endInteraction=function(pointerX,pointerY){null!=this.room&&this.room.endInteraction(pointerX,pointerY)},this.mouseStartInteraction=function(event){var mousePos=miniworldHouseCanvasHelper.relativeMousePosition(this.wallLinesCanvas,event);this.startInteraction(mousePos.x,mousePos.y)},this.mouseMoveInteraction=function(event){var mousePos=miniworldHouseCanvasHelper.relativeMousePosition(this.wallLinesCanvas,event);this.moveInteraction(mousePos.x,mousePos.y)},this.mouseEndInteraction=function(event){var mousePos=miniworldHouseCanvasHelper.relativeMousePosition(this.wallLinesCanvas,event);this.endInteraction(mousePos.x,mousePos.y)},this.canvasDiv.onmousedown=this.mouseStartInteraction.bind(this),this.canvasDiv.onmousemove=this.mouseMoveInteraction.bind(this),this.canvasDiv.onmouseup=this.mouseEndInteraction.bind(this),this.editableRoom&&(this.editButton.onclick=this.editRoomName.bind(this)),this.touchListeners=[this.menu],this.touchStartInteraction=function(e){for(var i=0;i<this.touchListeners.length;i++)this.touchListeners[0].touchStartInteraction(e);if(null===this.activeTouch){this.activeTouch=event.changedTouches[0].identifier;var touchPos=miniworldHouseCanvasHelper.relativeTouchPosition(this.wallLinesCanvas,event,this.activeTouch);this.startInteraction(touchPos.x,touchPos.y),e.preventDefault()}},this.touchMoveInteraction=function(e){for(var i=0;i<this.touchListeners.length;i++)this.touchListeners[0].touchMoveInteraction(e);var touchPos=miniworldHouseCanvasHelper.relativeTouchPosition(this.wallLinesCanvas,event,this.activeTouch);null!==touchPos&&(this.moveInteraction(touchPos.x,touchPos.y),e.preventDefault())},this.touchEndInteraction=function(e){for(var i=0;i<this.touchListeners.length;i++)this.touchListeners[0].touchEndInteraction(e);var touchPos=miniworldHouseCanvasHelper.relativeTouchPosition(this.wallLinesCanvas,event,this.activeTouch);null!==touchPos&&(this.activeTouch=null,this.endInteraction(touchPos.x,touchPos.y),e.preventDefault())},this.activeTouch=null,this.canvasDiv.addEventListener("touchstart",this.touchStartInteraction.bind(this)),this.canvasDiv.addEventListener("touchmove",this.touchMoveInteraction.bind(this)),this.canvasDiv.addEventListener("touchend",this.touchEndInteraction.bind(this)),this.canvasDiv.addEventListener("touchcancel",this.touchEndInteraction.bind(this)),MiniworldHouseTR.tr_questionRoomName=this.options.tr_questionRoomName,MiniworldHouseTR.tr_deleteRoom=this.options.tr_deleteRoom,MiniworldHouseTR.tr_deleteItem=this.options.tr_deleteItem},MiniworldHouseTR=function(){this.tr_questionRoomName="",this.tr_deleteRoom="",this.tr_deleteItem=""},miniworldHouseSwitchToRoom=function(){},miniworldHouseGetCurrentRoom=function(){},disableUserSelect=function(control){control.style.webkitUserSelect="none",control.style.MozUserSelect="none",control.style.MsUserSelect="none",control.style.userSelect="none"};
16var MiniworldHouseItemManager=function(canvasDiv,zIndexOffset,houseLevel){this.canvasDiv=canvasDiv,this.zIndexOffset=zIndexOffset,this.layerOrder=[],this.draggedItem=null,this.relativeDragPositionX=null,this.relativeDragPositionY=null,this.lastValidX=null,this.lastValidY=null,this.houseLevel=houseLevel,this.addItem=function(drawnItem){this.canvasDiv.appendChild(drawnItem.canvas),scaleToContainerWidth(),this.layerOrder.push(drawnItem),this.resortLayers()},this.loadRoomItems=function(items,doors){for(var i=0;i!=items.length;++i)this.loadItem(items[i]);for(i=0;i!=doors.length;++i)this.loadDoor(doors[i])},this.loadItem=function(item){var instanceId,imageUrl,posX,posY,width,height;return instanceId=item.instanceid,imageUrl=item.imagepath,posX=item.positionx,posY=item.positiony,width=item.width,height=item.height,item.free?new MiniworldHouseFloorItem(instanceId,imageUrl,posX,posY,width,height,this.houseLevel,this.addItem.bind(this),this.layerOrder):new MiniworldHouseWallItem(instanceId,imageUrl,posX,posY,width,height,this.houseLevel,this.addItem.bind(this),this.layerOrder)},this.loadDoor=function(door){posX=door.position,width=90,height=187,doorColor=door.color,doorLinkedRoom=door.roomid,new MiniworldHouseDoorItem(doorLinkedRoom,posX,width,height,doorColor,this.houseLevel,this.addItem.bind(this))},this.createPreviewDoor=function(){var prevDoor=new MiniworldHouseDoorItem(0,360,90,187,MiniworldHouseDoorItem.DEFAULT_COLOR,this.houseLevel,this.addItem.bind(this));prevDoor.state=MiniworldHouseDoorItem.interactionStates.PREVIEW,this.draggedItem=prevDoor},this.serializeRoomItems=function(){for(var doors=[],otherItems=[],i=0;i!=this.layerOrder.length;++i){var item=this.layerOrder[i];item.lastValidX&&item.lastValidY&&(item.type==miniworldHouseItem.itemType.DOOR?doors.push(item.serialize()):otherItems.push(item.serialize()))}return{doors:doors,items:otherItems}},this.removeItem=function(item){for(var i=0;i!=this.layerOrder.length;++i)if(this.layerOrder[i]===item){this.layerOrder.splice(i,1);break}this.resortLayers(),this.canvasDiv.removeChild(item.canvas)},this.itemComparator=function(a,b){return a.type!=miniworldHouseItem.itemType.WALL&&a.type!=miniworldHouseItem.itemType.DOOR||b.type!=miniworldHouseItem.itemType.FLOOR?a.type!=miniworldHouseItem.itemType.FLOOR||b.type!=miniworldHouseItem.itemType.WALL&&b.type!=miniworldHouseItem.itemType.DOOR?a.type==miniworldHouseItem.itemType.FLOOR?b.posY-a.posY:a===this.draggedItem?-1:b===this.draggedItem?1:0:-1:1},this.isSorted=function(array,comp){for(var i=0;i<array.length-1;++i)if(comp(array[i],array[i+1])<0)return!1;return!0},this.zIndexForPosition=function(position){return this.zIndexOffset+this.layerOrder.length-1-position},this.zIndicesCorrect=function(){for(var i=0;i<this.layerOrder.length;++i)if(this.layerOrder[i].canvas.style.zIndex!=this.zIndexForPosition(i))return!1;return!0},this.resortLayers=function(){if(!this.isSorted(this.layerOrder,this.itemComparator.bind(this))||!this.zIndicesCorrect()){this.layerOrder.sort(this.itemComparator.bind(this));for(var i=0;i!=this.layerOrder.length;++i)this.layerOrder[i].canvas.style.zIndex=this.zIndexForPosition(i)}},this.tryToDragItem=function(pointerX,pointerY){for(var i=0;i!=this.layerOrder.length;++i)if(!miniworldHouseCanvasHelper.isTransparentAtPosition(this.layerOrder[i].canvas,pointerX,pointerY))return this.draggedItem=this.layerOrder[i],this.draggedItem.startInteraction(pointerX,pointerY),this.resortLayers(),this.draggedItem;return null},this.moveInteraction=function(pointerX,pointerY){var mode=this.draggedItem.moveInteraction(pointerX,pointerY,this.layerOrder);return this.resortLayers(),mode},this.placeItemInteraction=function(pointerX,pointerY){this.draggedItem.endInteraction(pointerX,pointerY),this.resortLayers(),this.draggedItem=null},this.removeItemInteraction=function(){this.removeItem(this.draggedItem),this.draggedItem=null}};
17var miniworldHouseItem=new function(){this.displayMode={DISPLAY:"DISPLAY",NONE:"NONE",SEMI:"SEMI",ICON:"ICON"},this.itemType={FLOOR:"FLOOR",WALL:"WALL",DOOR:"DOOR"},this.setDisplayMode=function(mode,canvas){mode==miniworldHouseItem.displayMode.NONE?canvas.style.display="none":mode==miniworldHouseItem.displayMode.SEMI?(canvas.style.display="block",canvas.style.opacity=.5):mode!=miniworldHouseItem.displayMode.DISPLAY&&mode!=miniworldHouseItem.displayMode.ICON||(canvas.style.display="block",canvas.style.opacity=1)},this.drawIcon=function(context,image,width,height,pointerX,pointerY){var scalingFactor=miniworldHouseGeometry.iconMaxSideLength/Math.max(width,height);context.drawImage(image,pointerX-.5*width*scalingFactor,pointerY-.5*height*scalingFactor,width*scalingFactor,height*scalingFactor)},this.itemCollidesWithOtherItems=function(item,items){for(var i=0;i!=items.length;++i)if(items[i]!==item&&item.collidesWithItem(items[i]))return!0;return!1}},MiniworldHouseFloorItem=function(instanceId,imageUrl,posX,posY,width,height,houseLevel,onDraw,allItems){this.type=miniworldHouseItem.itemType.FLOOR,this.canvas=miniworldHouseCanvasHelper.createCanvas(),this.instanceId=instanceId,this.posX=posX,this.posY=posY,this.width=width*miniworldHouseGeometry.levelFactor(houseLevel),this.height=height*miniworldHouseGeometry.levelFactor(houseLevel),this.relativeDragPositionX=null,this.relativeDragPositionY=null,this.al
17lItems=allItems,this.lastValidX=this.posX,this.lastValidY=this.posY,this.displayImage(onDraw),this.loadImage=function(){this.image.src=imageUrl},this.serialize=function(){return{instanceid:this.instanceId,positionx:this.lastValidX,positiony:this.lastValidY}},this.upperLeftX=function(){var scalingFactor=miniworldHouseGeometry.scalingFactor(this.posY);return this.posX-this.width*scalingFactor*.5},this.upperLeftY=function(){var scalingFactor=miniworldHouseGeometry.scalingFactor(this.posY);return this.posY-this.height*scalingFactor},this.draw=function(mode,pointerX,pointerY){null!==pointerX&&null!==pointerY||mode!=miniworldHouseItem.displayMode.ICON||(pointerX=this.posX,pointerY=this.posY),miniworldHouseItem.setDisplayMode(mode,this.canvas);var context=this.canvas.getContext("2d");if(context.clearRect(0,0,this.canvas.width,this.canvas.height),mode==miniworldHouseItem.displayMode.ICON)miniworldHouseItem.drawIcon(context,this.image,this.width,this.height,pointerX,pointerY);else{var scalingFactor=miniworldHouseGeometry.scalingFactor(this.posY);scalingFactor>0&&context.drawImage(this.image,this.upperLeftX(),this.upperLeftY(),this.width*scalingFactor,this.height*scalingFactor)}},this.collidesWithItem=function(other){return other.type!=miniworldHouseItem.itemType.WALL&&other.type!=miniworldHouseItem.itemType.DOOR&&(Math.abs(this.posY-other.posY)<10&&!(this.upperLeftX()>other.upperLeftX()+other.width||other.upperLeftX()>this.upperLeftX()+this.width))},this.collidesWithWalls=function(){var imageWidth=miniworldHouseGeometry.scalingFactor(this.posY)*this.width;return!(miniworldHouseGeometry.isPointOnFloor(this.posX-.5*imageWidth,this.posY)&&miniworldHouseGeometry.isPointOnFloor(this.posX+.5*imageWidth,this.posY))},this.displayMode=function(allItems){return this.posY<350?miniworldHouseItem.displayMode.ICON:miniworldHouseItem.itemCollidesWithOtherItems(this,allItems)||this.collidesWithWalls()?miniworldHouseItem.displayMode.SEMI:miniworldHouseItem.displayMode.DISPLAY},this.startInteraction=function(pointerX,pointerY){var scalingFactor=miniworldHouseGeometry.scalingFactor(this.posY);this.relativeDragPositionX=parseInt((pointerX-this.posX)/(this.width*scalingFactor)),this.relativeDragPositionY=parseInt((pointerY-this.posY)/(this.height*scalingFactor)),this.lastValidX=this.posX,this.lastValidY=this.posY},this.moveInteraction=function(pointerX,pointerY,allItems){var scalingFactor=miniworldHouseGeometry.scalingFactor(this.posY);this.posX=parseInt(pointerX-this.relativeDragPositionX*this.width*scalingFactor),this.posY=parseInt(pointerY-this.relativeDragPositionY*this.height*scalingFactor);var mode=this.displayMode(allItems);return mode==miniworldHouseItem.displayMode.DISPLAY&&(this.lastValidX=this.posX,this.lastValidY=this.posY),this.draw(mode,pointerX,pointerY),mode},this.endInteraction=function(pointerX,pointerY){this.posX=this.lastValidX,this.posY=this.lastValidY,this.draw(miniworldHouseItem.displayMode.DISPLAY,null,null)},this.loadImage()},MiniworldHouseWallItem=function(instanceId,imageUrl,posX,posY,width,height,houseLevel,onDraw,allItems){this.type=miniworldHouseItem.itemType.WALL,this.canvas=miniworldHouseCanvasHelper.createCanvas(),this.instanceId=instanceId,this.posX=posX,this.posY=posY,this.allItems=allItems,this.width=width*miniworldHouseGeometry.levelFactor(houseLevel),this.height=height*miniworldHouseGeometry.levelFactor(houseLevel),this.relativeDragPositionX=null,this.relativeDragPositionY=null,this.lastValidX=this.posX,this.lastValidY=this.posY,this.displayImage(onDraw),this.loadImage=function(){this.image.src=imageUrl},this.serialize=function(){return{instanceid:this.instanceId,positionx:this.lastValidX,positiony:this.lastValidY}},this.upperLeftX=function(){return this.posX-.5*this.width},this.upperLeftY=function(){return this.posY-this.height},this.draw=function(mode,pointerX,pointerY){null!==pointerX&&null!==pointerY||mode!=miniworldHouseItem.displayMode.ICON||(pointerX=this.posX,pointerY=this.posY),miniworldHouseItem.setDisplayMode(mode,this.canvas);var context=this.canvas.getContext("2d");if(context.clearRect(0,0,this.canvas.width,this.canvas.height),mode==miniworldHouseItem.displayMode.ICON)miniworldHouseItem.drawIcon(context,this.image,this.width,this.height,pointerX,pointerY);else if(this.upperLeftX()>=150&&this.upperLeftX()+this.width<=800)context.drawImage(this.image,this.up
17perLeftX(),this.upperLeftY(),this.width,this.height);else for(var x=0;x<this.width;++x){var sliceTopLeft=miniworldHouseGeometry.mapWallPosition(this.upperLeftX()+x,this.upperLeftY()),sliceBottomRight=miniworldHouseGeometry.mapWallPosition(this.upperLeftX()+x+1,this.upperLeftY()+this.height);context.drawImage(this.image,x*this.image.width/this.width,0,1,this.image.height,sliceTopLeft.x,sliceTopLeft.y,sliceBottomRight.x-sliceTopLeft.x+1,sliceBottomRight.y-sliceTopLeft.y+1)}},this.collidesWithItem=function(other){return other.type!=miniworldHouseItem.itemType.FLOOR&&!(this.upperLeftX()>=other.upperLeftX()+other.width||other.upperLeftX()>this.upperLeftX()+this.width||this.upperLeftY()>=other.upperLeftY()+other.height||other.upperLeftY()>=this.upperLeftY()+this.height)},this.displayMode=function(allItems){return this.upperLeftY()+.5*this.height<150||this.upperLeftY()+.5*this.height>400?miniworldHouseItem.displayMode.ICON:this.upperLeftY()<150||this.upperLeftY()+this.height>400||this.upperLeftX()<-100||this.upperLeftX()+this.width>1050||this.upperLeftX()<150&&this.upperLeftX()+this.width>150||this.upperLeftX()<800&&this.upperLeftX()+this.width>800||miniworldHouseItem.itemCollidesWithOtherItems(this,allItems)?miniworldHouseItem.displayMode.SEMI:miniworldHouseItem.displayMode.DISPLAY},this.startInteraction=function(pointerX,pointerY){var translatedPointerPos=miniworldHouseGeometry.reverseMapWallPosition(pointerX,pointerY);this.relativeDragPositionX=parseInt((translatedPointerPos.x-this.posX)/this.width),this.relativeDragPositionY=parseInt((translatedPointerPos.y-this.posY)/this.height),this.lastValidX=this.posX,this.lastValidY=this.posY},this.moveInteraction=function(pointerX,pointerY,allItems){var translatedPointerPos=miniworldHouseGeometry.reverseMapWallPosition(pointerX,pointerY);this.posX=parseInt(translatedPointerPos.x-this.relativeDragPositionX*this.width),this.posY=parseInt(translatedPointerPos.y-this.relativeDragPositionY*this.height);var mode=this.displayMode(allItems);return mode==miniworldHouseItem.displayMode.DISPLAY&&(this.lastValidX=this.posX,this.lastValidY=this.posY),this.draw(mode,pointerX,pointerY),mode},this.endInteraction=function(pointerX,pointerY){this.posX=this.lastValidX,this.posY=this.lastValidY,this.draw(miniworldHouseItem.displayMode.DISPLAY,null,null)},this.loadImage()},MiniworldHouseDoorItem=function(linkedRoom,posX,width,height,color,houseLevel,onDraw){this.category="DOOR",this.type=miniworldHouseItem.itemType.DOOR,this.canvas=miniworldHouseCanvasHelper.createCanvas(),this.linkedRoom=linkedRoom,this.posX=posX,this.posY=400,this.width=width*miniworldHouseGeometry.levelFactor(houseLevel),this.height=height*miniworldHouseGeometry.levelFactor(houseLevel),this.color=color,this.relativeDragPositionX=null,this.relativeDragPositionY=null,this.lastValidX=this.posX,this.lastValidY=this.posY,this.startDragPositionY=null,this.startDragPositionX=null,this.state=MiniworldHouseDoorItem.interactionStates.RELEASED,this.setup=function(){this.state=MiniworldHouseDoorItem.interactionStates.RELEASED,this.draw(miniworldHouseItem.displayMode.DISPLAY,null,null),onDraw(this)},this.serialize=function(){return{roomid:this.linkedRoom,position:this.posX,color:this.color}},this.upperLeftX=function(){return this.posX-this.width/2},this.upperLeftY=function(){return this.posY-this.height},this.draw=function(mode,pointerX,pointerY){null!==pointerX&&null!==pointerY||mode!=miniworldHouseItem.displayMode.ICON||(pointerX=this.posX,pointerY=miniworldHouseGeometry.bottomLeft.y),miniworldHouseItem.setDisplayMode(mode,this.canvas);var context=this.canvas.getContext("2d");if(context.clearRect(0,0,this.canvas.width,this.canvas.height),mode==miniworldHouseItem.displayMode.ICON)miniworldHouseItem.drawIcon(context,this.image,this.width,this.height,pointerX,pointerY);else{var upperLeftX=this.upperLeftX(),upperLeftY=this.upperLeftY(),translatedUpperLeft=miniworldHouseGeometry.mapWallPosition(upperLeftX,upperLeftY),translatedUpperRight=miniworldHouseGeometry.mapWallPosition(upperLeftX+this.width,upperLeftY),translatedLowerLeft=miniworldHouseGeometry.mapWallPosition(upperLeftX,upperLeftY+this.height),translatedLowerRight=miniworldHouseGeometry.mapWallPosition(upperLeftX+this.width,upperLeftY+this.height),doorKnobCenter={x:upperLeftX+.15*this.width,y:upperLeftY+.5*this.height},doorKnobRadius=.07*this.width,translatedDoorKnobUpperLeft=miniworldHouseGeometry.mapWallPosition(doorKnobCenter.x-doorKnobRadius,doorKnobCenter.y-doorKnobRadius),translatedDoorKnobLowerRight=miniworldHouseGeometry.mapWallPosition(doorKnobCenter.x+doorKnobRadius,doorKnobCenter.y+doorKnobRadius);context.beginPath(),miniworldHouseCanvasHelper.moveToPoint(context,translatedLowerLeft),miniworldHouseCanvasHelper.lineToPoint(context,translatedUpperLeft),miniworldHouseCanvasHelper.lineToPoint(context,translatedUpperRight),miniworldHouseCanvasHelper.lineToPoint(context,translatedLowerRight),context.fillStyle=this.color,context.fill(),context.stroke(),context.closePath(),context.save(),context.beginPath(),context.translate(translatedDoorKnobUpperLeft.x,translatedDoorKnobUpperLeft.y),context.scale((translatedDoorKnobLowerRight.x-translatedDoorKnobUpperLeft.x)/2,(translatedDoorKnobLowerRight.y-translatedDoorKnobUpperLeft.y)/2),context.arc(1,1,1,0,2*Math.PI,!1),context.restore(
17),context.stroke(),context.closePath()}},this.collidesWithItem=function(other){return other.type!=miniworldHouseItem.itemType.FLOOR&&!(this.upperLeftX()>=other.upperLeftX()+other.width||other.upperLeftX()>this.upperLeftX()+this.width||this.upperLeftY()>=other.upperLeftY()+other.height||other.upperLeftY()>=this.upperLeftY()+this.height)},this.displayMode=function(allItems){return 400!=this.posY?miniworldHouseItem.displayMode.ICON:this.upperLeftY()<150||this.upperLeftY()+this.height>400||this.upperLeftX()<-100||this.upperLeftX()+this.width>1050||this.upperLeftX()<150&&this.upperLeftX()+this.width>150||this.upperLeftX()<800&&this.upperLeftX()+this.width>800||miniworldHouseItem.itemCollidesWithOtherItems(this,allItems)?miniworldHouseItem.displayMode.SEMI:miniworldHouseItem.displayMode.DISPLAY},this.isPlaceable=function(){return this.lastValidX==this.posX},this.startInteraction=function(pointerX,pointerY){this.state=MiniworldHouseDoorItem.interactionStates.CLICKED;var translatedPointerPos=miniworldHouseGeometry.reverseMapWallPosition(pointerX,pointerY);this.relativeDragPositionX=parseInt((translatedPointerPos.x-this.posX)/this.width),this.relativeDragPositionY=parseInt((translatedPointerPos.y-this.posY)/this.height),this.lastValidX=this.posX,this.startDragPositionX=translatedPointerPos.x,this.startDragPositionY=translatedPointerPos.y,miniworldHouseGetCurrentRoom().editable&&MiniworldHouseInstance.menu.deleteDoor.show()},this.moveInteraction=function(pointerX,pointerY,allItems){var translatedPointerPos=miniworldHouseGeometry.reverseMapWallPosition(pointerX,pointerY);this.mouseWasMoved(translatedPointerPos)&&(this.state=MiniworldHouseDoorItem.interactionStates.DRAGGED),translatedPointerPos.y>=400-this.height&&translatedPointerPos.y<=400?this.posY=400:this.posY=parseInt(translatedPointerPos.y-this.relativeDragPositionY*this.height),this.posX=parseInt(translatedPointerPos.x-this.relativeDragPositionX*this.width);var mode=this.displayMode(allItems);return mode==miniworldHouseItem.displayMode.DISPLAY&&(this.lastValidX=this.posX),this.draw(mode,pointerX,pointerY),mode},this.endInteraction=function(pointerX,pointerY){this.state==MiniworldHouseDoorItem.interactionStates.CLICKED&&miniworldHouseSwitchToRoom(this.linkedRoom),this.state!=MiniworldHouseDoorItem.interactionStates.PREVIEW&&(this.state=MiniworldHouseDoorItem.interactionStates.RELEASED),this.posX=this.lastValidX,this.posY=400,this.draw(miniworldHouseItem.displayMode.DISPLAY,null,null),miniworldHouseGetCurrentRoom().editable&&MiniworldHouseInstance.menu.deleteDoor.hide()},this.mouseWasMoved=function(translatedPointerPos){return this.startDragPositionX-translatedPointerPos.x!=0||this.startDragPositionY-translatedPointerPos.y!=0},this.colorMoveInteraction=function(pointerX,pointerY){if(miniworldHouseColorPicker.activeObject==this){var color=miniworldHouseColorPicker.getColor(pointerX,pointerY);null!==color&&(this.color=color)}this.draw(miniworldHouseItem.displayMode.DISPLAY,pointerX,pointerY),miniworldHouseColorPicker.draw()},this.image=document.createElement("img"),this.image.src=MiniworldHouseImages.door,this.setup()};MiniworldHouseWallItem.prototype.displayImage=MiniworldHouseFloorItem.prototype.displayImage=function(onDraw){this.image=document.createElement("img"),this.image.onload=function(){var displayMode=this.displayMode(this.allItems);(this.allItems&&displayMode==miniworldHouseItem.displayMode.ICON||displayMode==miniworldHouseItem.displayMode.SEMI&&!miniworldHouseItem.itemCollidesWithOtherItems(this,this.allItems))&&(this.lastValidX=null,this.lastValidY=null,miniworldHouseCommunication.storeItemInInventory(this.instanceId)),this.draw(miniworldHouseItem.displayMode.DISPLAY,null,null),onDraw(this)}.bind(this)},MiniworldHouseDoorItem.DEFAULT_COLOR="rgb(173, 114, 70)",MiniworldHouseDoorItem.interactionStates={RELEASED:"RELEASED",CLICKED:"CLICKED",DRAGGED:"DRAGGED",PREVIEW:"PREVIEW"};
18var MiniworldHouseInventory=function(svgId){this.svgIcon=document.getElementById(svgId),this.inventoryDiv=document.getElementById("inventoryDiv"),this.inventoryDiv.style.display="none",this.furnitureButton=document.getElementById("buttonFurniture"),this.artButton=document.getElementById("buttonArt"),this.petButton=document.getElementById("buttonPet"),this.closeButton=document.getElementById("buttonClose"),this.miniWorldHouseInsideCanvasDiv=jQuery(".mia-miniworldhouseinside-canvasDiv"),this.miniWorldHouse=jQuery(".miniworldHouse"),this.type=MiniworldHouseMenu.type.INVENTORY,this.reactToCurrentStateInteraction=function(){var room=miniworldHouseGetCurrentRoom();return room.state==MiniworldHouseRoom.interactionStates.NO_INTERACTION||room.state==MiniworldHouseRoom.interactionStates.ITEM_INTERACTION&&room.draggedItem().type!=miniworldHouseItem.itemType.DOOR},this.currentItemCategory="Furniture",this.changeInventoryCategory=function(type){document.getElementById("button"+this.currentItemCategory).classList.remove("selected"),InventoryListInstance.filterForCategory(type),this.currentItemCategory=type,document.getElementById("button"+this.currentItemCategory).classList.add("selected")},this.close=function(){this.inventoryDiv.style.display="none",this.svgIcon.style.backgroundColor="",this.miniWorldHouse.show(),this.miniWorldHouseInsideCanvasDiv.css("margin-bottom","0px"),trackAllScaleHeightToAbsoluteChildrenElements(),jQuery(window).on("resize",trackAllScaleHeightToAbsoluteChildrenElements)},this.clickInteraction=function(){this.svgIcon.style.backgroundColor="#bce5ff",this.inventoryDiv.style.display="block",jQuery(window).off("resize","",trackAllScaleHeightToAbsoluteChildrenElements),this.miniWorldHouseInsideCanvasDiv.he
18ight("unset"),this.miniWorldHouse.hide(),this.miniWorldHouseInsideCanvasDiv.css("margin-bottom","-48px"),this.changeInventoryCategory(this.currentItemCategory)},this.mouseUpInteraction=function(){miniworldHouseGetCurrentRoom().state==MiniworldHouseRoom.interactionStates.ITEM_INTERACTION&&miniworldHouseGetCurrentRoom().storeItemInInventory()},this.onItemSelected=function(item){var currentRoom=miniworldHouseGetCurrentRoom();currentRoom.placeItemFromInventory(item),this.close(),miniworldHouseCommunication.storeItemInRoom(currentRoom.id,item)},this.closeButton.onclick=function(){this.close()}.bind(this),this.furnitureButton.onclick=function(){this.changeInventoryCategory("Furniture")}.bind(this),this.artButton.onclick=function(){this.changeInventoryCategory("Art")}.bind(this),this.petButton&&(this.petButton.onclick=function(){this.changeInventoryCategory("Pet")}.bind(this)),GlobalOnInventoryItemSelectedListener=this.onItemSelected.bind(this)};
19var MiniworldHouseIcon=function(svgId,menuFunction,options){this.menuFunction=new menuFunction(svgId,options),this.svgIcon=document.getElementById(svgId),disableUserSelect(this.svgIcon),this.show=function(){this.svgIcon.classList.remove("hidden")},this.hide=function(){this.svgIcon.classList.add("hidden")},this.clickInteraction=function(){this.menuFunction.reactToCurrentStateInteraction()&&this.menuFunction.clickInteraction()},this.mouseUpInteraction=function(){!this.menuFunction.reactToCurrentStateInteraction()||this.menuFunction.type!=MiniworldHouseMenu.type.DELETEDOOR&&this.menuFunction.type!=MiniworldHouseMenu.type.INVENTORY||this.menuFunction.mouseUpInteraction()},this.getActiveTouch=function(touchEvent){for(var touchesList="touchend"==touchEvent.type?touchEvent.changedTouches:touchEvent.touches,i=0;i<touchesList.length;i++)if(touchesList[i].identifier==this.activeTouchId)return touchesList[i];return null},this.pointIntersectsThisElement=function(clientX,clientY){var bounds=this.svgIcon.getBoundingClientRect();return clientX>=bounds.left&&clientX<=bounds.right&&clientY>=bounds.top&&clientY<=bounds.bottom},this.activeTouchId=null,this.touchStartInteraction=function(event){null===this.activeTouchId&&(this.activeTouchId=event.changedTouches[0].identifier)},this.touchMoveInteraction=function(event){},this.touchEndInteraction=function(event){var activeTouch=this.getActiveTouch(event);this.activeTouchId=null,null!==activeTouch&&this.pointIntersectsThisElement(activeTouch.clientX,activeTouch.clientY)&&this.mouseUpInteraction()},this.svgIcon.addEventListener("click",this.clickInteraction.bind(this)),this.svgIcon.addEventListener("mouseup",this.mouseUpInteraction.bind(this))},MiniworldHouseDoorBack=function(svgId,options){this.svgId=svgId,this.options=options,this.type=MiniworldHouseMenu.type.DOORBACK,this.reactToCurrentStateInteraction=function(){return miniworldHouseGetCurrentRoom().state==MiniworldHouseRoom.interactionStates.NO_INTERACTION},this.clickInteraction=function(){var goBackToId=miniworldHouseGetCurrentRoom().parentId;null!=goBackToId?miniworldHouseSwitchToRoom(goBackToId):(MiniworldHouseInstance.saveRooms(),window.location.href=this.options.leaveHouseUrl)}},MiniworldHouseDeleteItem=function(svgId){this.svgId=svgId,this.type=MiniworldHouseMenu.type.DELETEDOOR,this.reactToCurrentStateInteraction=function(){var room=miniworldHouseGetCurrentRoom();return room.state==MiniworldHouseRoom.interactionStates.ITEM_INTERACTION&&"DOOR"==room.itemManager.draggedItem.category},this.clickInteraction=function(){},this.mouseUpInteraction=function(){var currentRoom=miniworldHouseGetCurrentRoom();currentRoom.state=MiniworldHouseRoom.interactionStates.NO_INTERACTION,currentRoom.tryToDeleteItem()}},MiniworldHouseColorMode=function(svgId){this.svgIcon=document.getElementById(svgId),this.type=MiniworldHouseMenu.type.COLORMODE,this.reactToCurrentStateInteraction=function(){var room=miniworldHouseGetCurrentRoom();return room.state==MiniworldHouseRoom.interactionStates.NO_INTERACTION||room.editable&&room.state==MiniworldHouseRoom.interactionStates.COLOR_INTERACTION},this.clickInteraction=function(){miniworldHouseGetCurrentRoom().switchColorState()?this.svgIcon.style.backgroundColor="#bce5ff":this.svgIcon.style.backgroundColor=""}};
20var miniworldHouseGeometry=new function(){this.topLeft={x:150,y:150},this.topRight={x:800,y:150},this.bottomLeft={x:150,y:400},this.bottomRight={x:800,y:400},this.cornerTopLeft={x:0,y:92},this.cornerTopRight={x:950,y:92},this.cornerBottomLeft={x:0,y:458},this.cornerBottomRight={x:950,y:458},this.frameTopLeft={x:0,y:0},this.frameTopRight={x:950,y:0},this.frameBottomLeft={x:0,y:550}
20,this.frameBottomRight={x:950,y:550},this.placementBarrierLeft={x:this.cornerBottomLeft.x+.85*(this.bottomLeft.x-this.cornerBottomLeft.x),y:this.cornerBottomLeft.y+.85*(this.bottomLeft.y-this.cornerBottomLeft.y)},this.placementBarrierRight={x:this.cornerBottomRight.x+.85*(this.bottomRight.x-this.cornerBottomRight.x),y:this.cornerBottomRight.y+.85*(this.bottomRight.y-this.cornerBottomRight.y)},this.leftWall=[this.cornerTopLeft,this.topLeft,this.bottomLeft,this.cornerBottomLeft],this.rightWall=[this.cornerTopRight,this.topRight,this.bottomRight,this.cornerBottomRight],this.ceiling=[this.frameTopRight,this.cornerTopRight,this.topRight,this.topLeft,this.cornerTopLeft,this.frameTopLeft],this.floor=[this.frameBottomLeft,this.cornerBottomLeft,this.bottomLeft,this.bottomRight,this.cornerBottomRight,this.frameBottomRight],this.backWall=[this.topLeft,this.topRight,this.bottomRight,this.bottomLeft],this.wallPolygon={left:this.leftWall,right:this.rightWall,ceiling:this.ceiling,floor:this.floor,back:this.backWall},this.wallUpperLeft={left:this.cornerTopLeft,right:{x:800,y:92},ceiling:this.frameTopLeft,floor:{x:0,y:400},back:this.topLeft},this.iconMaxSideLength=75,this.levelFactor=function(level){return Math.pow(.92,level)},this.scalingFactor=function(posY){return 3/377*posY-823/377},this.mapWallPosition=function(posX,posY){if(posX<this.topLeft.x){var mirroredPosition=this.mapWallPosition(950-posX,posY);return{x:950-mirroredPosition.x,y:mirroredPosition.y}}if(posX<=this.topRight.x)return{x:posX,y:posY};var newX=800-18750*(-800+posX)/(58*posX-92125);return{x:newX,y:150+(this.cornerTopRight.y-150)/150*(newX-800)+(this.bottomRight.y-this.topRight.y+(this.cornerBottomRight.y-this.cornerTopRight.y-this.bottomRight.y+this.topRight.y)/150*(newX-800))*(posY-150)/250}},this.reverseMapWallPosition=function(posX,posY){if(posX<this.topLeft.x){var mirroredPosition=this.reverseMapWallPosition(950-posX,posY);return{x:950-mirroredPosition.x,y:mirroredPosition.y}}if(posX<=this.topRight.x)return{x:posX,y:posY};var orgX=125*(737*posX-469600)/(2*(29*posX-13825)),wallUpperY=150+(this.cornerTopRight.y-150)/150*(posX-800),wallHeight=this.bottomRight.y-this.topRight.y+(this.cornerBottomRight.y-this.cornerTopRight.y-this.bottomRight.y+this.topRight.y)/150*(posX-800);return{x:orgX,y:this.topLeft.y+(posY-wallUpperY)/wallHeight*250}},this.isPointOnFloor=function(posX,posY){var polygon=[this.placementBarrierLeft,this.placementBarrierRight,this.cornerBottomRight,this.frameBottomRight,this.frameBottomLeft,this.cornerBottomLeft],point={x:posX,y:posY};return this.polygonCheck(point,polygon)},this.polygonCheck=function(point,vs){for(var x=point.x,y=point.y,inside=!1,i=0,j=vs.length-1;i<vs.length;j=i++){var xi=vs[i].x,yi=vs[i].y,xj=vs[j].x,yj=vs[j].y;yi>y!=yj>y&&x<(xj-xi)*(y-yi)/(yj-yi)+xi&&(inside=!inside)}return inside}};
21var MiniworldHouseDoorAdd=function(svgId){this.svgIcon=document.getElementById(svgId),this.type=MiniworldHouseMenu.type.DOORADD,this.reactToNormalMouseInteraction=function(){return!0},this.reactToCurrentStateInteraction=function(){var room=miniworldHouseGetCurrentRoom();return room.state==MiniworldHouseRoom.interactionStates.NO_INTERACTION||room.state==MiniworldHouseRoom.interactionStates.PREVIEW_DOOR_INTERACTION},this.newDoorPosition,this.newDoorColor,this.clickInteraction=function(){var roomState=miniworldHouseGetCurrentRoom().state;roomState==MiniworldHouseRoom.interactionStates.NO_INTERACTION?(this.svgIcon.style.backgroundColor="#bce5ff",miniworldHousePreviewDoor()):roomState==MiniworldHouseRoom.interactionStates.PREVIEW_DOOR_INTERACTION&&(this.svgIcon.style.backgroundColor="",miniworldHouseAbortPreviewDoor())},miniworldHouseTryToBuyNewRoom=function(position){this.newDoorPosition=position,this.newDoorColor=MiniworldHouseDoorItem.DEFAULT_COLOR,miniworldHouseCommunication.userHasEnoughMoneyToBuyRoom(this.popup.bind(this))}.bind(this),this.popup=function(ans,message){ans?confirmAI(message,this.getNewRoom.bind(this),(function(){}),!0,!0):confirmAI(message,(function(){}),(function(){}),!0,!1),this.svgIcon.style.backgroundColor=""},this.getNewRoom=function(){var currentRoomId=miniworldHouseGetCurrentRoom().id;miniworldHouseCommunication.buyDoor(currentRoomId,this.newDoorPosition,this.newDoorColor,this.reloadRoom)},this.reloadRoom=function(){miniworldHouseSwitchToRoom(miniworldHouseGetCurrentRoom().id)}},miniworldHouseTryToBuyNewRoom=function(){};
22var miniworldHouseCommunication=new function(){var wrapResponse=function(successHook){return function(response){response.data.settings=JSON.parse(response.data.settings),successHook(response)}};this.loadFirstRoom=function(ownerId,successHook){axios("/ajaj/games/miniworldHouseInside/loadfirstroom",{method:"get",params:{id:ownerId}}).then(wrapResponse(successHook))},this.loadRoom=function(roomId,successHook){axios("/ajaj/games/miniworldHouseInside/loadroom",{method:"get",params:{miniworldRoom:roomId}}).then(wrapResponse(successHook))},this.saveRoom=function(representation,successHook){axios("/ajaj/games/miniworldHouseInside/saveroom",{method:"post",headers:{"content-type":"application/x-www-form-urlencoded"},data:{miniworldRoomId:representation.id,miniworldRoomName:representation.name,miniworldRoomSettings:representation.settings,miniworldRoomDoors:JSON.stringify(representation.doors),miniworldRoomItems:JSON.stringify(representation.items)}}).then(successHook)},this.userHasEnoughMoneyToBuyRoom=function(successHook){axios("/ajaj/games/miniworldHouseInside/userhasenoughmoneytobuydoor",{method:"get"}).then((response=>{successHook(response.data.ans,response.data.message)}))},this.buyDoor=function(roomId,doorPosition,doorColor,successHook){axios("/ajaj/games/miniworldHouseInside/buydoor",{method:"get",params:{miniworldRoom:roomId,miniworldDoorPosition:doorPosition,miniworldRoomDoorColor:doorColor}}).then((response=>{response.data.success&&successHook(response.data.roomid)}))},this.storeItemInInventory=function(itemId){axios("/ajaj/games/miniworldHouseInside/storeItemInInventory",{method:"get",params:{miniworlditeminstanceid:itemId}})},this.storeItemInRoom=function(roomId,item){axios("/ajaj/games/miniworldHouseInside/storeItemInRoom",{method:"get",params:{miniworldRoom:roomId,miniworldRoomItem:JSON.stringify({instanceid:item.instanceid,positionx:item.positionx,positiony:item.positiony})}})},this.deleteItem=function(itemId,currentItemCategory){axios("/ajaj/games/miniworldHouseInside/deleteItemInstance",{method:"get",params:{miniworlditeminstanceid:itemId}}).then((response=>{null!=currentItemCategory&&InventoryListInstance.filterForCategory(currentItemCategory)}))},this.deleteRoom=function(roomId){axios("/ajaj/games/miniworldHouseInside/deleteroom",{method:"get",params:{miniworldRoom:roomId}})}};
23var MiniworldHouseColorPicker=function(canvas){this.canvas=canvas,this.frameSize=7,this.colorSize=200,this.textureSize=25,this.closeIconSize=4*this.frameSize,this.width,this.height=this.closeIconSize+this.colorSize+this.frameSize,this.posX,this.posY,this.activeObject=null,this.numberOfTextures=0,this.currentColorX=-1,this.currentColorY=-1,this.activated=!1,this.colorImage=document.createElement("img"),this.colorImage.src=MiniworldHouseImages.colorpickerspectrum,this.closeIcon=document.createElement("img"),this.closeIcon.src=MiniworldHouseImages.closeicon;this.textures=function(){for(var texturesWall=[],i=0;i<7;i++){(textureImg=document.createElement("img")).src=MiniworldHouseImages.colorpickerwalltextures[i],texturesWall[i]=textureImg}var texturesFloor=[];for(i=0;i<4;i++){var textureImg;(textureImg=document.createElement("img")).src=MiniworldHouseImages.colorpickerfloortextures[i],texturesFloor[i]=textureImg}var textures=[];return textures.wall=texturesWall,textures.floor=texturesFloor,textures}(),this.drawPicker=function(pointerX,pointerY,object){this.width=this.colorSize+2*this.frameSize,"DOOR"==this.activeObject.category?this.numberOfTextures=0:this.numberOfTextures=this.activeObject.allTextures.length-1,this.numberOfTextures>0&&(this.width+=(this.numberOfTextures+1)*(this.textureSize+this.frameSize)),this.getPosition(pointerX,pointerY),this.draw()},this.startInteraction=function(pointerX,pointerY){this.activated=!0},this.endInteraction=function(pointerX,pointerY){pointerX>=this.posX+this.width-this.closeIconSize&&pointerX<=this.posX+this.width&&pointerY>=this.posY&&pointerY<=this.posY+this.closeIconSize?(this.hide(),this.currentColorX=-1,this.currentColorY=-1,this.activated=!1,MiniworldHouseInstance.menu.colorMode.clickInteraction()):(this.activeObject&&(this.draw(),this.activated&&this.activeObject.colorMoveInteraction(pointerX,pointerY)),this.activated=!1)},this.getPosition=function(pointerX,pointerY){if("WALL"==this.activeObject.category)this.posX=Math.min(Math.max(pointerX-parseInt(this.width/2),5),945-this.width),this.posY=Math.min(Math.max(pointerY-parseInt(this.height/2),75),545-this.height);else if("DOOR"==this.activeObject.category)if(this.activeObject.posX+.5*this.activeObject.width<475){var translatedUpperRight=miniworldHouseGeometry.mapWallPosition(this.activeObject.upperLeftX()+this.activeObject.width,this.activeObject.upperLeftY()),translatedLowerRight=miniworldHouseGeometry.mapWallPosition(this.activeObject.upperLeftX()+this.activeObject.width,this.activeObject.upperLeftY()+this.activeObject.height);this.posX=translatedUpperRight.x+this.frameSize,this.posY=translatedUpperRight.y+parseInt((translatedLowerRight.y-translatedUpperRight.y-this.height)/2)}else{var translatedUpperLeft=miniworldHouseGeometry.mapWallPosition(this.activeObject.upperLeftX(),this.activeObject.upperLeftY()),translatedLowerLeft=miniworldHouseGeometry.mapWallPosition(this.activeObject.upperLeftX(),this.activeObject.upperLeftY()+this.activeObject.height);this.posX=translatedUpperLeft.x-this.width-this.frameSize,this.posY=translatedUpperLeft.y+parseInt((translatedLowerLeft.y-translatedUpperLeft.y-this.height)/2)}},this.draw=function(){this.canvas.style.display="block";var context=this.canvas.getContext("2d");if(context.clearRect(0,0,this.canvas.width,this.canvas.height),context.fillStyle="#aaaaaa",context.fillRect(this.posX,this.posY,this.width,this.height),context.fillStyle="#FFFFFF",context.font=2*this.frameSize+"px sans-serif",context.fillText("Pick a Color",this.posX+parseInt(1.5*this.frameSize),this.posY+this.closeIconSize-this.frameSize),this.numberOfTextures>0){context.fillText("Pick a Texture",this.posX+this.colorSize+parseInt(1.5*this.frameSize),this.posY+this.closeIconSize-this.frameSize);for(var type="floor"==this.activeObject.name?"floor":"wall",i=0;i<=this.numberOfTextures;i++)i==this.activeObject.textureIndex&&(context.fillStyle="#000000",context.fillRect(this.posX+this.colorSize+(i+2)*this.frameSize+i*this.textureSize-2,this.posY+this.closeIconSize-2,this.textureSize+4,this.colorSize+4)),context.drawImage(this.textures[type][i],this.posX+this.colorSize+(i+2)*this.frameSize+i*this.textureSize,this.posY+this.closeIconSize,this.textureSize,this.colorSize)}context.drawImage(this.closeIcon,this.posX+this.width-this.closeIconSize,this.posY,this.closeIconSize,this.closeIconSize),context.drawImage(this.colorImage,this.posX+this.frameSize,this.posY+this.closeIconSize,this.colorSize,this.colorSize),-1!=this.currentColorX?(this.drawCircle(context,this.currentColorX,this.currentColorY,5,"#000000"),this.drawCircle(context,this.currentColorX,this.currentColorY,3,"#00FFFF")):this.activeObject.color&&this.activeObject.color.indexOf("hsl")>=0&&this.drawInitialCoordinatesForColor(context,this.activeObject.color)},this.drawCircle=function(context,x,y,radius,color){context.strokeStyle=color,context.beginPath(),context.arc(x,y,radius,0,2*Math.PI,!1),context.stroke(),context.closePath()},this.hide=function(){this.activeObject=null,this.canvas.style.display="none"},this.getColor=function(pointerX,pointerY){if(pointerX>=this.posX+this.frameSize&&pointerX<=this.posX+this.frameSize+this.colorSize&&pointerY>=this.posY+this.closeIconSize&&pointerY<=this.posY+this.height-this.frameSize){this.currentColorX=parseInt(pointerX),this.currentColorY=parseInt(pointerY);var hue=(pointerY-this.posY-this.closeIconSize)/this.colorSize*360;return lightness=(pointerX-this.posX-this.frameSize)/this.colorSize*100,"hsl("+hue+", 80%, "+lightness+"%)"}return null},this.drawInitialCoordinatesForColor=function(context,color){var hue=parseFloat(color.slice(color.indexOf("(")+1,color.indexOf(","))),lightness=parseFloat(color.slice(color.lastIndexOf(" ")+1,color.lastIndexOf("%"))),initialX=this.colorSize*lightness/100+this.posX+this.frameSize,initialY=this.colorSize*hue/360+this.posY+this.closeIconSize;this.drawCircle(context,initialX,initialY,5,"#000000"),this.drawCircle(context,initialX,initialY,3,"#00FFFF")},this.getTexture=function(pointerX,pointerY){return pointerX>=this.posX+this.colorSize+2*this.frameSize&&pointerX<=this.posX+this.width&&pointerY>=this.posY+this.closeIconSize&&pointerY<=this.posY+this.height-this.frameSize?Math.min(Math.floor((pointerX-(this.posX+this.colorSize+2*this.frameSize))/(this.textureSize+this.frameSize)),this.numberOfTextures):null}},miniworldHouseColorPicker=null;
24var miniworldHouseCanvasHelper=new function(){this.createCanvas=function(canvasDiv,zIndex){var newCanvas=document.createElement("canvas");return newCanvas.width=950,newCanvas.height=550,newCanvas.style.position="absolute",newCanvas.style.left=0,newCanvas.style.top=0,newCanvas.classList.add("mia-js-scaleToContainerWidth"),null!=zIndex&&(newCanvas.style.zIndex=zIndex),null!=canvasDiv&&(canvasDiv.appendChild(newCanvas),scaleToContainerWidth()),newCanvas},this.moveToPoint=function(context,point){context.moveTo(point.x,point.y)},this.lineToPoint=function(context,point){context.lineTo(point.x,point.y)},this.relativeMousePosition=function(canvas,event){var rect=canvas.getBoundingClientRect(),scale=parseFloat(canvas.style.transform.substring(6,13));return{x:(event.clientX-rect.left)/scale,y:(event.clientY-rect.top)/scale}},this.relativeTouchPosition=function(canvas,event,activeTouch){for(var posX=null,posY=null,rect=canvas.getBoundingClientRect(),scale=parseFloat(canvas.style.transform.substring(6,13)),i=0;i<event.changedTouches.length;i++)if(event.changedTouches[i].identifier==activeTouch){posX=event.changedTouches[i].clientX,posY=event.changedTouches[i].clientY;break}
24return null===posX||null===posY?null:{x:(posX-rect.left)/scale,y:(posY-rect.top)/scale}},this.isTransparentAtPosition=function(canvas,posX,posY){return 0==canvas.getContext("2d").getImageData(posX,posY,1,1).data[3]}};
25class ListenerManager{constructor(){this.listenerList=[],this.onUnloadActions=[],this.unloadListenerAdded=!1}safeObserve(el,evStr,func){this.listenerList.push({el:el,evStr:evStr,func:func}),el.addEventListener(evStr,func),this.unloadListenerAdded||(window.addEventListener("unload",this.onUnload.bind(this)),this.unloadListenerAdded=!0)}stopObserve(el,evStr){this.listenerList.forEach((it=>{it.el==el&&it.evStr==evStr&&(it.el.removeEventListener(it.evStr,it.func),it.el=null,it.func=null,it=null)})),this.listenerList=this.listenerList.filter((item=>null!=item))}stopObserveAllListeners(el){this.listenerList.forEach((it=>{it.el==el&&(it.el.removeEventListener(it.evStr,it.func),it.el=null,it.func=null,it=null)})),this.listenerList=this.listenerList.filter((item=>null!=item))}onUnload(){this.listenerList.forEach((listenerItem=>{null!==listenerItem&&null!==listenerItem.el&&(listenerItem.el.removeEventListener(listenerItem.evStr,listenerItem.func),delete listenerItem.el,delete listenerItem.func,listenerItem.el=null,listenerItem.func=null)})),this.listenerList=[],this.onUnloadActions.forEach((action=>{action(),action=null})),this.onUnloadActions=[]}registerUnloadAction(func){this.onUnloadActions.push(func)}}
26class DOMAttached{constructor(el,options){if(this.listenerManager=new ListenerManager,this.options=options,this.el=document.getElementById(el),!this.el)throw new Error(`The element ${el} could not be found to initialize ${this.constructor.name}`);this.safeObserve(window,"unload",this.onUnload.bind(this))}onUnload(ev){this.listenerManager.onUnload(),this.el=null}safeObserve(el,evStr,func){this.listenerManager.safeObserve(el,evStr,func)}stopObserve(el,evStr){this.listenerManager.stopObserve(el,evStr)}stopObserveAllListeners(el){this.listenerManager.stopObserveAllListeners(el)}registerUnloadAction(func){this.listenerManager.registerUnloadAction(func)}removeElement(el){this.purge(el),el.remove()}purge(d){var l,n,a=d.attributes;if(a){l=a.length;for(var i=0;i<l;i+=1)"function"==typeof d[n=a[i].name]&&(d[n]=null)}if(a=d.childNodes){l=a.length;for(i=0;i<l;i+=1)this.purge(d.childNodes[i])}}}
27class MiniWorldExitButton extends DOMAttached{constructor(el,options){super(el,options),this.safeObserve(document.getElementById(this.options.exitButtonId),"click",this.onClick.bind(this))}onClick(){var gradXtable=document.getElementById("gradXtable");gradXtable&&!gradXtable.classList.contains("hidden")?gradXtable.classList.add("hidden"):window.location=this.options.worldUrl}}
28var legacyGlobal={currentlyActiveTabPopup:void 0,toplevelElement:void 0,isIE:null!=new RegExp("MSIE (\\d+)\\.(\\d+)","i").exec(navigator.appVersion),isIE6:null!=new RegExp("MSIE 6\\.(\\d+)","i").exec(navigator.appVersion),isIE7:null!=new RegExp("MSIE 7\\.(\\d+)","i").exec(navigator.appVersion),isIE8:null!=new RegExp("MSIE 8\\.(\\d+)","i").exec(navigator.appVersion),isIE9:null!=new RegExp("MSIE 9\\.(\\d+)","i").exec(navigator.appVersion),isIE10:null!=new RegExp("MSIE 10\\.(\\d+)","i").exec(navigator.appVersion),isIE11:null!=new RegExp("MSIE 11\\.(\\d+)","i").exec(navigator.appVersion),isOpera:/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent),isFirefox:/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent),isChrome:navigator.userAgent.toLowerCase().indexOf("chrome")>-1,isIPad:null!=navigator.userAgent.match(/iPad/i),isIPhone:null!=navigator.userAgent.match(/iPhone/i),portal:"classic",cloudComputeCalls:0,controls:{},getToplevelElement:function(){return legacyGlobal.toplevelElement||(legacyGlobal.toplevelElement=document.body.querySelector("form"),legacyGlobal.toplevelElement||(legacyGlobal.toplevelElement=document.body)),legacyGlobal.toplevelElement},getControlPromise:function(clazz){return void 0===legacyGlobal.controls[clazz]&&(control={},control.control=new Promise((resolve=>control.resolve=resolve)),legacyGlobal.controls[clazz]=control),legacyGlobal.controls[clazz]},DOMReadyConstruct:function(clazz,el,options){jQuery(document).ready((function(){legacyGlobal.getControlPromise(clazz).control.then((control
28=>{new control(el,options)}))}))},DOMReadyActions:function(){legacyGlobal.toplevelElement=document.body.querySelector("form"),legacyGlobal.toplevelElement||(legacyGlobal.toplevelElement=document.body),legacyGlobal.window=new Window(window),document.dispatchEvent(new CustomEvent("document:allSet"))},scaleScreen:function(){var val=window.innerWidth/1280;document.getElementsByTagName("html")[0].setAttribute("style","zoom: "+val+";")},onLoadActions:function(){window.removeEventListener("load",legacyGlobal.onLoadActions),window.addEventListener("unload",legacyGlobal.onUnloadActions),legacyGlobal.prepareBlinkingTitle()},onUnloadActions:function(){legacyGlobal.toplevelElement=null,legacyGlobal.currentlyActiveTabPopup=null,legacyGlobal.tagCloud=null,legacyGlobal.searchableList=null,window.removeEventListener("unload",legacyGlobal.onUnloadActions)},prepareBlinkingTitle:function(){document.addEventListener("blur",legacyGlobal.onBlur),document.addEventListener("focus",legacyGlobal.onFocus),legacyGlobal.isIE&&(document.onfocusin=legacyGlobal.onFocus,document.onfocusout=legacyGlobal.onBlur),legacyGlobal.oldTitle=document.title},onBlur:function(ev){legacyGlobal.isBackground=!0},onFocus:function(ev){legacyGlobal.isBackground=!1},blinkTitle:function(){if(legacyGlobal.isBackground){var title=document.title;title=title.substr(1)+title.substr(0,1),document.title=title,window.setTimeout(legacyGlobal.blinkTitle,100)}else void 0!==legacyGlobal.oldTitle&&(document.title=legacyGlobal.oldTitle)},registerTagSearchableList:function(el){legacyGlobal.searchableList=el},findTagSearchableList:function(el){return legacyGlobal.searchableList},registerTagCloud:function(el){legacyGlobal.tagCloud=el},findTagCloud:function(el){return legacyGlobal.tagCloud},hhmmss:function(secs){time=[0,0,secs];for(var i=2;i>0;i--)time[i-1]=Math.floor(time[i]/60),time[i]=Math.round(time[i]%60),time[i]<10&&(time[i]="0"+time[i]);return time.join(":")},mmss:function(secs){time=[0,secs];for(var i=1;i>0;i--)time[i-1]=Math.floor(time[i]/60),time[i]=Math.round(time[i]%60),time[i]<10&&(time[i]="0"+time[i]);return time.join(":")},isTouchDevice:function(){return Boolean(window.ontouchstart||navigator.maxTouchPoints)},hasMouseSupport:function(){return matchMedia("(pointer:fine)").matches}};jQuery(document).ready(legacyGlobal.DOMReadyActions),window.addEventListener("load",legacyGlobal.onLoadActions),document.querySelectorAll("head meta").forEach((meta=>{"portal"==meta.getAttribute("name")&&(legacyGlobal.portal=meta.getAttribute("content"))}));
29class Window{constructor(){this.listenerManager=new ListenerManager,this.listenerManager.safeObserve(window,"keypress",this.onKeyPress.bind(this)),this.uniqueId=1,this.escapeHandlers=new Map}onKeyPress(ev){27==ev.keyCode&&this.performEscapeActions()&&(ev.preventDefault(),ev.stopPropagation())}performEscapeActions(){var res=!1;return this.escapeHandlers.forEach((function(eh){eh.value(),res=!0})),res}registerEscapeHandler(fn){return this.escapeHandlers.set(this.uniqueId,fn),this.uniqueId++}unregisterEscapeHandler(id){this.escapeHandlers.unset(id)}}
30function waitForElementToBePresent(selector){return new Promise((function(resolve){if(document.querySelector(selector))return resolve(document.querySelector(selector));var observer=new MutationObserver((function(){document.querySelector(selector)&&(observer.disconnect(),resolve(document.querySelector(selector)))}));observer.observe(document.body,{childList:!0,subtree:!0})}))}
31class LegacyEffects{static appear(element,options={}){const duration=options.duration||.5,delay=options.delay||0;gsap.set(element,{display:null});return gsap.fromTo(element,{autoAlpha:0},{autoAlpha:1,clearProps:"opacity",duration:duration,delay:delay,onComplete:options.onComplete})}static fade(element,options={}){const duration=options.duration||.5,delay=options.delay||0;return gsap.to(element,{autoAlpha:0,display:"none",clearProps:"opacity",duration:duration,delay:delay,onComplete:options.onComplete})}static move(element,options={}){const duration=options.duration||.5,delay=options.delay||0,mode=options.mode||"relative",ease=options.ease||"power1.out";let xValue,yValue;"relative"===mode?(xValue=`+=${options.x||0}`,yValue=`+=${options.y||0}`):(xValue=options.x||0,yValue=options.y||0);return gsap.to(element,{left:xValue,top:yValue,duration:duration,delay:delay,ease:ease,onStart:
31options.onStart,onComplete:options.onComplete})}static pulsate(element,options={}){const pulses=options.pulses||3,pulseDuration=(options.duration||1)/(2*pulses),timeline=gsap.timeline({onComplete:options.onComplete});for(let i=0;i<pulses;i++)timeline.to(element,{opacity:.5,duration:pulseDuration}),timeline.to(element,{opacity:1,duration:pulseDuration});return timeline}static parallel(animations,options={}){const timeline=gsap.timeline({onComplete:options.onComplete});return animations.forEach((animFn=>{animFn&&("end"!==options.queue?timeline.add(animFn,0):timeline.add(animFn))})),timeline}}
32class VisibilitySwitcher extends DOMAttached{constructor(el,options){super(el,options),this.visible=this.options.visibleByDefault,this.otherControl=document.getElementById(this.options.otherControl),this.control=document.getElementById(el);var c=this;0!=this.autoPageInterval&&setInterval((function(){c.switchVisibility()}),this.options.interval)}switchVisibility(){this.visible=!this.visible,this.visible?(LegacyEffects.appear(this.control,{duration:.8}),LegacyEffects.fade(this.otherControl,{duration:.8,delay:.4})):(LegacyEffects.appear(this.otherControl,{duration:.8}),LegacyEffects.fade(this.control,{duration:.8,delay:.4}))}}
33class UrlTemplate{constructor(url){this.url=url}isNotNull(value){return"NULL"!=value}r(placeholder,value){return this.isNotNull(value)?this.url=this.url.replace(placeholder,encodeURIComponent(value)):this.url=this.url.replace(placeholder,encodeURIComponent(" ")),this}}
34function confirmAI(message,onConfirm,onCancel,showConfirm,showCancel,options){var choices=[];if(showConfirm){var confirmButton={value:!0};"object"==typeof options&&options.hasOwnProperty("confirmBtnCaption")?confirmButton.label=options.confirmBtnCaption:confirmButton.label="Ok",choices.push(confirmButton)}if(showCancel){var cancelButton={value:!1};"object"==typeof options&&options.hasOwnProperty("cancelBtnCaption")?cancelButton.label=options.cancelBtnCaption:cancelButton.label="Cancel",choices.push(cancelButton)}MiaPrompt(message,choices).promise.then((function(isConfirmed){isConfirmed?onConfirm():onCancel()}))}
35class VimeoPlayer extends DOMAttached{constructor(el,options){super(el,options),this.vimeoPlayer=document.getElementById(this.options.vimeoIframe),this.showSubtitles=this.options.showSubtitles,this.autoplay=this.options.autoPlay,this.videoProgressKey="videoTimeElapsed_"+this.options.videoId+"_"+this.options.memberUUId,this.initializeListeners();try{this.player=new Vimeo.Player(this.vimeoPlayer)}catch(err){throw MiaErrorPrompt(this.options.playerCreationError),new Error(err)}this.setVideoProgress(),this.player.on("progress",this.onVimeoPlayerLoadProgress.bind(this)),this.player.on("timeupdate",this.onVimeoPlayerPlayProgress.bind(this)),this.player.on("play",this.onVimeoPlayerPlay.bind(this)),this.player.on("pause",this.onVimeoPlayerPause.bind(this)),this.player.on("ended",this.onVimeoPlayerFinish.bind(this)),this.player.ready().then(this.onVimeoPlayerReady(this.player))}setVideoProgress(){this.player.setCurrentTime(this.getTimeWatched())}initializeListeners(){this.listeners=[],null!=this.options.rewardUrl&&this.addListener(new RewardVideoListener(this.options.rewardTimeSpan,this.options.rewardUrl)),null!=this.options.fullyWatchedUrl&&this.addListener(new ReportWatchedVideoListener(this.options.fullyWatchedUrl,this.options.duration,this.videoProgressKey))}addListener(listener){this.listeners.push(listener)}removeListener(listener){var index=this.listeners.indexOf(listener);-1!=index&&this.listeners.splice(index,1)}notifyListenersOnPlayProgress(currentSeconds){var index;for(index=0;index<this.listeners.length;index++)this.listeners[index].onPlayProgress(currentSeconds)}notifyListenersOnLoadProgress(percentage){var index;for(index=0;index<this.listeners.length;index++)this.listeners[index].onLoadProgress(percentage)}notifyListenersOnPlay(){var index;for(index=0;index<this.listeners.length;index++)this.listeners[index].onPlay()}notifyListenersOnPause(){var index;for(index=0;index<this.listeners.length;index++)this.listeners[index].onPause()}notifyListenersOnEnd(){var index;for(index=0;index<this.listeners.length;index++)this.listeners[index].onEnd()}onVimeoPlayerReady(player){player.setVolume("1.0"),this.showSubtitles&&player.enableTextTrack("en"),this.autoplay&&!this.isSafari()&&player.play()}onVimeoPlayerLoadProgress(data){this.notifyListenersOnLoadProgress(100*data.percent)}
35onVimeoPlayerPlayProgress(data){this.notifyListenersOnPlayProgress(data.seconds)}onVimeoPlayerPlay(){this.notifyListenersOnPlay()}onVimeoPlayerPause(){this.notifyListenersOnPause()}onVimeoPlayerFinish(){this.notifyListenersOnEnd(),this.player.element.src=this.player.element.src}getDurationSeconds(){return this.options.duration}isSafari(){var userAgent=navigator.userAgent.toLowerCase();return-1!==userAgent.indexOf("safari")&&-1==userAgent.indexOf("chrome")}getTimeWatched(){var videoProgressFromLocalStorage=localStorage.getItem(this.videoProgressKey),videoProgressFromSessionStorage=sessionStorage.getItem(this.videoProgressKey);return videoProgressFromLocalStorage||videoProgressFromSessionStorage?Math.max(videoProgressFromLocalStorage,videoProgressFromSessionStorage):0}}
36class TextResource{constructor(tr){this.tr=tr,this.unusedReplacements=new Array}string(){return this.tr}r(placeholder,value){return this.tr.indexOf(placeholder)<0?this.unusedReplacements.push(placeholder+" -> "+value):this.tr=this.tr.replace(placeholder,value),this}}
37var TypingGuardianServerInterface=null;class TypingGuardian extends DOMAttached{constructor(el,options){super(el,options),TypingGuardianServerInterface=this,/iPad|iPhone|iPod|Android|webOS|Windows Phone/.test(navigator.userAgent)&&confirmAI(options.mobileMessage,this.onMobileRedirect.bind(this),this.onMobileRedirect.bind(this),!0,!1,{confirmBtnCaption:this.options.mobileButtonText})}onMobileRedirect(){window.location.href=this.options.mobileRedirectURL}levelReachedRequest(level,score){axios(new UrlTemplate(this.options.levelReachedURL).r("PLH_level",level).r("PLH_score",score).url,{method:"get"}).then((response=>{var parsedResponse=response.data;(new TypingGuardianClientInterface).levelReachedResponse(parsedResponse.medal)}))}getCurrentLevel(){return this.options.lastCompletedLevel}getHighestMedalOnGameStart(){return this.options.highestAwardedMedal}}
38EasierLevelInstance=null;class EasierLevel{constructor(options,safeObserve){this.trEasierLevelButton=options.trEasierLevelButton,this.trEasierLevelModalDescription=options.trEasierLevelModalDescription,this.safeObserve=safeObserve,EasierLevelInstance=this}setEasierLevel(url,onSuccess){axios(new UrlTemplate(url).r("PLH_level",-1).url,{method:"get"}).then(onSuccess.bind(this))}updateModalTitle(element,previousLevel){element.querySelector(".title").innerText=new TextResource(EasierLevelInstance.trEasierLevelButton).r("{number}",previousLevel).string()}updateModalDescription(element,previousLevel){element.querySelector(".easierLevelText").innerText=new TextResource(EasierLevelInstance.trEasierLevelModalDescription).r("{number}",previousLevel).string()}updateEasierLevelButtonText(element,previousLevel){element.innerText=new TextResource(EasierLevelInstance.trEasierLevelButton).r("{number}",previousLevel).string()}initializeEasierLevel(context){waitForElementToBePresent(".mia-EasierLevelModal").then(EasierLevelInstance.initializeEasierLevelModal.bind(context)),waitForElementToBePresent(".mia-GameSettingsMenu").then((function(element){EasierLevelInstance.onGameSettingsMenuOpen=EasierLevelInstance.onGameSettingsMenuClick.bind(context,element)}))}onGameSettingsMenuClick(element){var easierLevelButtonElement=element.querySelector(".mia-easierLevelButton");easierLevelButtonElement&&("none"===document.querySelector("#levelUpScreen").style.display&&null===document.querySelector("#typingGameTouchDevicesScreen")?(easierLevelButtonElement.style.display="",EasierLevelInstance.initializeEasierLevelButton.call(this,easierLevelButtonElement),EasierLevelInstance.initializeEasierLevelButtonText.call(this,easierLevelButtonElement.querySelector(".mia-easierLevelButtonText"))):easierLevelButtonElement.style.display="none")}initializeEasierLevelModal(element){var previousLevel=this.level-1;EasierLevelInstance.updateModalTitle(element,previousLevel),EasierLevelInstance.updateModalDescription(element,previousLevel)}initializeEasierLevelButton(element){element.style.display=this.level>this.medalMinLevel?"":"none"}initializeEasierLevelButtonText(element){EasierLevelInstance.updateEasierLevelButtonText(element,this.level-1)}}
39var Typing={};class TypingGame extends DOMAttached{constructor(el,options){super(el,options),Typing.id=el,Typing.cjson=options;var svg,svgHeight,svgWidth,rectWidth,keySize,keyOffset,upperBackgroun
39d,lowerBackground,keys,handGroup,handOpacity,typingText,highlight,textBoxWidth,keySounds,wrongKeySound,pieCenter,piePath,pieObject,pieArc,lastHighlightLeft,counterUpperHeight,counterUpperWidth,counterLowerWidth,counterLowerHeight,hiddenInput,levelUpScreen,levelUpScreenId,levelText,nextMedalArea,nextMedalIcon,nextMedalText,medalBoxImage,progressBar,questionsLeft,rootElement,keyboardOverlay=null;function initializeTypingGame(context){rootElement=context,function(){Typing.SpeedSelection="normal",Typing.svg=svg=d3.select("svg.map"),Typing.svgHeight=svgHeight=svg.node().parentNode.clientHeight,Typing.svgWidth=svgWidth=svg.node().parentNode.clientWidth,svg.attr("overflow","hidden"),Typing.rectWidth=rectWidth=svgWidth/16,keySize=40,keyOffset=15,handOpacity=.6,upperBackground=svg.append("g").attr("class","upperBackground"),lowerBackground=svg.append("g").attr("class","lowerBackground").attr("transform","translate(0 "+svgHeight/2+")"),Typing.counterUpperHeight=counterUpperHeight=.3*svgHeight,Typing.counterUpperWidth=counterUpperWidth=12.5*rectWidth,Typing.counterLowerWidth=counterLowerWidth=14.5*rectWidth,void(Typing.counterLowerHeight=counterLowerHeight=.4*svgHeight),(hiddenInput=document.getElementById(Typing.cjson.hiddenInput)).focus(),void svg.on("click",(function(){hiddenInput.focus()})),function(){keySounds=[];for(var i=0;i<5;i++)keySounds[i]=new Audio(Typing.cjson["keysound"+(i+1)]);wrongKeySound=new Audio(Typing.cjson.wrongkeysound)}(),function(){function levelUpClick(event){event.preventDefault(),Typing.LevelJSON.medal.endsWith("games/medals/medal_none.svg")?Typing.ResetInterface():(updateNextMedalArea(Typing.LevelJSON),Typing.LevelJSON.medal.endsWith("games/medals/medal_none.svg")||(medalBoxImage.attr("src",Typing.LevelJSON.medal),medalBoxImage.style("display","inline")),Typing.LevelJSON.medal="games/medals/medal_none.svg"),levelUpScreen.css("display","none"),showGameFeedbackButton(!0),rootElement.el.querySelector(".mia-ProgressSection").style.display="",rootElement.el.querySelector(".mia-svgGameContainer").style.display=""}levelUpScreenId="#levelUpScreen",waitForElementToBePresent(levelUpScreenId).then((function(){(levelUpScreen=jQuery(levelUpScreenId)).css("display","none"),showGameFeedbackButton(!0),levelUpScreen.find(".levelUpButton").on("click",levelUpClick)})),levelText=d3.select(".mia-levelText"),nextMedalArea=d3.select(".nextMedalArea"),nextMedalIcon=d3.select(".medalIcon"),nextMedalText=d3.select(".nextMedalText"),medalBoxImage=d3.select(".mia-medalBox").select("img"),progressBar=d3.select(".mia-progressBar"),questionsLeft=d3.select(".questionsLeft"),waitForElementToBePresent(".mia-easierLevelConfirmButton").then((element=>{element.addEventListener("click",Typing.OnLevelJumpClick)}))}(),stripeBits=d3.range(0,16,1),void upperBackground.selectAll("rect").data(stripeBits).enter().append("rect").attr("width",rectWidth).attr("height",svgHeight/2).attr("x",(function(d){return d*rectWidth})).attr("fill",(function(d){return d%2==0?"rgb(191,122,233)":"rgb(214,170,241)"})),function(){var accuracyBox=upperBackground.append("g").attr("transform","translate("+11.25*rectWidth+" "+.25*rectWidth+")");accuracyBox.append("rect").attr("width",4.5*rectWidth).attr("height",rectWidth).attr("fill","beige").attr("stroke","rgba(156,39,12,1)").attr("stroke-width",2);Typing.AccuracyLabel=accuracyBox.append("text").text("Accuracy: 100%").attr("x",rectWidth/4).attr("y",rectWidth/2).attr("alignment-baseline","central").attr("font-size",rectWidth/2)}(),"typing1"==Typing.cjson.gameName?(upperBackground.append("polygon").attr("points","-1, "+counterUpperHeight+" "+counterUpperWidth+", "+counterUpperHeight+" "+counterLowerWidth+", "+counterLowerHeight+" -1, "+counterLowerHeight).attr("fill","rgb(239,213,188)").attr("stroke","rgb(144,91,53)").attr("stroke-width",1),upperBackground.append("rect").attr("width",counterLowerWidth).attr("height",10).attr("y",counterLowerHeight).attr("fill","rgb(144,91,53)"),upperBackground.append("rect").attr("width",counterLowerWidth-10).attr("height",svgHeight/2-counterLowerHeight-10).attr("y",counterLowerHeight+10).attr("fill","rgb(167,71,27)"),function(){var scoreBox=upperBackgroun
39d.append("g").attr("transform","translate("+11.25*rectWidth+" "+1.75*rectWidth+")");scoreBox.append("rect").attr("width",4.5*rectWidth).attr("height",rectWidth).attr("fill","beige").attr("stroke","rgba(156,39,12,1)").attr("stroke-width",2);Typing.ScoreLabel=scoreBox.append("text").text("Score: 0").attr("x",rectWidth/4).attr("y",rectWidth/2).attr("alignment-baseline","central").attr("font-size",rectWidth/2)}()):(function(){textBoxWidth=10.5*rectWidth;var textBox=upperBackground.append("g").attr("transform","translate("+rectWidth/4+" "+rectWidth/4+")");textBox.append("rect").attr("width",textBoxWidth).attr("height",5*rectWidth).attr("fill","beige").attr("stroke","rgba(156,39,12,1)").attr("stroke-width",2);typingText=textBox.append("text").attr("x",rectWidth/4).attr("y",3*rectWidth/4).attr("font-size",rectWidth/2).call(wrap,textBoxWidth-.5*rectWidth),highlight=textBox.append("text").attr("x",rectWidth/4).attr("y",3*rectWidth/4).attr("font-size",rectWidth/2).attr("fill","lightgray").call(wrap,textBoxWidth-.5*rectWidth)}(),function(){var width=4.5*rectWidth,height=3.5*rectWidth,radius=Math.min(width,height)/2,timerBox=upperBackground.append("g").attr("transform","translate("+11.25*rectWidth+" "+1.75*rectWidth+")");timerBox.append("rect").attr("width",width).attr("height",height).attr("fill","beige").attr("stroke","rgba(156,39,12,1)").attr("stroke-width",2);pieCenter=timerBox.append("g").attr("transform","translate("+width/2+" "+height/2+")");var initialData=[{frame:0},{frame:100}];pieObject=d3.pie().value((function(d){return d.frame})).sort(null),pieArc=d3.arc().innerRadius(0).outerRadius(radius-10),piePath=pieCenter.datum(initialData).selectAll("path").data(pieObject).enter().append("path").attr("fill",(function(d,i){return 0==i?"beige":"rgba(156,39,12,1)"})).attr("d",pieArc).each((function(d){this._current=d}))}());var stripeBits;(function(){lowerBackground.append("rect").attr("width","100%").attr("height","50%").attr("fill","beige");var topRow=(keys=lowerBackground.append("g").attr("class","keys")).append("g").attr("class","topRow"),midRow=keys.append("g").attr("class","midRow"),botRow=keys.append("g").attr("class","botRow"),spaceBar=keys.append("g").attr("class","spaceBar"),topRowLetters=[{key:"Q",finger:0},{key:"W",finger:1},{key:"E",finger:2},{key:"R",finger:3},{key:"T",finger:3},{key:"Y",finger:4},{key:"U",finger:4},{key:"I",finger:5},{key:"O",finger:6},{key:"P",finger:7},{key:"[",finger:7},{key:"]",finger:7}],midRowLetters=[{key:"A",finger:0},{key:"S",finger:1},{key:"D",finger:2},{key:"F",finger:3},{key:"G",finger:3},{key:"H",finger:4},{key:"J",finger:4},{key:"K",finger:5},{key:"L",finger:6},{key:";",finger:7},{key:"'",finger:7},{key:"\\",finger:7}],botRowLetters=[{key:"Z",finger:0},{key:"X",finger:1},{key:"C",finger:2},{key:"V",finger:3},{key:"B",finger:3},{key:"N",finger:4},{key:"M",finger:4},{key:",",finger:5},{key:".",finger:6},{key:"/",finger:7}],spaceBarLetter=[{key:" ",finger:8}];topRow.selectAll("g").data(topRowLetters).enter().append("g").attr("transform",(function(d,i){return"translate("+(20+i*(keyOffset+keySize))+" 20)"})),midRow.selectAll("g").data(midRowLetters).enter().append("g").attr("transform",(function(d,i){return"translate("+(40+i*(keyOffset+keySize))+" "+(20+(keyOffset+keySize))+")"})),botRow.selectAll("g").data(botRowLetters).enter().append("g").attr("transform",(function(d,i){return"translate("+(60+i*(keyOffset+keySize))+" "+(20+2*(keyOffset+keySize))+")"})),spaceBar.selectAll("g").data(spaceBarLetter).enter().append("g").attr("transform",(function(d,i){return"translate(140 "+(20+3*(keyOffset+keySize))+")"})),keys.selectAll("g").selectAll("g").append("rect").attr("width",keySize).attr("height",keySize).attr("fill","beige").attr("stroke",(function(d){return getColorForFinger(d.finger)})).attr("stroke-width",4),keys.selectAll("g").selectAll("g").append("text").text((function(d){return d.key})).attr("font-size",keySize/2).attr("text-anchor","middle").attr("alignment-baseline","central").attr("transform","translate("+keySize/2+" "+keySize/2+")");keys.selectAll("g").selectAll("g").select((function(d){return d&&" "==d.key?this:null})).select("rect").attr("width",5*(keyOffset+keySize))}
39)(),handGroup=lowerBackground.append("g").attr("opacity",handOpacity),function(){for(var i=0;i<2;i++)handGroup.append("ellipse").attr("cx",20+55*i+"%").attr("cy","62%").attr("rx","17%").attr("ry","17%").attr("fill","orange").attr("class","palm"+i)}(),function(){for(var letters="ASDFJKL;",fingerIndex=0;fingerIndex<8;fingerIndex++){var finger=handGroup.append("line"),fingerTip=keys.selectAll("g").selectAll("g").select((function(d){return d&&d.key==letters[fingerIndex]?this:null})),x=getTransformation(fingerTip)[0],y=getTransformation(fingerTip)[1];finger.attr("x1",x+keySize/2).attr("y1",y+keySize/2).attr("x2",(fingerIndex>3?svgWidth/2+100:60)+fingerIndex%4*50).attr("y2",svgHeight/2).attr("stroke","orange").attr("stroke-width",keySize-5).attr("stroke-linecap","round").attr("class","finger"+fingerIndex)}}(),drawThumb(!0),drawThumb(!1),fontsize=30,(keyboardOverlay=lowerBackground.append("g").attr("opacity",0)).append("rect").attr("width","100%").attr("height","50%").attr("fill","beige"),overlayText=keyboardOverlay.append("text").attr("text-anchor","middle").attr("x","50%").attr("y","25%").attr("font-size",fontsize),overlayText.append("tspan").text("Now try to do it without the fingers shown."),overlayText.append("tspan").text("Only look at the letters on the screen!").attr("dy",1.2*fontsize).attr("x","50%");var fontsize,overlayText}(),"text"==options.flavour&&rootElement.initializeTypingTexts()}function onHaveKeyboardButtonClick(){this.el.querySelector(".mia-svgGameContainer").style.display="",this.el.querySelector(".mia-TypingGameTouchDevicesContainer").style.display="none",showGameFeedbackButton(!0),scaleToContainerWidth(),initializeTypingGame(this)}function updateNextMedalArea(levelJSON){levelJSON.nextMedalLevel>0&&!levelJSON.noNextMedal?(nextMedalArea.style("display","inline-block"),nextMedalIcon.attr("src",levelJSON.nextMedalImageSource),nextMedalText.text("after Level: "+levelJSON.nextMedalLevel)):nextMedalArea.style("display","none")}function showGameFeedbackButton(show){var feedbackButton=document.querySelector(".mia-GameFeedbackButton");null!==feedbackButton&&(feedbackButton.style.display=show?"flex":"none")}function wrap(text,width,maxLetters){text.each((function(){for(var word,text=d3.select(this),words=text.text().split(/\s+/).reverse(),line=[],lineNumber=0,y=text.attr("y"),x=text.attr("x"),letterCount=0,tspan=text.text(null).append("tspan").attr("x",x).attr("y",y).attr("dy","0em");word=words.pop();)if(line.push(word),tspan.text(line.join(" ")),tspan.node().getComputedTextLength()>width){if(line.pop(),tspan.text(line.join(" ").substring(0,maxLetters-letterCount)),(letterCount+=line.join(" ").length+1)>=maxLetters)return;line=[word],tspan=text.append("tspan").attr("x",x).attr("y",y).attr("dy",1.1*++lineNumber+"em").text(word)}tspan.text(line.join(" ").substring(0,maxLetters-letterCount))}))}function getColorForFinger(fingerIndex){return d3.schemeCategory10[fingerIndex]}function drawThumb(isLeftOne){var prefix=isLeftOne?"left":"right",spaceBarKey=keys.selectAll("g").selectAll("g").select((function(d){return d&&" "==d.key?this:null})),x=getTransformation(spaceBarKey)[0],y=getTransformation(spaceBarKey)[1],thumb=handGroup.append("line");thumb.attr("class",prefix+"Thumb"),thumb.attr("x1",x+(isLeftOne?3.5:5.5)*keySize).attr("y1",y+keySize/2).attr("x2",isLeftOne?250:450).attr("y2",svgHeight/2+keySize).attr("stroke-width",keySize-5).attr("stroke-linecap","round")}function resetHand(){"ASDFJKL; ".split("").forEach((function(letter){updateFingers(letter,!1)}))}function updateFingers(letter,highlight){if(" "!=letter){var fingerTip=keys.selectAll("g").selectAll("g").select((function(d){return d&&d.key==letter?this:null}));if(void 0!==fingerTip.data()[0]){var fingerIndex=fingerTip.data()[0].finger,x=getTransformation(fingerTip)[0],y=getTransformation(fingerTip)[1];handGroup.select(".finger"+fingerIndex).transition().duration(300).attr("x1",x+keySize/2).attr("y1",y+keySize/2).attr("stroke",highlight?"green":"orange"),highlight&&(lastHighlightLeft=fingerIndex<4)}}else!function(highlight){highlight?updateThumb(!lastHighlightLeft,!0):(updateThumb(!0,!1),updateThumb(!1,!1))}(highlight)}function updateThumb(isLeftOne,highlight){var prefix=isLeftOne?"left"
39:"right",spaceBarKey=keys.selectAll("g").selectAll("g").select((function(d){return d&&" "==d.key?this:null}));getTransformation(spaceBarKey)[0],getTransformation(spaceBarKey)[1];handGroup.select("."+prefix+"Thumb").transition().duration(300).attr("stroke",highlight?"green":"orange")}function getTransformation(node){return node.attr("transform").split("(")[1].split(")")[0].split(" ").map(Number)}null==EasierLevelInstance&&(EasierLevelInstance=new EasierLevel(this.options,this.safeObserve.bind(this))),null==GenericSoundsInstance&&(GenericSoundsInstance=new GenericSounds(this.options.playFeedbackSound)),jQuery(document).ready(function(){if(!document.querySelector(".mia-LevelUpScreen")){window.createVueApplication("legacy-level-up-screen").mount(this.el.querySelector(".mia-LegacyLevelUpScreen"))}if(legacyGlobal.isTouchDevice()){this.el.querySelector(".mia-svgGameContainer").style.display="none";const wrapper=document.createElement("div");wrapper.classList.add("mia-TypingGameTouchDevicesContainer"),wrapper.appendChild(this.el.querySelector(".mia-TypingGameTouchDevices")),this.el.appendChild(wrapper);window.createVueApplication("legacy-typing-game-touch-devices").mount(wrapper),showGameFeedbackButton(!1),waitForElementToBePresent(".mia-haveKeyboardButton").then(function(element){this.safeObserve(element,"click",onHaveKeyboardButtonClick.bind(this))}.bind(this)),EasierLevelInstance.initializeEasierLevel(Typing.cjson)}else initializeTypingGame(this)}.bind(this)),Typing.OnLevelJumpClick=function(){EasierLevelInstance.setEasierLevel(Typing.cjson.levelJumpUrl,(function(){d3.select(".mia-EasierLevelModal").select(".mia-img").node().click(),Typing.GetInitialParams()}))},Typing.InitializeEasierLevel=function(json){EasierLevelInstance.initializeEasierLevel(json)},Typing.SetLevelText=function(curLevel){levelText.text("Level: "+curLevel)},Typing.UpdateNextMedalArea=updateNextMedalArea,Typing.SetProgressBar=function(percentage,numberQuestionsLeft){progressBar.style("width",percentage+"%"),1==numberQuestionsLeft?questionsLeft.text(Typing.cjson.questionsLeftMessageSingular):numberQuestionsLeft||0==numberQuestionsLeft?(questionsLeft.style("display","flex"),questionsLeft.text(Typing.cjson.questionsLeftMessage.replace("{num}",numberQuestionsLeft))):questionsLeft.style("display","none")},Typing.ShowLevelUpOverlay=function(success,level,maxLevel,amount,medalName,robotPictureSrc,robotWrongSrc,medalReceived,medalRobotSrc){levelUpScreen.css("display","flex"),showGameFeedbackButton(!1),rootElement.el.querySelector(".mia-svgGameContainer").style.display="none",rootElement.el.querySelector(".mia-ProgressSection").style.display="none";var previousLevel=level-1;if(success)if(levelUpScreen.find(".title").text(Typing.cjson.trCongratulations),levelUpScreen.find(".levelUpButton").text(Typing.cjson.levelUpContinue),medalReceived){var endingScreenLevel=Typing.LevelJSON.isLastLevel?maxLevel:previousLevel;Typing.ShowEndingScreen(endingScreenLevel,medalName,amount,medalRobotSrc),window.invalidateSelectedTask()}else levelUpScreen.find(".endingScreenButtons").css("display","none"),levelUpScreen.find(".levelButtons").css("display","flex"),levelUpScreen.find(".image").attr("src",robotPictureSrc),Typing.LevelJSON.medal.endsWith("games/medals/medal_none.svg")?(levelUpScreen.find(".header").text(Typing.cjson.trHeaderWithoutMedal.replace("{number}",previousLevel)),levelUpScreen.find(".description").text(Typing.cjson.trDescriptionWithoutMedal.replace("{number}",previousLevel).replace("{coins}",amount))):(levelUpScreen.find(".header").text(Typing.cjson.trHeaderWithMedal.replace("{number}",previousLevel).replace("{medalType}",medalName)),levelUpScreen.find(".description").text(Typing.cjson.trDescriptionWithMedal.replace("{number}",previousLevel).replace("{coins}",amount).replace("{medalType}",medalName))),1===level&&(levelUpScreen.find(".levelButtons").css("display","none"),levelUpScreen.find(".endGameButtons").css("display","flex"),levelUpScreen.find(".continueButton").css("display","inline-block"));else levelUpScreen.find(".title").text(Typing.cjson.trOops),levelUpScreen.find(".image").attr("src",robotWrongSrc),levelUpScreen.find(".description").text(Typing.cjson.trLevelNotPassed),levelUpScreen.find(".header").text(Typing.cjson.youLostTitleText),levelUpScreen.find(".levelUp
39Button").text(Typing.cjson.retryButtonText)},Typing.ShowEndingScreen=function(level,medalName,amount,robotSrc){waitForElementToBePresent(levelUpScreenId).then((function(){levelUpScreen.css("display","flex"),showGameFeedbackButton(!1),rootElement.el.querySelector(".mia-svgGameContainer").style.display="none",rootElement.el.querySelector(".mia-ProgressSection").style.display="none",levelUpScreen.find(".endingScreenButtons").css("display","flex"),levelUpScreen.find(".levelButtons").css("display","none"),levelUpScreen.find(".title").text(Typing.cjson.trCongratulations),levelUpScreen.find(".image").attr("src",robotSrc),levelUpScreen.find(".header").text(Typing.cjson.trHeaderWithMedal.replace("{number}",level).replace("{medalType}",medalName)),levelUpScreen.find(".description").text(Typing.cjson.trDescriptionWithMedal.replace("{number}",level).replace("{coins}",amount).replace("{medalType}",medalName)),levelUpScreen.find(".repeatButton").on("click",Typing.OnRepeatMedalClick),Typing.InitializeEasierLevel(Typing.cjson)}))},Typing.OnRepeatMedalClick=function(event){event.preventDefault(),axios(new UrlTemplate(Typing.cjson.endingScreenRepeatMedalUrl).url,{method:"get"}).then(Typing.GetInitialParams),levelUpScreen.css("display","none"),showGameFeedbackButton(!0),rootElement.el.querySelector(".mia-svgGameContainer").style.display="",rootElement.el.querySelector(".mia-ProgressSection").style.display=""},Typing.DrawStartButton=function(){if(!upperBackground.selectAll(".startMenu").empty())return;var width=7.5*rectWidth,height=2*rectWidth,posX=1.75*rectWidth,posY=.75*rectWidth,buttonContainer=upperBackground.append("g").attr("transform","translate("+posX+" "+posY+")").attr("class","startMenu"),startButton=buttonContainer.append("g").on("mouseup",(function(){Typing.Start(),buttonContainer.remove()}));startButton.append("rect").attr("width",width).attr("height",height).attr("rx",15).attr("ry",15).style("fill","rgba(7,134,0,1)").style("stroke","rgba(156,39,12,1)").style("stroke-width",3),startButton.append("text").text("Start").attr("font-size",rectWidth).style("fill","white").attr("x",width/2).attr("y",2*height/3).attr("text-anchor","middle");var speedButtonsTranslateY=height+rectWidth/4,speedButtons=buttonContainer.append("g").attr("transform","translate(0 "+speedButtonsTranslateY+")"),slowButton=speedButtons.append("g").attr("transform","translate(0 0)").on("click",(function(){onSpeedClick(slowButton)}));slowButton.append("rect"),slowButton.append("text").text("Slow");var normalButtonTranslateX=width/3+.125*rectWidth,normalButton=speedButtons.append("g").attr("transform","translate("+normalButtonTranslateX+" 0)").on("click",(function(){onSpeedClick(normalButton)}));normalButton.append("rect"),normalButton.append("text").text("Normal");var fastButtonTranslateY=.125*rectWidth+2*width/3,fastButton=speedButtons.append("g").attr("transform","translate("+fastButtonTranslateY+" 0)").on("click",(function(){onSpeedClick(fastButton)}));switch(fastButton.append("rect"),fastButton.append("text").text("Fast"),buttonContainer.selectAll("g").attr("cursor","pointer"),speedButtons.selectAll("rect").attr("width",width/3-.5*rectWidth/3).attr("height",rectWidth).attr("rx",15).attr("ry",15).style("fill","beige").style("stroke","rgba(156,39,12,1)").style("stroke-width",3),speedButtons.selectAll("text").attr("font-size",rectWidth/2).attr("x",width/6-.125*rectWidth).attr("y",2*rectWidth/3).attr("text-anchor","middle"),Typing.SpeedSelection){case"Slow":onSpeedClick(slowButton);break;case"Fast":onSpeedClick(fastButton);break;default:onSpeedClick(normalButton)}function onSpeedClick(button){speedButtons.selectAll("rect").style("fill","beige"),button.select("rect").style("fill","lightgreen"),Typing.SpeedSelection=button.select("text").text()}},Typing.UpdateTextBox=function(content){typingText.text(content).call(wrap,textBoxWidth-.5*rectWidth,1e6),highlight.text("")},Typing.ColorizeTextBox=function(content,position){highlight.text(content).call(wrap,textBoxWidth-.5*rectWidth,position)},Typing.UpdateTimer=function(framesLeft,framesPast){var updatedData=[{frame:framesPast},{frame:framesLeft}];pieCenter.datum(updatedData),(piePath=piePath.data(pieObject)).transition().duration(0).attrTween("d",(function(a){var i=d3.interpolate(this._current,a);return this._current=i(0),function(t){return pieArc(i(t))}}))},Typing.GetColorForLetter=function(letter){return getColorForFinger(function(letter){var key=keys.selectAll("g").selectAll("g").select((function(d){return d&&d.key==letter?this:null}));return void 0===key.data()[0]?9:key.data()[0].finger}(letter))},Typing.ShowKeyboard=function(bool){bool?keyboardOverlay.attr("opacity",0):keyboardOverlay.attr("opacity",1)},Typing.CorrectKeyHit=function(key){return function(){if(null!=GenericSoundsInstance&&GenericSoundsInstance.playFeedbackSound){var soundNum=Math.floor(5*Math.random());keySounds[soundNum].load(),keySounds[soundNum].play()}}(),!keys.selectAll("rect").select((function(d){return d.key==key?this:null})).attr("fill","green").transition().duration(500).attr("fill","beige").empty()},Typing.WrongKeyHit=function(key){var isPrintableKeyHit=!keys.selectAll("rect").select((function(d){return d.key==key?this:null})).attr("fill","red").transition().duration(500).attr("fill","beige").empty();isPrintableKeyHit&&null!=GenericSoundsInstance&&GenericSoundsInstance.playFeedbackSound&&(wrongKeySound.load(),wrongKeySound.play());return isPrintableKeyHit},Typing.ResetHand=resetHand,Typing.ResetHandHighlightNextKey=function(letter){resetHand(),updateFingers(letter.toUpperCase(),!0)}}initializeTypingTexts(){var frame=-1,correctKeys=0,wrongKeys=0,levelLoopHandle=null,showKeyboard=!0,maxLevel=50,numberOfLetters=50,level=1,amountWon=0,success=!1,typingText="",levelRunning=!1,speed=45,frameThreshold=1e6;function resetInterface(){stop(),Typing.SetProgressBar(0,numberOfLetters),Typing.AccuracyLabel.text("Accuracy: 100%"),Typing.ResetHand(),Typing.DrawStartButton()}function getInitialParams(){axios(new UrlTemplate(Typing.cjson.processAnswerUrl).r("PLH_TimeNeeded",0).r("PLH_KeystrokesCorrect",0).r("PLH_KeystrokesIncorrect",0).r("PLH_success",!1).r("PLH_Status",1).r("PLH_MedalType",Typing.cjson.medalType).r("PLH_itemId",-1).url,{method:"get"}).then(onInitSuccess)}function loadLevelParams(req,finished){var levelJSON=req.data;Typing.LevelJSON=levelJSON,frame=-1,correctKeys=0,wrongKeys=0,showKeyboard=levelJSON.showKeyboard,maxLevel=levelJSON.maxLevel,level!=levelJSON.level,level=levelJSON.level,amountWon=levelJSON.amount,levelJSON.newreward,levelJSON.openProdding,success=levelJSON.success,typingText=levelJSON.text.trim(),numberOfLetters=typingText.length,speed=levelJSON.speed,levelJSON.medalMinLevel=Typing.cjson.medalMinLevel,Typing.SetLevelText(level),Typing.ShowKeyboard(showKeyboard),Typing.InitializeEasierLevel(levelJSON),Typing.UpdateNextMedalArea(levelJSON),finished||Typing.SetProgressBar(0,numberOfLetters)}function onInitSuccess(req){resetInterface(),loadLevelParams(req,!1)}function onLevelFinished(req){loadLevelParams(req,!0),Typing.ShowLevelUpOverlay(success,level,maxLevel,amountWon,req.data.medalName,req.data.robotPictureSrc,req.data.robotWrongSrc,req.data.medalReceived,req.data.medalRobotPictureSrc)}function updateKeyboardVisual(){correctKeys>=numberOfLetters?Typing.ResetHand():(Typing.ColorizeTextBox(typingText,correctKeys),Typing.ResetHandHighlightNextKey(typingText.charAt(correctKeys)))}function endOfLevelCheck(accuracy,timeOut){!function(timeNeeded,correctKeys,incorrectKeys,success,status){axios(new UrlTemplate(Typing.cjson.processAnswerUrl).r("PLH_TimeNeeded",timeNeeded).r("PLH_KeystrokesCorrect",correctKeys).r("PLH_KeystrokesIncorrect",incorrectKeys).r("PLH_success",success).r("PLH_Status",status).r("PLH_MedalType",Typing.cjson.medalType).r("PLH_itemId",-1).url,{method:"get"}).then(onLevelFinished)}(60*frame,correctKeys,wrongKeys,!timeOut&&100*accuracy>=85,2)}function stop(){levelRunning=!1,Typing.UpdateTextBox(""),clearInterval(levelLoopHandle)}d3.select("body").on("keydown",(function(){!function(key){if("INPUT"==d3.event.target.tagName.toUpperCase()&&"TEXT"==d3.event.target.type.toUpperCase())return;" "!=key&&"BACKSPACE"!=key||d3.event.preventDefault();
39if(!levelRunning)return;key!=typingText.charAt(correctKeys).toUpperCase()?Typing.WrongKeyHit(key)&&wrongKeys++:(Typing.CorrectKeyHit(key),correctKeys++,updateKeyboardVisual());!function(){var totalKeys=correctKeys+wrongKeys;if(totalKeys>0){var accuracy=(100*correctKeys/totalKeys).toFixed(0);Typing.AccuracyLabel.text("Accuracy: "+accuracy+"%")}Typing.SetProgressBar(100*correctKeys/numberOfLetters,numberOfLetters-correctKeys),correctKeys==numberOfLetters&&(stop(),endOfLevelCheck(correctKeys/totalKeys,!1))}()}(d3.event.key.toUpperCase())})),Typing.cjson.endingScreenShown?Typing.ShowEndingScreen(Typing.cjson.endingScreenLevel,Typing.cjson.endingScreenMedalName,Typing.cjson.endingScreenAmountOfScoops,Typing.cjson.endingScreenRobotSrc):getInitialParams(),Typing.ResetInterface=resetInterface,Typing.GetInitialParams=getInitialParams,Typing.Start=function(){levelRunning=!0,Typing.UpdateTextBox(typingText),updateKeyboardVisual(),"Fast"==Typing.SpeedSelection?speed+=25:"Normal"==Typing.SpeedSelection||"Slow"==Typing.SpeedSelection&&(speed=Math.max(1,speed-15));frameThreshold=3600*typingText.length/speed,levelLoopHandle=setInterval((function(){document.getElementById(Typing.id)||stop(),frame++,Typing.UpdateTimer(frameThreshold-frame,frame),frame>=frameThreshold&&(endOfLevelCheck(correctKeys/(correctKeys+wrongKeys),!0),stop())}),1e3/60)}}onMobileRedirect(){window.location.href=this.options.mobileRedirectURL}}
40class UpScaledImageHandler{constructor(game){this.game=game}initializeListenerForZoomInQuestionImg(){var image=this.game.el.querySelector(".mia-QuestionImg"),upscaledImagePopup=document.querySelector(".mia-upscaledQuestionImage");null!=image&&(null==upscaledImagePopup&&(upscaledImagePopup=this.createUpScaledImageDiv()),this.setImageToUpscaledImagePopup(image),this.game.stopObserveAllListeners(upscaledImagePopup),this.game.safeObserve(upscaledImagePopup,"click",this.onUpscaledImagePopupCloseClick.bind(this.game)),this.game.safeObserve(upscaledImagePopup,"touchstart",this.onUpscaledImagePopupCloseTouch.bind(this.game)),this.game.safeObserve(image,"click",this.onUpscaledImagePopupOpenClick.bind(this.game)))}createUpScaledImageDiv(){var formTagElement=document.querySelector("form"),newUpscaledImageDiv=document.createElement("div");newUpscaledImageDiv.className="mia-upscaledQuestionImagePopup";var newUpscaledImageDivPopUp=document.createElement("div");return newUpscaledImageDivPopUp.className="mia-upscaledQuestionImage",newUpscaledImageDiv.appendChild(newUpscaledImageDivPopUp),formTagElement.appendChild(newUpscaledImageDiv),newUpscaledImageDiv}setImageToUpscaledImagePopup(image){var upscaledImage=document.querySelector(".mia-upscaledQuestionImage"),style=image.currentStyle||window.getComputedStyle(image,!1);upscaledImage.style.backgroundImage=style.backgroundImage}onUpscaledImagePopupCloseClick(event){event.stopPropagation(),document.querySelector(".mia-upscaledQuestionImagePopup").classList.remove("revealed")}onUpscaledImagePopupOpenClick(){document.querySelector(".mia-upscaledQuestionImagePopup").classList.add("revealed")}onUpscaledImagePopupCloseTouch(event){event.stopPropagation()}}
41var ExceptionHandling={onPageLoadException:function(req,ex){throw MiaErrorPrompt("Sorry, an unexpected error occurred."),ex}};
42class ProgressIndicator{constructor(el){this.progressIndicator=null,this.positionRelative=!1,this.el=el}showProgressIndicator(positionRelative=!1,cssRuleForAlignEl="div",searchCssRuleDown=!1){if(!this.progressIndicator){this.progressIndicator=document.createElement("div"),this.progressIndicator.className="progressIndicatorDiv";const progImg=document.createElement("img");progImg.src="/static-images/shared/shared/tng/progress.gif",progImg.className="progressIndicator",this.progressIndicator.appendChild(progImg),positionRelative?this.positionRelative=!0:(legacyGlobal.getToplevelElement().appendChild(this.progressIndicator),this.positionRelative=!1)}cssRuleForAlignEl||(cssRuleForAlignEl="div");let alignEl=this.el?searchCssRuleDown?this.el.querySelector(cssRuleForAlignEl):this.el.closest(cssRuleForAlignEl):null;alignEl=alignEl||this.el;const masterDims_width=alignEl.offsetWidth,masterDims_height=alignEl.offsetHeight;if(this.positionRelative)alignEl.style.position="relative",alignEl.appendChild(this.progressIndicator),this.progressIndicator.style.left=0,this.progressIndicator.style.top=0,this.progressIndicator.style.width="100%",this.progressIndicator.style.height="100%",this.progressIndicator.style.minHeight="inherit";else{const masterPos=alignEl.getBoundingClientRect();this.progressIndicator.style.left=masterPos.left+"px",this.progressIndicator.style.top=masterPos.top+"px",this.progressIndicator.style.width=masterDims_width+"px",this.progressIndicator.style.height=masterDims_height+"px"}this.progressIndicator.style.display="",this.progressIndicator.style.position="absolute",this.progressIndicator.style.zIndex="900",this.progressIndicator.style.opacity=.5}hideProgressIndicator(){this.progressIndicator&&(this.progressIndicator.style.display="none")}}
43class Levels{constructor(container,levelOptions){this.container=container,this.levelOptions=levelOptions,this.el=this.container.el,this.showTextMediaInitially=!0,this.jumpLevelsClicked=!1,this.hasJustJumpedLevels=!1,this.setLevelInformation(this.levelOptions.level),this.modalId="levelUpModal",this.modalElement=jQuery(".modal[modal-id="+this.modalId+"]"),this.medalBox=this.el.querySelector(".medalBox").querySelector("img"),this.hideMedalBoxIfThereIsNoMedal(),this.displayChallengeCompletedWindow=!1,this.initializeClickListeners(),document.querySelector(".mia-Lightbox")||this.modalElement.appendTo("form")}
43customLoadEvent(pageLoadJSON){this.container.disableInput();var newLevelText="Level: "+pageLoadJSON.level;return this.adjustDisplayToNewRegularLevel(pageLoadJSON),!pageLoadJSON.isLevelUp||this.onLevelUp(newLevelText)}onSendAnswerToServerSuccess(response,rejectPromise){this.json=response}initializeClickListeners(){jQuery(".levelUpButton").click(this.onNextLevelOkayClick.bind(this)),jQuery(".lastLevelContinueButton").click(this.onNextLevelOkayClick.bind(this)),jQuery(".levelDown").click(this.onLevelDownClick.bind(this)),removeFocusFromModalInWindow(this.modalId)}hideMedalBoxIfThereIsNoMedal(){("true"==this.levelOptions.nomedal||null!=this.medalBox&&""==this.medalBox.src)&&(this.medalBox.style.display="none")}setLevelInformation(level){this.el.querySelector("span.messageLevel").innerHTML=new TextResource(this.levelOptions.trLevelInformation).r("{level}",level).string()}setLevelDownVisibility(currentLevel){this.el.querySelector(".levelDown").style.display=1==currentLevel?"none":""}setNextMedalSignVisibility(nextMedalLevel,hasNextMedal){hasNextMedal&&nextMedalLevel>0?(this.el.querySelector(".nextMedalSpan").innerHTML="after Level "+nextMedalLevel,this.el.querySelector(".nextMedalSign").style.display="inline-block"):this.el.querySelector(".nextMedalSign").style.display="none"}
43adjustDisplayToNewRegularLevel(pageLoadJSON){this.el.querySelector(".medalIcon").src=pageLoadJSON.nextMedalImageSource,this.el.querySelector(".maxLevelSpan").style.display="inline-block",this.setNextMedalSignVisibility(pageLoadJSON.nextMedalLevel,!pageLoadJSON.noNextMedal),this.setLevelDownVisibility(pageLoadJSON.level)}onLevelUp(newLevelText){var previousLevelWasLastLevelOfGame="Level: 1"==newLevelText;return this.el.querySelector(".currentLevel").innerHTML=newLevelText,jQuery(".level").html(newLevelText),this.el.querySelector(".questionsLeft").innerHTML="",this.el.querySelector(".progressBar").style.width=document.querySelectorAll(".progressBox")[0].clientWidth+"px",jQuery(".lastLevelContinueButton").css("display",previousLevelWasLastLevelOfGame?"inline-block":"none"),jQuery(".levelUpButton").css("display",previousLevelWasLastLevelOfGame?"none":""),jQuery(".endGameButtons").css("display","none"),jQuery(".modal[modal-id="+this.modalId+"] .modal-header > h3").html(this.levelOptions.trCongratsTitle),jQuery(".infoText").html(new TextResource(this.levelOptions.trLevelReached).r("{level}",this.json.level).r("{amount}",this.json.amount).string()),this.hasJustJumpedLevels||(this.modalElement.modal({backdrop:"static",keyboard:!1}),this.container.disableInput()),this.hasJustJumpedLevels?(this.hasJustJumpedLevels=!1,!0):(previousLevelWasLastLevelOfGame&&this.onNextLevelOkayClick(),!1)}
43encloseModalInGameWindow(){jQuery(".modal-backdrop").appendTo(".quiz");var bodyJQuery=jQuery("body");bodyJQuery.removeClass("modal-open"),bodyJQuery.css("padding-right",0)}onNextLevelOkayClick(ev){null!=ev&&ev.preventDefault();var gotNewMedal=null!=this.json.medal&&!this.json.medal.endsWith("games/medals/medal_none.svg"),gotNewPet=null!=this.json.pet&&""!=this.json.pet,finishedTheGame=1==this.json.level&&!this.hasJustJumpedLevels;gotNewMedal?(null!=this.medalBox&&(this.medalBox.src=this.json.medal,this.medalBox.style.display="inline"),this.modalElement.find(".infoText").html(this.levelOptions.trMedalMessage),this.modalElement.find(".level").css("display","none"),this.modalElement.find(".image").css("display","inline-block"),this.modalElement.find(".image").attr("src",this.json.medal),this.modalElement.find(".imageCaption").css("display","block"),this.modalElement.find(".imageCaption").html(this.json.medalName),null!=this.json.openProdding&&""!=this.json.openProdding&&this.modalElement.find(".openProdding").html(this.json.openProdding),this.json.medal="games/medals/medal_none.svg",this.displayChallengeCompletedWindow=!0):gotNewPet?(this.modalElement.find(".infoText").html(this.levelOptions.trPetMessage),this.modalElement.find(".level").css("display","none"),this.modalElement.find(".image").attr("src",this.json.pet),this.modalElement.find(".image").css("display","inline-block"),this.modalElement.find(".imageCaption").html(this.json.petName),this.modalElement.find(".imageCaption").css("display","block"),this.modalElement.find(".openProdding").html(""),this.json.pet=""):(this.modalElement.find(".image").css("display","none"),this.modalElement.find(".imageCaption").css("display","none"),this.modalElement.find(".openProdding").html(""),finishedTheGame?(this.modalElement.find(".infoText").html(new TextResource(this.levelOptions.trEndOfGame).r("{amount}",this.json.amount).r("{newreward}",this.json.newreward).string()),this.modalElement.find(".level").css("display","none"),this.modalElement.find(".levelButtons").css("display","none"),this.modalElement.find(".endGameButtons").css("display","block"),this.modalElement.find(".continueButton").css("display","inline-block")):(this.startNextLevel(),null!=ev&&this.container.showPage(!0))),this.json.challengeWasCompleted&&(this.modalElement.find(".levelButtons").css("display","none"),this.modalElement.find(".challengeCompletedButtons").css("display","inline-block"))}startNextLevel(){this.modalElement.modal("hide"),this.jumpLevelsClicked&&(this.jumpLevelsClicked=!1,this.jumpLevels(4)),this.container.progressIndicator.hideProgressIndicator(),this.container.enableInput()}jumpLevels(n){this.hasJustJumpedLevels=!0,axios(new UrlTemplate(this.levelOptions.levelJumpUrl).r("PLH_level",n).url,{method:"get"}).then((response=>{var responseTextJSON=response.data;this.container.updateQuestion(Object.assign({},responseTextJSON.ProcessAnswerResult,responseTextJSON.QuestionData));var newLevelText="Level: "+responseTextJSON.ProcessAnswerResult.level;this.el.querySelector(".currentLevel").innerHTML=newLevelText}))}onLevelDownClick(ev){this.jumpLevels(-1)}}Object.assign(Levels.prototype,ExceptionHandling);
44class LevelMedia{constructor(game){this.game=game,this.mediaOverlay=this.game.el.querySelector(".LevelMediaOverlay"),this.mediaOverlay.querySelector(".background").style.opacity=.8,this.mediaText=this.mediaOverlay.querySelector(".LevelMediaText"),this.initializeListenersForOpeningMedia(),this.initializeListenersForClosingMedia(),this.closeMedia()}initializeListenersForClosingMedia(){this.game.safeObserve(this.mediaOverlay.querySelector(".levelTextClose"),"click",this.onLevelMediaCloseButtonClick.bind(this))}onLevelMediaCloseButtonClick(ev){this.closeMedia()}initializeListenersForOpeningMedia(){this.attachHandlerOnClickIfElementExists(".textMediaButton",this.onToLessonClick)}onToLessonClick(ev){this.showMedia()}loadMedia(mediaText){this.hasTextMedia=null!=mediaText&&null!=mediaText.text,this.hasTextMedia&&(this.mediaText.innerHTML=mediaText.text,this.viewCount=0,this.viewTimeSeconds=mediaText.viewTimeSeconds,this.secondViewTimeSeconds=mediaText.secondViewTimeSeconds)}showMedia(){if(this.hasTextMedia){var maximumDisplayTimeInSeconds=0==this.viewCound?this.viewTimeSeconds:this.secondViewTimeSeconds;this.openMedia(maximumDisplayTimeInSeconds)}}closeMedia(){this.mediaOverlay.style.display="none",this.stopCountdown();var event=document.createEvent("Event");event.initEvent("closeMedia",!0,!0),this.game.el.dispatchEvent(event)}openMedia(maximumDisplayTimeInSeconds){this.mediaOverlay.style.display="",this.viewCount++,null!=maximumDisplayTimeInSeconds&&this.startCountdown(maximumDisplayTimeInSeconds)}startCountdown(time){this.stopCountdown(),this.secondsLeftToViewLeveMedia=time,this.countdown=setInterval(this.decreaseSecondsLeftToViewLevelMedia.bind(this),1e3),this.updateDisplayOfTimeLeftToViewLevelMedia()}stopCountdown(){null!=this.countdown&&(clearInterval(this.countdown),this.countdown=void 0)}decreaseSecondsLeftToViewLevelMedia(){this.secondsLeftToViewLeveMedia--,this.updateDisplayOfTimeLeftToViewLevelMedia(),this.secondsLeftToViewLeveMedia<=0&&(this.stopCountdown(),this.closeMedia())}updateDisplayOfTimeLeftToViewLevelMedia(){this.game.el.querySelector(".LevelMediaTimer").innerHTML=this.secondsLeftToViewLeveMedia}attachHandlerOnClickIfElementExists(elementSelector,handlerCallback){var selectedElement=this.game.el.querySelector(elementSelector);null!=selectedElement&&this.game.safeObserve(selectedElement,"click",handlerCallback.bind(this))}}
45class MultipleChoiceQuiz{constructor(container,gameSettings,correctAnswerCallback,incorrectAnswerCallback,updateQuestionCallback){this.correctAnswerBackgroun
45dColor="#1F974D",this.incorrectAnswerBackgroundColor="#BA1D04",this.correctAnswerFontColor="#FFFFFF",this.incorrectAnswerFontColor="#FFFFFF",this.container=container,this.gameSettings=gameSettings,this.correctAnswerCallback=correctAnswerCallback,this.incorrectAnswerCallback=incorrectAnswerCallback,this.updateQuestionCallback=updateQuestionCallback}onNextQuestionLoaded(){this.locked=!1,this.correctAnswerElement=this.getCorrectAnswerElement(),this.incorrectAnswerElements=this.getIncorrectAnswerElements(),this.initializeAllAnswerClickHandlers()}createTextToSpeechElements(questionSpeechFilePath,answerSpeechFilePaths){var textToSpeechElements=[];textToSpeechElements.push(this.createQuestionTextToSpeechElement(questionSpeechFilePath));for(var i=0;i<answerSpeechFilePaths.length;i++)textToSpeechElements.push(this.createAnswerTextToSpeechElement(i,answerSpeechFilePaths));return textToSpeechElements}getIdentifierOfCorrectAnswer(){return this.correctAnswerIdentifier}getCorrectAnswerElement(){return this.container.el.querySelector(".solution")}getIncorrectAnswerElements(){return[this.container.el.querySelector(".answer0"),this.container.el.querySelector(".answer1"),this.container.el.querySelector(".answer2"),this.container.el.querySelector(".answer3")].filter((function(value){return!value.classList.contains("solution")}))}getAnswerId(domElement){for(var classes=domElement.className.split(/\s+/),i=0;i<classes.length;i++)if(0==classes[i].indexOf("answerId"))return parseInt(classes[i].substring(8));return-1}initializeAllAnswerClickHandlers(){this.initializeCorrectAnswerClickHandler();for(var i=0;i<this.incorrectAnswerElements.length;i++)this.initializeIncorrectAnswerClickHandler(i)}initializeCorrectAnswerClickHandler(){this.addListener(this.correctAnswerElement,"click",this.onCorrectAnswerClicked)}initializeIncorrectAnswerClickHandler(index){this.addListener(this.incorrectAnswerElements[index],"click",(function(ev){this.onIncorrectAnswerClicked(this.incorrectAnswerElements[index],ev)}))}addListener(element,event,func){this.container.safeObserve(element,event,func.bind(this))}onCorrectAnswerClicked(ev){this.locked||(this.locked=!0,this.displayAnswerFeedback(this.correctAnswerElement,!0),this.correctAnswerCallback(this.getAnswerId(this.correctAnswerElement)).then(function(response){this.updateQuestionCallback(Object.assign({},response.ProcessAnswerResult,response.QuestionData),!1)}.bind(this)))}onIncorrectAnswerClicked(clickedElement,ev){this.locked||(this.locked=!0,this.displayAnswerFeedback(clickedElement,!1),this.incorrectAnswerCallback(this.getAnswerId(clickedElement)).then(function(response){this.updateQuestionCallback(Object.assign({},response.ProcessAnswerResult,response.QuestionData))}.bind(this)))}displayAnswerFeedback(clickedElement,answerIsCorrect){this.gameSettings.shouldDisplayWhetherChosenAnswerIsCorrect&&(answerIsCorrect?(this.setBackgroundColor(clickedElement,this.correctAnswerBackgroundColor),this.setFontColor(clickedElement,this.correctAnswerFontColor)):(this.setBackgroundColor(clickedElement,this.incorrectAnswerBackgroundColor),this.setFontColor(clickedElement,this.incorrectAnswerFontColor))),!answerIsCorrect&&this.gameSettings.shouldDisplayCorrectSolution&&this.flashCorrectSolution(3e3)}flashCorrectSolution(durationInMilliseconds){this.flashingCorrectSolution=setInterval(this.toggleCorrectSolutionBackground.bind(this),250),setTimeout((function(){clearInterval(this.flashingCorrectSolution),this.toggleCorrectSolutionBackground()}),durationInMilliseconds)}toggleCorrectSolutionBackground(){this.getBackgroundColor(this.correctAnswerElement)==this.correctAnswerBackgroundColor?(this.setBackgroundColor(this.correctAnswerElement,this.defaultAnswerBackgroundColor),this.setFontColor(this.correctAnswerElement,this.incorrectAnswerFontColor)):(this.defaultAnswerBackgroundColor=this.getBackgroundColor(this.correctAnswerElement),this.setBackgroundColor(this.correctAnswerElement,this.correctAnswerBackgroundColor),this.setFontColor(this.correctAnswerElement,this.correctAnswerFontColor))}setBackgroundColor(element,color){element.style.backgroundColor=color}setFontColor(element,color){element.style.color=color}
45getBackgroundColor(element){return window.getComputedStyle(element).getPropertyValue("backgroundColor")}getFontColor(element){return window.getComputedStyle(element).getPropertyValue("color")}createQuestionTextToSpeechElement(questionSpeechFilePath){var questionElement={};return questionElement.domElement=this.container.el.querySelector(".question"),questionElement.identifier="question",questionElement.soundUrl=questionSpeechFilePath,questionElement.highlightFontColor="white",questionElement.defaultFontColor=this.getFontColor(questionElement.domElement),questionElement}createAnswerTextToSpeechElement(answerIndex,answerSpeechFilePaths){var answerElement={};return answerElement.domElement=this.container.el.querySelector(".answer"+answerIndex),answerElement.identifier="answer"+answerIndex,answerElement.soundUrl=answerSpeechFilePaths[answerIndex],answerElement.highlightFontColor="white",answerElement.defaultFontColor=this.getFontColor(answerElement.domElement),this.isCorrectAnswer(answerElement)&&(this.correctAnswerIdentifier=answerElement.identifier),answerElement}isCorrectAnswer(answerElement){return answerElement.domElement.className.split(/\s+/).indexOf("solution")>-1}}
46var createGameSettings=function(feedbackMode){var settings={};return settings.shouldDisplayWhetherChosenAnswerIsCorrect=/^Feedback/.test(feedbackMode),settings.shouldDisplayCorrectSolution="FeedbackAndCorrectSolution"==feedbackMode,settings};
47class TextToSpeech{constructor(){this.sounds={}}setSounds(identifierToSoundUrlDictioary){this.destroyAllExistingSounds(),this.createSounds(identifierToSoundUrlDictioary)}playSpeechForTextIdentifier(identifier,onFinished){var sound=this.sounds[identifier];sound?sound.play({onfinish:function(){this.stop(),onFinished()}}):console.log("No sound found for identifier "+identifier+".")}stopSpeechForTextIdentifier(identifier){var sound=this.sounds[identifier];sound?sound.stop():console.log("No sound found for identifier "+identifier+".")}stopAllExistingSounds(){for(var identifier in this.sounds)this.sounds[identifier].stop()}
47destroyAllExistingSounds(){for(var identifier in this.sounds)this.sounds[identifier].destruct()}createSounds(identifierToSoundUrlDictioary){for(var identifier in this.sounds={},identifierToSoundUrlDictioary){var soundUrl=identifierToSoundUrlDictioary[identifier];this.sounds[identifier]=soundManager.createSound({id:identifier,url:soundUrl})}}}
48var GamesTextToSpeechInstance=null;class GamesTextToSpeech extends TextToSpeech{constructor(game,isEnabled,isEnabledByParent){super(),GamesTextToSpeechInstance=this,this.game=game,this.textToSpeechElements=[],this.isEnabled=isEnabled,this.isEnabledByParent=isEnabledByParent}setTextToSpeechElements(textToSpeechElements){this.textToSpeechElements=textToSpeechElements,this.setSounds(this.getIdentifierToSoundUrlDictioary(textToSpeechElements)),this.isEnabledByParent?(this.showPlayButtons(),this.initializePlayButtonClickHandlers()):this.hidePlayButtons()}readSpeechForAllElementsInOrder(){this.isEnabled&&this.readSpeechForElementsInOrder(this.textToSpeechElements)}removeTextToSpeechEffects(){this.stopAllExistingSounds();for(var i=0;i<this.textToSpeechElements.length;i++){var currentElement=this.textToSpeechElements[i];this.stopHighlighting(currentElement)}}turnOnTextToSpeech(){this.isEnabled=!0}turnOffTextToSpeech(){this.isEnabled=!1,this.removeTextToSpeechEffects()}stopHighlighting(element){this.setBoxShadow(element.domElement,element.defaultFontColor)}readSpeechForElementsInOrder(textToSpeechElements){var currentElement=textToSpeechElements[0];this.setBoxShadow(currentElement.domElement,currentElement.highlightFontColor);this.playSpeechForTextIdentifier(currentElement.identifier,(()=>{this.setBoxShadow(currentElement.domElement,currentElement.defaultFontColor),1!=textToSpeechElements.length&&this.readSpeechForElementsInOrder(textToSpeechElements.slice(1))}))}getIdentifierToSoundUrlDictioary(textToSpeechElements){for(var identifierToSoundUrlDictioary={},i=0;i<textToSpeechElements.length;i++){var currentElement=textToSpeechElements[i];identifierToSoundUrlDictioary[currentElement.identifier]=currentElement.soundUrl}return identifierToSoundUrlDictioary}initializePlayButtonClickHandlers(){for(var i=0;i<this.textToSpeechElements.length;i++)this.initializePlayButtonClickHandler(this.textToSpeechElements[i])}initializePlayButtonClickHandler(textToSpeechElement){var button=textToSpeechElement.domElement.querySelector(".mia-ttsButton");button&&(this.game.stopObserveAllListeners(button),this.game.safeObserve(button,"click",(ev=>{ev.preventDefault(),ev.stopPropagation();for(var i=0;i<this.textToSpeechElements.length;i++)this.setBoxShadow(this.textToSpeechElements[i].domElement,this.textToSpeechElements[i].defaultFontColor);this.setBoxShadow(textToSpeechElement.domElement,textToSpeechElement.highlightFontColor),this.playSpeechForTextIdentifier(textToSpeechElement.identifier,(()=>{this.setBoxShadow(textToSpeechElement.domElement,textToSpeechElement.defaultFontColor)}))})))}setBoxShadow(domElement,color){null!=domElement&&(domElement.style.boxShadow="0px 0px 8px 0px "+color)}hidePlayButtons(){for(var i=0;i<this.textToSpeechElements.length;i++){var button=this.textToSpeechElements[i].domElement.querySelector(".mia-ttsButton");null!=button&&null!=button&&(this.game.stopObserve(button,"click"),button.style.display="none")}}showPlayButtons(){for(var i=0;i<this.textToSpeechElements.length;i++){var button=this.textToSpeechElements[i].domElement.querySelector(".mia-ttsButton");null!=button&&null!=button&&(button.style.display="inline-block")}}}
49class FreeInputQuiz{constructor(container,gameSettings,correctAnswerCallback,incorrectAnswerCallback,updateQuestionCallback){this.container=container,this.gameSettings=gameSettings,this.correctAnswerCallback=correctAnswerCallback,this.incorrectAnswerCallback=incorrectAnswerCallback,this.updateQuestionCallback=updateQuestionCallback,this.questionResponse=null}onNextQuestionLoaded(){this.locked=!1,this.initializeListeners(),this.container.el.querySelector(".solutionInput")&&this.container.el.querySelector(".solutionInput").querySelector("input").focus()}createTextToSpeechElements(questionSpeechFilePath,answerSpeechFilePaths){var textToSpeechElements=[];return textToSpeechElements.push(this.createQuestionTextToSpeechElement(questionSpeechFilePath)),textToSpeechElements}createQuestionTextToSpeechElement(questionSpeechFilePath){var questionElement={};return questionElement.domElement=this.container.el.querySelector(".question"),questionElement.identifier="question",questionElement.soundUrl=questionSpeechFilePath,questionElement.highlightFontColor="white",questionElement.defaultFontColor=this.getFontColor(questionElement.domElement),questionElement}
49getBackgroundColor(element){return window.getComputedStyle(element).getPropertyValue("backgroundColor")}getFontColor(element){return window.getComputedStyle(element).getPropertyValue("color")}initializeListeners(){this.container.safeObserve(this.container.el.querySelector(".submitButton"),"click",this.onSubmitButtonClick.bind(this)),this.container.safeObserve(this.container.el.querySelector(".nextQuestionButton"),"click",this.onNextQuestionButtonClick.bind(this)),jQuery(this.container.el).on("keypress",this.onKeyPress.bind(this))}onSubmitButtonClick(ev){this.onAnswerSubmitted(ev)}onNextQuestionButtonClick(ev){ev.stopPropagation(),this.updateQuestionCallback(this.questionResponse)}onKeyPress(ev){ev.keyCode==Event.KEY_RETURN&&(ev.stopImmediatePropagation(),jQuery(".submitButton").is(":visible")?this.onAnswerSubmitted(ev):jQuery(".nextQuestionButton").is(":visible")&&(jQuery(".nextQuestionButton").hide(),this.updateQuestionCallback(this.questionResponse)))}onAnswerSubmitted(ev){if(ev.preventDefault(),!this.locked){if(!this.getTextsSubmittedByUser()[0])return this.container.el.querySelector(".dispIfSolutionInputIsEmpty").style.display="",void this.container.el.querySelector(".solutionInput").addEventListener("input",this.onInputChange.bind(this),{once:!0});this.locked=!0,this.hideAnswerInput();var answerWasCorrect=this.doesSubmittedTextEqualCorrectSolution();this.displayFeedback(answerWasCorrect),answerWasCorrect?this.correctAnswerCallback(" ").then(function(response){this.questionResponse=Object.assign({},response.ProcessAnswerResult,response.QuestionData),this.updateQuestionCallback(this.questionResponse,!1)}.bind(this)):this.incorrectAnswerCallback(" ").then(function(response){this.questionResponse=Object.assign({},response.ProcessAnswerResult,response.QuestionData),this.gameSettings.shouldDisplayWhetherChosenAnswerIsCorrect?jQuery(".nextQuestionButton").show():this.updateQuestionCallback(this.questionResponse)}.bind(this))}}onInputChange(){this.container.el.querySelector(".dispIfSolutionInputIsEmpty").style.display="none"}hideAnswerInput(){jQuery(".solutionInput").find("input").prop("readonly",!0),this.container.el.querySelector(".specialLetters").style.display="none",this.container.el.querySelector(".submitButton").style.display="none"}displayFeedback(answerWasCorrect){this.gameSettings.shouldDisplayWhetherChosenAnswerIsCorrect&&(answerWasCorrect?(this.container.el.querySelector(".dispIfSolutionCorrect").style.display="",jQuery(".mia-solutionIcon.mia-correctIcon").show()):(jQuery(".mia-solutionIcon.mia-wrongIcon").show(),this.gameSettings.shouldDisplayCorrectSolution?this.container.el.querySelector(".dispIfSolutionIncorrectWithCorrectSolution").style.display="":this.container.el.querySelector(".dispIfSolutionIncorrect").style.display=""))}doesSubmittedTextEqualCorrectSolution(){var textsSubmittedByUser=this.getTextsSubmittedByUser();return-1==this.getTextsOfCorrectSolution().map(function(correctText,index){return this.isAnswerCorrect(correctText,textsSubmittedByUser[index])}.bind(this)).indexOf(!1)}getTextsSubmittedByUser(){return this.getValuesOfInputChildrenElementsOf(".solutionInput")}getTextsOfCorrectSolution(){return this.getValuesOfInputChildrenElementsOf(".correctSolution")}getValuesOfInputChildrenElementsOf(parentSelector){for(var inputIndex=0,valuesOfInputElements=new Array,inputElement=this.container.el.querySelector(parentSelector).querySelectorAll("input")[inputIndex];null!=inputElement;)valuesOfInputElements.push(inputElement.value.trim()),inputIndex++,inputElement=this.container.el.querySelector(parentSelector).querySelectorAll("input")[inputIndex];return valuesOfInputElements}isAnswerCorrect(correctText,textSubmittedByUser){var validTimeRegex=/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/,validRemainderRegex=/^-?\d+\sR\s\d+$/,validPercentageRegex=/^-?\d+(\.\d+)?%$/,validDollarMoneyRegex=/^\$-?(\d{1,3}(?:,\d{3})*|\d+)(\.\d{2})?$/,validNumberRegex=/^(-?(?=0|\d)(\d{1,3}(,\d{3})*|\d+)?(\.\d+)?|\.\d+)$/;return validTimeRegex.test(correctText)?validTimeRegex.test(textSubmittedByUser)&&correctText==textSubmittedByUser:validRemainderRegex.test(correctText)?validRemainderRegex.test(textSubmittedByUser)&&correctText==textSubmittedByUser:validPercentageRegex.test(correctText)?validPercentageRegex.test(textSubmittedByUser)&&parseFloat(correctText.replace(/%/,""))==parseFloat(textSubmittedByUser.replace(/%/,"")):validDollarMoneyRegex.test(correctText)?validDollarMoneyRegex.test(textSubmittedByUser)&&parseFloat(correctText.replace(/[$,]/g,""))==parseFloat(textSubmittedByUser.replace(/[$,]/g,"")):validNumberRegex.test(correctText)?validNumberRegex.test(textSubmittedByUser)&&parseFloat(correctText.replace(/,/g,""))==parseFloat(textSubmittedByUser.replace(/,/g,"")):(window.onerror
49("Regex is not exist for {0}".format(correctText)),!0)}}
50class AssessmentMode{constructor(container,assessmentOptions){this.container=container,this.assessmentOptions=assessmentOptions,this.el=this.container.el,this.showTextMediaInitially=!1,this.restartOverlay=this.container.el.querySelector(".restartOverlay"),this.restartOverlay.style.display="none",this.initializeRestartClickHandlers()}customLoadEvent(){return!0}onSendAnswerToServerSuccess(response,rejectPromise){response&&response.page&&(this.container.pageLoadJSON=response,this.container.showPage(),this.initializeTryAgainButtonClickHandler(),rejectPromise())}initializeTryAgainButtonClickHandler(){var tryAgainButton=this.el.querySelector(".tryAgain");null!=tryAgainButton&&this.container.safeObserve(tryAgainButton,"click",this.restartAssessmentGame.bind(this))}initializeRestartClickHandlers(){this.container.safeObserve(this.el.querySelector(".restartOverlayYesButton"),"click",this.onRestartOverlayYesClick.bind(this)),this.container.safeObserve(this.el.querySelector(".restartOverlayNoButton"),"click",this.onRestartOverlayNoClick.bind(this)),this.container.safeObserve(this.el.querySelector(".restartButton"),"click",this.onRestartClick.bind(this))}onRestartOverlayYesClick(ev){ev.preventDefault(),ev.stopPropagation(),this.restartAssessmentGame()}onRestartOverlayNoClick(ev){ev.preventDefault(),ev.stopPropagation(),this.restartOverlay.style.display="none"}onRestartClick(ev){ev.preventDefault(),ev.stopPropagation(),this.restartOverlay.style.display=""}restartAssessmentGame(event){event&&jQuery(event.target).addClass("disabled"),this.restartOverlay.style.display="none",axios(this.assessmentOptions.restartURL,{method:"get"}).then((response=>{this.container.updateQuestion(response.data,this.showTextMediaInitially)}))}}Object.assign(AssessmentMode.prototype,ExceptionHandling);
51var GamesQuizInstance=null;class GamesQuiz extends DOMAttached{constructor(el,options){super(el,options),GamesQuizInstance=this,this.progressIndicator=new ProgressIndicator(this.el),this.displayMath=this.options.DisplayMath,this.levelMedia=new LevelMedia(this),this.upScaledImageHandler=new UpScaledImageHandler(this),this.gameSettings=createGameSettings(this.options.feedbackMode),this.levelHandling=this.options.IsAssessmentMode?new AssessmentMode(this,this.options):new Levels(this,this.options),this.hideEasierQuestion=!1,1==this.options.level&&this.el.querySelector(".levelDown")&&(this.el.querySelector(".levelDown").style.visibility="hidden",this.hideEasierQuestion=!0),null==GamesTextToSpeechInstance&&new GamesTextToSpeech(this,this.options.TextToSpeechEnabled&&this.options.ReadQuestionsOn,this.options.TextToSpeechEnabledByParent),null==GenericSoundsInstance&&new GenericSounds(this.options.FeedbackSoundOn),this.options.useList?this.quiz=new MultipleChoiceQuiz(this,this.gameSettings,this.onCorrectAnswerGiven.bind(this),this.onIncorrectAnswerGiven.bind(this),this.updateQuestion.bind(this)):this.quiz=new FreeInputQuiz(this,this.gameSettings,this.onCorrectAnswerGiven.bind(this),this.onIncorrectAnswerGiven.bind(this),this.updateQuestion.bind(this)),this.safeObserve(this.el,"closeMedia",function(){this.displayQuestions()}.bind(this)),soundManager.ok()||!GamesTextToSpeechInstance.isEnabled?this.loadFirstQuestion(this.levelHandling.showTextMediaInitially):soundManager.onready(this.loadFirstQuestion(this.levelHandling.showTextMediaInitially))}disableInput(){this.quiz.locked=!0}enableInput(){this.quiz.locked=!1}onCorrectAnswerGiven(answerId){GamesTextToSpeechInstance.removeTextToSpeechEffects();var millisecondsToNextQuestion=1500;return this.gameSettings.shouldDisplayWhetherChosenAnswerIsCorrect||this.gameSettings.shouldDisplayCorrectSolution?this.playFeedbackSoundForCorrectAnswer():millisecondsToNextQuestion=0,this.sendAnswerToServer(!0,this.pageLoadJSON.questionID,answerId,millisecondsToNextQuestion)}onIncorrectAnswerGiven(answerId){GamesTextToSpeechInstance.removeTextToSpeechEffects();var millisecondsToNextQuestion=this.gameSettings.shouldDisplayCorrectSolution?3e3:1500;return this.gameSettings.shouldDisplayWhetherChosenAnswerIsCorrect||this.gameSettings.shouldDisplayCorrectSolution?this.playFeedbackSoundForIncorrectAnswer():millisecondsToNextQuestion=0,this.options.useList||(millisecondsToNextQuestion=0),this.sendAnswerToServer(!1,this.pageLoadJ
51SON.questionID,answerId,millisecondsToNextQuestion)}createAndReadAllTextToSpeech(){GamesTextToSpeechInstance.setTextToSpeechElements(this.quiz.createTextToSpeechElements(this.pageLoadJSON.questionPath,this.pageLoadJSON.answerPaths)),GamesTextToSpeechInstance.readSpeechForAllElementsInOrder()}sendAnswerToServer(success,questionId,answerId,millisecondsToNextQuestion){return axios(new UrlTemplate(this.options.processAnswerUrl).r("PLH_success",success).r("PLH_nquestion",questionId||-2).r("PLH_answer",answerId).url,{method:"get"}).then((response=>new Promise(((resolve,reject)=>{setTimeout((()=>{this.onSendAnswerToServerSuccess(Object.assign({},response.data.ProcessAnswerResult,response.data.QuestionData),reject),resolve(response.data)}),millisecondsToNextQuestion)}))))}onSendAnswerToServerSuccess(response,rejectPromise){this.levelHandling.onSendAnswerToServerSuccess(response,rejectPromise)}loadFirstQuestion(displayTextMedia){axios(new UrlTemplate(this.options.firstQuestionUrl).url,{method:"get"}).then((response=>{this.updateQuestion(response.data,displayTextMedia)}))}updateQuestion(response,displayTextMedia){this.progressIndicator.showProgressIndicator();var isLevelUp=response&&response.isLevelUp;try{this.pageLoadJSON=response,this.pageLoadJSON.isLevelUp=isLevelUp,this.hideEasierQuestion&&isLevelUp&&this.el.querySelector(".levelDown")&&!this.options.hideEasierQuestion&&(this.el.querySelector(".levelDown").style.visibility="visible",this.hideEasierQuestion=!1)}catch(e){return void legacyGlobal.handleFailedAJAJRequest()}this.progressIndicator.hideProgressIndicator(),this.levelHandling.customLoadEvent(this.pageLoadJSON)&&this.showPage(displayTextMedia)}showPage(displayTextMedia){void 0!==this.pageLoadJSON&&(this.pageLoadJSON.mediaText&&!jQuery.isEmptyObject(this.pageLoadJSON.mediaText)?(this.levelMedia.loadMedia(this.pageLoadJSON.mediaText),jQuery(".textMediaButton").show(),displayTextMedia?this.levelMedia.showMedia():this.displayQuestions()):(jQuery(".textMediaButton").hide(),this.displayQuestions()))}displayQuestions(){this.displayPage(this.pageLoadJSON.page),this.styleQuestionDisplay(this.el.querySelector(".question2")),this.updateProgressBar(this.pageLoadJSON.progress,this.pageLoadJSON.questionsLeft),this.updatePlayPauseButtonSoundFile(this.pageLoadJSON.soundFile),this.pageLoadJSON.questionPath&&(this.quiz.onNextQuestionLoaded(),this.renderMath(),this.createAndReadAllTextToSpeech())}renderMath(){this.displayMath&&MathJax.Hub.Typeset()}updatePlayPauseButtonSoundFile(soundFile){null!=PlayPauseButtonInstance&&soundFile&&PlayPauseButtonInstance.setSoundUrl(soundFile,!0,!0)}updateProgressBar(progress,numberQuestionsLeft){if(null!=progress){this.el.querySelector(".progressBar").style.width=progress*this.el.querySelector(".progressBox").clientWidth+"px";var questionsLeftText="1"==numberQuestionsLeft?this.options.questionsLeftTR_singular:this.options.questionsLeftTR.replace("{num}",numberQuestionsLeft);this.el.querySelector(".questionsLeft").innerHTML=questionsLeftText}}displayPage(page){this.el.querySelector(".questionContainer").innerHTML=page,this.levelMedia.initializeListenersForOpeningMedia(),this.upScaledImageHandler.initializeListenerForZoomInQuestionImg()}styleQuestionDisplay(questionContainer){if(void 0!==questionContainer&&""!=questionContainer){var questionContent=questionContainer.firstChild.firstChild;for(this.questionParent=questionContent.parentNode;void 0!==questionContent.innerHTML;)this.questionParent=questionContent,questionContent=questionContent.innerHTML;if(questionContent.length<400){document.getElementById(this.questionParent).style.fontSize="25px",document.getElementById(this.questionParent).style.lineHeight="30px",document.getElementById(this.questionParent).style.align="center",160<this.questionParent.scrollHeight&&(document.getElementById(this.questionParent).style.fontSize="20px",document.getElementById(this.questionParent).style.lineHeight="20px");var questionPaddingTop=(160-questionContainer.scrollHeight)/2;document.getElementById(questionContainer).style.paddingTop=questionPaddingTop.toString()+"px"}}}playFeedbackSoundForCorrectAnswer(){GenericSoundsInstance.successSound()}playFeedbackSoundForIncorrectAnswer(){GenericSoundsInstance.failSound()}playSpeechForCorrectAnswer(){if(this.gameSettings.shouldDisplayCorrectSolution&&"function"==typeof this.quiz.getIdentifierOfCorrectAnswer){var identifierOfCorrectAnswer=this.quiz.getIdentifierOfCorrectAnswer();void 0!==identifierOfCorrectAnswer&&GamesTextToSpeechInstance.playSpeechForTextIdentifier(identifierOfCorrectAnswer,(function(){}))}}}Object.assign(GamesQuiz.prototype,ExceptionHandling);
52var ToggleFeedbackSoundInstance=null;class ToggleFeedbackSound extends DOMAttached{constructor(el,options){super(el,options),ToggleFeedbackSoundInstance=this,this.button=document.getElementById(options.buttonLink),this.imgPlay=document.getElementById(options.playButton),this.imgPause=document.getElementById(options.pauseButton),this.turnOnTooltip=options.turnOnTooltip,this.turnOffTooltip=options.turnOffTooltip,this.url=this.button.href,this.button.href="#?",this.safeObserve(this.button,"click",this.onClick.bind(this)),void 0!==GenericSoundsInstance&&null!==GenericSoundsInstance&&(GenericSoundsInstance.playFeedbackSound?(this.imgPlay.style.display="none",this.imgPause.style.display="block",this.button.title=this.turnOffTooltip):(this.imgPlay.style.display="block",this.imgPause.style.display="none",this.button.title=this.turnOnTooltip))}onClick(ev){ev.preventDefault(),axios(this.url,{method:"get"}).then((()=>{this.onSuccess()}))}onSuccess(){void 0!==GenericSoundsInstance&&void 0!==GenericSoundsInstance.playFeedbackSound&&(GenericSoundsInstance.playFeedbackSound=!GenericSoundsInstance.playFeedbackSound,GenericSoundsInstance.playFeedbackSound?(this.imgPlay.style.display="none",this.imgPause.style.display="block",this.button.title=this.turnOffTooltip,null!=window.PlayFeedbackSound&&(window.PlayFeedbackSound=!0)):(soundManager.stop("intro"),soundManager.stop("theme"),this.imgPlay.style.display="block",this.imgPause.style.display="none",this.button.title=this.turnOnTooltip,null!=window.PlayFeedbackSound&&(window.PlayFeedbackSound=!1)))}}
53class ThemedButton extends DOMAttached{constructor(el,options){super(el,options),this.linkElement=document.getElementById(el).querySelector("a"),this.safeObserve(this.linkElement,"click",this.onClick.bind(this))}onClick(ev){ev.preventDefault(),ev.stopPropagation(),confirmAI(this.options.trConfirmText,this.onConfirm.bind(this),this.onDelete.bind(this),!0,!0)}onConfirm(ev){window.location.href=this.linkElement.href}onDelete(ev){}}
54class TextBox extends DOMAttached{constructor(el,options){super(el,options),this.defaultButton=document.getElementById(options.defaultButtonId),null!=this.defaultButton&&this.safeObserve(this.el.querySelector("input"),"keypress",this.onKeyPress.bind(this)),null!=this.options.CapsLockWarningID&&(this.safeObserve(this.el.querySelector("input"),"keypress",this.onKeyup2.bind(this)),this.warningLabel=document.getElementById("contentcontent_"+this.options.CapsLockWarningID)),"SingleLine"==this.options.TextBoxMode?(this.fadeInterval=100,this.safeObserve(this.el.querySelector("input"),"focus",this.onFocus.bind(this)),this.safeObserve(this.el.querySelector("input"),"blur",this.onBlur.bind(this)),this.safeObserve(this.el.querySelector("input"),"keyup",this.onChange.bind(this))):"MultiLine"==this.options.TextBoxMode&&(this.makeTextareaAutoResize(),this.options.MaxLength>0&&this.safeObserve(this.el.querySelector("textarea"),"keyup",this.onKeyup.bind(this)),this.previous=this.el.querySelector("textarea").value,
54null!=this.options.RemainingCharactersControl&&(this.counter=document.getElementById(this.options.RemainingCharactersControl),this.counter.innerHTML=this.options.RemainingCharactersTR.replace("{charactersleft}",this.options.MaxLength-this.el.querySelector("textarea").value.length))),this.options.isFocused&&this.el.querySelector("input").focus(),this.options.showPasswordControlId&&(this.isPasswordShownAsText=!1,this.safeObserve(document.getElementById(this.options.showPasswordControlId),"click",this.onShowPasswordClick.bind(this)))}onKeyPress(ev){1!=this.isEnterKeyPressed(ev)||ev.shiftKey||(ev.preventDefault(),ev.stopPropagation(),this.defaultButton.dispatchEvent(new MouseEvent("click")))}isEnterKeyPressed(ev){return 13==ev.keyCode}onFocus(ev){this.el.classList.add("focused"),void 0!==this.options.passwordRulesId&&this.el.querySelector("input").value.length<this.options.passwordMinimalLength&&jQuery("#"+this.options.passwordRulesId).fadeIn(this.fadeInterval)}onBlur(ev){this.el.classList.remove("focused")}onChange(ev){void 0!==this.options.passwordRulesId&&(this.el.querySelector("input").value.length<this.options.passwordMinimalLength?jQuery("#"+this.options.passwordRulesId).fadeIn(this.fadeInterval):jQuery("#"+this.options.passwordRulesId).fadeOut(this.fadeInterval))}onKeyup2(e){kc=e.keyCode?e.keyCode:e.which,sk=e.shiftKey?e.shiftKey:16==kc,kc>=65&&kc<=90&&!sk||kc>=97&&kc<=122&&sk?this.warningLabel.style.visibility="visible":this.warningLabel.style.visibility="hidden";var charKeyCode=e.keyCode?e.keyCode:e.which;e.shiftKey&&e.shiftKey}onKeyup(ev){this.el.querySelector("textarea").value.length>this.options.MaxLength?this.el.querySelector("textarea").value=this.previous:(this.previous=this.el.querySelector("textarea").value,null!==this.counter&&void 0!==this.counter&&(this.counter.innerHTML=this.options.RemainingCharactersTR.replace("{charactersleft}",this.options.MaxLength-this.el.querySelector("textarea").value.length)))}onShowPasswordClick(){this.isPasswordShownAsText?(this.el.querySelector("input").setAttribute("type","password"),document.getElementById(this.options.showPasswordControlId).innerHTML=this.options.showPasswordText):(this.el.querySelector("input").setAttribute("type","text"),document.getElementById(this.options.showPasswordControlId).innerHTML=this.options.hidePasswordText),this.isPasswordShownAsText=!this.isPasswordShownAsText}makeTextareaAutoResize(){jQuery(this.el.querySelector("textarea")).each((function(){this.setAttribute("style","height:"+this.scrollHeight+"px;overflow-y:scroll;")})).on("input",(function(){this.style.height="auto",this.style.height=this.scrollHeight+"px"}))}}
55function evalScripts(container){container.querySelectorAll("script").forEach((script=>{const newScript=document.createElement("script");script.src?newScript.src=script.src:newScript.textContent=script.textContent,script.parentNode.replaceChild(newScript,script)}))}function replaceElement(oldEl,newContent){let newEl;if("string"==typeof newContent){const temp=document.createElement("div");if(temp.innerHTML=newContent.trim(),newEl=temp.firstElementChild,!newEl)return;oldEl.replaceWith(newEl),evalScripts(newEl)}else newContent instanceof HTMLElement&&(oldEl.replaceWith(newContent),evalScripts(newContent))}
56var GenericSoundsInstance=null;class GenericSounds{constructor(playFeedbackSound){this.playFeedbackSound=playFeedbackSound,GenericSoundsInstance=this}clickSound(override){if(this.playFeedbackSound||override){var clickSound=soundManager.createSound({id:"click",url:"/snd/genericClick.mp3"});soundManager.setVolume("click",50),clickSound.play()}}softClickSound(override){if(this.playFeedbackSound||override){var clickSound=soundManager.createSound({id:"softClick",url:"/snd/clickSoft_option2.mp3"});soundManager.setVolume("softClick",50),clickSound.play()}}notificationSound(){soundManager.createSound({id:"notification",url:"/snd/sound106.mp3"}).play()}putDownSound(override){if(this.playFeedbackSound||override){var putDownSound=soundManager.createSound({id:"putDown",url:"/snd/genericPutDown.mp3"});soundManager.setVolume("putDown",50),putDownSound.play()}}pickUpSound(override){if(this.playFeedbackSound||override){var pickUpSound=soundManager.createSound({id:"pickUp",url:"/snd/genericPickUp.mp3"});soundManager.setVolume("pickUp",70),pickUpSound.play()}}whooshSound(override){if(this.playFeedbackSound||override){var whooshSound=soundManager.createSound({id:"whoosh",url:"/snd/outfitWhoosh.mp3"});soundManager.setVolume("whoosh",70),whooshSound.play()}}longWhooshSound(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){var whooshSound=soundManager.createSound({id:"longWhoosh",url:"/snd/listWhoosh.mp3"});soundManager.setVolume("longWhoosh",50),window.setTimeout((function(){whooshSound.play()}),200)}))}themeSound(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"theme",url:"/snd/cleverDragonTheme.mp3"}).play({onstop:function(){this.afterThemeSound()},onfinish:function(){this.afterThemeSound()}})}))}afterThemeSound(){null!=ThemePlayerInstance&&ThemePlayerInstance.stop()}successSound(override,onFinished){this.playFeedbackSound||override?soundManager.createSound({id:"succ",url:"/snd/genericReward.mp3"}).play({onfinish:function(){onFinished&&onFinished()}}):onFinished&&onFinished()}failSound(override){(this.playFeedbackSound||override)&&soundManager.createSound({id:"fail",url:"/snd/genericWrong.mp3"}).play()}shopSound(override){(this.playFeedbackSound||override)&&soundManager.createSound({id:"shop",url:"/snd/shop.mp3"}).play()}introSound(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"intro",url:"/snd/intro.mp3"}).play()}))}foodContact1(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"foodContact1",url:"/snd/foodContact1.mp3"}).play()}))}foodContact2(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"foodContact2",url:"/snd/foodContact2.mp3"}).play()}))}toweling(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"toweling",url:"/snd/toweling.mp3"}).play()}))}eggMusic(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"eggMusic",url:"/snd/gnom.mp3"}).play()}))}happyPet(override){(this.playFeedbackSound||override)&&(1==Math.floor(2*Math.random())+1?soundManager.onready((function(){soundManager.createSound({id:"happyPet",url:"/snd/happyPet.mp3"}).play()})):soundManager.onready((function(){soundManager.createSound({id:"happyPet",url:"/snd/happyPet2.mp3"}).play()})))}yawn(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"yawn",url:"/snd/yawn.mp3"}).play()}))}hairdryer(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"hairdryer",url:"/snd/hairdryer.mp3"}).play()}))}runningWater(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"runningWater",url:"/snd/runningWater.mp3"}).play({onfinish:function(){GenericSoundsInstance.runningWater()}})}))}outside(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"outside",url:"/snd/outside.mp3"}).play()}))}jump(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"jump",url:"/snd/jump.mp3"}).play()}))}circus(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"circus",url:"/snd/circus.mp3"}).play()}))}shoppingMall(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"shoppingMall",url:"/snd/shoppingMall.mp3"}).play()}))}circus2(override){(this.playFeedbackSound||override)&&soundManager.onready((function(){soundManager.createSound({id:"circus2",url:"/snd/circus2.mp3"}).play()}))}}
57var blocked=new Boolean(!1);class TabbedApplication extends DOMAttached{constructor(el,options){super(el,options),this.el.attachedObj=this,this.progressIndicator=new ProgressIndicator(this.el),this.tabs=document.querySelectorAll(".tabappTab:not(.mia-feedbackSoundTab)"),this.links=options.tabLinks,this.playFeedbackSound=options.playFeedbackSound,this.content=this.el.querySelector(".contentPane"),this.currentTab=this.tabs[0],this.currentTab.classList.add("selected"),this.selectTab(0);for(let i=0;i<this.tabs.length;i++)this.safeObserve(this.tabs[i],"click",(()=>this.loadTab(i)));this.registerLinks(),null==GenericSoundsInstance&&(GenericSoundsInstance=new GenericSounds(this.playFeedbackSound)),GenericSoundsInstance.introSound(),null!=this.options.defaultPage&&this.loadPage(this.options.defaultPage)}registerLinks(){var links=this.el.querySelector(".contentPane").querySelectorAll("a.tabLink");for(let i=0;i<links.length;i++)this.safeObserve(links[i],"click",(ev=>this.onClickLink(ev,links[i].href)))}onClickLink(ev,url){this.blocked||(ev.preventDefault(),ev.stopPropagation(),this.loadPage(url))}registerTimer(timer){this.timer=timer}registerInterval(interval){this.interval=interval}loadPage(url){this.blocked||this.loadPageWithOwnSuccessHandler(url,this.onPageLoaded.bind(this))}loadPageWithOwnSuccessHandler(url,onSuccessHandler){if(this.progressIndicator.showProgressIndicator(!0,!1),null!=this.timer)try{clearTimeout(this.timer)}finally{this.timer=void 0}if(null!=this.interval)try{clearInterval(this.interval)}finally{this.interval=void 0}axios(url,{method:"get"}).then(onSuccessHandler)}loadTab(index){this.blocked||(soundManager.stopAll(),GenericSoundsInstance.clickSound(),3==index&&GenericSoundsInstance.shopSound()),this.selectTab(index),this.loadPage(this.links[index])}findTab(url){for(var i=0;i<this.links.length;++i)if(this.links[i]==url)return i;return-1}findAndLoadTab(url){this.loadTab(this.findTab(url))}selectTab(index){this.blocked||(this.currentTab.classList.remove("selected"),this.currentTab=this.tabs[index],this.currentTab.classList.add("selected"))}activatePlaceholder(name,caption,url){for(var i=0;i<this.tabs.length;i++)if(this.tabs[i].id.endsWith("_"+name)){this.tabs[i].innerHTML=caption,this.links[i]=url,this.tabs[i].style.display="block",this.selectTab(i);break}}onPageLoaded(req){var json=req.data;if(json.success){if(null!=json.successpopup)return this.el.querySelector(".popupContainer").attachedObj.showContent(json.successpopup),void this.progressIndicator.hideProgressIndicator();this.content.innerHTML=json.page,evalScripts(this.content),this.registerLinks()}else{if(null!=json.errorpopup)return this.el.querySelector(".popupContainer").attachedObj.showContent(json.errorpopup),void this.progressIndicator.hideProgressIndicator();this.content.innerHTML="<b>Could not load page. Try again!</b>"}this.progressIndicator.hideProgressIndicator()}}
58class TabPopupMenu extends DOMAttached{constructor(el,options){super(el,options),this.style.display="none",this.options.attachTo=document.getElementById(this.options.attachTo),this.safeObserve(this.options.attachTo,"mouseover",this.onAttMouseOver.bind(this)),this.safeObserve(this.el,"mouseover",this.onAttMouseOver.bind(this)),this.safeObserve(this.options.attachTo,"mouseout",this.onAttMouseOut.bind(this)),this.safeObserve(this.el,"mouseout",this.onAttMouseOut.bind(this)),this.reparented=!1,this.registerUnloadAction(this.cleanUp.bind(this))}cleanUp(){this.options.attachTo=null}onAttMouseOver(ev){this.visible?(this.hideTimer&&clearTimeout(this.hideTimer),this.hideTimer=void 0):this.style.display=""}onAttMouseOut(ev){this.hideTimer||(this.hideTimer=setTimeout(this.hide.bind(this),1e3))}show(){this.reparented||(this.el.remove(),legacyGlobal.getToplevelElement().appendChild(this.el),this.reparented=!0);var attPos=this.options.attachTo.getBoundingClientRect();this.el.style.left=Math.round(attPos.left+(attPos.width-this.el.getBoundingClientRect().width)/2)+"px",this.el.style.top=attPos.top+attPos.height+"px",this.el.style.display="",this.visible=!0,legacyGlobal.currentlyActiveTabPopup&&(legacyGlobal.currentlyActiveTabPopup.style.display="none"),legacyGlobal.currentlyActiveTabPopup=this}hide(){this.el.style.display="none",this.visible=!1,this.hideTimer&&clearTimeout(this.hideTimer),this.hideTimer=void 0,legacyGlobal.currentlyActiveTabPopup=void 0}}
59var SuperDragonFireServerInterface=null;class SuperDragonFire extends DOMAttached{constructor(el,options){super(el,options),this.valueParameterName="PLH_number",this.actionParameterName="PLH_Action",SuperDragonFireServerInterface=this}storeMusicVolume(volume,onSuccessCallback,onFailureCallback){}storeSoundVolume(volume,onSuccessCallback,onFailureCallback){}hasMemberEnoughMoney(amount,onTrueCallback,onFalseCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,amount).r(this.actionParameterName,0).url,{method:"get"}).then((response=>{response.data.success?onTrueCallback():onFalseCallback()}))}callForMoneyTransaction(amount,onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,amount).r(this.actionParameterName,1).url,{method:"get"}).then((response=>{}))}storeScore(score,onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,score).r(this.actionParameterName,2).url,{method:"get"}).then((response=>{onSuccessCallback()}))}storeItem(itemLevel,itemID,onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,itemLevel).r(this.actionParameterName,itemID).url,{method:"get"}).then((response=>{}))}}
60var SpellingFireServerInterface=null;class SpellingFire extends DOMAttached{constructor(el,options){super(el,options),this.valueParameterName="PLH_number",this.actionParameterName="PLH_Action",SpellingFireServerInterface=this}storeMusicVolume(volume,onSuccessCallback,onFailureCallback){}storeSoundVolume(volume,onSuccessCallback,onFailureCallback){}hasMemberEnoughMoney(onTrueCallback,onFalseCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,0).r(this.actionParameterName,0).url,{method:"get"}).then((response=>{response.data.success?onTrueCallback():onFalseCallback()}))}callForMoneyTransaction(onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,0).r(this.actionParameterName,1).url,{method:"get"}).then((response=>{}))}storeScore(score,onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,score).r(this.actionParameterName,2).url,{method:"get"}).then((response=>{onSuccessCallback()}))}
60storeCurrentLevel(level,onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.spellingFireServerCommunicationURL).r(this.valueParameterName,level).r(this.actionParameterName,1).url,{method:"get"}).then((response=>{0==response.data.response&&onSuccessCallback()}))}storeMedal(medal,onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.spellingFireServerCommunicationURL).r(this.valueParameterName,medal).r(this.actionParameterName,2).url,{method:"get"}).then((response=>{}))}getLevel(level,onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.spellingFireServerCommunicationURL).r(this.valueParameterName,level).r(this.actionParameterName,1).url,{method:"get"}).then((response=>{onSuccessCallback(response.data)}))}storeScoops(amount,onSuccessCallback,onFailureCallback){}}
61class ShowcaseItem extends DOMAttached{constructor(el,options){super(el,options),this.trigger=document.getElementById(options.Trigger),this.width=options.Width,this.height=options.Height,this.left=options.Left,this.top=options.Top,this.url=options.Url,this.safeObserve(this.trigger,"click",this.openPopup.bind(this))}openPopup(ev){var optionString="width="+this.width+", height="+this.height+", left="+this.left+", top="+this.top;window.open(this.url,"Award",optionString).focus(),ev.preventDefault()}}
62var ShootingPrototypeServerInterface=null;class ShootingPrototype extends DOMAttached{constructor(el,options){super(el,options),this.valueParameterName="PLH_number",this.actionParameterName="PLH_Action",Sho
62otingPrototypeServerInterface=this}storeMusicVolume(volume,onSuccessCallback,onFailureCallback){}storeSoundVolume(volume,onSuccessCallback,onFailureCallback){}hasMemberEnoughMoney(onTrueCallback,onFalseCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,0).r(this.actionParameterName,0).url,{method:"get"}).then((response=>{response.data.success?onTrueCallback():onFalseCallback()}))}callForMoneyTransaction(onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,0).r(this.actionParameterName,1).url,{method:"get"}).then((()=>{}))}storeScore(score,onSuccessCallback,onFailureCallback){axios(new UrlTemplate(this.options.serverCommunicationURL).r(this.valueParameterName,score).r(this.actionParameterName,2).url,{method:"get"}).then((response=>{onSuccessCallback()}))}}
63class ListBase extends DOMAttached{constructor(el,options){if(super(el,Object.assign({currentPage:0,lastPage:!1,pagingEffect:"none",fixDimensions:!0,reversePagingEffect:!1,noProgressIndicator:!1,legacy:!0,removeButtonsForOnePageLists:!1,maxHeight:0},options)),this.progressIndicator=new ProgressIndicator(this.el),this.el.attachedObj=this,this.listEl=this.el.querySelector(".fxListWrapper"),null==GenericSoundsInstance&&new GenericSounds(this.options.FeedbackSoundOn),null==this.listEl&&(this.listEl=this.el.querySelector("ul")),this.prevBtn=this.el.querySelectorAll(".prevBtn"),this.nextBtn=this.el.querySelectorAll(".nextBtn"),1==options.buttonsMustBeChildren)for(var children=Array.from(this.el.children),i=0;i<children.length;i++)children[i].classList.contains("prevBtn")&&(this.prevBtn=new Array(children[i])),children[i].classList.contains("nextBtn")&&(this.nextBtn=new Array(children[i]));
63this.setBtnVisibility(),this.prevBtn.forEach(function(e){this.safeObserve(e,"click",this.onPrevBtn.bind(this)),this.safeObserve(e,"doubleclick",this.onPrevBtn.bind(this))}.bind(this)),this.nextBtn.forEach(function(e){this.safeObserve(e,"click",this.onNextBtn.bind(this)),this.safeObserve(e,"doubleclick",this.onNextBtn.bind(this))}.bind(this)),this.disablePaging=!1,this.dimensionsFixed=!1,null!=this.options.progressDotsControl&&void 0!==this.options.progressDotsControl&&this.setupDotNavigation(),this.registerUnloadAction(this.cleanUp.bind(this))}setupDotNavigation(){for(var children=Array.from(document.getElementById(this.options.progressDotsControl).children),i=0;i<children.length;++i)this.safeObserve(children[i],"click",this.onDotClick.bind(this)),i==this.options.currentPage&&children[i].setAttribute("src",this.options.progressDotsFullDotImageUrl)}resetDots(){for(var children=Array.from(document.getElementById(this.options.progressDotsControl).children),i=0;i<children.length;++i)children[i].getAttribute("src")!=this.options.progressDotsEmptyDotImageUrl&&children[i].setAttribute("src",this.options.progressDotsEmptyDotImageUrl)}onDotClick(ev){this.resetDots(),ev.currentTarget.setAttribute("src",this.options.progressDotsFullDotImageUrl);for(var classNames=$w(ev.currentTarget.className),i=0;i<classNames.length;++i)if(classNames[i].startsWith("dot_")){var page=classNames[i].substring(4);return void this.loadPage(page)}}cleanUp(){this.listEl=null,this.prevBtn=null,this.nextBtn=null,this.newList=null}
63setBtnVisibility(){(this.prevBtn.forEach(function(e){0!=this.options.currentPage||this.options.circle?(e.classList.remove("deactivated"),e.classList.remove("disabled")):(e.classList.add("deactivated"),e.classList.add("disabled")),this.enableButton(e,0!=this.options.currentPage||this.options.circle)}.bind(this)),this.nextBtn.forEach(function(e){this.options.lastPage&&!this.options.circle?(e.classList.add("deactivated"),e.classList.add("disabled")):(e.classList.remove("deactivated"),e.classList.remove("disabled")),this.enableButton(e,!this.options.lastPage||this.options.circle)}.bind(this)),this.options.removeButtonsForOnePageLists)&&(this.options.lastPage&&0==this.options.currentPage&&(this.prevBtn.forEach((function(e){e.style.visibility="hidden",e.classList.add("mia-u-remove")})),this.nextBtn.forEach((function(e){e.style.visibility="hidden",e.classList.remove("mia-u-remove")})),this.el.style.paddingTop="0px",this.el.style.paddingBottom="0px",this.el.querySelectorAll(".mia-ListHeaderFooter").forEach((function(w){w.classList.contains("legacyControl")||w.remove()}))))}enableButton(btn,enabled){"TurnGrey"==this.options.buttonDeactivation?enabled?(btn.style.backgroundImage=btn.style.backgroundImage.replace("_grey.png",".png"),btn.style.cursor="pointer"):(btn.style.backgroundImage=btn.style.backgroundImage.replace("_grey.png",".png").replace(".png","_grey.png"),btn.style.cursor="default"):"Remove"==this.options.buttonDeactivation&&(btn.style.display=enabled?"":"none")}onPrevBtn(ev){this.disablePaging||(!this.dimensionsFixed&&this.options.fixDimensions&&this.fixDimensions(),this.options.currentPage>0?(this.disablePaging=!0,this.loadPage(this.options.currentPage-1),"none"==this.options.pagingEffect&&GenericSoundsInstance.clickSound()):this.options.circle&&(this.disablePaging=!0,this.loadPage(this.options.count-1)))}onNextBtn(ev){this.disablePaging||(!this.dimensionsFixed&&this.options.fixDimensions&&this.fixDimensions(),this.options.lastPage?this.options.circle&&(this.disablePaging=!0,this.loadPage(0)):(this.disablePaging=!0,this.loadPage(this.options.currentPage+1),"none"==this.options.pagingEffect&&GenericSoundsInstance.clickSound()))}fixDimensions(){if(!this.options.legacy)if(this.dimensionsFixed=!0,legacyGlobal.isIE){var elDims={width:this.el.offsetWidth,height:this.el.offsetHeight};this.el.style.height=elDims.height+"px",this.el.style.width=elDims.width+"px";var newDims={width:this.el.offsetWidth,height:this.el.offsetHeight},diffX=newDims.width-elDims.width,diffY=newDims.height-elDims.height;0==diffX&&0==diffY||(this.el.style.height=elDims.height-diffY+"px",this.el.style.width=elDims.width-diffX+"px")}else this.el.style.height=this.window.getComputedStyle(el).getPropertyValue("height"),this.el.style.width=this.window.getComputedStyle(el).getPropertyValue("width")}resetDimensions(){this.el.style.height="",this.el.style.width="",this.listEl.style.height="",this.listEl.style.width="",this.dimensionsFixed=!1}displayPage(page,oldPageNum){if(this.newList=document.createElement("div"),this.newList.innerHTML=page,this.newList=this.newList.firstElementChild,evalScripts(this.newList),!this.options.legacy&&this.dimensionsFixed&&this.listEl){const elDim={width:this.listEl.offsetWidth,height:this.listEl.offsetHeight};this.newList.style.width=`${elDim.width}px`,this.newList.style.height=`${elDim.height}px`}if(this.options.progressDotsControl){const dotContainer=document.getElementById(this.options.progressDotsControl),dots=Array.from(dotContainer.children);null!=oldPageNum&&dots[oldPageNum]&&dots[oldPageNum].setAttribute("src",this.options.progressDotsEmptyDotImageUrl),dots[this.options.currentPage]&&dots[this.options.currentPage].setAttribute("src",this.options.progressDotsFullDotImageUrl)}const pagingEffect=this.options.pagingEffect,samePage=this.options.currentPage===oldPageNum,isEffectEnabled=["horizSlide","vertSlide","fade"].includes(pagingEffect)||samePage;if(!legacyGlobal.isIE6&&isEffectEnabled)if(this.listEl.style.position="absolute",this.listEl.parentNode.insertBefore(this.newList,this.listEl.nextSibling),this.newList.style.visibility="hidden","vertSlide"===pagingEffect&&this.stretchPagesToUniformHeight(),!samePage&&["horizSlide","vertSlide"].includes(pagingEffect)){let edge1="left",edge2="right";"vertSlide"===pagingEffect?(edge1=oldPageNum<this.options.currentPage?"top":"bottom",edge2=oldPageNum<this.options.currentPage?"bottom":"top"):"horizSlide"===pagingEffect&&(edge1=oldPageNum<this.options.currentPage?"left":"right",edge2=oldPageNum<this.options.currentPage?"right":"left"),(this.options.reversePagingEffect||this.options.circle&&(0===this.options.currentPage&&1!==oldPageNum||this.options.currentPage===this.options.count-1&&0===oldPageNum))&&([edge1,edge2]=[edge2,edge1]),GenericSoundsInstance.longWhooshSound();const effDuration=1,fromOff=this.getSlideOffset(edge1,this.listEl),toOn=this.getSlideOffset(edge2,this.newList);gsap.set(this.newList,{...toOn,visibility:"visible"});gsap.timeline({onComplete:()=>{this.cleanupAfterPageSwitch()}}).to(this.listEl,{...fromOff,duration:effDuration,ease:"power1.inOut"},0).to(this.newList,{x:0,y:0,duration:effDuration,ease:"power1.inOut"},0)}else gsap.set(this.newList,{opacity:0,visibility:"visible"}),gsap.to(this.listEl,{opacity:0,duration:.05}),gsap.to(this.newList,{opacity:1,duration:.05,onComplete:()=>{this.cleanupAfterPageSwitch()}});else this.listEl.parentNode.insertBefore(this.newList,this.listEl.nextSibling),this.cleanupAfterPageSwitch();if(this.onLoadPage(this.listEl),"returnToTop"===this.options.pagingEffect&&this.el){const position=this.el.offsetTop-32;window.scrollTo(0,position)}}getSlideOffset(edge,el){const rect=el.getBoundingClientRect();switch(edge){case"left":return{x:-rect.width};case"right":return{x:rect.width};case"top":return{y:-rect.height};case"bottom":return{y:rect.height};default:return{}}}cleanupAfterPageSwitch(){this.removeElement(this.listEl),this.listEl=this.newList,this.newList=void 0,this.reenablePaging(),this.options.legacy&&(this.listEl.style.height="",this.listEl.style.width=""),legacyGlobal.isIE7&&(this.listEl.style.display="none",setTimeout(this.renderPageIE7.bind(this),1))}stretchPagesToUniformHeight(){this.listEl.offsetHeight>=this.options.maxHeight?(this.options.maxHeight=this.listEl.offsetHeight,this.newList.style.height=this.options.maxHeight+"px"):this.listEl.style.height=this.options.maxHeight+"px"}standardJSONRequest(url){null!=this.blockRequests||this.requestRunning||(this.requestRunning=!0,axios(url,{method:"get",params:{nocache:Math.random()}}).then(this.standardJSONSuccess.bind(this)))}standardJSONSuccess(req){this.requestRunning=!1;var json=req.data;if(null!=json.html&&0!=json.html.length){var oldPage=this.options.currentPage,html=json.html;json.html=void 0,this.options=Object.assign(this.options,json),this.setBtnVisibility(),this.displayPage(html,oldPage)}}reenablePaging(req){this.disablePaging=!1}refresh(){this.disablePaging=!0,this.loadPage(this.options.currentPage)}loadPage(page){this.options.noProgressIndicator||(this.options.customProgressIndicator?this.progressIndicator.showProgressIndicator("div",!1):this.progressIndicator.showProgressIndicator("div.listCtrl",!1))}onLoadPage(pageEl){this.options.noProgressIndicator||this.progressIndicator.hideProgressIndicator(),this.el.dispatchEvent(new CustomEvent("list:criteriaChanged",{detail:{options:this.options}})),setTimeout(this.fixDimensions.bind(this),10)}renderPageIE7(){this.listEl.style.display="block"}}
64class GNOMList extends ListBase{constructor(el,options){super(el,Object.assign({pagingEffect:"horizSlide",noProgressIndicator:!1},options)),this.emptyel=this.el.querySelector(".emptyList a"),this.el.attachedObj=this,null!=this.emptyel&&null!=this.options.emptyListUrl&&this.safeObserve(this.emptyel,"click",this.onClick.bind(this))}loadPage(page,customUrl){super.loadPage(page),null==customUrl?this.standardJSONRequest(this.options.url.replace("PLH_pagenum",page)):this.standardJSONRequest(customUrl.replace("PLH_pagenum",page))}onClick(ev){this.el.closest(".tabbedApplication").attachedObj.findAndLoadTab(this.options.emptyListUrl),ev.preventDefault(),ev.stopPropagation()}}
65var SharedListInstance;class SharedList extends GNOMList{constructor(el,options){super(el,Object.assign({pagingEffect:"horizSlide",noProgressIndicator:!0},options)),SharedListInstance=this}loadPageWithCustomUrl(page,customUrl){this.customUrl=customUrl,this.loadPage(page)}loadPage(page){super.loadPage(page,this.customUrl)}}
66class RewardVideoListener{constructor(rewardTimeSpan,rewardUrl){this.rewardTimeSpan=rewardTimeSpan,this.rewardUrl=rewardUrl,this.previousSeconds=0,this.secondsCounter=0}onPlayProgress(currentSeconds){var difference=currentSeconds-this.previousSeconds;difference>0&&difference<5&&(this.secondsCounter+=difference,this.secondsCounter>=this.rewardTimeSpan&&(this.secondsCounter=0,axios(this.rewardUrl,{method:"get"}))),this.previousSeconds=currentSeconds}onLoadProgress(percentage){}onPlay(){}onPause(){}onEnd(){}}
67class ReportWatchedVideoListener{constructor(fullyWatchedUrl,videoDuration,videoProgressKey){this.fullyWatchedUrl=fullyWatchedUrl,this.videoDuration=videoDuration,this.fullyWatchedNotificationWasSent=!1,this.logMessageWasSent=!1,this.videoProgressKey=videoProgressKey}onPlayProgress(currentSeconds){this.saveVideoProgress(currentSeconds),!this.fullyWatchedNotificationWasSent&&this.videoDuration-currentSeconds<=30&&(axios(this.fullyWatchedUrl,{method:"post",headers:{"content-type":"application/x-www-form-urlencoded"}}),this.fullyWatchedNotificationWasSent=!0)}saveVideoProgress(currentSeconds){if(this.videoProgressKey)try{localStorage.setItem(this.videoProgressKey,currentSeconds)}catch(e){"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||"QUOTA_EXCEEDED_ERR"===e.name?sessionStorage.setItem(this.videoProgressKey,currentSeconds):this.logMessageWasSent||(window.onerror
67("Storage error: "+e,window.location.href,void 0,void 0,e),this.logMessageWasSent=!0)}}removeVideoProgress(currentSeconds){this.videoProgressKey&&(localStorage.removeItem(this.videoProgressKey),sessionStorage.removeItem(this.videoProgressKey))}onLoadProgress(percentage){}onPlay(){}onPause(){}onEnd(){this.removeVideoProgress()}}
68class RegisterHelp extends DOMAttached{constructor(el){super(el);this.el.querySelectorAll("li").forEach((curLi=>{let inp=curLi.querySelector("input");inp||(inp=curLi.querySelector("select"));const tooltip=curLi.querySelector(".registerHelpTooltip");inp&&tooltip&&(this.safeObserve(inp,"focus",this.onFocusBlur.bind(this)),this.safeObserve(inp,"blur",this.onFocusBlur.bind(this)))}))}onFocusBlur(){var data=$A(arguments);data.shift(),null!=data[0]&&(data[0].classList.contains("registerHelpTooltipShown")?data[0].classList.remove("registerHelpTooltipShown"):data[0].classList.add("registerHelpTooltipShown"))}}
69class PostingVisibility extends DOMAttached{constructor(el){super(el),this.all=this.el.querySelector(".all"),this.friends=this.el.querySelector(".friends"),this.friendslist=this.el.querySelector("ul"),this.safeObserve(this.all,"click",this.applyConstraints.bind(this)),this.safeObserve(this.friends,"click",this.applyConstraints.bind(this)),this.all.checked&&(this.friends.checked=!0),PostingVisibility.instance=this,this.applyConstraints()}applyConstraints(){this.all.checked?(this.friends.disabled=!0,this.friends.checked=!1):this.friends.disabled=!1,null!=this.friendslist&&(this.friends.checked||this.all.checked?(this.friendslist.querySelectorAll("input").forEach((function(el){el.disabled=!0,el.checked=!1})),"undefined"!=typeof FriendslistCreateOnTheFly&&void 0!==FriendslistCreateOnTheFly.instance&&FriendslistCreateOnTheFly.instance.staticEnable(!1)):(this.friendslist.querySelectorAll("input").forEach((function(el){el.disabled=!1})),"undefined"!=typeof FriendslistCreateOnTheFly&&void 0!==FriendslistCreateOnTheFly.instance&&FriendslistCreateOnTheFly.instance.staticEnable(!0)))}uncheckAllAndFriends(){this.all.checked=!1,this.friends.checked=!1,this.applyConstraints()}}
70class PostingRating extends DOMAttached{constructor(el,options){super(el,options),this.btn=this.el.querySelector("span"),this.count=this.el.querySelector(".count"),this.safeObserve(this.btn,"click",this.onClick.bind(this)),this.disableRating=!1}onClick(ev){this.rate(),ev.stop}rate(){this.disableRating||(this.disableRating=!0,axios(this.options.rateUrl,{method:"get"}).then((response=>{this.ratingSuccess()})))}ratingSuccess(){this.disableRating=!1,this.count.innerHTML=parseInt(this.count.innerHTML+1),this.stopObserve(this.btn,"click"),this.btn.classList.remove("link"),this.btn.querySelector("img").setAttribute("title",this.options.ratedTooltip)}}
71class PopupOpener extends DOMAttached{constructor(el,options){super(el,options),this.safeObserve(this.el,"click",this.onClick.bind(this)),this.url=document.getElementById(el).href}onClick(e){this.popup=window.open(this.url,"","scrollbars=1"),this.popup.resizeTo(this.options.Width,this.options.Height),void 0!==this.options.adjustHeightToContent&&this.options.adjustHeightToContent&&this.safeObserve(this.popup,"load",this.onLoad.bind(this)),e.preventDefault(),e.stopPropagation()}onLoad(){this.headerHeight=this.options.Height-this.popup.document.documentElement.clientHeight,this.contentHeight=this.popup.document.body.clientHeight,this.popup.resizeTo(this.options.Width,this.headerHeight+this.contentHeight)}}
72var SortableBox={initializeSortableBox:function(tagName){this.sortTagName=tagName,this.sorterBtnDiv=this.el.querySelector(".sorterBtns"),null!=this.sorterBtnDiv&&this.setupSorterBtns()},setupSorterBtns:function(opacityOnly){this.sorterBtnDiv.querySelectorAll(this.sortTagName).forEach((btn=>{this.options.sortOrder==btn.getAttribute("class")?(btn.classList.add("selected"),btn.style.fontWeight="bold"):(btn.classList.remove("selected"),btn.style.fontWeight="normal"),opacityOnly||(this.safeObserve(btn,"click",this.onSorterBtnClick.bind(this)),this.safeObserve(btn,"mouseover",this.onSorterBtnOver.bind(this)),this.safeObserve(btn,"mouseout",this.onSorterBtnOut.bind(this)))}))},onSorterBtnClick:function(ev){if(ev.preventDefault(),ev.stopPropagation(),!this.requestRunning&&!this.disablePaging){var btn=ev.target.closest(this.sortTagName);this.options.sortOrder!=btn.getAttribute("class").replace(/\s*selected\s*/,"")&&(this.options.sortOrder=btn.getAttribute("class").replace(/\s*selected\s*/,""),this.setupSorterBtns(!0),this.options.currentPage=0,this.refresh())}},onSorterBtnOver:function(ev){var btn=ev.target.closest(this.sortTagName);btn.hover||(btn.hover=!0)},onSorterBtnOut:function(ev){var btn=ev.target.closest(this.sortTagName);btn.hover=!1,this.options.sortOrder==btn.getAttribute("class").replace(/\s*selected\s*/,"")?btn.classList.add("selected"):btn.classList.remove("selected")}};
73var ActivePlazasListLastInstances={};class ActivePlazasList extends ListBase{constructor(el,options){const classList=document.getElementById(el).classList;classList.contains("myFriendsList")||classList.contains("guestBookList")?super(el,Object.assign({pagingEffect:"returnToTop"},options)):classList.contains("commentsList")?super(el,Object.assign({pagingEffect:"returnToTop",customProgressIndicator:"div"},options)):classList.contains("memberList")?super(el,Object.assign({pagingEffect:"vertSlide",legacy:!1},options)):classList.contains("messageList")?super(el,Object.assign({pagingEffect:"returnToTop",legacy:!0,fixDimensions:!1},options)):classList.contains("inventoryList")||classList.contains("designedItemList")||classList.contains("shapeList")?super(el,Object.assign({pagingEffect:"horizSlide"},options)):super(el,Object.assign({pagingEffect:"vertSlide",removeButtonsForOnePageLists:!0},options)),ActivePlazasListLastInstances[options.activePlazaListIdentifier]=this}loadPage(page,search){super.loadPage(page),this.resetDimensions(),null==search&&(search=null===this.options.search||void 0===this.options.search?"":this.options.search);var url=this.options.url.replace("PLH_pagenum",page).replace("PLH_search",search),minslider=document.getElementById("contentcontent_grade_slider_min"),maxslider=document.getElementById("contentcontent_grade_slider_max");if(minslider&&maxslider){var min=minslider.value||0,max=maxslider.value||8;url=url.replace("PLH_gradeMin",min).replace("PLH_gradeMax",max)}else url=url.replace("PLH_gradeMin",0).replace("PLH_gradeMax",8);return this.standardJSONRequest(url),!0}}
74class SearchBox extends DOMAttached{constructor(el,options){super(el,options),this.inputBox=document.getElementById(options.inputBox),this.searchButton=document.getElementById(options.searchButton),this.previousSearch=this.inputBox.value,this.safeObserve(this.searchButton,"click",this.onSearchButtonClick.bind(this))}onSearchButtonClick(event){var searchText=this.inputBox.value;if(event.preventDefault(),event.stopPropagation(),searchText!==this.previousSearch){this.previousSearch=searchText;for(var headings=document.getElementsByClassName("categoryheading"),i=0;i<headings.length;i++)headings[i].style.display="none";var activePlazaListToNotify=ActivePlazasListLastInstances[this.options.activePlazaListToNotify];activePlazaListToNotify&&activePlazaListToNotify.loadPage(0,searchText),jQuery("#"+this.options.activePlazaListToNotify).trigger("searchList",[searchText])}}}
75class PlazaList extends ListBase{constructor(el,options){super(el,Object.assign({pagingEffect:"vertSlide",tags:[],searchPhrases:[]},options)),this.initializeSearchBox(),this.initializeSortableBox("a"),this.sorterControl=this.el.querySelector(".sorterBtns"),legacyGlobal.registerTagSearchableList(this)}loadPage(page){super.loadPage(page);var tagCloud=legacyGlobal.findTagCloud();null!=tagCloud&&tagCloud.preUpdate(),this.standardJSONRequest(new 
75UrlTemplate(this.options.url).r("PLH_page",page).r("PLH_Csearch",this.options.searchPhrases.join(",")).r("PLH_Ctag",this.options.tags.join(",")).r("PLH_PlazaListSorting",this.options.sortOrder).url)}onLoadPage(pageEl){if(super.onLoadPage(pageEl),null!=this.options.sorters&&null!=this.sorterControl&&(this.sorterControl.innerHTML=this.options.sorters,this.initializeSortableBox("a")),null!=this.options.tagCloud){var tagCloud=legacyGlobal.findTagCloud();null!=tagCloud&&(tagCloud.innerHTML=this.options.tagCloud)}}refresh(){this.loadPage(0),this.el.dispatchEvent(new CustomEvent("list:criteriaChanged",{detail:{options:this.options}}))}addTag(tag){this.options.tags.push(tag),this.refresh()}removeTag(tag){this.options.tags=this.options.tags.without(tag),this.refresh()}}Object.assign(PlazaList.prototype,SearchBox),Object.assign(PlazaList.prototype,SortableBox);
76var PlayPauseButtonInstance=null;class PlayPauseButton extends DOMAttached{constructor(el,options){super(el,options),PlayPauseButtonInstance=this,this.imgPlay=document.getElementById(options.playButton),this.imgPause=document.getElementById(options.pauseButton),null!=options.soundUrl&&(this.soundUrl=options.soundUrl),this.autoplay=options.autoplay,this.playInfinite=options.playInfinite;var finishInitialization=function(){this.safeObserve(this.imgPlay,"click",this.play.bind(this,this.playInfinite)),this.safeObserve(this.imgPause,"click",this.pause.bind(this)),null!=this.soundUrl&&this.setSoundUrl(this.soundUrl,this.autoplay,this.playInfinite)};soundManager.ok()?finishInitialization():soundManager.onready(finishInitialization)}play(infinitely){this.displayPauseButton(),infinitely?this.playInfinitely(this):this.playOnce(this)}playInfinitely(obj){obj.sound&&obj.sound.id&&soundManager.play(obj.sound.id,{onfinish:function(){obj.delayedPlay=setTimeout((function(){obj.playInfinitely(obj)}),1800)}})}playOnce(obj){obj.sound&&obj.sound.id&&soundManager.play(obj.sound.id,{onfinish:function(){obj.displayPlayButton()}})}pause(){if(this.sound&&this.sound.id){this.delayedPlay&&clearTimeout(this.delayedPlay),this.displayPlayButton();var soundId=this.sound.id;soundManager.pause(soundId)}}displayPlayButton(){this.imgPlay.style.display="block",this.imgPause.style.display="none"}displayPauseButton(){this.imgPause.style.display="block",this.imgPlay.style.display="none"}createSound(soundUrl){return soundManager.createSound({id:"sound",url:soundUrl})}setSoundUrl(soundUrl,autoplay,repeatInfinitely){soundUrl&&(soundManager.destroySound("sound"),this.soundUrl=soundUrl,this.sound=this.createSound(soundUrl),autoplay?this.play(repeatInfinitely):this.pause())}}
77class PetOwnerSelector extends DOMAttached{constructor(el,options){super(el,options),this.sharedListUrl=options.sharedListUrl,this.filterMemberUrl=options.filterMemberUrl,this.dropDownList=document.getElementById(options.dropDownList),this.safeObserve(this.dropDownList,"change",this.onChange.bind(this))}onChange(){var url="null"===this.dropDownList.options[this.dropDownList.selectedIndex].value?new UrlTemplate(this.sharedListUrl).url:new UrlTemplate(this.filterMemberUrl).r("PLH_nchild",this.dropDownList.options[this.dropDownList.selectedIndex].value).url;SharedListInstance.loadPageWithCustomUrl(0,url)&&(event.preventDefault(),event.stopPropagation())}}
78class NewspaperEditionList extends ListBase{constructor(el,options){super(el,Object.assign({pagingEffect:"vertSlide"},options))}loadPage(page){super.loadPage(page),this.standardJSONRequest(this.options.url.replace("PLH_pagenum",page))}}
79class NewspaperAd extends DOMAttached{constructor(el,options){super(el,options),this.options.isInPreviewMode&&this.initializeChangeHandlers()}initializeChangeHandlers(){this.titleText=this.el.querySelector(".titleText"),this.bodyText=this.el.querySelector(".bodyText"),this.titleBoundTextArea=document.getElementById(this.options.textBoxTitleId).querySelector("textarea"),this.bodyBoundTextArea=document.getElementById(this.options.textBoxBodyId).querySelector("textarea"),this.boundImageContainer=document.getElementById(this.options.pictureSelection).querySelector(".imageShow"),this.safeObserve(this.titleBoundTextArea,"change",this.onTitleChange.bind(this)),this.safeObserve(this.bodyBoundTextArea,"change",this.onBodyChange.bind(this))}onTitleChange(ev){this.titleText.innerHTML=this.titleBoundTextArea.value}onBodyChange(ev){this.bodyText.innerHTML=this.bodyBoundTextArea.value}}
80class PopupEmailPreview extends DOMAttached{constructor(el,options){super(el,options),this.previewUrl=options.previewUrl,this.previewButton=document.getElementById(options.previewButton),this.safeObserve(this.previewButton,"click",this.loadPreview.bind(this))}loadPreview(evt){evt.preventDefault(),evt.stopPropagation(),this.previewWindow=window.open("","Preview","height=800,width=800,resizable=1");var url=this.previewUrl,params=this.getParameters();for(var key in params)url=url.replace(key,encodeURIComponent(JSON.stringify(params[key])));this.previewWindow.location.href=url,this.previewWindow.focus()}}
81class NewsletterDesign extends PopupEmailPreview{constructor(el,options){super(el,options),this.subjectBox=document.getElementById(options.subjectBox),this.salutationBox=document.getElementById(options.salutationBox),this.messageBox=document.getElementById(options.messageBox)}getParameters(){return{PLH_subject:this.subjectBox.value,PLH_salutation:this.salutationBox.value,PLH_message:this.messageBox.value}}}
82class MoveAnimation extends DOMAttached{constructor(el,options){super(el,options),this.target=-1,this.xTarget=0,this.yTarget=0,this.nextTarget(),this.el.style.left=this.xTarget+"px",this.el.style.top=this.yTarget+"px",this.nextTarget(),this.el.style.visibility="visible",setInterval(function(){var xCurrent=parseInt(this.el.style.left,10),yCurrent=parseInt(this.el.style.top,10),distance=Math.pow(this.xTarget-xCurrent,2)+Math.pow(this.yTarget-yCurrent,2),angle=Math.atan2(this.yTarget-yCurrent,this.xTarget-xCurrent),distance2=(xCurrent=xCurrent+Math.cos(angle)*this.options.speed,yCurrent=yCurrent+Math.sin(angle)*this.options.speed,Math.pow(this.xTarget-xCurrent,2)+Math.pow(this.yTarget-yCurrent,2));this.el.style.left=xCurrent+"px",this.el.style.top=yCurrent+"px",(distance2>=distance||distance2<4)&&(this.nextTarget(),0==this.target&&this.options.jumpBack&&(this.el.style.left=this.xTarget+"px",this.el.style.top=this.yTarget+"px",this.nextTarget()))}.bind(this),this.options.framerate)}nextTarget(){this.target=this.target+1,eval("if(!this.options.x"+this.target+") this.target = 0;"),this.xTarget=parseInt(eval("this.options.x"+this.target),10),this.yTarget=parseInt(eval("this.options.y"+this.target),10),-1==this.xTarget&&(this.xTarget=-(window.screen.availWi
82dth-1e3)/2-100),-2==this.xTarget&&(this.xTarget=1e3+(window.screen.availWidth-1e3)/2+150)}}
83class SaveableSVG{constructor(svgDoc,saveUrl,callback){this.svgDoc=svgDoc,this.saveUrl=saveUrl,this.callback=callback}saveSVG(parameters,ids,version){MiniMeLastVersionSaved!=version&&(this.parameters=parameters,this.ids=ids,this.version=version,this.first=!1,this.convertToCanvas())}convertToCanvas(){var clone;if(this.createCanvas(),this.createCanvasTransparent(),canvg("miniMeCanvas",this.getXMLString(this.svgDoc),{ignoreMouse:!0,ignoreAnimation:!0,renderCallback:this.sentAjaxRequest.bind(this)}),window.DOMParser){clone=(new DOMParser).parseFromString(this.getXMLString(this.svgDoc),"image/svg+xml")}else(clone=new ActiveXObject("Microsoft.XMLDOM")).async=!1,clone.loadXML(this.getXMLString(this.svgDoc));clone.getElementById("background").style.display="none",canvg("miniMeCanvasTransparent",this.getXMLString(clone),{ignoreMouse:!0,ignoreAnimation:!0,renderCallback:this.sentAjaxRequest.bind(this)})}createCanvas(){this.canvas=document.getElementById("miniMeCanvas"),null==this.canvas&&(this.canvas=document.createElement("canvas"),this.canvas.id="miniMeCanvas",this.canvas.style.display="none",this.canvas.width=510,this.canvas.height=727,document.body.insertBefore(this.canvas,document.body.childNodes[0]))}createCanvasTransparent(){this.canvasTransparent=document.getElementById("miniMeCanvasTransparent"),null==this.canvasTransparent&&(this.canvasTransparent=document.createElement("canvas"),this.canvasTransparent.id="miniMeCanvasTransparent",this.canvasTransparent.style.display="none",this.canvasTransparent.width=510,this.canvasTransparent.height=727,document.body.insertBefore(this.canvasTransparent,document.body.childNodes[0]))}sentAjaxRequest(){if(this.first){var parameters=this.parameters,ids=this.ids,version=this.version,normal=this.canvas.toDataURL(),transparent=this.canvasTransparent.toDataURL();normal.length<35e3||transparent.length<35e3||axios(this.saveUrl,{method:"post",headers:{"content-type":"application/x-www-form-urlencoded"},data:{pngBase64:normal,pngBase64Transparent:transparent,settings:JSON.stringify(MiniMeSettings),accsettings:parameters,accuniqueId:ids}}).then((transport=>{document.dispatchEvent(new CustomEvent("miniMe:hideProgressIndicator")),transport.data.success?(MiniMeLastVersionSaved=version,document.dispatchEvent(new CustomEvent("miniMe:showSuccessfulSaveBubble"))):this.callback()}))}else this.first=!0}getXMLString(svg){return(new window.XMLSerializer).serializeToString(svg)}}
84class MiniMeSpeechBubble{constructor(svgDoc){this.svgDoc=svgDoc,this.currentBubble=null,this.timeoutId=null}show(bubble,durationMs=1e4){this.dismiss(),this.currentBubble=document.createElementNS("http://www.w3.org/2000/svg","image"),this.currentBubble.setAttribute("x",bubble.x),this.currentBubble.setAttribute("y",bubble.y),this.currentBubble.setAttribute("width",bubble.width),this.currentBubble.setAttribute("height",bubble.height),this.currentBubble.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",bubble.src),this.currentBubble.setAttribute("style","opacity:0"),this.svgDoc.appendChild(this.currentBubble),gsap.to(this.currentBubble,{opacity:1,duration:.5}),this.timeoutId=window.setTimeout((()=>this.dismiss()),durationMs)}dismiss(){if(!this.currentBubble)return;clearTimeout(this.timeoutId);const bubble=this.currentBubble;this.currentBubble=null,this.timeoutId=null,gsap.to(bubble,{opacity:0,duration:.5,onComplete:()=>{bubble.style.display="none"}})}}
85var ColorSelectorActiveColor=null;class ColorSelector{constructor(editor,colors,width,height,vertical,feedback,speechBubble){this.colors=[],this.height=0,this.width=0,this.namespace="http://www.w3.org/2000/svg",this.mouseUpHappened=!0,this.activeElement=null,this.editor=editor,this.colors=colors,this.width=width,this.height=height,this.playFeedbackSound=feedback,this.speechBubble=speechBubble,null==GenericSoundsInstance&&new GenericSounds(this.playFeedbackSound),vertical&&this.drawVerticalSelector()}drawVerticalSelector(){for(var colorsCount=this.colors.length,boxHeight=this.height/colorsCount,boxWidth=boxHeight,i=0;i<colorsCount;i++){var r=boxWidth/2,x=this.width-boxWidth-20+r,y=i*boxHeight+r,color=document.createElementNS(this.namespace,"circle");color.setAttribute("cx",x),color.setAttribute("cy",y),color.setAttribute("r",r-1),color.style.fill=this.colors[i],color.style.stroke=this.colors[i],color.style.strokeWidth=2,color.onclick=this.colorClickHandler.bind(this),color.onmousedown=function(e){this.mouseUpHappened=!1}.bind(this),color.onmouseup=function(e){this.mouseUpHappened=!0}.bind(this),color.onmouseout=function(e){this.mouseUpHappened||this.speechBubble.show(MiniMeSpeechBubbles.colors)}.bind(this),this.editor.getElementById("colorSelector").appendChild(color)}}resetColors(){null!=this.activeElement&&(this.activeElement.setAttribute("cx",parseFloat(this.activeElement.getAttribute("cx"))+20),this.activeElement.style.stroke=this.activeElement.style.fill,this.activeElement=null),ColorSelectorActiveColor=null}colorClickHandler(e){GenericSoundsInstance.putDownSound(),this.resetColors();var selectedColorElement=e.target;ColorSelectorActiveColor=selectedColorElement.style.fill,selectedColorElement.setAttribute("cx",selectedColorElement.getAttribute("cx")-20),selectedColorElement.style.stroke="#000000",selectedColorElement.style.x-=20,this.activeElement=selectedColorElement}}
86var DragInProgress=!1;class DraggableSvgItem{constructor(editor){this.listenerManager=new ListenerManager,this.namespace="http://www.w3.org/2000/svg",this.dragx=0,this.dragy=0,this.posx=0,this.posy=0,this.isActive=!1,this.svgHeight=798,this.svgWidth=450,this.startx=0,this.starty=0,this.lastDrag=0,this.editor=editor}addListeners(){this.item.style.userSelect="none",this.listenerManager.safeObserve(this.item,"mousedown",this.dragStart.bind(this)),this.listenerManager.safeObserve(this.editor,"mousemove",this.drag.bind(this)),this.listenerManager.safeObserve(this.editor,"mouseup",this.dragStop.bind(this)),legacyGlobal.isTouchDevice()&&(this.listenerManager.safeObserve(this.item,"touchstart",this.dragStart.bind(this)),this.listenerManager.safeObserve(this.editor,"touchmove",this.drag.bind(this)),this.listenerManager.safeObserve(this.editor,"touchend",this.dragStop.bind(this)),this.listenerManager.safeObserve(this.editor,"touchcancel",this.dragStop.bind(this)))}dragStart(e){return this.pauseEvent(e),this.startx=this.item.getAttribute("x"),this.starty=this.item.getAttribute("y"),this.isActive=!0,DragInProgress=!0,legacyGlobal.isTouchDevice()&&"touchstart"===e.type&&(this.posx=e.touches[0].pageX,this.posy=e.touches[0].pageY),this.dragx=this.posx-this.item.getAttribute("x"),this.dragy=this.posy-this.item.getAttribute("y"),!1}dragStop(e){this.isActive&&(this.isActive=!1,DragInProgress=!1)}drag(e){this.isActive&&this.pauseEvent(e);var now=new Date;if(now.getTime()-this.lastDrag>70&&(legacyGlobal.isTouchDevice()&&"touchmove"===e.type?(this.posx=e.touches[0].pageX,this.posy=e.touches[0].pageY):(this.posx=document.all?e.clientX:e.pageX,this.posy=document.all?e.clientY:e.pageY),this.isActive)){var newX=this.posx-this.dragx,newY=this.posy-this.dragy,width=parseFloat(this.item.getAttribute("width")),height=parseFloat(this.item.getAttribute("height"));newX+width/2<0&&(newX=-1*width/2),newY+height/2<0&&(newY=-1*height/2),newX+width/2>this.svgWidth&&(newX=this.svgWidth-width/2),newY+height/2>this.svgHeight&&(newY=this.svgHeight-height/2),this.item.setAttribute("x",Math.round(newX)),this.item.setAttribute("y",Math.round(newY)),now=new Date,this.lastDrag=now.getTime()}return!1}pauseEvent(e){if(void 0!==e)return e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault(),e.cancelBubble=!0,e.returnValue=!1,!1}}
87function colorToHex(color){if("#"===color.substr(0,1))return color;for(var digits=/(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color),red=parseInt(digits[2]),green=parseInt(digits[3]),rgb16=(parseInt(digits[4])|green<<8|red<<16).toString(16);rgb16.length<6;)rgb16="0"+rgb16;return digits[1]+"#"+rgb16}function getActiveColor(){return colorToHex(ColorSelectorActiveColor)}function hexToDec(hex){return parseInt("FF"+hex,16)}function fillShape(shape,color){if(!shape.parentNode||null==shape.id||!shape.id.startsWith(shape.parentNode.id+"-static"))if(shape.hasChildNodes())for(var child=shape.firstChild;null!=child;child=child.nextSibling)fillShape(child,color);else shape.style&&(shape.style.fill=color)}function decToHex(dec){return dec.toString(16).toUpperCase().substring(2)}function check(ele){return void 0!==ele}class ColorableSvgItem{constructor(colorSelector,item,settingKey,colorableId){this.namespace="http://www.w3.org/2000/svg",this.colorSelector=colorSelector,this.item=item,this.settingKey=settingKey,this.colorableId=colorableId,this.setInitialColor(),this.setListeners()}setInitialColor(){var initialColor=MiniMeSettings[this.settingKey]?.[this.colorableId];initialColor&&fillShape(document.getElementById(this.colorableId),"#"+decToHex(initialColor))}setListeners(){var selector=this.colorSelector,settingKey=this.settingKey,colorableId=this.colorableId,namespace=this.namespace;this.item.addEventListener("click",(function color(){var useNode,useNodeCopy;null!=ColorSelectorActiveColor&&(fillShape(document.getElementById(colorableId),ColorSelectorActiveColor),useNode=this,(useNodeCopy=document.createElementNS(namespace,"use")).setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","#"+colorableId),useNodeCopy.addEventListener("click",color),useNode.parentNode.replaceChild(useNodeCopy,useNode),MiniMeSettings[settingKey]=MiniMeSettings[settingKey]||{},MiniMeSettings[settingKey][colorableId]=hexToDec(getActiveColor().substring(1)),MiniMeLastVersion++,document.dispatchEvent(new CustomEvent(MINI_ME_EVENTS.CHANGE_ITEM_COLOR)),selector.resetColors())}))}}
88var ChangeInProgress=!1,ChangeElementFade=null,ChangeElementAppear=null;class ChangeableMiniMeItem{constructor(editor,groupIdentifier,colorSelector,svgItems,customItems,setting,designedItemIdPrefix){this.listenerManager=new ListenerManager,this.index=0,this.namespace="http://www.w3.org/2000/svg",this.givenItems=0,this.store=null,this.itemInstancePrefix=designedItemIdPrefix,this.editor=editor,this.groupIdentifier=groupIdentifier,this.colorSelector=colorSelector,this.svgItems=svgItems,this.customItem=customItems,this.items=[],this.itemsLoaded=[],this.colorSelector=colorSelector,this.groupElement=document.createElementNS(this.namespace,"g"),this.groupElement.setAttribute("class",this.groupIdentifier),this.editor.appendChild(this.groupElement),this.playFeedbackSound=colorSelector.playFeedbackSound,this.setting=setting,null==GenericSoundsInstance&&(GenericSoundsInstance=new GenericSounds(this.playFeedbackSound)),this.givenItems=this.svgItems.length;for(var i=0;i<this.svgItems.length;++i)this.items.push({type:"svg",content:this.svgItems[i]}),this.itemsLoaded.push(null);if(1!=customItems.length||""!=customItems[0])for(i=0;i<customItems.length;i++)this.items.push({type:"image",content:customItems[i]}),this.itemsLoaded.push(null);if("string"==typeof this.setting&&0==this.setting.indexOf(this.itemInstancePrefix)){this.index=0;for(i=0;i<this.items.length;i++)if("image"==this.items[i].type&&this.itemInstancePrefix+this.items[i].content.id==this.setting){this.index=i;break}}else null==this.setting||parseInt(this.setting)>this.items.length?this.index=0:this.index=this.setting-1;var selectedItem=this.items[this.index];this.loadItem(selectedItem,this.index,!0),this.listenerManager.safeObserve(document,MINI_ME_CLOSET_EVENTS.SELECTED_ITEM_CHANGED,(event=>{this.itemSelectionEventHandler(event)}))}addItem(item,visible){this.groupElement.appendChild(item),item.style.display=visible?"block":"none"}
88loadItem(item,idx,visible){if("image"==item.type){var customItem=this.createImageItem(item.content,idx);this.addItem(customItem,visible)}else{if("svg"!=item.type)throw"Unknown item type "+item.type;for(var svg=document.createElementNS(this.namespace,"g"),chains=item.content.objectChains,i=0;i<chains.length;++i){var svgItem=this.createSvgItem(item.content,chains[i][0],chains[i][chains[i].length-1]);svg.appendChild(svgItem)}this.addItem(svg,visible),this.itemsLoaded[idx]=svg}}createImageItem(imageItem,idx){var image=document.createElementNS(this.namespace,"image");return image.setAttribute("x",imageItem.x),image.setAttribute("y",imageItem.y),image.setAttribute("width",imageItem.width),image.setAttribute("height",imageItem.height),image.setAttribute("preserveAspectRatio","none"),image.id=this.itemInstancePrefix+imageItem.id,image.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",imageItem.src),image.style.pointerEvents="painted",this.itemsLoaded[idx]=image,image}createSvgItem(svgItem,settingKey,colorableId){var useSvg=document.createElementNS(this.namespace,"use");return useSvg.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","#"+colorableId),new ColorableSvgItem(this.colorSelector,useSvg,settingKey,colorableId).item}getSelectedItemId(){const selectedItem=this.items[this.index];return selectedItem?selectedItem.content.id:""}itemSelectionEventHandler({detail:{item:item,category:category}}){if(category!==this.groupIdentifier)return!1;var targetIndex=this.findOrAddItem(item);return this.applyMiniMeItemByIndex(targetIndex),!0}findOrAddItem(itemData){var index=this.items.findIndex((item=>item.content.id===itemData.content.id));return-1===index&&(index=this.items.length,this.items.push(itemData),this.itemsLoaded.push(null)),index}applyMiniMeItemByIndex(selectedItemIndex){null!=ColorSelectorActiveColor&&(GenericSoundsInstance.softClickSound(),this.colorSelector.resetColors()),GenericSoundsInstance.softClickSound();var currentIdx=this.index,nextIdx=selectedItemIndex;null==this.itemsLoaded[nextIdx]&&this.loadItem(this.items[nextIdx],nextIdx,!1),this.itemsLoaded[currentIdx].style.pointerEvents="none",this.fadeOutToNextItem(currentIdx,nextIdx),this.itemsLoaded[nextIdx].style.pointerEvents="all",this.store=nextIdx+1,this.store>this.givenItems&&(this.store=this.itemsLoaded[nextIdx].id),this.index=nextIdx}fadeOutToNextItem(currentIndex,nextIndex){ChangeInProgress=!0;var ChangeElementFade=this.itemsLoaded[currentIndex];ChangeElementFade.style.opacity=1,ChangeElementFade.style.cursor="wait";var ChangeElementAppear=this.itemsLoaded[nextIndex];ChangeElementAppear.style.opacity=0,ChangeElementAppear.style.cursor="wait",ChangeElementAppear.style.display="block";var step=0;!function fadeOver(){step<10?(step++,ChangeElementFade.style.opacity-=.1,ChangeElementAppear.style.opacity=parseFloat(ChangeElementAppear.style.opacity)+.1,window.setTimeout((function(){fadeOver()}),50)):(ChangeElementFade.style.opacity=0,ChangeElementAppear.style.opacity=1,ChangeElementAppear.style.cursor="default",ChangeElementFade.style.cursor="default",ChangeInProgress=!1,MiniMeLastVersion++)}()}}class MiniMeFaces extends ChangeableMiniMeItem{constructor(svgDoc,colorSelector,groupIdentifier,designedItemIdPrefix){super(svgDoc,groupIdentifier,colorSelector,MiniMeStaticItems.face,[],MiniMeSettings.face,designedItemIdPrefix)}itemSelectionEventHandler(event){super.itemSelectionEventHandler(event)&&(MiniMeSettings.face=this.index+1)}}class MiniMeHair extends ChangeableMiniMeItem{constructor(svgDoc,colorSelector,groupIdentifier,designedItemIdPrefix){super(svgDoc,groupIdentifier,colorSelector,MiniMeStaticItems.hair,[],MiniMeSettings.hair,designedItemIdPrefix)}itemSelectionEventHandler(event){super.itemSelectionEventHandler(event)&&(MiniMeSettings.hair=this.index+1)}}class MiniMeBottom extends ChangeableMiniMeItem{constructor(svgDoc,colorSelector,customItems,groupIdentifier,designedItemIdPrefix){super(svgDoc,groupIdentifier,colorSelector,MiniMeStaticItems.bottom,customItems,MiniMeSettings.bottom,designedItemIdPrefix)}itemSelectionEventHandler(event){super.itemSelectionEventHandler(event)&&this.store&&(MiniMeSettings.bottom=this.store)}}class MiniMeTop extends ChangeableMiniMeItem{constructor(svgDoc,colorSelector,customItems,groupIdentifier,designedItemIdPrefix){super(svgDoc,groupIdentifier,colorSelector,MiniMeStaticItems.top,customItems,MiniMeSettings.top,designedItemIdPrefix)}itemSelectionEventHandler(event){super.itemSelectionEventHandler(event)&&this.store&&(MiniMeSettings.top=this.store)}}class MiniMeShoes extends ChangeableMiniMeItem{constructor(svgDoc,colorSelector,customItems,groupIdentifier,designedItemIdPrefix){super(svgDoc,groupIdentifier,colorSelector,MiniMeStaticItems.shoes,customItems,MiniMeSettings.shoes,designedItemIdPrefix)}itemSelectionEventHandler(event){super.itemSelectionEventHandler(event)&&this.store&&(MiniMeSettings.shoes=this.store)}}
89class MiniMeAccessory extends DraggableSvgItem{constructor(editor,accessory,feedback){super(editor),this.accessory=accessory,null==GenericSoundsInstance&&new GenericSounds(feedback),this.item=document.createElementNS(this.namespace,"image"),this.item.setAttribute("x",accessory.x),this.item.setAttribute("y",accessory.y),this.item.setAttribute("width",accessory.width),this.item.setAttribute("height",accessory.height),this.item.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",accessory.src),this.item.style.pointerEvents="painted",this.displayItem(),accessory.isApplied||this.hideItem(),this.addListeners()}addListeners(){super.addListeners(),this.listenerManager.safeObserve(this.item,"dblclick",function(){this.changeTopBottomLayer()}.bind(this))}dragStop(e){this.isActive&&(this.isCurrentPositionInsideOfElementBoundaries("boxGroup")&&this.hideItem(),GenericSoundsInstance.softClickSound(),MiniMeLastVersion++),super.dragStop()}isCurrentPositionInsideOfElementBoundaries(elementId){var elementX=this.posx,elementY=this.posy,box=document.getElementById(elementId).getBoundingClientRect(),offset=this.getOffset(box);return elementX>offset.left&&elementX<offset.left+box.width&&elementY>offset.top&&elementY<offset.top+box.height}getOffset(element){var html=document.documentElement;return{top:element.top+window.pageYOffset-html.clientTop,left:element.left+window.pageXOffset-html.clientLeft}}changeTopBottomLayer(){this.accessory.isTopLayer=!this.accessory.isTopLayer,this.displayItem()}displayItem(){this.accessory.isTopLayer?this.editor.getElementById("accessories-pre").appendChild(this.item):this.editor.getElementById("accessories-post").appendChild(this.item)}hideItem(){this.item.style.display="none",this.accessory.isApplied=!1}showItem(){this.item.style.display="block",this.accessory.isTopLayer=!0,this.accessory.isApplied=!0,this.displayItem()}}
90const MINI_ME_ACCESSORIES_SETTINGS={itemsPerRow:3,itemHeight:90,itemHeightOffset:10,itemWidth:90,itemWidthOffset:10,maxVisibleRows:7,scrollableContainerWidth:450,scrollableContainerHeight:798,divider:2,accessoryWidth:85,accessoryHeight:85,accessoryWidthOffset:5,accessoryHeightOffset:5,accessoryOpacity:.3,accessoryX:100,accessoryY:2
9000,accessoryDivider:2,accessoryScrollWidth:280,windowRX:20,windowRY:20,overlayFill:"#FFFFFF",overlayOpacity:.7,windowFill:"#AA3333",windowStroke:"#000000",windowStrokeWidth:"5"};class MiniMeAccessoryManager{constructor(editor,accessories,feedback,speechBubble){this.listenerManager=new ListenerManager,this.accessoryInstances=[],this.namespace="http://www.w3.org/2000/svg",this.firstAccessory=!0,this.editor=editor,this.scrollableContent=null,this.speechBubble=speechBubble,null==GenericSoundsInstance&&new GenericSounds(feedback);for(var i=0;i<accessories.length;i++)this.accessoryInstances.push(new MiniMeAccessory(this.editor,accessories[i],feedback));this.initializeAccessoriesBox(),0!=this.accessoryInstances.length&&(this.editor.getElementById("boxGroup").style.display="block")}initializeAccessoriesBox(){this.accessoriesBox=this.editor.getElementById("box"),this.accessoriesBoxShadow=this.editor.getElementById("boxShadow"),0!=this.accessoryInstances.length&&(this.listenerManager.safeObserve(this.accessoriesBox,"mouseover",(()=>{this.accessoriesBoxMouseOver()})),this.listenerManager.safeObserve(this.accessoriesBox,"mouseout",(()=>{this.accessoriesBoxMouseOut()})),this.listenerManager.safeObserve(this.accessoriesBox,"mouseup",(()=>{this.dropItemCheck()})),this.listenerManager.safeObserve(this.accessoriesBox,"click",(()=>{this.openAccessoryPopUp()})))}accessoriesBoxMouseOver(){this.accessoriesBoxShadow.style.display="block",this.accessoriesBox.style.cursor="pointer"}accessoriesBoxMouseOut(){this.accessoriesBoxShadow.style.display="none"}dropItemCheck(){var activeItem=this.getActiveItem();null!=activeItem&&this.dropItem(activeItem)}dropItem(item){GenericSoundsInstance.softClickSound(),this.accessoryInstances[item].hideItem()}getActiveItem(){for(var i=0;i<this.accessoryInstances.length;i++)if(this.accessoryInstances[i].isActive)return i;return null}closeOverlay(){const overlayGroup=this.editor.querySelector("#overlayGroup");overlayGroup&&overlayGroup.remove(),this.scrollableContent=null}openAccessoryPopUp(){GenericSoundsInstance.softClickSound();var rows=Math.floor(this.accessoryInstances.length/MINI_ME_ACCESSORIES_SETTINGS.itemsPerRow);this.accessoryInstances.length%MINI_ME_ACCESSORIES_SETTINGS.itemsPerRow!=0&&rows++;var group=this.createOverlay(),bgWindow=this.createBackgroundWindow(rows);group.appendChild(bgWindow);var scrollContainer=this.createScrollContainer(rows);group.appendChild(scrollContainer);var borderFrame=this.createBorderFrame(rows);group.appendChild(borderFrame),this.editor.appendChild(group),this.insertAccessoriesWithScroll(rows)}createScrollContainer(rows){var height=Math.min(rows,MINI_ME_ACCESSORIES_SETTINGS.maxVisibleRows)*MINI_ME_ACCESSORIES_SETTINGS.itemHeight+MINI_ME_ACCESSORIES_SETTINGS.itemHeightOffset,width=MINI_ME_ACCESSORIES_SETTINGS.itemsPerRow*MINI_ME_ACCESSORIES_SETTINGS.itemWidth+MINI_ME_ACCESSORIES_SETTINGS.itemWidthOffset,x=(MINI_ME_ACCESSORIES_SETTINGS.scrollableContainerWidth-width)/MINI_ME_ACCESSORIES_SETTINGS.divider,y=(MINI_ME_ACCESSORIES_SETTINGS.scrollableContainerHeight-height)/MINI_ME_ACCESSORIES_SETTINGS.divider,foreignObject=document.createElementNS(this.namespace,"foreignObject");foreignObject.setAttribute("x",x),foreignObject.setAttribute("y",y),foreignObject.setAttribute("width",width),foreignObject.setAttribute("height",height);var scrollDiv=document.createElement("div");return scrollDiv.style.width="100%",scrollDiv.style.height="100%",scrollDiv.style.overflowY=rows>MINI_ME_ACCESSORIES_SETTINGS.maxVisibleRows?"scroll":"hidden",scrollDiv.style.overflowX="hidden",scrollDiv.style.borderRadius="20px",scrollDiv.style.boxSizing="border-box",foreignObject.appendChild(scrollDiv),this.scrollableContent=scrollDiv,foreignObject}insertAccessoriesWithScroll(rows){var contentDiv=this.scrollableContent,svgContent=document.createElementNS(this.namespace,"svg"),contentHeight=rows*MINI_ME_ACCESSORIES_SETTINGS.itemHeight+MINI_ME_ACCESSORIES_SETTINGS.itemHeightOffset;svgContent.setAttribute("width",`${MINI_ME_ACCESSORIES_SETTINGS.accessoryScrollWidth}`),svgContent.setAttribute("height",contentHeight);for(var i=0;i<this.accessoryInstances.length;i++){var x=i%MINI_ME_ACCESSORIES_SETTINGS.itemsPerRow,y=Math.floor(i/MINI_ME_ACCESSORIES_SETTINGS.itemsPerRow);this.insertAccessoryIntoScrollable(svgContent,i,x,y)}contentDiv.appendChild(svgContent)}insertAccessoryIntoScrollable(svgContent,i,x,y){var newHeight,newWidth,instance=this.accessoryInstances[i],accessory=instance.accessory,clone=document.createElementNS(this.namespace,"image");if(clone.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",accessory.src),accessory.height<=MINI_ME_ACCESSORIES_SETTINGS.accessoryHeight&&accessory.width<=MINI_ME_ACCESSORIES_SETTINGS.accessoryWidth)newWidth=accessory.width,newHeight=accessory.height;else if(accessory.height>accessory.width){var ratio=accessory.height/accessory.width;newWidth=(newHeight=MINI_ME_ACCESSORIES_SETTINGS.accessoryHeight)/ratio}else{ratio=accessory.width/accessory.height;newHeight=(newWidth=MINI_ME_ACCESSORIES_SETTINGS.accessoryWidth)/ratio}clone.setAttribute("width",newWidth),clone.setAttribute("height",newHeight);var newX=MINI_ME_ACCESSORIES_SETTINGS.accessoryWidthOffset+x*MINI_ME_ACCESSORIES_SETTINGS.itemWidth;newWidth<MINI_ME_ACCESSORIES_SETTINGS.accessoryWidth&&(newX+=(MINI_ME_ACCESSORIES_SETTINGS.accessoryWidth-newWidth)/MINI_ME_ACCESSORIES_SETTINGS.accessoryDivider);var newY=MINI_ME_ACCESSORIES_SETTINGS.accessoryHeightOffset+y*MINI_ME_ACCESSORIES_SETTINGS.itemHeight;newHeight<MINI_ME_ACCESSORIES_SETTINGS.accessoryHeight&&(newY+=(MINI_ME_ACCESSORIES_SETTINGS.accessoryHeight-newHeight)/MINI_ME_ACCESSORIES_SETTINGS.accessoryDivider),clone.setAttribute("x",newX),clone.setAttribute("y",newY),clone.style.cursor="pointer",accessory.isApplied&&(clone.style.opacity=MINI_ME_ACCESSORIES_SETTINGS.accessoryOpacity),svgContent.appendChild(clone),this.firstAccessory&&this.listenerManager.safeObserve(clone,"click",(()=>{this.speechBubble.show(MiniMeSpeechBubbles.accessory),this.firstAccessory=!1})),this.listenerManager.safeObserve(clone,"click",(()=>{instance.showItem(),instance.item.setAttribute("x",MINI_ME_ACCESSORIES_SETTINGS.accessoryX),instance.item.setAttribute("y",MINI_ME_ACCESSORIES_SETTINGS.accessoryY),this.closeOverlay(),MiniMeLastVersion++}))}createOverlay(){var group=document.createElementNS(this.namespace,"g"),overlay=document.createElementNS(this.namespace,"rect");return overlay.setAttribute("x","0"),overlay.setAttribute("y","0"),overlay.setAttribute("width",`${MINI_ME_ACCESSORIES_SETTINGS.scrollableContainerWidth}`),overlay.setAttribute("height",`${MINI_ME_ACCESSORIES_SETTINGS.scrollableContainerHeight}`),overlay.style.fill=MINI_ME_ACCESSORIES_SETTINGS.overlayFill,overlay.style.fillOpacity=MINI_ME_ACCESSORIES_SETTINGS.overlayOpacity,overlay.id="overlay",group.id="overlayGroup",group.appendChild(overlay),this.listenerManager.safeObserve(overlay,"click",this.closeOverlay.bind(this)),group}
90createBackgroundWindow(rows){var height=Math.min(rows,MINI_ME_ACCESSORIES_SETTINGS.maxVisibleRows)*MINI_ME_ACCESSORIES_SETTINGS.itemHeight+MINI_ME_ACCESSORIES_SETTINGS.itemHeightOffset,width=MINI_ME_ACCESSORIES_SETTINGS.itemsPerRow*MINI_ME_ACCESSORIES_SETTINGS.itemWidth+MINI_ME_ACCESSORIES_SETTINGS.itemWidthOffset,x=(MINI_ME_ACCESSORIES_SETTINGS.scrollableContainerWidth-width)/MINI_ME_ACCESSORIES_SETTINGS.divider,y=(MINI_ME_ACCESSORIES_SETTINGS.scrollableContainerHeight-height)/MINI_ME_ACCESSORIES_SETTINGS.divider,backgroundWindow=document.createElementNS(this.namespace,"rect");return backgroundWindow.setAttribute("x",x),backgroundWindow.setAttribute("y",y),backgroundWindow.setAttribute("width",width),backgroundWindow.setAttribute("height",height),backgroundWindow.setAttribute("rx",MINI_ME_ACCESSORIES_SETTINGS.windowRX),backgroundWindow.setAttribute("ry",MINI_ME_ACCESSORIES_SETTINGS.windowRY),backgroundWindow.style.fill=MINI_ME_ACCESSORIES_SETTINGS.windowFill,backgroundWindow.style.stroke="none",backgroundWindow.id="backgroundWindow",backgroundWindow}createBorderFrame(rows){var height=Math.min(rows,MINI_ME_ACCESSORIES_SETTINGS.maxVisibleRows)*MINI_ME_ACCESSORIES_SETTINGS.itemHeight+MINI_ME_ACCESSORIES_SETTINGS.itemHeightOffset,width=MINI_ME_ACCESSORIES_SETTINGS.itemsPerRow*MINI_ME_ACCESSORIES_SETTINGS.itemWidth+MINI_ME_ACCESSORIES_SETTINGS.itemWidthOffset,x=(MINI_ME_ACCESSORIES_SETTINGS.scrollableContainerWidth-width)/MINI_ME_ACCESSORIES_SETTINGS.divider,y=(MINI_ME_ACCESSORIES_SETTINGS.scrollableContainerHeight-height)/MINI_ME_ACCESSORIES_SETTINGS.divider,borderFrame=document.createElementNS(this.namespace,"rect");return borderFrame.setAttribute("x",x),borderFrame.setAttribute("y",y),borderFrame.setAttribute("width",width),borderFrame.setAttribute("height",height),borderFrame.setAttribute("rx",MINI_ME_ACCESSORIES_SETTINGS.windowRX),borderFrame.setAttribute("ry",MINI_ME_ACCESSORIES_SETTINGS.windowRY),borderFrame.style.fill="none",borderFrame.style.stroke=MINI_ME_ACCESSORIES_SETTINGS.windowStroke,borderFrame.style.strokeWidth=MINI_ME_ACCESSORIES_SETTINGS.windowStrokeWidth,borderFrame.style.pointerEvents="none",borderFrame.id="borderFrame",borderFrame}saveAccessorySettings(){for(var parameter,id,_parameters=new Array,_ids=new Array,_dimensions=new Array,i=0;i<this.accessoryInstances.length;i++){var instance=this.accessoryInstances[i];if(parameter="{",parameter+='"isApplied":'+(instance.accessory.isApplied?'"True"':'"False"')+",",parameter+='"isTopLayer":'+(instance.accessory.isTopLayer?'"True"':'"False"')+",",parameter+='"X":"'+instance.item.getAttribute("x")+'",',parameter+='"Y":"'+instance.item.getAttribute("y")+'",',parameter+='"uniqueId":"'+instance.accessory.uniqueId+'"',id=instance.accessory.uniqueId,parameter+="}",_parameters.push(parameter),_ids.push(id),instance.accessory.isApplied){var dim={x:parseFloat(instance.item.getAttribute("x")),y:parseFloat(instance.item.getAttribute("y")),width:parseFloat(instance.item.getAttribute("width")),height:parseFloat(instance.item.getAttribute("height"))};_dimensions.push(dim)}}return{parameters:_parameters.join(";"),ids:_ids.join(";"),dimensions:_dimensions}}}
91var MiniMeSettings={},MiniMeStaticItems={hair:[],bottom:[],top:[],shoes:[]},MiniMeLastVersion=0,MiniMeLastVersionSaved=0,MiniMeLastVersionSaving=0,MiniMeSpeechBubbles=[],MiniMeWasSaveReminderBubbleShown=!1;const MINI_ME_EVENTS={HIDE_PROGRESS_INDICATOR:"miniMe:hideProgressIndicator",SHOW_SUCCESSFUL_SAVE_BUBBLE:"miniMe:showSuccessfulSaveBubble",SAVE_REQUESTED:"miniMe:saveRequested",SELECTED_ITEMS_READY:"miniMe:selectedItemsReady",CHANGE_ITEM_COLOR:"miniMe:changeItemColor"},MINI_ME_CLOSET_EVENTS={SELECTED_ITEM_CHANGED:"miniMeCloset:selectedItemChanged"},MINI_ME_SCALE_SETTINGS={CANVAS_HEIGHT:727,CURRENT_MINIME_OFFSET_Y:-69,SAFETY_MARGIN_Y:20,DEFAULT_MARGIN_Y:5,SAFE_SCALE:.95};class MiniMeMain extends DOMAttached{constructor(el,options){super(el,options),window.MiniMeMainInstance=this,this.options=options,this.namespace="http://www.w3.org/2000/svg",this.lastSave=null,this.itemInstancePrefix=this.options.designedItemIdPrefix,this.progressIndicator=new ProgressIndicator(this.el),this.progressIndicator.showProgressIndicator(!0,".mia-Column",!1),this.safeObserve(document,MINI_ME_EVENTS.HIDE_PROGRESS_INDICATOR,(()=>this.progressIndicator.hideProgressIndicator())),this.safeObserve(document,MINI_ME_EVENTS.SHOW_SUCCESSFUL_SAVE_BUBBLE,(()=>this.showSuccessfulSaveBubble())),this.safeObserve(document,MINI_ME_EVENTS.SAVE_REQUESTED,(()=>this.saveButtonClick(!0))),this.safeObserve(document,MINI_ME_EVENTS.CHANGE_ITEM_COLOR,(()=>this.showSaveReminderBubble())),this.safeObserve(document,MINI_ME_CLOSET_EVENTS.SELECTED_ITEM_CHANGED,(()=>this.showSaveReminderBubble())),this.playFeedbackSound=this.options.feedbackSoundOn,null==GenericSoundsInstance&&new GenericSounds(this.playFeedbackSound),MiniMeSettings=JSON.parse(options.settings),this.ensureSelectedItemConfiguration(),this.validateMiniMeSettings(),MiniMeStaticItems.face=options.staticFace,MiniMeStaticItems.hair=options.staticHair,MiniMeStaticItems.bottom=options.staticBottom,MiniMeStaticItems.top=options.staticTop,MiniMeStaticItems.shoes=options.staticShoes,MiniMeSpeechBubbles=options.speechBubbles,this.loadItems()}ensureSelectedItemConfiguration(){var defaultSettings=JSON.parse(this.options.defaultSettings);this.ensureSelectedItemConfigurationFor("hair",defaultSettings.hair),this.ensureSelectedItemConfigurationFor("face",defaultSettings.face),this.ensureSelectedItemConfigurationFor("top",defaultSettings.top),this.ensureSelectedItemConfigurationFor("bottom",defaultSettings.bottom),this.ensureSelectedItemConfigurationFor("shoes",defaultSettings.shoes)}ensureSelectedItemConfigurationFor(itemKey,defaultSetting){null!=MiniMeSettings[itemKey]&&null!=MiniMeSettings[itemKey]||(MiniMeSettings[itemKey]=defaultSetting)}validateMiniMeSettings(){this.miniMeSettingsAreValid=!0,this.isSelectedCustomItemMissing(MiniMeSettings.bottom,this.options.customBottoms)&&(MiniMeSettings.bottom=1,this.miniMeSettingsAreValid=!1),this.isSelectedCustomItemMissing(MiniMeSettings.top,this.options.customTops)&&(MiniMeSettings.top=1,this.miniMeSettingsAreValid=!1),this.isSelectedCustomItemMissing(MiniMeSettings.shoes,this.options.customShoes)&&(MiniMeSettings.shoes=1,this.miniMeSettingsAreValid=!1)}
91isSelectedCustomItemMissing(setting,customItems){return"string"==typeof setting&&0===setting.indexOf(this.itemInstancePrefix)&&-1==customItems.map((function(i){return i.id})).indexOf(setting.substring(this.itemInstancePrefix.length))}loadItems(){var svgDatas=[{id:this.options.blank.id,relativePath:this.options.blank.relativePath}];svgDatas=svgDatas.concat(this.getSvgData(this.options.staticFace),this.getSvgData(this.options.staticHair),this.getSvgData(this.options.staticTop),this.getSvgData(this.options.staticBottom),this.getSvgData(this.options.staticShoes)),axios(this.options.itemsLoadUrl,{method:"post",headers:{"content-type":"application/x-www-form-urlencoded"},data:{svgData:JSON.stringify(svgDatas)}}).then(this.onSuccess.bind(this))}getSvgData(staticItems){return staticItems.map((function(item){return{id:item.id,relativePath:item.relativePath}}))}onSuccess(req){var json=req.data,node=document.createElement("div");node.innerHTML=json.content,document.body.appendChild(node),this.initializeSVG(),scaleToContainerWidth(),this.editor&&(this.editor.style.visibility="visible"),this.progressIndicator.hideProgressIndicator()}initializeSVG(){this.editor=document.getElementById(this.options.miniMeEditorId),this.editor&&(this.editor.style.visibility="hidden"),this.speechBubble=new MiniMeSpeechBubble(this.editor),this.initializeColorSelector(),this.initializeBackgroun
91d(),this.initializeMiniMe(),this.initializeSpeechBubble()}showSaveReminderBubble(){MiniMeWasSaveReminderBubbleShown||(this.speechBubble.show(MiniMeSpeechBubbles.saveChanges,5e3),MiniMeWasSaveReminderBubbleShown=!0)}saveButtonClick(sound){sound&&GenericSoundsInstance.softClickSound();var version=MiniMeLastVersion;if(!(version<=MiniMeLastVersionSaved||version<=MiniMeLastVersionSaving||(MiniMeLastVersionSaving=version,ChangeInProgress))){var miniMeDocument=document.getElementById(this.options.miniMeContainerForSavingId).getSVGDocument();this.copyBackgroundColorToDocument(miniMeDocument);var miniMe=document.createElementNS(this.namespace,"g");this.copySelectedItemsToDocument(miniMe),miniMeDocument.getElementById("layer1").appendChild(miniMe);var accSettings=this.accessoryManager.saveAccessorySettings(),scalingTransform=this.calculateScalingTransform(accSettings.dimensions);scalingTransform.scale<1&&this.applyScalingToMiniMe(miniMe,scalingTransform);var svgSaver=new SaveableSVG(miniMeDocument,this.options.savePictureUrl,this.retrySaving.bind(this));this.progressIndicator.showProgressIndicator(!0,".mia-Column",!1),svgSaver.saveSVG(accSettings.parameters,accSettings.ids,version),miniMe.remove(),MiniMeWasSaveReminderBubbleShown=!1}}showSuccessfulSaveBubble(){this.speechBubble.show(MiniMeSpeechBubbles.successfulSave,5e3)}calculateScalingTransform(dimensions){if(!dimensions||0===dimensions.length)return{scale:1,offsetY:0};for(var maxTop=dimensions[0].y,maxBottom=dimensions[0].y+dimensions[0].height,i=1;i<dimensions.length;i++){var dimension=dimensions[i],accessoryTop=dimension.y,accessoryBottom=dimension.y+dimension.height;maxTop=Math.min(maxTop,accessoryTop),maxBottom=Math.max(maxBottom,accessoryBottom)}var actualTop=maxTop+MINI_ME_SCALE_SETTINGS.CURRENT_MINIME_OFFSET_Y,actualBottom=maxBottom+MINI_ME_SCALE_SETTINGS.CURRENT_MINIME_OFFSET_Y;if(!(actualTop<0||actualBottom>MINI_ME_SCALE_SETTINGS.CANVAS_HEIGHT))return{scale:1,offsetY:0};var scaleY=MINI_ME_SCALE_SETTINGS.CANVAS_HEIGHT/(actualBottom-actualTop),scaleForOffsetY=1;actualTop<0&&(scaleForOffsetY=MINI_ME_SCALE_SETTINGS.CANVAS_HEIGHT/(MINI_ME_SCALE_SETTINGS.CANVAS_HEIGHT-actualTop)*MINI_ME_SCALE_SETTINGS.SAFE_SCALE),actualBottom>MINI_ME_SCALE_SETTINGS.CANVAS_HEIGHT&&(scaleForOffsetY=Math.min(scaleForOffsetY,MINI_ME_SCALE_SETTINGS.CANVAS_HEIGHT/actualBottom));var scale=Math.min(scaleY,scaleForOffsetY),offsetY=MINI_ME_SCALE_SETTINGS.DEFAULT_MARGIN_Y;return actualTop*scale<0&&(offsetY=-actualTop*scale+MINI_ME_SCALE_SETTINGS.SAFETY_MARGIN_Y),actualBottom*scale>MINI_ME_SCALE_SETTINGS.CANVAS_HEIGHT&&(offsetY=MINI_ME_SCALE_SETTINGS.CANVAS_HEIGHT-actualBottom*scale),{scale:scale,offsetY:offsetY}}applyScalingToMiniMe(miniMe,transform){var currentTransform=miniMe.getAttribute("transform")||"",newTransform="translate(0,"+transform.offsetY+") scale("+transform.scale+")";currentTransform&&(newTransform=currentTransform+" "+newTransform),miniMe.setAttribute("transform",newTransform)}copyBackgroundColorToDocument(miniMeDocument){miniMeDocument.getElementById("bgStop1").style.stopColor=this.editor.getElementById("bgStop1").style.stopColor,miniMeDocument.getElementById("bgStop2").style.stopColor=this.editor.getElementById("bgStop2").style.stopColor}copySelectedItemsToDocument(miniMe){miniMe.setAttribute("transform","translate(127,-69)"),miniMe.appendChild(this.cloneNodeById("accessories-post")),miniMe.appendChild(this.cloneNodeById("body")),miniMe.appendChild(this.cloneNodeById("face"+MiniMeSettings.face)),miniMe.appendChild(this.cloneClothingNodeByKey("bottom")),miniMe.appendChild(this.cloneClothingNodeByKey("top")),miniMe.appendChild(this.cloneClothingNodeByKey("shoes")),miniMe.appendChild(this.cloneNodeById("hair"+MiniMeSettings.hair)),miniMe.appendChild(this.cloneNodeById("accessories-pre"))}cloneClothingNodeByKey(key){var setting=MiniMeSettings[key];return"string"==typeof setting&&0===setting.indexOf(this.itemInstancePrefix)?document.getElementById(setting).cloneNode():this.cloneNodeById(key+setting)}cloneNodeById(id){for(var groupElement=document.createElementNS(this.namespace,"g"),child=document.getElementById(id).firstElementChild;null!=child;child=child.nextElementSibling)"metadata"!==child.tagName&&groupElement.appendChild(child.cloneNode(!0));return groupElement}retrySaving(){MiniMeLastVersionSaving--,this.saveButtonClick(!1,!0)}
91initializeBackground(){var svg=this.editor;this.bgStop1=svg.getElementById("bgStop1"),this.bgStop2=svg.getElementById("bgStop2");var settings=MiniMeSettings;void 0===settings.background&&(settings.background={}),null!=settings.background.backgroundcolor&&(this.bgStop1.style.stopColor="#"+this.decToHex(settings.background.backgroundcolor),this.bgStop2.style.stopColor="#"+this.decToHex(settings.background.backgroundcolor)),this.safeObserve(svg.getElementById("background"),"mouseup",function(){this.colorBackground()}.bind(this))}colorBackground(){null!=ColorSelectorActiveColor&&(this.bgStop1.style.stopColor=this.getActiveColor(ColorSelectorActiveColor),this.bgStop2.style.stopColor=this.getActiveColor(ColorSelectorActiveColor),GenericSoundsInstance.softClickSound(),MiniMeSettings.background.backgroundcolor=this.hexToDec(this.getActiveColor(ColorSelectorActiveColor).substring(1)),MiniMeLastVersion++,ColorSelectorActiveColor=null,this.colorSelector.resetColors())}initializeColorSelector(){this.colorSelector=new ColorSelector(this.editor,this.options.colorSelectorColors,450,798,!0,this.playFeedbackSound,this.speechBubble)}initializeMiniMe(){var fragment=document.createDocumentFragment(),options=this.options,colorSelector=this.colorSelector,blank=new ColorableSvgItem(colorSelector,this.createBlankSvg(),options.blank.objectChains[0][0],options.blank.objectChains[0][options.blank.objectChains[0].length-1]);fragment.appendChild(blank.item),this.MiniMeSections=[new MiniMeFaces(fragment,colorSelector,options.facesCategoryName,options.designedItemIdPrefix),new MiniMeBottom(fragment,colorSelector,options.customBottoms,options.bottomsCategoryName,options.designedItemIdPrefix),new MiniMeTop(fragment,colorSelector,options.customTops,options.topsCategoryName,options.designedItemIdPrefix),new MiniMeHair(fragment,colorSelector,options.hairCategoryName,options.designedItemIdPrefix),new MiniMeShoes(fragment,colorSelector,options.customShoes,options.shoesCategoryName,options.designedItemIdPrefix)],this.editor.getElementById("character").appendChild(fragment),this.selectedItemsByCategory=this.MiniMeSections.reduce(((object,miniMeSection)=>(object[miniMeSection.groupIdentifier]=miniMeSection.getSelectedItemId(),object)),{}),queueMicrotask((()=>{document.dispatchEvent(new CustomEvent("miniMe:selectedItemsReady"))})),this.accessoryManager=new MiniMeAccessoryManager(this.editor,this.options.accessories,this.playFeedbackSound,this.speechBubble)}createBlankSvg(){var useSvg=document.createElementNS(this.namespace,"use");return useSvg.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","#bodycolor"),useSvg}initializeSpeechBubble(){this.options.firstMiniMe?this.speechBubble.show(MiniMeSpeechBubbles.firstMiniMe):this.miniMeSettingsAreValid?this.speechBubble.show(MiniMeSpeechBubbles.initial):this.speechBubble.show(MiniMeSpeechBubbles.changeAvatar)}hexToDec(hex){return parseInt("FF"+hex,16)}decToHex(dec){return dec.toString(16).toUpperCase().substring(2)}colorToHex(color){if("#"===color.substr(0,1))return color;for(var digits=/(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color),red=parseInt(digits[2]),green=parseInt(digits[3]),rgb16=(parseInt(digits[4])|green<<8|red<<16).toString(16);rgb16.length<6;)rgb16="0"+rgb16;return digits[1]+"#"+rgb16}getActiveColor(){return this.colorToHex(ColorSelectorActiveColor)}onUnload(ev){super.onUnload(ev),window.MiniMeMainInstance===this&&(window.MiniMeMainInstance=null)}}
92class FocusFirstInput extends DOMAttached{constructor(el,options){if(super(el,options),1!=this.options.overrideFocusFirstInput&&this.el.visible())for(var inputs=this.el.querySelectorAll("*"),i=0;i<inputs.length;++i){var curInput=inputs[i];if(("TEXTAREA"==curInput.tagName||"INPUT"==curInput.tagName&&"text"==curInput.type)&&1!=curInput.disabled)try{return void curInput.focus()}catch(e){}}}}
93class MessageSend extends FocusFirstInput{constructor(el,options){super(el,options);var submit=this.el.querySelector("input[type=submit]");this.safeObserve(submit,"click",this.onSubmit.bind(this)),this.online=!0}onSubmit(ev){if(axios(this.options.loginStatusUrl,{method:"get",params:{nocache:Math.random()}}).then(this.onLoginCheck.bind(this)),!this.online)throw ev.preventDefault(),ev.stopPropagation(),new Error(this.options.loginStatusWarning)}onLoginCheck(req){var json=req.data;this.online=json.online}}
94var MessageListUtility={cleanUpMessages:function(el){if(void 0!==(li=el.closest("li"))){li.style.display="none";for(var hasVisible=!1,li=li.closest("ul").querySelector("li");li;li=li.next("li"))if("none"!=window.getComputedStyle(li).getPropertyValue("display")){hasVisible=!0;break}if(!hasVisible){var container=el.closest(".messageContainer");container&&(container.style.display="none")}}}};
95class MemberSelector extends DOMAttached{constructor(el,options){super(el,options),this.groupSelector=this.el.querySelector("select"),this.memberPart=this.el.querySelector(".memberPart");var checkAllBox=document.getElementById("contentcontent_allChk");null!=checkAllBox&&this.safeObserve(checkAllBox,"click",this.onClick.bind(this)),this.groupSelector&&this.safeObserve(this.groupSelector,"change",this.onChanged.bind(this))}onClick(){var input=document.getElementsByTagName("input");for(var i in input)"checkbox"==input[i].type&&"contentcontent_allChk"!=input[i].id&&(document.getElementById("contentcontent_allChk").checked?input[i].style.visibility="hidden":input[i].style.visibility="visible")}onChange(){0!=this.groupSelector.value?this.memberPart.classList.add("collapsed"):this.memberPart.classList.remove("collapsed")}}
96class LegacyGameHeader extends DOMAttached{constructor(el,options){super(el,options),this.isShown=options.isS
96hown,this.toggleFeedbackSoundUrl=options.toggleFeedbackSoundUrl,this.toggleGameContentReadingUrl=options.toggleGameContentReadingUrl,window.LegacyGameHeaderInstance=this;if(this.el.querySelector(".mia-"+options.className)){window.createVueApplication("legacy-game-header").mount(this.el)}this.isShown&&waitForElementToBePresent(".mia-GameSettingsMenu").then((element=>{this.onGameSettingsMenuOpen=()=>this.onGameSettingsMenuClick(element)}))}onGameSettingsMenuClick(element){var lessonSoundToggleButtonElement=element.querySelector(".mia-lessonSoundToggleButton .mia-ToggleButton-input"),readAloudToggleButtonElement=element.querySelector(".mia-readAloudToggleButton .mia-ToggleButton-input");lessonSoundToggleButtonElement&&this.initializeLessonSoundToggleButton(lessonSoundToggleButtonElement),readAloudToggleButtonElement&&this.initializeReadAloudToggleButton(readAloudToggleButtonElement)}onLessonSoundToggleButtonChange(){axios(this.toggleFeedbackSoundUrl,{method:"get"}).then((response=>{this.onLessonSoundToggleButtonChangeSuccess()}))}onLessonSoundToggleButtonChangeSuccess(){void 0!==GenericSoundsInstance&&void 0!==GenericSoundsInstance.playFeedbackSound&&(GenericSoundsInstance.playFeedbackSound=!GenericSoundsInstance.playFeedbackSound,GenericSoundsInstance.playFeedbackSound?null!=window.PlayFeedbackSound&&(window.PlayFeedbackSound=!0):(soundManager.stop("intro"),soundManager.stop("theme"),null!=window.PlayFeedbackSound&&(window.PlayFeedbackSound=!1)))}onReadAloudToggleButtonChange(){axios(this.toggleGameContentReadingUrl,{method:"get"}).then((response=>{this.onReadAloudToggleButtonSuccess()}))}onReadAloudToggleButtonSuccess(){null!==GamesTextToSpeechInstance&&void 0!==GamesTextToSpeechInstance&&(GamesTextToSpeechInstance.isEnabled?GamesTextToSpeechInstance.turnOffTextToSpeech():(GamesTextToSpeechInstance.turnOnTextToSpeech(),GamesQuizInstance.createAndReadAllTextToSpeech()))}initializeLessonSoundToggleButton(element){this.safeObserve(element,"click",this.onLessonSoundToggleButtonChange.bind(this))}initializeReadAloudToggleButton(element){this.safeObserve(element,"click",this.onReadAloudToggleButtonChange.bind(this))}}
97class JSTabSelector extends DOMAttached{constructor(el,options){super(el,options),this.tabs=document.getElementById(options.Tabs);for(var i=0;i<this.tabs.length;i++){var button=document.getElementById(this.tabs[i].button),content=document.getElementById(this.tabs[i].content);i>0&&(content.style.display="none",button.style.opacity="0.5"),this.safeObserve(button,"click",(()=>this.change(button,content)))}}change(button,content){for(var i=0;i<this.tabs.length;i++)document.getElementById(this.tabs[i].content).style.display="none",document.getElementById(this.tabs[i].button).style.opacity="0.5";content.style.display="",button.style.opacity="1"}}
98class InvitationMethod extends DOMAttached{constructor(el){super(el),null==InvitationMethod.CurrentMethod&&(InvitationMethod.CurrentMethod=this.el.closest(0).querySelector(".selected"),null==InvitationMethod.CurrentMethod&&this.changeSelectedMethod(this.el)),this.safeObserve(this.el,"click",this.onInvitationMethodClick.bind(this))}onInvitationMethodClick(ev){this.changeSelectedMethod(ev.currentTarget)}changeSelectedMethod(element){null!=element&&element!=InvitationMethod.CurrentMethod&&(element.classList.add("selected"),null!=InvitationMethod.CurrentMethod&&InvitationMethod.CurrentMethod.classList.remove("selected"),InvitationMethod.CurrentMethod=element)}}
99class Invitation extends DOMAttached{constructor(el,options){super(el,options),this.nextLink=this.el.querySelector(".nextStep"),this.addLink=this.el.querySelector(".addName"),this.namesForm=this.el.querySelector(".namesForm"),this.noNamesError=this.el.querySelector(".error"),this.nameslist=this.el.querySelector(".allNamesToInvite"),this.invitationForm=this.el.querySelector(".invitationForm"),this.invitationFormAnyError=this.invitationForm.querySelector(".error"),this.heading=this.invitationForm.querySelector("h3"),this.currentName=void 0,this.inviteLink=this.el.querySelector(".inviteSinglePerson"),this.stateMessageForm=this.el.querySelector(".invitationStateMessageForm"),this.nextInvitationName=this.stateMessageForm.querySelector(".nextNameToInvite"),this.nextInvitationLink=this.stateMessageForm.querySelector(".nextInvitation"),this.moreInvitationsLink=this.stateMessageForm.querySelector(".moreInvitations"),this.safeObserve(this.nextLink,"click",this.onNextClick.bind(this)),this.safeObserve(this.addLink,"click",this.onAddClick.bind(this)),this.safeObserve(this.inviteLink,"click",this.onInviteClick.bind(this)),this.safeObserve(this.nextInvitationLink,"click",this.onNextInvitationClick.bind(this)),this.namesArray=new Array}onNextClick(ev){this.fillNamesArray(),this.retrieveNextCurrentName(),null!=this.currentName?(this.putNameInHeading(),this.goToSecondStep()):this.displayNoNamesError()}onAddClick(ev){this.addNameRow()}onInviteClick(ev){this.sendInvitation()}onNextInvitationClick(ev){this.tryToAdaptMessageForNextName(),this.retrieveNextCurrentName(),this.putNameInHeading(),this.cleanUpInputMethod(),this.goToSecondStep()}displayNoNamesError(){this.noNamesError.classList.remove("collapsed")}
99sendInvitation(){var selectedMethod=this.invitationForm.querySelector(".selected"),name=this.currentName,message=selectedMethod.querySelector("textarea").value,contact=selectedMethod.querySelector(".invitationMethodInput").querySelector('input[type="text"]').value,method=selectedMethod.querySelector(".invitationMethodValue").value;axios(this.options.inviteURL,{method:"post",headers:{"content-type":"application/x-www-form-urlencoded"},data:{name:name,message:message,contact:contact,method:method}}).then((response=>{this.requestSuccess(response)}))}addNameRow(){var newNameField=this.nameslist.querySelector(".singleNameToInvite").cloneNode(!0);newNameField.querySelector(".textbox").querySelector('input[type="text"]').value="",this.nameslist.appendChild(newNameField)}goToSecondStep(){this.namesForm.classList.add("collapsed"),this.stateMessageForm.classList.add("collapsed"),this.invitationForm.classList.remove("collapsed")}goToFinalStep(){this.invitationForm.classList.add("collapsed"),this.stateMessageForm.classList.remove("collapsed")}fillNamesArray(){this.nameslist.querySelectorAll(".singleNameToInvite").forEach(function(el){var name=el.querySelector(".textbox").querySelector('input[type="text"]').value.strip();name.length>0&&this.namesArray.push(name)}.bind(this)),this.namesArray.reverse()}putNameInHeading(){this.heading.innerHTML=this.currentName}putNextNameInNextInvitationLinkOrShowMoreInvitationsLink(){var nextName=this.namesArray[this.namesArray.length-1];null!=nextName?this.nextInvitationName.innerHTML=nextName:(this.nextInvitationLink.classList.add("collapsed"),this.moreInvitationsLink.classList.remove("collapsed"))}retrieveNextCurrentName(){this.currentName=this.namesArray.pop()}cleanUpInputMethod(){this.invitationForm.querySelectorAll(".invitationMethodInput").forEach((function(item){item.querySelector('input[type="text"]').value=""}))}tryToAdaptMessageForNextName(){var message=this.invitationForm.querySelector(".selected").querySelector("textarea").value;message=message.replace(new RegExp("\\b"+this.currentName+"\\b","gi"),this.namesArray[this.namesArray.length-1]),this.invitationForm.querySelector(".selected").querySelector("textarea").value=message}putSuccessMessageInPlace(message){this.stateMessageForm.querySelector(".successMessage").innerHTML=message}showInvitationFormError(errorMsg){this.invitationFormAnyError.querySelector("p").innerHTML=errorMsg,this.invitationFormAnyError.classList.remove("collapsed")}requestSuccess(req){var json;try{json=req.data}catch(e){return void this.requestFailure(req)}json.message?json.success?(this.putNextNameInNextInvitationLinkOrShowMoreInvitationsLink(),this.putSuccessMessageInPlace(json.message),this.goToFinalStep()):this.showInvitationFormError(json.message):this.requestFailure(req)}requestFailure(req){this.showInvitationFormError(this.options.genericError)}}
100var InventoryListInstance=void 0;class InventoryList extends DOMAttached{constructor(el,options){super(el,options),InventoryListInstance=this}filterForCategory(category){var shoppingCart=document.getElementById("houseInventory-shoppingCart");"Pet"===category?shoppingCart.classList.add("hidden"):(shoppingCart.classList.remove("hidden"),shoppingCart.href=this.options.shopUrl.replace("PLH_PublicShopType",category));var newDataUrl=this.options.dataUrl.replace("PLH_inventoryType",category);useStore(this.options.storeName).reset(newDataUrl)}}
101class IFrame extends DOMAttached{constructor(el,options){super(el,options),this.loadReady(),document.loadReady=this.loadReady.bind(this)}loadReady(){this.iframeDoc=this.el.contentWindow||this.el.contentDocument,this.iframeDoc.document&&(this.iframeDoc=this.iframeDoc.document,this.el.style.height=this.iframeDoc.body.scrollHeight+"px")}}
102class HideableControl extends DOMAttached{constructor(el,options){super(el,options),this.hidden_control=document.getElementById(options.hidden_control),this.replacement=document.getElementById(options.replacement),this.trigger=document.getElementById(options.trigger),this.hidden_control.style.display="none"===this.hidden_control.style.display?"":"none",this.safeObserve(this.trigger,"click",this.change.bind(this))}change(){this.replacement.style.display="none"===this.replacement.style.display?"":"none",this.hidden_control.style.display="none"===this.hidden_control.style.display?"":"none"}}
103class GamesSearchBox extends SearchBox{constructor(el,options){super(el,options),this.listSelector=".mia-SearchGameList",this.categoriesSelector=".mia-AllGames"}onSearchButtonClick(event){super.onSearchButtonClick(event),this.inputBox.value?(jQuery(this.listSelector).show(),jQuery(this.categoriesSelector).hide()):(jQuery(this.categoriesSelector).show(),jQuery(this.listSelector).hide())}}
104var GamesRaceInstance=null;class GamesRace extends DOMAttached{constructor(el,options){super(el,options),GamesRaceInstance=this,this.instance=options.instance,this.opponentIds=options.opponentIds,document.getElementById(this.options.dragonImages[0]).style.zIndex=100,SignalRConnection.connect("/multiplayerGameHub",(function(connection){connection.on("MoveDragon",GamesRaceInstance.onMove.bind(GamesRaceInstance))})).then((function(connection){connection.invoke("RegisterToGroup",options.instance)}))}onMove(json){json.Position==this.options.maximum&&GamesMultiplayerQuizInstance.handleNextSpecificPageLoad(json.Instance),json.Exhausted?this.takePlayerDown(json.Sender,json.Position,json.Instance):this.movePlayerTo(json.Sender,json.Position,json.Instance)}movePlayerTo(memberId,position,messageInstance){if(messageInstance==this.instance)for(var i=0;i<this.opponentIds.length;i++)this.opponentIds[i]==memberId&&this.moveDragonTo(i+1,position)}takePlayerDown(memberId,position,messageInstance){if(messageInstance==this.instance)for(var i=0;i<this.opponentIds.length;i++)this.opponentIds[i]==memberId&&this.takeDragonDown(i+1,position)}moveDragonTo(dragonNr,position){var dragonDelay,switchedNr=this.options.dragonImages.length-1-dragonNr,dragon=document.getElementById(this.options.dragonImages[dragonNr]);dragonDelay=0==dragonNr?500:0,0!=position&&position!=this.options.endPosition?this.timer=window.setTimeout((function(){LegacyEffects.move(dragon,{x:45*position-50*dragonNr+10*switchedNr,y:30*(switchedNr+1),mode:"absolute",duration:3})}),dragonDelay):this.timer=0==position?window.setTimeout((function(){LegacyEffects.move(dragon,{x:-50*dragonNr,y:120+20*switchedNr,mode:"absolute",duration:3})}),dragonDelay):window.setTimeout((function(){LegacyEffects.move(dragon,{x:45*position-50*dragonNr-30,y:120,mode:"absolute",duration:3})}),dragonDelay)}takeDragonDown(dragonNr,position){if(position==this.options.endPosition)this.moveDragonTo(dragonNr,position);else{var switchedNr=this.options.dragonImages.length-1-dragonNr;LegacyEffects.move(document.getElementById(this.options.dragonImages[dragonNr]),{x:45*position-50*dragonNr+10*switchedNr,y:180,mode:"absolute",duration:3})}}}
105class GamesRaceOpponent{constructor(minTimeout,maxTimeout,probabilityCorrect,endPosition,processAnswerUrl){this.position=0,this.questionNumber=0,this.endPosition=endPosition,this.minTimeout=minTimeout,this.maxTimeout=maxTimeout,this.probabilityCorrect=probabilityCorrect,this.processAnswerUrl=processAnswerUrl,this.timer=window.setTimeout(function(){this.answer()}.bind(this),this.getTimeout())}getTimeout(){return this.minTimeout+Math.random()*(this.maxTimeout-this.minTimeout)}answer(){if(GamesMultiplayerQuizInstance.isOpponentAlive()&&this.questionNumber!=this.endPosition){this.timeout=this.getTimeout();var correct=Math.random()<this.probabilityCorrect;correct?this.position<=this.endPosition-2?this.position+=2:this.position=this.endPosition:0!=this.position&&this.position--,GamesRaceInstance.moveDragonTo(1,this.position),axios(new UrlTemplate(this.processAnswerUrl).r("PLH_success",correct).r("PLH_nquestion",-2).url,{method:"get"}).then(this.onSuccess.bind(this))}}onSuccess(req){this.json=req.data,this.position==this.endPosition?GamesMultiplayerQuizInstance.handleNextPageLoad():(clearTimeout(this.timer),this.questionNumber++,this.timer=window.setTimeout(function(){this.answer()}.bind(this),this.timeout),this.questionNumber==this.endPosition&&GamesRaceInstance.takeDragonDown(1,this.position))}}
106var GamesMultiplayerConstructionInstance=null;class GamesMultiplayerConstruction extends DOMAttached{constructor(el,options){super(el,options),GamesMultiplayerConstructionInstance=this,SignalRConnection.connect("/multiplayerGameHub",(function(connection){connection.on("React",GamesMultiplayerConstructionInstance.onPing.bind(GamesMultiplayerConstructionInstance))})),this.options.needsConstruction&&(null==GenericSoundsInstance&&(GenericSoundsInstance=new GenericSounds(this.options.playFeedbackSound)),this.constructionElement=document.getElementById(this.options.construction_element),this.friendButton=this.constructionElement.querySelector(".friendBtn"),this.friendsChooser=this.constructionElement.querySelectorAll('[id*="friendsChooserddl"]')[0],this.safeObserve(this.friendsChooser,"change",this.onFriendsChooserChange.bind(this)),this.json="",this.opponent="",this.accepted=!1,this.options.needsRefreshing&&(this.safeObserve(document,"click",this.resetTimer.bind(this)),this.safeObserve(document,"mousemove",this.resetTimer.bind(this)),this.refreshTR=this.options.trRefresh,this.timeout=0,this.setTimer()))}setTimer(){""==this.json&&(this.timeout=setTimeout((function(){"block"==document.getElementById(this.constructionElement.querySelector(".friendsChooserContainer")).getStyle("display")&&
106confirmAI(this.refreshTR,(function(){location.reload(!0)}),(function(){}),!0,!0),this.resetTimer}),3e5))}resetTimer(){window.clearTimeout(this.timeout),this.setTimer()}onFriendsChooserChange(event){0!=this.friendsChooser.selectedIndex?(this.friendButton.disabled=!1,this.friendButton.style.opacity="1",this.friendButton.style.cursor="pointer"):(this.friendButton.disabled=!0,this.friendButton.style.opacity="0.3",this.friendButton.style.cursor="default")}onPing(json){if(json.Instance==this.json.instance){if(void 0===this.waitScreen&&this.waitForFriend(!0,json),this.accepted=!0,json.Status==this.options.status_accepted)this.onSuccess(null);else if(json.Status==this.options.status_declined){GenericSoundsInstance.notificationSound();var declineMessage=document.createElement("p").innerHTML=this.opponent+" "+new TextResource(this.options.trDeclined.string());declineMessage.style.color=this.options.secondaryColor,declineMessage.style.fontWeight="bold",this.waitScreen.prepend(declineMessage)}return!0}return!1}waitForFriend(goPing,json){this.waitScreen=this.constructionElement.getElementsByClassName("wait_screen")[0];for(var container=this.constructionElement.querySelectorAll('[id*="multiplayer_mainDiv"]')[0];container.lastChild;){var elem=container.lastChild;this.stopObserveAllListeners(elem),container.removeChild(elem)}container.prepend(this.waitScreen),this.waitScreen.style.display="block",this.waitDragon=this.constructionElement.getElementsByClassName("waiting_dragon").item(0),this.waitDragonMirror=this.constructionElement.getElementsByClassName("waiting_dragon_mirrored").item(0),this.dragonFly(!0),goPing&&this.onPing(json)}dragonFly(isLeft){isLeft?(this.waitDragon.style.visibility="visible",this.waitDragonMirror.style.visibility="hidden",LegacyEffects.move(this.waitDragon,{x:290,y:0,mode:"relative",duration:10}),LegacyEffects.move(this.waitDragonMirror,{x:290,y:0,mode:"relative",duration:10})):(this.waitDragon.style.visibility="hidden",this.waitDragonMirror.style.visibility="visible",LegacyEffects.move(this.waitDragon,{x:-290,y:0,mode:"relative",duration:10}),LegacyEffects.move(this.waitDragonMirror,{x:-290,y:0,mode:"relative",duration:10})),window.setTimeout((()=>{this.dragonFly(!isLeft)}),1e4)}onSuccess(req){if(this.accepted||!req.data.not_allowed){if(0==this.level&&this.accepted||(this.json=req.data),0==this.level&&!this.accepted)return this.waitForFriend(!1,null),!0;for(;this.constructionElement.lastChild;){var elem=this.constructionElement.lastChild;this.stopObserveAllListeners(elem),this.constructionElement.removeChild(elem)}this.constructionElement.innerHTML=this.json.multiplayerGame,evalScripts(this.constructionElement)}else confirmAI(this.options.trForbidden,(function(){}),(function(){}),!0,!1)}onError(req){}onFailure(req){console.log("GamesMultiplayerConstruction.onFailure",req)}}
107class GamesMultiplayerQuizListItem extends DOMAttached{constructor(el,options){super(el,options),this.constructionElement=document.getElementById(this.options.construction_element),this.teamChooser=this.constructionElement.querySelectorAll('[id*="teamChooserddl"]')[0],this.friendsChooser=this.constructionElement.querySelectorAll('[id*="friendsChooserddl"]')[0],this.gameSelection=this.constructionElement.querySelector(".gameSelection"),this.dragonChooser=this.constructionElement.querySelector(".dragonChooser"),this.friendsChooserContainer=this.constructionElement.querySelector(".friendsChooserContainer"),this.raceAkiBtnWrapper=this.constructionElement.querySelector(".raceAkiWrapper"),this.raceAkiButton=this.constructionElement.querySelector(".raceAkiBtn"),this.akiDifficultyWrapper=this.constructionElement.querySelector(".akiDifficulty"),this.backButton=this.constructionElement.querySelector(".backButton"),this.animatedDragon=this.constructionElement.querySelector(".animatedDragon"),this.easyAkiButton=this.constructionElement.querySelector(".akiEasyBtn"),this.mediumAkiButton=this.constructionElement.querySelector(".akiMediumBtn"),this.hardAkiButton=this.constructionElement.querySelector(".akiHardBtn"),this.friendButton=this.constructionElement.querySelector(".friendBtn"),null!=GamesMultiplayerQuizListItem.previous&&(GamesMultiplayerQuizListItem.previous.stopObserveAllListeners(this.easyAkiButton),GamesMultiplayerQuizListItem.previous.stopObserveAllListeners(this.mediumAkiButton),GamesMultiplayerQuizListItem.previous.stopObserveAllListeners(this.hardAkiButton),GamesMultiplayerQuizListItem.previous.stopObserveAllListeners(this.friendButton),GamesMultiplayerQuizListItem.previous.stopObserveAllListeners(this.backButton)),GamesMultiplayerQuizListItem.previous=this,this.safeObserve(this.easyAkiButton,"click",this.onAkiOkClick.bind(this)),this.safeObserve(this.mediumAkiButton,"click",this.onAkiOkClick.bind(this)),this.safeObserve(this.hardAkiButton,"click",this.onAkiOkClick.bind(this)),this.safeObserve(this.friendButton,"click",this.onAkiOkClick.bind(this)),this.safeObserve(this.raceAkiButton,"click",this.onRaceAkiClick.bind(this)),this.safeObserve(document.getElementById(this.options.gamePic),"click",this.onGamePicClick.bind(this)),this.safeObserve(this.backButton,"click",this.show
107FirstScreen.bind(this)),window.setTimeout((()=>{this.getNextButton()}),500)}getNextButton(){this.nextBtnSearch=document.getElementsByClassName("nextBtn"),void 0!==this.nextBtnSearch&&(this.nextBtn=this.nextBtnSearch[0])}onAkiOkClick(event){event.preventDefault(),event.stopPropagation(),this.friendButton.disabled=!0;var teamId=this.teamChooser.options[this.teamChooser.selectedIndex].value,friendId=this.friendsChooser.options[this.friendsChooser.selectedIndex].value;GamesMultiplayerConstructionInstance.opponent=this.friendsChooser.options[this.friendsChooser.selectedIndex].text;var classList=Array.from(event.target.classList);if(this.level=0,classList.includes("akiEasyBtn")&&(this.level=1),classList.includes("akiMediumBtn")&&(this.level=2),classList.includes("akiHardBtn")&&(this.level=3),0==this.level&&"mem"==friendId)return!1;if(0==this.level&&"mem"!=friendId){teamId=this.teamChooser.options[0].value;var member=[this.options.member_array,friendId]}else member=[this.options.member_array];GamesMultiplayerConstructionInstance.level=this.level,axios(new UrlTemplate(this.options.create_url).r("PLH_AkiLevel",this.level).r("PLH_team",teamId).r("PLH_Cmem",member).url,{method:"get"}).then(this.onSuccess.bind(this)).catch(this.onError.bind(this))}showFirstScreen(event){event.preventDefault(),event.stopPropagation(),this.backButton.style.display="none",this.raceAkiBtnWrapper.style.display="none",this.friendsChooserContainer.style.display="none",this.akiDifficultyWrapper.style.display="none",this.animatedDragon.style.display="none",this.gameSelection.style.display="block",this.dragonChooser.style.display="block"}showSecondScreen(event){event.preventDefault(),event.stopPropagation(),this.gameSelection.style.display="none",this.dragonChooser.style.display="none",this.akiDifficultyWrapper.style.display="none",this.backButton.style.display="block",this.animatedDragon.style.display="block",this.options.communityPlusEnabled?(this.raceAkiBtnWrapper.style.display="block",this.friendsChooserContainer.style.display="block"):this.akiDifficultyWrapper.style.display="block",this.bindBackButton(this.showFirstScreen)}showThirdScreen(event){event.preventDefault(),event.stopPropagation(),this.raceAkiBtnWrapper.style.display="none",this.friendsChooserContainer.style.display="none",this.akiDifficultyWrapper.style.display="block",this.bindBackButton(this.showSecondScreen)}bindBackButton(screen){this.stopObserveAllListeners(this.backButton),this.safeObserve(this.backButton,"click",screen.bind(this))}onGamePicClick(event){this.showSecondScreen(event)}onRaceAkiClick(event){this.showThirdScreen(event)}onSuccess(req){GamesMultiplayerConstructionInstance.onSuccess(req)}onError(req){GamesMultiplayerConstructionInstance.onError(req)}}
108var ToggleQuestionReaderInstance=null;class ToggleQuestionReader extends DOMAttached{constructor(el,options){super(el,options),this.options=options,ToggleQuestionReaderInstance=this,this.button=document.getElementById(options.buttonLink),this.imgPlay=document.getElementById(options.playButton),this.imgPause=document.getElementById(options.pauseButton),this.turnOnTooltip=options.turnOnTooltip,this.turnOffTooltip=options.turnOffTooltip,this.url=this.button.href,this.button.href="#?",this.isAndroid=null!=navigator.userAgent.match(/droid/i),this.safeObserve(this.button,"click",this.onClick.bind(this)),this.showCorrectImage()}onClick(ev){ev.preventDefault(),axios(this.url,{method:"get"}).then(this.onSuccess.bind(this))}onSuccess(ev){null!==GamesTextToSpeechInstance&&void 0!==GamesTextToSpeechInstance&&(GamesTextToSpeechInstance.isEnabled?GamesTextToSpeechInstance.turnOffTextToSpeech():(GamesTextToSpeechInstance.turnOnTextToSpeech(),GamesQuizInstance.createAndReadAllTextToSpeech()),this.showCorrectImage())}showCorrectImage(){null!==GamesTextToSpeechInstance&&void 0!==GamesTextToSpeechInstance&&(GamesTextToSpeechInstance.isEnabled?(this.imgPlay.style.display="none",this.imgPause.style.display="block",this.button.title=this.turnOffTooltip):(GamesTextToSpeechInstance.removeTextToSpeechEffects(),this.imgPlay.style.display="block",this.imgPause.style.display="none",this.button.title=this.turnOnTooltip))}}
109var GamesMultiplayerQuizInstance=null,GamesQuizInstance=null;class GamesMultiplayerQuiz extends DOMAttached{constructor(el,options){super(el,options),GamesMultiplayerQuizInstance=this,GamesQuizInstance=this,this.upScaledImageHandler=new UpScaledImageHandler(this),this.container=this.el.querySelector(".questionContainer"),this.message=this.el.querySelector("span.message"),this.tpReportQuestion=this.el.querySelector(".tpReportQuestion"),this.beginSound=null,this.displayMath=this.options.DisplayMath,this.instance=this.options.instance,this.playFeedbackSound=this.options.FeedbackSoundOn,null==GenericSoundsInstance&&new GenericSounds(this.playFeedbackSound),this.readQuestions=this.options.ReadQuestionsOn&&this.options.TextToSpeechEnabled,null==GamesTextToSpeechInstance&&new GamesTextToSpeech(this,this.readQuestions,this.options.TextToSpeechEnabledByParent),ToggleFeedbackSoundInstance&&this.options.TextToSpeechEnabled&&(ToggleFeedbackSoundInstance.url=this.options.ToggleFeedbackSoundUrl),ToggleQuestionReaderInstance&&this.options.TextToSpeechEnabled&&(ToggleQuestionReaderInstance.url=this.options.ToggleQuestionReaderUrl,ToggleQuestionReaderInstance.showCorrectImage()),this.position=0,this.questionNumber=0,this.lockPageLoad=!1;var finishInitialization=()=>{this.playFeedbackSound&&this.sound(),this.options.useList?this.safeObserve(this.el,"click",this.onListClick.bind(this)):(this.safeObserve(this.el,"click",this.onSubmitButtonClick.bind(this)),this.safeObserve(this.el,"keypress",this.onKeypress.bind(this))),this.handleNextPageLoad()};soundManager.ok()||!this.readQuestions&&!this.playFeedbackSound?finishInitialization():soundManager.onready(finishInitialization),this.options.playingAgainstAki&&(this.opponent=new GamesRaceOpponent(this.options.akiMinTimeout,this.options.akiMaxTimeout,this.options.akiProbabilityCorrect,this.options.endPosition,this.options.akiAnswerUrl),this.opponentAlive=!0)}sound(){this.beginSound=soundManager.createSound({id:"succ",url:"/snd/first_call.mp3"}),this.beginSound.play({onfinish:function(){this.destruct()}})}onSubmitButtonClick(ev){this.locked||(ev.target.closest(".submitButton")?this.processInputSolution():this.handleOtherClick(ev))}removeTextToSpeechEffects(){soundManager.stopAll(),void 0!==this.beginSound&&null!==this.beginSound&&this.beginSound.destruct(),GamesTextToSpeechInstance.removeTextToSpeechEffects()}onKeypress(ev){this.locked||13==ev.keyCode&&(this.processInputSolution(),ev.preventDefault(),ev.stopPropagation())}processInputSolution(){this.locked=!0,this.lockPageLoad=!0,this.success=this.checkInputSolution(),this.el.querySelector(".solutionInput").style.display="none",this.playSound(),this.success?this.el.querySelector(".dispIfSolutionCorrect").style.display="":this.el.querySelector(".dispIfSolutionIncorrectWithCorrectSolution").style.display="",this.success?this.position<this.options.endPosition-2?this.position+=2:(this.position=this.options.endPosition,this.opponentAlive=!1,this.container.parentNode.style.backgroundColor=this.options.dullred):0!=this.position&&this.position--,GamesRaceInstance.moveDragonTo(0,this.position),this.questionNumber++,this.questionNumber==this.options.endPosition&&GamesRaceInstance.takeDragonDown(0,this.position),axios(new UrlTemplate(this.options.processAnswerUrl).r("PLH_success",this.success).r("PLH_nquestion",-2).url,{method:"get"}).then(this.onSuccess.bind(this))}checkInputSolution(){for(var i=0,input=this.el.querySelector(".solutionInput").querySelectorAll("input")[i],solution=this.el.querySelector(".correctSolution").querySelectorAll("input")[i];null!=input&&null!=solution;){if(input.value.gsub(/\s+/,"")!=solution.value)return!1;++i,input=this.el.querySelector(".solutionInput").querySelectorAll("input")[i],solution=this.el.querySelector(".correctSolution").querySelectorAll("input")[i]}return!0}handleOtherClick(ev){ev.target.closest("input")&&(ev.preventDefault(),ev.stopPropagation(),void 0!==this.tpReportQuestion&&(this.tpReportQuestion.style.display="block"))}onListClick(ev){if(!this.locked){this.lockPageLoad=!0;var li=ev.target.closest("li");if(li){if(li.closest("ol, ul")){this.removeTextToSpeechEffects(),li.classList.contains("solution")?li.style.backgroundColor="green":li.style.backgroundColor="red",this.locked=!0;this.el.querySelector(".question").innerHTML,this.el.querySelector(".solution").innerHTML;this.success=li.classList.contains("solution"),this.success||(this.flashInterval=setInterval(this.flashCorrectSolution.bind(this),250)),this.playSound(),this.success?this.position<this.options.endPosition-2?this.position+=2:(this.position=this.options.endPosition,this.opponentAlive=!1,this.container.parentNode.style.backgroundColor=this.options.dullred):0!=this.position&&this.position--,this.questionNumber++,this.questionNumber==this.options.endPosition&&this.position!=this.options.endPosition?GamesRaceInstance.takeDragonDown(0,this.position):GamesRaceInstance.moveDragonTo(0,this.position),axios(new UrlTemplate(this.options.processAnswerUrl).r("PLH_success",this.success).r("PLH_nquestion",this.pageLoadJ
109SON.questionID).url,{method:"get"}).then(this.onSuccess.bind(this))}}else this.handleOtherClick(ev)}}isOpponentAlive(){return this.opponentAlive}handleProcessResult(){this.success?setTimeout(this.handleNextPageLoad.bind(this),1500):setTimeout(this.handleNextPageLoad.bind(this),3e3)}flashCorrectSolution(){var sol=this.el.querySelector(".solution");"green"==sol.style.backgroundColor?sol.style.backgroundColor=this.prevBgColor:(this.prevBgColor=sol.style.backgroundColor,sol.style.backgroundColor="green")}handleNextPageLoad(){clearInterval(this.flashInterval),axios(this.getPageLoadUrl(),{method:"get"}).then(this.onPageLoaded.bind(this))}handleNextSpecificPageLoad(messageInstance){this.lockPageLoad||messageInstance!=this.instance||(clearInterval(this.flashInterval),axios(this.getPageLoadUrl(),{method:"get"}).then(this.onPageLoaded.bind(this)))}getPageLoadUrl(){return new UrlTemplate(this.options.loadUrl).url}onSuccess(req){this.json=req.data,this.handleProcessResult()}onPageLoaded(req){try{this.pageLoadJSON=req.data}catch(e){return void legacyGlobal.handleFailedAJAJRequest()}this.customLoadEvent()&&(this.showPage(),this.locked=!1,this.lockPageLoad=!1,this.options.useList||this.el.querySelector(".solutionInput")&&this.el.querySelector(".solutionInput").querySelector("input").focus())}customLoadEvent(){return!0}showPage(){if(void 0!==this.pageLoadJSON){if(this.container.innerHTML=this.pageLoadJSON.page,this.el.querySelector(".question2")){for(var questiontext=this.el.querySelector(".question2").firstChild.firstChild,questionbox=this.el.querySelector(".question2"),questionContent=questiontext,questionParent=questiontext.parentNode;void 0!==questionContent.innerHTML;)questionParent=questionContent,questionContent=questionContent.innerHTML;questionContent.length<400&&(questionParent.style.fontSize="30px",questionParent.style.lineHeight="30px",questionParent.style.align="center",160<questionParent.scrollHeight&&(questionParent.style.fontSize="25px"),160<questionParent.scrollHeight&&(questionParent.style.fontSize="20px"),questionbox.style.paddingTop=((210-questionParent.offsetHeight)/2).toString()+"px")}null!=PlayPauseButtonInstance&&this.pageLoadJSON.soundFile&&PlayPauseButtonInstance.setSoundUrl(this.pageLoadJSON.soundFile,!0,!0),this.renderMath(),this.el.querySelector(".question")&&this.createAndReadAllTextToSpeech(),this.upScaledImageHandler.initializeListenerForZoomInQuestionImg()}}createAndReadAllTextToSpeech(){GamesTextToSpeechInstance.setTextToSpeechElements(this.createTextToSpeechElements()),GamesTextToSpeechInstance.readSpeechForAllElementsInOrder()}createTextToSpeechElements(){var textToSpeechElements=[];textToSpeechElements.push(this.createQuestionElement());for(var i=0;i<this.pageLoadJSON.answerPaths.length;i++)textToSpeechElements.push(this.createAnswerElement(i));return textToSpeechElements}createQuestionElement(){var questionElement={};return questionElement.domElement=this.el.querySelector(".question"),questionElement.identifier="question",questionElement.soundUrl=this.pageLoadJSON.questionPath,questionElement.highlightFontColor="#7F82D2",questionElement.defaultFontColor="white",questionElement}createAnswerElement(answerNumber){var answerElement={};return answerElement.domElement=this.el.querySelector(".answer"+answerNumber),answerElement.identifier="answer"+answerNumber,answerElement.soundUrl=this.pageLoadJSON.answerPaths[answerNumber],answerElement.highlightFontColor="#7F82D2",answerElement.defaultFontColor="white",answerElement}getBackgroundColor(className){var element=this.el.querySelector(className);return null!=element?window.getComputedStyle(element).getPropertyValue("background-color"):""}getFontColor(className){var element=this.el.querySelector(className);return null!=element?window.getComputedStyle(element).getPropertyValue("color"):""}playSound(){this.success?GenericSoundsInstance.successSound():GenericSoundsInstance.failSound()}renderMath(){this.displayMath&&MathJax.Hub.Typeset()}}
110class GamesMathPuzzle extends DOMAttached{constructor(el,options){super(el,options);var splash=this.el.querySelector(".splash");"1"==this.options.level?(splash.querySelector(".background").style.opacity=.7,this.demoMode=!0,this.el.querySelector(".levelDown").style.display="none"):(splash.style.display="none",this.demoMode=!1),this.medalImage=this.el.querySelector(".medalBox").querySelector(".medal"),this.happySmiley=this.el.querySelector(".medalBox").querySelector(".win"),this.sadSmiley=this.el.querySelector(".medalBox").querySelector(".fail"),this.levelUpOverlay=this.el.querySelector(".levelUpOverlay"),this.safeObserve(document.querySelectorAll(".splashClose")[0],"click",(ev=>{void 0!==ev&&(ev.preventDefault(),ev.stopPropagation()),this.el.querySelector(".splash").style.display="none"}
110)),this.safeObserve(this.el.querySelector(".levelUpButton"),"click",(ev=>{void 0!==ev&&(ev.preventDefault(),ev.stopPropagation()),this.showNextOverlayContent()})),this.safeObserve(this.el.querySelector(".medalOkButton"),"click",(ev=>{void 0!==ev&&(ev.preventDefault(),ev.stopPropagation()),this.showNextOverlayContent()})),this.safeObserve(this.el.querySelector(".levelDown"),"click",(ev=>{axios(new UrlTemplate(this.options.levelJumpUrl).r("PLH_level",-1).url,{method:"get"}).then(this.ajajCallHandler.bind(this)),void 0!==ev&&(ev.preventDefault(),ev.stopPropagation())})),this.setRunningEffects(),this.originalPuzzle=this.el.querySelector(".questionContainer").innerHTML,this.initialOperations(),this.resetTimer(),this.startTimer()}getHint(){switch(this.solution[0]){case void 0:return"";case"Addition":return this.options.trAdditionHint;case"Subtraction":return this.options.trSubtractionHint;case"Multiplication":return this.options.trMultiplicationHint;case"Division":return this.options.trDivisionHint;default:return new TextResource(this.options.trOperandHint).r("{operand}",this.solution[0]).string()}}showHint(){this.addAfterAllEffectsFinishedFunction(function(){var newHint=this.getHint();this.hint.querySelector(".text").innerHTML!=newHint&&("none"==this.hint.style.display?(this.hint.querySelector(".text").innerHTML=newHint,LegacyEffects.appear(this.hint)):LegacyEffects.fade(this.hint,{onComplete:()=>{this.hint.querySelector(".text").innerHTML=newHint,LegacyEffects.appear(this.hint)}}))}.bind(this))}nextHint(){this.solution.shift(),this.solution.length>0&&this.showHint()}setRunningEffects(change){if(null==change)this.runningEffects=0,this.afterAllEffectsFinished=new Array;else if(this.runningEffects+=change,0==this.runningEffects){for(var i=0;i<this.afterAllEffectsFinished.length;i++)this.afterAllEffectsFinished[i]();this.afterAllEffectsFinished=new Array}}addAfterAllEffectsFinishedFunction(func){0==this.runningEffects?func():this.afterAllEffectsFinished.push(func)}initialOperations(){var demoModeButton=this.el.querySelector(".DemoModeButton");this.hint=this.el.querySelector(".hint"),legacyGlobal.isIE&&this.hint.querySelectorAll("*").forEach((function(el){el.style.filter="inherit"})),this.demoMode?(demoModeButton.querySelector(".end").style.display="",demoModeButton.querySelector(".start").style.display="none",this.hint.style.display="none",this.hint.style.visibility="visible",this.solution=this.el.querySelector(".questionContainer").querySelector("div").querySelector(".solution").innerHTML.split("|"),this.showHint()):(demoModeButton.querySelector(".end").style.display="none",demoModeButton.querySelector(".start").style.display="",this.hint.style.display="none",this.hint.style.visibility="visible"),1==this.showTryOnYourOwnInfo&&(this.hint.style.display="",this.hint.querySelector(".text").innerHTML=this.options.trTryOnYourOwn,LegacyEffects.appear(this.hint,{onComplete:()=>{LegacyEffects.fade(this.hint,{delay:3})}}),this.showTryOnYourOwnInfo=!1);var questionContainerDimensions_width=this.el.querySelector(".questionContainer").offsetWidth,questionContainerDimensions_height=this.el.querySelector(".questionContainer").offsetHeight;this.leftOperandPosition={left:questionContainerDimensions_width/2-this.options.operatorSize/2-this.options.operandSize,top:questionContainerDimensions_height/2-this.options.operandSize/2},this.operatorPosition={left:questionContainerDimensions_width/2-this.options.operatorSize/2,top:questionContainerDimensions_height/2-this.options.operatorSize/2},this.rightOperandPosition={left:questionContainerDimensions_width/2+this.options.operatorSize/2,top:questionContainerDimensions_height/2-this.options.operandSize/2},this.duration=.4,this.resetInput(!0,!0,!0),document.querySelectorAll(".OperatorButton").forEach(function(btn){btn.unmove=void 0,btn.locked=void 0}.bind(this)),document.querySelectorAll(".OperandButton").forEach(function(btn){btn.unmove=void 0,btn.locked=void 0}.bind(this));var i=0;document.querySelectorAll(".OperandButton").forEach(function(btn){btn.number=i++,this.safeObserve(btn.querySelector(".bubble-button"),"click",function(ev){1!=this.globalLock&&(this.demoMode&&btn.querySelector(".bubble-button").innerHTML!=this.solution[0]||(null==this.operand1?this.selectOperand1(btn):null==this.operand2?btn.number!=this.operand1?this.selectOperand2(btn):this.demoMode||this.resetInput(!0,!0,!0):this.demoMode||(btn.number==this.operand1?this.resetInput(!1,!1,!0):btn.number!=this.operand2&&(this.resetInput(!0,!1,!0),this.selectOperand1(btn)))))}.bind(this))}.bind(this));var j=0;document.querySelectorAll(".OperatorButton").forEach(function(btn
110){btn.number=j++,this.safeObserve(btn.querySelector(".bubble-button"),"click",function(ev){if(null==this.operator){if(this.demoMode&&btn.title!=this.solution[0])return;this.selectOperator(btn)}else this.demoMode||this.resetInput(!1,!0,!1)}.bind(this))}.bind(this)),this.undoPossible=!1,this.safeObserve(this.el.querySelector(".UndoButton"),"click",function(ev){this.demoMode||(null!=this.operand1||null!=this.operator||null!=this.operand2?(this.seconds+=5,this.blinkingSmiley(this.sadSmiley),this.addAfterAllEffectsFinishedFunction(function(){this.resetInput(!0,!0,!0)}.bind(this))):this.undoPossible&&(this.seconds+=5,this.blinkingSmiley(this.sadSmiley),axios(new UrlTemplate(this.options.undoUrl).url,{method:"get"}).then(this.ajajCallHandler.bind(this))))}.bind(this)),this.safeObserve(this.el.querySelector(".DemoModeButton"),"click",function(ev){this.demoMode=!this.demoMode,0==this.demoMode?(this.showTryOnYourOwnInfo=!0,axios(new UrlTemplate(this.options.levelJumpUrl).r("PLH_level",0).url,{method:"get"}).then(this.ajajCallHandler.bind(this))):(this.pauseTimer(),axios(new UrlTemplate(this.options.undoAllUrl).url,{method:"get"}).then((()=>{this.addAfterAllEffectsFinishedFunction((()=>{var container=this.el.querySelector(".questionContainer");LegacyEffects.fade(container,{onComplete:()=>{container.innerHTML=this.originalPuzzle,LegacyEffects.appear(container),this.initialOperations(),this.resetInput(!0,!0,!0)}})}))})))}.bind(this))}move(btn,dx,dy){if(null==btn.locked){btn.locked=!0,btn.classList.contains("OperatorButton")&&document.querySelectorAll(".OperatorButton").forEach((otherOperator=>{otherOperator!=btn&&LegacyEffects.fade(otherOperator)}));var dxOld=btn.dx,dyOld=btn.dy;return btn.dx=dx,btn.dy=dy,LegacyEffects.move(btn,{x:btn.dx,y:btn.dy,mode:"relative",duration:this.duration,onStart:()=>{this.setRunningEffects(1)},onComplete:()=>{this.setRunningEffects(-1),btn.locked=void 0,btn.unmove&&this.unmove(btn)}}),null!=dxOld&&null!=dyOld&&(btn.dx+=dxOld,btn.dy+=dyOld),!0}return!1}unmove(btn){null==btn.locked&&null!=btn.dx&&null!=btn.dy?(btn.locked=!0,btn.unmove=void 0,LegacyEffects.move(btn,{x:-btn.dx,y:-btn.dy,mode:"relative",duration:this.duration,onStart:()=>{this.setRunningEffects(1)},onComplete:()=>{this.setRunningEffects(-1),btn.locked=void 0,btn.classList.contains("OperatorButton")&&LegacyEffects.appear(".OperatorButton")}}),btn.dx=void 0,btn.dy=void 0):btn.unmove=!0}selectOperand1(btn){null!=this.operand1&&this.operand1!=btn.number&&this.deselectOperand1(),null==this.operand1&&this.move(btn,this.leftOperandPosition.left-btn.offsetLeft,this.leftOperandPosition.top-btn.offsetTop)&&(this.operand1=btn.number),this.checkTerm()}deselectOperand1(){if(null!=this.operand1){var btn=document.querySelectorAll(".OperandButton")[this.operand1];this.operand1=void 0,this.unmove(btn)}}selectOperand2(btn){null!=this.operand2&&this.operand2!=btn.number&&this.deselectOperand2(),null==this.operand2&&this.move(btn,this.rightOperandPosition.left-btn.offsetLeft,this.rightOperandPosition.top-btn.offsetTop)&&(this.operand2=btn.number),this.checkTerm()}deselectOperand2(){if(null!=this.operand2){var btn=document.querySelectorAll(".OperandButton")[this.operand2];this.operand2=void 0,this.unmove(btn)}}selectOperator(btn){null!=this.operator&&this.operator!=btn.number&&this.deselectOperator(),null==this.operator&&this.move(btn,this.operatorPosition.left-(btn.offsetLeft+btn.parentNode.offsetLeft),this.operatorPosition.top-(btn.offsetTop+btn.parentNode.offsetTop))&&(this.operator=btn.number),this.checkTerm()}checkTerm(){null!=this.operand1&&null!=this.operator&&null!=this.operand2?axios(new UrlTemplate(this.options.performOperationUrl).r("PLH_Operations",document.querySelectorAll(".OperatorButton")[this.operator].title).r("PLH_term1",this.operand1).r("PLH_term2",this.operand2).r("PLH_time",this.seconds).r("PLH_demoMode",this.demoMode).url,{method:"get"}).then(this.ajajCallHandler.bind(this)):this.demoMode&&this.nextHint()}deselectOperator(){if(null!=this.operator){var btn=document.querySelectorAll(".OperatorButton")[this.operator];this.operator=void 0,this.unmove(btn)}}resetInput(operand1,operator,operand2){operand1&&this.deselectOperand1(),operator&&this.deselectOperator(),operand2&&this.deselectOperand2()}ajajCallHandler(req){if(this.json=req.data,null!=this.json.invalidOperation)this.resetInput(!0,!0,!0);else if(null!=this.json.result){var operand1=document.querySelectorAll(".OperandButton")[this.operand1],operand2=document.querySelectorAll(".OperandButton")[this.operand2],operator=document.querySelectorAll(".OperatorButton")[this.operator];
110this.globalLock=!0,this.setRunningEffects(1),LegacyEffects.parallel([LegacyEffects.fade(operator),LegacyEffects.fade(operand1),LegacyEffects.fade(operand2)],{onComplete:()=>{if(null!=this.json.page){var isWin=this.demoMode||this.json.levelUp||this.json.progress>0;const imgElement=operand2.querySelector(".img");imgElement&&(imgElement.classList.toggle("win",isWin),imgElement.classList.toggle("fail",!isWin))}operand2.querySelector(".bubble-button").innerHTML=this.json.result;var originalx=parseFloat(window.getComputedStyle(operand2).getPropertyValue("left")||"0"),dx=Math.floor((this.leftOperandPosition.left-this.rightOperandPosition.left)/2);operand2.style.left=originalx+dx+"px",operand2.dx+=dx,LegacyEffects.appear(operand2,{onComplete:()=>{this.globalLock=void 0,null==this.json.page&&this.resetInput(!0,!0,!0),this.setRunningEffects(-1)}})}}),this.demoMode&&this.nextHint(),this.undoPossible=this.json.undoPossible}null!=this.json.page?(this.originalPuzzle=this.json.page,this.addAfterAllEffectsFinishedFunction((()=>{this.undoPossible=!1;var container=this.el.querySelector(".questionContainer");if(null!=this.json.result){var operand2=document.querySelectorAll(".OperandButton")[this.operand2];this.demoMode||this.json.levelUp||this.json.progress>0?LegacyEffects.move(operand2,{x:0,y:-150,mode:"relative"}):LegacyEffects.move(operand2,{x:0,y:150,mode:"relative"})}LegacyEffects.fade(container,{onComplete:()=>{container.innerHTML=this.json.page,LegacyEffects.appear(container),null!=this.json.progressBar&&replaceElement(this.el.querySelector(".progressBar"),this.json.progressBar),null!=this.json.personalRecordBox&&replaceElement(this.el.querySelector(".personalRecordBox"),this.json.personalRecordBox),null!=this.json.overallRecordBox&&replaceElement(this.el.querySelector(".overallRecordBox"),this.json.overallRecordBox);for(var progressBar=this.el.querySelector(".progressBar"),i=0;i<this.json.maxProgress;i++)i<this.json.progress?(progressBar.querySelectorAll(".greySegment")[i].style.visibility="hidden",progressBar.querySelectorAll(".yellowSegment")[i].style.visibility="visible"):(progressBar.querySelectorAll(".yellowSegment")[i].style.visibility="hidden",progressBar.querySelectorAll(".greySegment")[i].style.visibility="visible");this.el.querySelector(".currentLevel").innerHTML="Level: "+this.json.level,this.el.querySelector(".levelDown").style.display=1==this.json.level?"none":"",this.demoMode||this.json.levelUp||this.json.progress>0?this.blinkingSmiley(this.happySmiley):this.blinkingSmiley(this.sadSmiley),this.demoMode&&(this.demoMode=!1,this.showTryOnYourOwnInfo=!0),this.showNextOverlayContent(),this.initialOperations(),this.resetInput(!0,!0,!0)}})}))):null!=this.json.idx1&&(this.undoPossible=this.json.undoPossible,document.querySelectorAll(".OperandButton")[this.json.idx1].querySelector(".bubble-button").innerHTML=this.json.result1,document.querySelectorAll(".OperandButton")[this.json.idx1].style.display="",document.querySelectorAll(".OperandButton")[this.json.idx2].querySelector(".bubble-button").innerHTML=this.json.result2,document.querySelectorAll(".OperandButton")[this.json.idx2].style.display="",this.resetInput.bind(this).delay(1,!0,!0,!0))}blinkingSmiley(smiley){smiley.style.display="none",smiley.style.visibility="visible",LegacyEffects.fade(this.medalImage),LegacyEffects.appear(smiley,{onComplete:()=>{LegacyEffects.pulsate(smiley,{pulses:2,duration:1.5,onComplete:()=>{LegacyEffects.fade(smiley),LegacyEffects.appear(this.medalImage)}})}})}showNextOverlayContent(){this.pauseTimer(),null==this.json.medal||this.json.medal.endsWith("games/medals/medal_none.svg")?this.json.levelUp&&this.json.level>1?(this.levelUpOverlay.querySelector(".medalOkButton").style.display="none",this.levelUpOverlay.querySelector(".image").style.display="none",this.levelUpOverlay.querySelector(".imageCaption").style.display="none",this.levelUpOverlay.querySelector(".levelUpButton").style.display="block",this.levelUpOverlay.querySelector(".infoText").innerHTML=new TextResource(this.options.trLevelReached).r("{level}",this.json.level).r("{amount}",this.json.amount).string(),this.levelUpOverlay.querySelector(".level").style.display="block",this.json.overallRecord?this.levelUpOverlay.querySelector(".level").innerHTML=new TextResource(this.options.trOverallRecord).r("{seconds}",this.json.timeInSeconds).string():this.json.personalRecord?this.levelUpOverlay.querySelector(".level").innerHTML=new TextResource(this.options.trPersonalRecord).r("{seconds}",this.json.timeInSeconds).string():this.levelUpOverlay.querySelector(".level").innerHTML=new TextResource(this.options.trLevelTime).r("{seconds}",this.json.timeInSeconds).string(),this.json.levelUp=void 0,this.levelUpOverlay.style.display="block"):null!=this.json.pet&&""!=this.json.pet?(this.levelUpOverlay.querySelector(".medalOkButton").style.display="none",this.levelUpOverlay.querySelector(".level").style.display="none",this.levelUpOverlay.querySelector(".continueButton").style.display="none",this.levelUpOverlay.querySelector(".levelUp
110Button").style.display="block",this.levelUpOverlay.querySelector(".image").style.display="block",this.levelUpOverlay.querySelector(".imageCaption").style.display="block",this.levelUpOverlay.querySelector(".infoText").innerHTML=this.options.trPetMessage,this.levelUpOverlay.querySelector(".image").querySelector("img").src=this.json.pet,this.levelUpOverlay.querySelector(".imageCaption").innerHTML=this.json.petName,this.json.pet=void 0,this.levelUpOverlay.style.display="block"):this.json.levelUp&&1==this.json.level?(this.levelUpOverlay.querySelector(".level").style.display="none",this.levelUpOverlay.querySelector(".image").style.display="none",this.levelUpOverlay.querySelector(".imageCaption").style.display="none",this.levelUpOverlay.querySelector(".levelButtons").style.display="none",this.levelUpOverlay.querySelector(".continueButton").style.display="block",this.levelUpOverlay.querySelector(".infoText").innerHTML=new TextResource(this.options.trEndOfGame).r("{amount}",this.json.amount).r("{newreward}",this.json.newreward).string(),this.json.levelUp=void 0,this.levelUpOverlay.style.display="block"):(this.levelUpOverlay.style.display="none",0==this.json.progress&&this.resetTimer(),this.demoMode||this.startTimer()):(this.levelUpOverlay.querySelector(".level").style.display="none",this.levelUpOverlay.querySelector(".levelUpButton").style.display="none",this.levelUpOverlay.querySelector(".continueButton").style.display="none",this.levelUpOverlay.querySelector(".medalOkButton").style.display="block",this.levelUpOverlay.querySelector(".image").style.display="block",this.levelUpOverlay.querySelector(".imageCaption").style.display="block",this.levelUpOverlay.querySelector(".infoText").innerHTML=this.options.trMedalMessage,this.levelUpOverlay.querySelector(".image").querySelector("img").src=this.json.medal,this.levelUpOverlay.querySelector(".imageCaption").innerHTML=this.json.medalName,this.medalImage.src=this.json.medal,this.json.medal=void 0,this.levelUpOverlay.style.display="block")}startTimer(){null==this.timer&&(this.increaseTimer(),this.timer=setInterval(this.increaseTimer.bind(this),1e3))}pauseTimer(){null!=this.timer&&(clearInterval(this.timer),this.seconds--,this.timer=void 0)}resetTimer(){null!=this.timer&&(clearInterval(this.timer),this.timer=void 0),this.seconds=-1,this.el.querySelector(".timer").innerHTML="00:00"}increaseTimer(){this.seconds++;var string=Math.floor(this.seconds%60);String(string).length<2&&(string="0"+string),(string=Math.floor(this.seconds/60)+":"+string).length<5&&(string="0"+string),this.el.querySelector(".timer").innerHTML=string}}
111class GamesHangman extends DOMAttached{constructor(el,options){super(el,options),this.completed=!1,this.solution=this.options.solution,this.errorImage=this.el.querySelector("img.errors"),this.message=this.el.querySelector("span.message"),this.word=this.el.querySelector(".mia-word"),this.wordLetters=this.el.querySelectorAll(".letter"),this.rightCount=0,this.maxErrorCount=this.el.querySelector(".maxErrors").value,this.errorCount=0,this.errorImage.src=this.errorImage.src.replace(/\d+_\d+\.png/,this.maxErrorCount+"_"+(this.maxErrorCount-this.errorCount)+".png"),this.marginRight=2,this.el.querySelectorAll(".letter").forEach(function(e){this.safeObserve(e,"mouseover",function(ev){if(null!=this.letterToFind&&"_"==e.innerHTML){this.originalFontColor=e.style.color,e.style.color="red",e.style.cursor="pointer";var oldWidth=e.offsetWidth;e.innerHTML=this.letterToFind;var dwidth=oldWidth-e.offsetWidth;dwidth>0?e.style.paddingRight=dwidth+"px":e.style.marginRight=dwidth+this.marginRight+"px"}}.bind(this)),this.safeObserve(e,"mouseout",function(ev){null!=this.letterToFind&&e.innerHTML==this.letterToFind&&(e.style.color=this.originalFontColor,e.style.cursor="default",e.style.paddingRight="",e.style.marginRight=this.marginRight+"px",e.innerHTML="_")}.bind(this)),this.safeObserve(e,"click",function(ev){if(null!=this.letterToFind&&e.innerHTML==this.letterToFind){e.style.color=this.originalFontColor,e.style.cursor="default",e.style.paddingRight="",e.style.marginRight=this.marginRight+"px",e.innerHTML="_";var letter=this.letterToFind;this.letterToFind=void 0,this.spanClicked.style.backgroundColor="#FFA7D1",e.assocLetter==letter?(this.uncover(letter,this.spanClicked),this.checkSuccess()):(this.onError(letter),this.setMessage(new TextResource(this.options.trWrongPosition).r("{letter}",letter).string(),"red"))}}.bind(this))}.bind(this)),this.letters="",this.el.querySelectorAll(".letterSelector div.char").forEach(function(e){this.safeObserve(e,"click",this.onLetterClick.bind(this)),this.letters=this.letters+e.title}.bind(this));var count=0;
111this.wordLetters.forEach(function(e){var ch=this.solution.charAt(count);-1==this.letters.indexOf(ch)&&(++this.rightCount,e.innerHTML=ch,e.style.display="none"),e.assocLetter=this.solution.charAt(count++)}.bind(this)),this.el.querySelectorAll(".letterToUncover").forEach(function(e){this.el.querySelectorAll(".letterSelector div.char").forEach(function(f){e.value==f.title&&this.uncover(e.value,f)}.bind(this))}.bind(this))}onLetterClick(ev){if(!(this.completed||this.errorCount>=this.maxErrorCount)){var span=ev.target.closest("div.char");if(!span.classList.contains("used")){null==this.spanClicked||this.spanClicked.classList.contains("used")||(this.spanClicked.style.backgroundColor="#FFA7D1"),this.spanClicked=void 0,this.letterToFind=void 0;var letter=span.lastChild.data,lettercnt=this.solution.split(letter).length-1;0==lettercnt?(this.uncover(letter,span),this.onError(letter)):lettercnt<3?(this.uncover(letter,span),this.checkSuccess()):(this.setMessage(new TextResource(this.options.trGuessPosition).r("{letter}",letter).string(),""),this.spanClicked=span,this.spanClicked.style.backgroundColor="#ADFF2F",this.letterToFind=letter)}}}uncover(letter,span){span.classList.add("used"),span.style.backgroundColor="#ccc",span.style.cursor="default",this.wordLetters.forEach(function(e){if(e.assocLetter==letter){e.innerHTML=letter,e.style.marginRight="0px";var next=e.nextElementSibling;null!=next&&"none"==next.style.display&&(next.style.display="");var previous=e.previousElementSibling;null!=previous&&"none"==previous.style.display&&(previous.style.display=""),++this.rightCount}}.bind(this))}checkSuccess(){this.removeMessage(),this.rightCount==this.solution.length&&axios(this.options.urlCompleted,{method:"get"}).then(this.onSuccess.bind(this))}onSuccess(req){var amount=req.data.Amount;this.setMessage(new TextResource(this.options.trCompleted).r("{amount}",amount).string(),"green"),this.message.style.color="green",this.word&&(this.word.style.color="green"),this.completed=!0}onError(letter){if(++this.errorCount,this.errorImage.src=this.errorImage.src.replace(/\d+\.png/,this.maxErrorCount-this.errorCount+".png"),this.errorCount>=this.maxErrorCount)return this.setMessage(this.options.trFailed,"red"),this.word&&(this.word.style.color="red"),this.el.querySelectorAll(".letterSelector div.char").forEach((function(e){e.classList.add("used"),e.style.backgroundColor="#ccc",e.style.cursor="default"})),void this.wordLetters.forEach((function(el){el.innerHTML=el.assocLetter}));this.setMessage(new TextResource(this.options.trWrong).r("{letter}",letter).string(),"red")}removeMessage(){this.message.style.display="none"}setMessage(message,color){this.message.style.display="block",this.message.style.color=color,this.message.innerHTML=message}}
112var GamesQuizInstance=null;class GamesFlashQuiz extends DOMAttached{constructor(el,options){super(el,options),GamesQuizInstance=this,this.progressIndicator=new ProgressIndicator(this.el),this.progressBar=document.getElementById(this.options.progressBar),this.container=this.el.querySelector(".questionContainer"),this.message=this.el.querySelector("span.message"),this.level=-1,this.progress=0,this.amount=-1,this.numberList=[],this.textList=[],this.medalType=this.options.medalType,this.questionSoundPaths=[],null==GenericSoundsInstance&&new GenericSounds(this.options.FeedbackSoundOn),null==GamesTextToSpeechInstance&&new GamesTextToSpeech(this,this.options.ReadQuestionsOn&&this.options.TextToSpeechEnabled,this.options.TextToSpeechEnabledByParent),this.loadPage()}userAnswer(success){if(this.success=success,GamesTextToSpeechInstance.removeTextToSpeechEffects(),this.success){var itemId=0|this.numberList[this.progress];this.progress++,this.setTaskText(new TextResource(this.options.trLoadingLevel).string()),axios(new UrlTemplate(this.options.processAnswerUrl).r("PLH_success",this.success).r("PLH_Status",2).r("PLH_MedalType",this.medalType).r("PLH_progress",this.progress).r("PLH_itemId",itemId).r("PLH_nquestion",-2).url,{method:"get"}).then(this.onSuccess.bind(this)),this.updateProgressBar(),this.progress<this.numberList.length?(GenericSoundsInstance.successSound(!1,this.createAndReadAllTextToSpeech.bind(this)),this.setToClick(this.numberList[this.progress],this.textList[this.progress])):(GenericSoundsInstance.successSound(),this.removeAllListeners())}else GenericSoundsInstance.failSound(),this.handleWrongAnswer()}updateProgressBar(){this.progressBar.style.width=this.progress/this.numberList.length*100+"%";var numberQuestionsLeft=this.numberList.length-this.progress,questionsLeftText=1===numberQuestionsLeft?this.options.questionsLeftTR_singular:this.options.questionsLeftTR.replace("{num}",numberQuestionsLeft);this.el.querySelector(".questionsLeft").innerText=questionsLeftText}createTextToSpeechElements(){var questionElement={};return questionElement.domElement=this.el.querySelector(".question"),questionElement.identifier="question",questionElement.soundUrl=this.questionSoundPaths[this.progress],questionElement.highlightFontColor="#7F82D2",questionElement.defaultFontColor=this.getFontColor(".question"),[questionElement]}
112getBackgroundColor(className){var element=this.el.querySelector(className);return null!=element?window.getComputedStyle(document.getElementById(element)).getPropertyValue("background-color"):""}getFontColor(className){var element=this.el.querySelector(className);return null!=element?window.getComputedStyle(element).getPropertyValue("color"):""}handleWrongAnswer(){var itemId=0|this.numberList[this.progress];this.progress=0,this.progressBar.style.width="0",axios(new UrlTemplate(this.options.processAnswerUrl).r("PLH_success",this.success).r("PLH_Status",2).r("PLH_MedalType",this.medalType).r("PLH_progress",this.progress).r("PLH_itemId",itemId).r("PLH_nquestion",-2).url,{method:"get"}).then(this.onSuccess.bind(this)),this.amount=-1,this.level=-1,this.resetUI(),this.initFlashGame()}loadPage(){axios(new UrlTemplate(this.options.processAnswerUrl).r("PLH_TimeNeeded",1).r("PLH_KeystrokesCorrect",1).r("PLH_KeystrokesIncorrect",1).r("PLH_success",!0).r("PLH_Status",0).r("PLH_MedalType",this.medalType).r("PLH_progress",0).r("PLH_itemId",-1).r("PLH_nquestion",-2).url,{method:"get"})}initFlashGame(){axios(new UrlTemplate(this.options.processAnswerUrl).r("PLH_success",!0).r("PLH_Status",1).r("PLH_MedalType",this.medalType).r("PLH_progress",this.progress).r("PLH_itemId",-1).r("PLH_nquestion",-2).url,{method:"get"}).then((response=>this.onInitSuccess(response)))}onInitSuccess(response){if(null!=document.getElementById(this.el.id)){if(this.json=response.data,0==this.json.numberList.length||null==this.json.textList[0])return this.progress=0,void this.initFlashGame();this.level=this.json.level,this.progress=this.json.progress,this.amount=this.json.amount,this.numberList=this.json.numberList,this.textList=this.json.textList,this.questionSoundPaths=this.json.questionSoundPaths,this.showPage(),this.initGame(this.numberList[this.progress],this.textList[this.progress]),window.dispatchEvent(new Event("flashGameInitialized")),waitForElementToBePresent("#levelUpScreen").then((()=>{"none"===window.getComputedStyle(document.getElementById("levelUpScreen")).display&&this.createAndReadAllTextToSpeech()}))}}createAndReadAllTextToSpeech(){GamesTextToSpeechInstance.setTextToSpeechElements(this.createTextToSpeechElements()),setTimeout(function(){GamesTextToSpeechInstance.readSpeechForAllElementsInOrder()}.bind(this),1e3)}
112handleProcessResult(){if(this.success){if(0==this.json.numberList.length||null==this.json.textList[0])return this.progress=0,void this.initFlashGame();this.level=this.json.level,this.progress=0,this.amount=this.json.amount,this.numberList=this.json.numberList,this.textList=this.json.textList,this.questionSoundPaths=this.json.questionSoundPaths,this.progressBar.style.width="0",this.resetUI(),this.setToClick(this.numberList[0],this.textList[0]),this.createAndReadAllTextToSpeech()}}handleNextPageLoad(){this.progressIndicator.showProgressIndicator(),axios(this.getPageLoadUrl(),{method:"get"})}getPageLoadUrl(){return new UrlTemplate(this.options.loadUrl).url}onSuccess(req){try{this.json=req.data}catch(e){return void legacyGlobal.handleFailedAJAJRequest()}this.progress==this.level&&this.handleProcessResult(this.json)}customLoadEvent(json){throw new Error("wrong method")}showPage(){}}
113class GamesLeveledFlashQuiz extends GamesFlashQuiz{constructor(el,options){if(super(el,options),this.level=this.options.level,this.medalMinLevel=this.options.medalMinLevel,this.progress=this.options.progress,this.setLevelInformation(),this.blinkLength=this.options.blinkLength,this.nrOfBlinks=this.options.nrOfBlinks,this.isArcade=this.options.isArcade,this.screenId="#levelUpScreen",this.medalBox=document.getElementById(this.options.medalBox).querySelector("img"),this.levelText=document.getElementById(this.options.levelText),this.progressBar=document.getElementById(this.options.progressBar),this.menuBar=document.getElementsByClassName("menubar")[0],this.easierLevel=new EasierLevel(this.options,this.safeObserve.bind(this)),"true"!=options.nomedal&&""!=this.medalBox.src||(this.medalBox.style.display="none"),this.setTaskText(new TextResource(this.options.trLoadingLevel).string()),!document.querySelector(".mia-LevelUpScreen")){window.createVueApplication("legacy-level-up-screen").mount(this.el.querySelector(".mia-LegacyLevelUpScreen"))}waitForElementToBePresent(this.screenId).then(this.initializeLevelUpScreen.bind(this)),this.easierLevel.initializeEasierLevel(this),waitForElementToBePresent(".mia-easierLevelConfirmButton").then(this.initializeLevelDown.bind(this))}initializeLevelUpScreen(){this.screenJQuery=jQuery(this.screenId),this.screenJQuery.find(".levelUpButton").on("click",this.onNextLevelOkClick.bind(this)),this.screenJQuery.find(".lastLevelContinueButton").on("click",this.onNextLevelOkClick.bind(this)),this.options.endingScreenShown?this.showEndingScreen(this.options.endingScreenRobotSrc,this.options.endingScreenLevel,this.options.endingScreenMedalName,this.options.endingScreenAmountOfScoops):this.hideLevelFinalScreen()}setLevelInformation(){var nextMedalLevel=this.options.nextMedalLevel;nextMedalLevel>0&&"true"!=this.options.noNextMedal?(this.el.querySelector(".nextMedalArea").style.display="inline-block",this.el.querySelector(".nextMedalText").innerHTML="after Level: "+nextMedalLevel):this.el.querySelector(".nextMedalArea").style.display="none"}customLoadEvent(json){}showPage(){this.updateProgressBar(),this.levelText.innerHTML="Level: "+this.json.level,this.easierLevel.initializeEasierLevel(this);var nextMedalLevel=this.json.nextMedalLevel;if(nextMedalLevel>0&&!this.json.noNextMedal){this.el.querySelector(".nextMedalArea").style.display="inline-block";var realNextMedalLevel=nextMedalLevel;realNextMedalLevel>0&&realNextMedalLevel<this.json.level&&(realNextMedalLevel=this.json.level),this.el.querySelector(".nextMedalText").innerHTML="after Level: "+realNextMedalLevel}else this.el.querySelector(".nextMedalArea").style.display="none"}initializeLevelDown(element){this.safeObserve(element,"click",this.onLevelDownClick.bind(this))}onNextLevelOkClick(ev){void 0!==ev&&ev.preventDefault(),this.startNextLevel(),this.handleProcessResult()}startNextLevel(){this.showPage(),this.screenJQuery.find(".levelButtons").css("display","flex"),this.screenJQuery.find(".continueButton").css("display","none"),this.isArcade?this.screenJQuery.find(".returnToArcadeButton").css("display","none"):this.screenJQuery.find(".continueButton").css("display","none"),this.hideLevelFinalScreen()}handleWrongAnswer(){var itemId=0|this.numberList[this.progress];this.progress>0&&(this.progress--,this.updateProgressBar());var wrongAnswerPromise=new Promise(function(resolve,reject){var url=new UrlTemplate(this.options.processAnswerUrl).r("PLH_success",this.success).r("PLH_Status",2).r("PLH_MedalType",this.medalType).r("PLH_progress",this.progress).r("PLH_itemId",itemId).r("PLH_nquestion",-2).url;axios(url,{method:"get"}).then((response=>{resolve(response.data)})).catch((error=>{reject(error)}))}.bind(this)),blickingDelay=this.blinkLength*this.nrOfBlinks;new Promise((function(resolve){setTimeout(resolve,blickingDelay)})).then(function(){this.setTaskText(new TextResource(this.options.trLoadingLevel).string()),wrongAnswerPromise.then(this.onWrongAnswerSuccess.bind(this))}.bind(this))}onWrongAnswerSuccess(response){if(this.json=response,0==this.json.numberList.length||null==this.json.textList[0])return this.progress=0,void this.initFlashGame();this.numberList=this.json.numberList,this.textList=this.json.textList,this.questionSoundPaths=this.json.questionSoundPaths,this.resetUI(),this.setToClick(this.numberList[this.progress],this.textList[this.progress]),this.createAndReadAllTextToSpeech()}onSuccess(req){var response=req.data;this.screenJQuery.find(".endingScreenButtons").css("display","none"),this.screenJQuery.find(".levelButtons").css("display","flex"),!this.isArcade&&response.medalReceived?(this.showEndingScreen(response.medalRobotPictureSrc,this.json.level,response.medalName,response.amount),window.invalidateSelectedTask()):null==response.medal||response.medal.endsWith("games/medals/medal_none.svg")?(this.screenJQuery.find(".image").attr("src",response.robotPictureSrc),this.screenJQuery.find(".header").text(new TextResource(this.options.trHeaderWithoutMedal).r("{number}",this.json.level).string()),this.screenJQuery.find(".description").text(new TextResource(this.options.trDescriptionWithoutMedal).r("{number}",this.json.level).r("{coins}",response.amount).string()),this.screenJQuery.find(".levelButtons").css("display","flex"),this.isArcade&&this.screenJQuery.find(".returnToArcadeButton").css("display","inline-block")):(this.medalBox.src=this.json.medal,this.medalBox.style.display="inline",this.screenJQuery.find(".header").text(new TextResource(this.options.trHeaderWithMedal).r("{number}",this.json.level).r("{medalType}",response.medalName).string()),this.screenJQuery.find(".description").text(new TextResource(this.options.trDescriptionWithMedal).r("{number}",this.json.level).r("{coins}",response.amount).r("{medalType}",response.medalName).string()),this.screenJQuery.find(".image").attr("src",response.robotPictureSrc),this.json.medal="games/medals/medal_none.svg",this.json.challengeWasCompleted&&(this.screenJQuery.find(".levelButtons").css("display","none"),this.screenJQuery.find(".challengeCompletedButtons").css("display","inline-block"))),this.json=response;var newLevel="Level: "+this.json.level;if(this.progress==this.numberList.length&&newLevel!=this.levelText.innerHTML){if(this.showLevelFinalScreen(),this.removeAllListeners(),this.updateProgressBar(),0==this.json.amount)return void axios(new UrlTemplate(this.options.processAnswerUrl).r("PLH_success",!0).r("PLH_Status",2).r("PLH_MedalType",this.medalType).r("PLH_progress",this.progress).r("PLH_itemId",-1).r("PLH_nquestion",-2).url,{method:"get"}).then(this.onSuccess.bind(this));this.progress=0,this.numberList=this.json.numberList,this.textList=this.json.textList,this.questionSoundPaths=this.json.questionSoundPaths,this.levelText.innerHTML=newLevel;var nextMedalLevel=this.json.nextMedalLevel;nextMedalLevel>0&&!this.json.noNextMedal?(this.el.querySelector(".nextMedalText").innerHTML="after Level: "+nextMedalLevel,this.el.querySelector(".medalIcon").src=this.json.nextMedalImageSource,this.el.querySelector(".nextMedalArea").style.display="inline-block"):this.el.querySelector(".nextMedalArea").style.display="none"}}onLevelJumpSuccess(req){try{this.json=req.data}catch(e){return void legacyGlobal.handleFailedAJAJRequest()}this.success=!0,this.handleProcessResult(),this.el.querySelector(".modal-header").querySelector(".mia-img").click(),this.startNextLevel()}onLevelDownClick(ev){this.easierLevel.setEasierLevel(this.options.levelJumpUrl,this.onLevelJumpSuccess.bind(this))}showLevelFinalScreen(){this.el.querySelector(".mia-ProgressSection").style.display="none",this.el.querySelector(".mia-svgGameC
113ontainer").style.display="none",this.el.querySelector(".questionContainer").style.display="none";var lessonIntro=this.el.querySelector(".mia-LessonIntro");lessonIntro&&(lessonIntro.style.display="none"),this.changeFeedbackButtonVisibility(!1),this.screenJQuery.css("display","flex")}hideLevelFinalScreen(){this.el.querySelector(".mia-ProgressSection").style.display="",this.el.querySelector(".mia-svgGameContainer").style.display="",this.el.querySelector(".questionContainer").style.display="";var lessonIntro=this.el.querySelector(".mia-LessonIntro");lessonIntro&&(lessonIntro.style.display=""),this.changeFeedbackButtonVisibility(!0),this.screenJQuery.css("display","none")}showEndingScreen(robotSrc,level,medalName,amount){this.showLevelFinalScreen(),this.screenJQuery.find(".endingScreenButtons").css("display","flex"),this.screenJQuery.find(".levelButtons").css("display","none"),this.screenJQuery.find(".title").text(this.options.trCongratulations),this.screenJQuery.find(".image").attr("src",robotSrc),this.screenJQuery.find(".header").text(this.options.trHeaderWithMedal.replace("{number}",level).replace("{medalType}",medalName)),this.screenJQuery.find(".description").text(this.options.trDescriptionWithMedal.replace("{number}",level).replace("{coins}",amount).replace("{medalType}",medalName)),this.screenJQuery.find(".repeatButton").on("click",this.onRepeatMedalClick.bind(this))}onRepeatMedalClick(event){event.preventDefault(),axios(new UrlTemplate(this.options.endingScreenRepeatMedalUrl).url,{method:"get"}).then(this.initFlashGame.bind(this)),this.progress=0,this.hideLevelFinalScreen()}changeFeedbackButtonVisibility(show){var feedbackButton=document.querySelector(".mia-GameFeedbackButton");null!==feedbackButton&&(feedbackButton.style.display=show?"flex":"none")}}
114class GamesFlashlessGeography extends GamesLeveledFlashQuiz{constructor(el,options){super(el,options),this.progressIndicator=new ProgressIndicator(this.el),this.progressIndicator.showProgressIndicator(!0,"#"+this.options.frame,!0),GamesQuizInstance=this,this.playFeedbackSound="on"==this.options.feedbackSound,this.fillColorsEnum=Object.freeze({regular:1,hover:2,correct:3,incorrect:4}),this._toClick=null,this._gameInitialized=!1,this._stateArray=new Array,this._blinkCounter=0,this._itemArray=this.options.ItemArray.split(","),this._geoIdsArray=this.options.GeoIdsArray.split(","),"undefined"!==this._itemArray&&null!==this._itemArray||confirmAI(this.options.couldNotLoadText,this.onConfirmOkButtonClick,(function(){}),!0,!1),jQuery("meta[name=viewport]").attr("content","width=device-width, initial-scale=1"),document.getElementById(this.options.objectId).addEventListener("load",function(){this.initializeScript()}.bind(this))}onConfirmOkButtonClick(){history.back()}fillShape(shape,fillColor){if(this.options.classicColoring)if(shape.hasChildNodes())for(var child=shape.firstChild;null!==child;child=child.nextSibling)this.fillShape(child,fillColor);else if("g"!==shape.nodeName&&shape.style){var color=null;fillColor===this.fillColorsEnum.regular?color=this.getRegularColor(shape):fillColor===this.fillColorsEnum.hover&&(color=this.getColorFromRegular(shape,"hover",50)),color&&(shape.style.fill=color)}}getRegularColor(shape){var regularColor=shape.getAttribute("data-regular-color");return regularColor||(regularColor=window.getComputedStyle(shape,null).fill,shape.setAttribute("data-regular-color",regularColor),regularColor)}getColorFromRegular(shape,key,amount){var color=shape.getAttribute("data-"+key+"-color");if(color)return color;var regularColor=this.getRegularColor(shape);return"#"!==regularColor[0]&&(regularColor=this.rgbToHex(regularColor)),color=this.lightenDarkenColor(regularColor,amount),shape.setAttribute("data-"+key+"-color",color),color}rgbToHex(rgb){return(rgb=rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i))&&4===rgb.length?"#"+("0"+parseInt(rgb[1],10).toString(16)).slice(-2)+("0"+parseInt(rgb[2],10).toString(16)).slice(-2)+("0"+parseInt(rgb[3],10).toString(16)).slice(-2):""}lightenDarkenColor(colorCode,amount){var usePound=!1;"#"===colorCode[0]&&(colorCode=colorCode.slice(1),usePound=!0);var num=parseInt(colorCode,16),r=(num>>16)+amount;r=this.fixColorBoundaries(r);var b=(num>>8&255)+amount;b=this.fixColorBoundaries(b);var g=(255&num)+amount;return(usePound?"#":"")+((g=this.fixColorBoundaries(g))|b<<8|r<<16).toString(16)}fixColorBoundaries(color){return color>255?255:color<0?0:color}
114clearUI(){for(var i=0;i<this._stateArray.length;i++)this.fillShape(this._stateArray[i],this.fillColorsEnum.regular)}resetUI(){this._toClick=null,clearTimeout(this._blinkTimer1),clearTimeout(this._blinkTimer2),this._blinkCounter=0,this.clearUI(),this.removeAllListeners(),this.addAllListeners()}removeAllListeners(){for(var i=0;i<this._stateArray.length;i++)this.stopObserveAllListeners(this._stateArray[i])}setTaskText(string){this.el.querySelector(".mia-questionText").innerHTML=string}setToClick(number,string){this._toClick=number,this.setTaskText(string)}initGame(toClick,taskText){this.addAllListeners(),this._toClick=toClick,this.setTaskText(taskText),this._gameInitialized=!0,this.progressIndicator.hideProgressIndicator()}pushStateIntoArray(state){this._stateArray.push(state)}addListenerToState(state){this.safeObserve(state,"mousedown",function(){this.stateClicked(state)}.bind(this)),this.safeObserve(state,"mouseover",function(){this.fillShape(state,this.fillColorsEnum.hover),state.style.cursor="pointer"}.bind(this)),this.safeObserve(state,"mouseout",function(){this.fillShape(state,this.fillColorsEnum.regular)}.bind(this))}stateClicked(state){var found=!1;if(null!=this._toClick)for(var i=0;i<this._itemArray.length;i++)if(this._itemArray[i]==state.id&&this._geoIdsArray[i]==this._toClick){found=!0,this.stopObserveAllListeners(state),state.style.cursor="default",this.fillShape(state,this.fillColorsEnum.correct),this.userAnswer(!0);break}if(!found){this.removeAllListeners(),this.fillShape(state,this.fillColorsEnum.incorrect);for(i=0;i<this._geoIdsArray.length;i++)if(this._geoIdsArray[i]==this._toClick){this.blink(this.svgDoc.getElementById(this._itemArray[i]));break}this.userAnswer(!1)}}blink(state){this._blinkCounter<this.nrOfBlinks?(this.blinker(state,this._blinkCounter%2),this._blinkCounter++,window.setTimeout(function(){this.blink(state)}.bind(this),this.blinkLength)):(this.blinker(state,!0),this._blinkCounter=0,this.clearUI())}blinker(state,normal){var opacity=normal?1:0;state.style.opacity=opacity}initializeScript(){var svg=this.el.querySelector(".map");this.addViewBoxIfNotExist(svg),this.removeWidthAndHeightAttributes(svg),this.svgDoc=svg.contentDocument,svg.style.opacity=1,this.initFlashGame()}addViewBoxIfNotExist(svg){var svgElement=svg.contentDocument.querySelector("svg");if(!svgElement.hasAttribute("viewBox")){var width=svgElement.getAttribute("width"),height=svgElement.getAttribute("height");null!==width&&null!==height&&svgElement.setAttribute("viewBox","0 0 "+width+" "+height)}}removeWidthAndHeightAttributes(svg){var svgElement=svg.contentDocument.querySelector("svg");svgElement.removeAttribute("width"),svgElement.removeAttribute("height")}addAllListeners(){for(var i=0;i<this._itemArray.length;i++){var item=this.svgDoc.getElementById(this._itemArray[i]);if(null==item||void 0===item)throw new Error('Error in geography game configuration: id "'+this._itemArray[i]+'" was not found in the SVG. (Found '+this._itemArray.length+" items in the database.) Please select Feedback at the bottom of this page to let our tech team know about this problem.");this.pushStateIntoArray(item),this.addListenerToState(item),this.fillShape(item,this.fillColorsEnum.regular)}}}
115class GamePopupContainer extends DOMAttached{constructor(el,options){super(el,options),this.popup=this.el.querySelector(".outerPopup"),this.el.attachedObj=this}loadPopup(url,onPopupLoaded){this.popup.style.display="none",this.el.style.display="block",axios(url,{method:"get"}).then(onPopupLoaded)}showPopup(url){this.loadPopup(url,this.onPopupLoaded.bind(this))}showContent(content,popupCssClass){if(this.el.closest(".GNOMApplication").querySelector(".animationContainer")&&(soundManager.stopAll(),this.el.closest(".GNOMApplication").querySelector(".tabbedApplication").attachedObj.blocked=!1,this.el.closest(".GNOMApplication").querySelector(".animationContainer").style.display="none"),this.popup.innerHTML=content,evalScripts(this.popup),this.popup.style.display="block",popupCssClass&&(this.popup.classList.add(popupCssClass),"playAction"===popupCssClass)){var playActionPopup=this.popup;setTimeout((function(){playActionPopup.style.display="none",playActionPopup.classList.remove("playAction")}),5e3)}var inputEl=this.el.querySelector('input[type="text"]');null!=inputEl&&inputEl.focus()}hidePopup(){this.el.style.display="none"}isPopupVisible(){return"block"==this.el.style.display}onPopupLoaded(req){this.popup.style.display="none",this.el.style.display="block";var json=req.data;if(json.success)this.showContent(json.popup,json.popupCssClass);else{if(null!=json.errorpopup)return void this.showContent(json.errorpopup);this.hidePopup()}}}
116class GamePopup extends DOMAttached{constructor(el,options){super(el,options),this.buttons=this.el.querySelector(".buttonPane").querySelectorAll("input");for(let i=0;i<this.buttons.length;i++)"nolink"!=this.options["button"+i]&&this.safeObserve(this.buttons[i],"click",(ev=>this.onButtonClick(ev,"button"+i)))}onButtonClick(ev,id){if(GenericSoundsInstance.clickSound(),ev.preventDefault(),ev.stopPropagation(),""==this.options[id])null!=this.el.closest(".popupContainer")?this.el.closest(".popupContainer").attachedObj.hidePopup():this.el.closest(".animationContainer").attachedObj.hideAnimation();else{for(var textboxes=this.el.querySelectorAll(".textbox"),url=this.options[id],i=0;i<textboxes.length;i++){id=textboxes[i].id;url=url.replace("PLH_"+id.substr(id.lastIndexOf("_")+1),encodeURIComponent(textboxes[i].querySelector("input").value))}this.el.closest(".tabbedApplication").attachedObj.loadPage(url)}}}
117class GameLoadTabAndPopupButton extends DOMAttached{constructor(el,options){super(el,options),this.popupLink=options.popupLink,this.tabLink=options.tabLink,this.tabApp=this.el.closest(".tabbedApplication").attachedObj,this.safeObserve(this.el.querySelector("input"),"click",this.onClick.bind(this))}onClick(ev){ev.preventDefault(),ev.stopPropagation(),""!=this.tabLink?document.querySelectorAll(".GNOMApplication")[0].querySelector(".popupContainer").attachedObj.loadPopup(this.popupLink,this.onPopupLoaded.bind(this)):document.querySelectorAll(".GNOMApplication")[0].querySelector(".popupContainer").attachedObj.showPopup(this.popupLink)}onPopupLoaded(response){this.popup=response,document.querySelectorAll(".GNOMApplication")[0].querySelector(".popupContainer").attachedObj.onPopupLoaded(this.popup),this.tabApp.loadPageWithOwnSuccessHandler(this.tabLink,this.onPageLoaded.bind(this))}onPageLoaded(response){this.tabApp.currentTab.style.display="none",this.tabApp.selectTab(this.tabApp.findTab(this.tabLink)),this.tabApp.onPageLoaded(response)}}
118class GameList extends ListBase{constructor(el,options){super(el,Object.assign({pagingEffect:"returnToTop"},options))}loadPage(page){super.loadPage(page),this.standardJSONRequest(this.options.url.replace("PLH_pageNum",page))}}
119var xMouse,pageUrl,index,pony,pony1,pony2,pony3,pony4,pony5,pony6,water,water1,water2,prevBtnVis=!1,nextBtnVis=!1;class GameAnimationContainer extends DOMAttached{constructor(el,options){super(el,options),this.el.attachedObj=this,this.popup=this.el.querySelector(".outerPopup")}loadAnimation(url,xMouse){this.xMouse=xMouse;axios(url,{method:"get"}).then(this.onAnimationLoaded.bind(this))}onAnimationLoaded(req){var json=req.data;if(json.success){if(null!=json.successpopup)return void this.showPopup(json.successpopup);switch(this.imgUrl=json.imgUrl,this.petImgUrl=json.petImgUrl,this.pageUrl=json.pageUrl,this.el.closest(".tabbedApplication").attachedObj.blocked=!0,json.animationType){case"Food":this.foodAnimation();break;case"Polish":this.polishAnimation();break;case"Music":this.musicAnimation();break;case"Incubate":this.incubateAnimation();break;case"Sunshine":this.sunshineAnimation();break;case"Blanket":this.blanketAnimation();break;case"Cuddle":this.cuddleAnimation();break;case"Bath":this.bathAnimation();break;case"Play":this.playAnimation();break;case"Trip":this.tripAnimation();break;case"Exercise":this.exerciseAnimation();break;case 11:this.beautySaloonAnimation(json.popup,json.popupWidth,json.popupHeight,json.receivedItems,json.numberOfItems,json.petImgUrl);break;case 12:this.circusAnimation(json.popup,json.popupWidth,json.popupHeight,json.receivedItems,json.numberOfItems);break;case 13:this.shoppingAnimation(json.popup,json.popupWidth,json.popupHeight,json.receivedItems,json.numberOfItems);break;case 14:this.treasureHuntAnimation(json.popup,json.popupWidth,json.popupHeight,json.receivedItems,json.numberOfItems,json.portal);break;case-1:throw new Error("unknown animation type")}}else null!=json.errorpopup&&this.showPopup(json.errorpopup)}showPopup(content,cssClass){this.popup.style.visibility="visible",this.popup.style.display="block",this.el.querySelector("img").style.visibility="hidden",this.el.style.display="block",this.popup.innerHTML=content,evalScripts(this.popup),cssClass&&this.popup.classList.add(cssClass),this.popup.style.display="block";var inputEl=this.el.querySelector('input[type="text"]');null!=inputEl&&inputEl.focus()}hideAnimation(){this.el.style.display="none"}loadImg(name,x,y,img){return img||(img=new Image),img.src=this.options.pictures[name],img.style.position="absolute",img.style.left=x+"px",img.style.top=y+"px",img.style.display="none",img}foodAnimation(){soundManager.stopAll(),this.popup.style.visibility="hidden";var itemList=this.el.closest(".GNOMApplication").querySelector(".ajajScrollList").
119children,img=this.el.querySelector("img");img.src=this.imgUrl,img.width=80,img.height=80,(legacyGlobal.isFirefox||legacyGlobal.isChrome||legacyGlobal.isOpera||legacyGlobal.isIpad||legacyGlobal.isIphone)&&(itemList.length<3||this.xMouse<450?itemList[0].style.visibility="hidden":itemList.length<5||this.xMouse<550?itemList[2].style.visibility="hidden":itemList.length<7||this.xMouse<650?itemList[4].style.visibility="hidden":itemList[6].style.visibility="hidden"),this.xMouse<450?(img.style.top="335px",img.style.left="95px"):this.xMouse<550?(img.style.top="335px",img.style.left="195px"):this.xMouse<650?(img.style.top="335px",img.style.left="295px"):(img.style.top="335px",img.style.left="395px"),img.onload=()=>{const x=this.options.xMouthPet-img.width/2,y=this.options.yMouthPet-img.height/2;this.el.style.display="block",img.style.position="relative",LegacyEffects.move(img,{x:x,y:y,mode:"absolute",duration:.8}),gsap.to(img,{scale:0,duration:.8}),window.setTimeout((()=>GenericSoundsInstance.foodContact1()),800),window.setTimeout((()=>GenericSoundsInstance.foodContact2()),1e3);const tabApp=this.el.closest(".tabbedApplication").attachedObj;this.timer=window.setTimeout((()=>{tabApp.blocked=!1,tabApp.loadPage(this.pageUrl)}),1600)}}polishAnimation(){soundManager.stopAll();var img=this.el.querySelector("img");img.src=this.options.pictures.towel2;var img1=this.el.appendChild(this.loadImg("sparkle",10,50));this.popup.style.visibility="hidden",this.el.style.display="block",img.style.top="90px",img.style.left="10px",img.style.position="relative",GenericSoundsInstance.toweling(),LegacyEffects.move(img,{x:70,y:20,mode:"relative",duration:.3}),LegacyEffects.move(img,{x:-70,y:20,mode:"relative",duration:.3,delay:.3}),LegacyEffects.move(img,{x:70,y:20,mode:"relative",duration:.3,delay:.6}),LegacyEffects.move(img,{x:-70,y:20,mode:"relative",duration:.3,delay:.9}),LegacyEffects.move(img,{x:70,y:20,mode:"relative",duration:.3,delay:1.2}),this.timer=window.setTimeout((function(){GenericSoundsInstance.happyPet()}),1200),LegacyEffects.move(img,{x:-70,y:20,mode:"relative",duration:.3,delay:1.5}),this.timer=window.setTimeout((function(){soundManager.stop("toweling"),img.style.visibility="hidden",img1.style.visibility="visible",LegacyEffects.appear(img1,{duration:.3})}),1800),this.timer=window.setTimeout((function(){LegacyEffects.fade(img1,{duration:.3})}),2200);var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked&&(soundManager.stopAll(),tabApp.blocked=!1,tabApp.loadPage(page))}),2800)}musicAnimation(){GenericSoundsInstance.eggMusic();var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked&&(soundManager.stopAll(),tabApp.blocked=!1,tabApp.loadPage(page))}),37e3)}incubateAnimation(){var backImgEgg=this.el.closest(".GNOMApplication").querySelector(".eggImage");gsap.fromTo(backImgEgg,{backgroundColor:"#DC3401"},{backgroundColor:"#FF5926",duration:.7,clearProps:"backgroundColor"}),gsap.fromTo(backImgEgg,{backgroundColor:"#DC3401"},{backgroundColor:"#FF5926",duration:.7,delay:.7,clearProps:"backgroundColor"}),gsap.fromTo(backImgEgg,{backgroundColor:"#DC3401"},{backgroundColor:"#ffbbfa",duration:.7,delay:1.4,clearProps:"backgroundColor"});var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked&&(tabApp.blocked=!1,tabApp.loadPage(page))}),2100)}sunshineAnimation(){var backImgEgg=this.el.closest(".GNOMApplication").querySelector(".eggImage");gsap.fromTo(backImgEgg,{backgroundColor:"#FAD400"},{backgroundColor:"#FFFE8B",duration:.7,clearProps:"backgroundColor"}),gsap.fromTo(backImgEgg,{backgroundColor:"#FAD400"},{backgroundColor:"#FFFE8B",duration:.7,delay:.7,clearProps:"backgroundColor"}),gsap.fromTo(backImgEgg,{backgroundColor:"#FAD400"},{backgroundColor:"#ffbbfa",duration:.7,delay:1.4,clearProps:"backgroundColor"});var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked&&(tabApp.blocked=!1,tabApp.loadPage(page))}),2100)}blanketAnimation(){this.popup.style.visibility="hidden";var blanket=this.el.querySelector("img");blanket.src=this.options.pictures.blanket,blanket.style.top="166px",blanket.style.left="10px",blanket.style.display="none",blanket.style.zIndex=2e3;var pillow=this.el.closest(".GNOMApplication").querySelector(".imageBox").appendChild(this.loadImg("pillow",0,15));this.el.closest(".GNOMApplication").querySelector(".eggImage").style.zIndex=1e3,this.el.style.display="block",LegacyEffects.appear(blanket,{duration:1}),LegacyEffects.appear(pillow,{duration:1}),this.timer=window.setTimeout((function(){GenericSoundsInstance.yawn()}),900);var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked&&(tabApp.blocked=!1,tabApp.loadPage(page))}),5e3)}cuddleAnimation(){var petImg=new Image;petImg.src=this.petImgUrl,petImg.style.position="absolute",petImg.style.top="47px",petImg.style.left="10px",petImg.style.display="block",petImg.style.height="260px",this.el.appendChild(petImg);var heart=this.loadImg("heart",50,140,this.el.querySelector("img")),heart1=this.el.appendChild(this.loadImg("heart",90,240)),heart2=this.el.appendChild(this.loadImg("heart",140,200));this.popup.style.visibility="hidden",this.el.closest(".GNOMApplication").querySelector(".imageBox").style.visibility="hidden",this.el.style.display="block",g
119sap.to(petImg,{x:5,duration:.1,repeat:9,yoyo:!0,ease:"none"}),LegacyEffects.appear(heart,{duration:.3}),LegacyEffects.move(heart,{x:0,y:-80,mode:"relative",duration:.3,delay:.3}),LegacyEffects.fade(heart,{duration:.3,delay:.6}),this.timer=window.setTimeout((function(){LegacyEffects.appear(heart1,{duration:.3}),LegacyEffects.move(heart1,{x:0,y:-150,mode:"relative",duration:.3,delay:.3}),LegacyEffects.fade(heart1,{duration:.3,delay:.6})}),300),this.timer=window.setTimeout((function(){LegacyEffects.appear(heart2,{duration:.3}),LegacyEffects.move(heart2,{x:0,y:-100,mode:"relative",duration:.3,delay:.3}),LegacyEffects.fade(heart2,{duration:.3,delay:.6})}),600);var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked=!1,tabApp.loadPage(page)}),2300)}bathAnimation(){GenericSoundsInstance.runningWater();var shower=this.el.appendChild(this.loadImg("shower",15,-10));this.water=this.el.appendChild(this.loadImg("water1",40,45)),this.water1=this.el.appendChild(this.loadImg("water2",40,45)),this.water2=this.el.appendChild(this.loadImg("water3",40,45)),this.el.querySelector("img").style.visibility="hidden",this.popup.style.visibility="hidden",this.el.style.display="block",shower.style.display="block",this.waterAnimation(0);var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){soundManager.stop("runningWater"),tabApp.blocked=!1,tabApp.loadPage(page)}),6e3)}waterAnimation(index){var water=this.water,water1=this.water1,water2=this.water2;if(water.style.display="block",this.timer=window.setTimeout((function(){water1.style.display="block",water.style.display="none"}),100),this.timer=window.setTimeout((function(){water2.style.display="block",water1.style.display="none"}),200),index<30){14==index&&GenericSoundsInstance.happyPet(),index++;var act=this;this.timer=window.setTimeout((function(){act.waterAnimation(index)}),200)}}playAnimation(){var ball=this.el.appendChild(this.loadImg("ball",0,200));ball.style.display="block";var ball1=this.el.appendChild(this.loadImg("ball",100,650));ball1.style.display="block",this.el.querySelector("img").style.visibility="hidden",this.popup.style.visibility="hidden",this.el.style.display="block";const ballTimeline=gsap.timeline(),ball1Timeline=gsap.timeline();ballTimeline.add(LegacyEffects.move(ball,{x:325,y:415,mode:"absolute",duration:.97,ease:"none"})).add(LegacyEffects.move(ball,{x:650,y:200,mode:"absolute",duration:.97,ease:"none"})).add(LegacyEffects.move(ball,{x:518,y:0,mode:"absolute",duration:.6,ease:"none"})).add(LegacyEffects.move(ball,{x:243,y:415,mode:"absolute",duration:1.24,ease:"none"})).add(LegacyEffects.move(ball,{x:0,y:109,mode:"absolute",duration:.98,ease:"none"})).add(LegacyEffects.move(ball,{x:87,y:0,mode:"absolute",duration:.35,ease:"none"})).add(LegacyEffects.move(ball,{x:416,y:415,mode:"absolute",duration:1.32,ease:"none"})).add(LegacyEffects.move(ball,{x:650,y:120,mode:"absolute",duration:.94,ease:"none"})).add(LegacyEffects.fade(ball,{duration:.5})),ball1Timeline.add(LegacyEffects.move(ball1,{x:400,y:415,mode:"absolute",duration:1,ease:"none"})).add(LegacyEffects.move(ball1,{x:70,y:0,mode:"absolute",duration:1.33,ease:"none"})).add(LegacyEffects.move(ball1,{x:0,y:88,mode:"absolute",duration:.28,ease:"none"})).add(LegacyEffects.move(ball1,{x:260,y:415,mode:"absolute",duration:1.04,ease:"none"})).add(LegacyEffects.move(ball1,{x:535,y:0,mode:"absolute",duration:1.24,ease:"none"})).add(LegacyEffects.move(ball1,{x:650,y:174,mode:"absolute",duration:.52,ease:"none"})).add(LegacyEffects.move(ball1,{x:490,y:415,mode:"absolute",duration:.72,ease:"none"})).add(LegacyEffects.move(ball1,{x:215,y:0,mode:"absolute",duration:1.24,ease:"none"})).add(LegacyEffects.fade(ball1,{duration:.5})),this.timer=window.setTimeout((function(){GenericSoundsInstance.happyPet()}),1e3),this.timer=window.setTimeout((function(){GenericSoundsInstance.happyPet()}),5e3);var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked=!1,tabApp.loadPage(page)}),8e3)}tripAnimation(){GenericSoundsInstance.outside();var leftFoot=this.el.appendChild(this.loadImg("leftFoot",0,150)),leftFoot1=this.el.appendChild(this.loadImg("leftFoot",0,150)),leftFoot2=this.el.appendChild(this.loadImg("leftFoot",0,150)),leftFoot3=this.el.appendChild(this.loadImg("leftFoot",0,150)),leftFoot4=this.el.appendChild(this.loadImg("leftFoot",0,150)),leftFoot5=this.el.appendChild(this.loadImg("leftFoot",0,150)),rightFoot=this.el.appendChild(this.loadImg("rightFoot",0,150)),rightFoot1=this.el.appendChild(this.loadImg("rightFoot",0,150)),rightFoot2=this.el.appendChild(this.loadImg("rightFoot",0,150)),rightFoot3=this.el.appendChild(this.loadImg("rightFoot",0,150)),rightFoot4=this.el.appendChild(this.loadImg("rightFoot",0,150)),rightFoot5=this.el.appendChild(this.loadImg("rightFoot",0,150));this.el.querySelector("img").style.visibility="hidden",this.popup.style.visibility="hidden",this.el.style.display="block",this.walkAnimation(0,50,70,rightFoot,rightFoot1,rightFoot2,leftFoot,leftFoot1,leftFoot2);var act=this;this.timer=window.setTimeout((function(){act.walkAnimation(0,170,190,rightFoot3,rightFoot4,rightFoot5,leftFoot3,leftFoot4,leftFoot5)}),3e3);var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){soundManager.stop("outside"),tabApp.blocked=!1,tabApp.loadPage(page)}),14e3)}walkAnimation(index,xDistanceRightFoot,xDistanceLeftFoot,rightFoot,rightFoot1,rightFoot2,leftFoot,leftFoot1,leftFoot2){var xR=xDistanceRightFoot,xL=xDistanceLeftFoot,r=rightFoot,r1=rightFoot1,r2=rightFoot2,l=leftFoot,l1=leftFoot1,l2=leftFoot2;r.style.left=xR+"px",xR+=40,r1.style.left=xR+"px",xR+=40,r2.style.left=xR+"px",l.style.left=xL+"px",xL+=40,l1.style.left=xL+"px",xL+=40,l2.style.left=xL+"px";const appearTimeline=gsap.timeline(),fadeTimeline=gsap.timeline();if(appearTimeline.add(LegacyEffects.appear(r,{duration:.5})),appearTimeline.add(LegacyEffects.appear(l,{duration:.5})),appearTimeline.add(LegacyEffects.appear(r1,{duration:.5})),appearTimeline.add(LegacyEffects.appear(l1,{duration:.5})),appearTimeline.add(LegacyEffects.appear(r2,{duration:.5})),appearTimeline.add(LegacyEffects.appear(l2,{duration:.5})),this.timer=window.setTimeout((function(){fadeTimeline.add(LegacyEffects.fade(r,{duration:.5})),fadeTimeline.add(LegacyEffects.fade(l,{duration:.5})),fadeTimeline.add(LegacyEffects.fade(r1,{duration:.5})),fadeTimeline.add(LegacyEffects.fade(l1,{duration:.5})),fadeTimeline.add(LegacyEffects.fade(r2,{duration:.5})),fadeTimeline.add(LegacyEffects.fade(l2,{duration:.5}))}),2e3),index<1){var act=this;this.timer=window.setTimeout((function(){act.walkAnimation(index+1,xR+160,xL+160,r,r1,r2,l,l1,l2)}),6e3)}}exerciseAnimation(){var petImg=new Image;petImg.src=this.petImgUrl,petImg.style.position="absolute",petImg.style.top="110px",petImg.style.left="10px",petImg.style.height="260px",petImg.style.display="block",this.el.appendChild(petImg),this.el.closest(".GNOMApplication").querySelector(".imageBox").style.visibility="hidden",this.el.querySelector("img").style.visibility="hidden",this.popup.style.visibility="hidden",this.el.style.display="block",GenericSoundsInstance.jump(),this.timer=window.setTimeout((function(){GenericSoundsInstance.jump()}),1600),this.timer=window.setTimeout((function(){GenericSoundsInstance.jump()}),3200),this.timer=window.setTimeout((function(){GenericSoundsInstance.jump()}),4800),gsap.to(petImg,{y:"+=-100",duration:.8,yoyo:!0,repeat:7,ease:"none"});var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked=!1,tabApp.loadPage(page)}),6800)}beautySaloonAnimation(popup,width,height,receivedItems,numberOfItems,petImgUrl){this.setButtonsInv
119isible(),GenericSoundsInstance.hairdryer(),this.showPopup(popup,"playAction"),this.el.querySelector("img").style.visibility="hidden",this.el.querySelector(".outerPopup").querySelector("img").style.visibility="hidden";var petImg=new Image;petImg.src=petImgUrl,petImg.style.position="absolute",petImg.style.top="50px",petImg.style.left="50px",petImg.style.display="block",petImg.style.height="260px",this.el.appendChild(petImg);this.el.appendChild(this.loadImg("hair0",200,70));var hairdryer1=this.el.appendChild(this.loadImg("hair1",200,70)),hairdryer2=this.el.appendChild(this.loadImg("hair2",200,70));this.el.style.display="block",this.timer=window.setTimeout((function(){for(var i=0;i<11;i++){let delay=.6*i;LegacyEffects.appear(hairdryer1,{duration:.3,delay:delay}),LegacyEffects.fade(hairdryer1,{duration:.3,delay:delay+.3}),LegacyEffects.appear(hairdryer2,{duration:.3,delay:delay+.3}),LegacyEffects.fade(hairdryer2,{duration:.3,delay:delay+.6})}}),1e3);var act=this;this.timer=window.setTimeout((function(){act.itemAppearAnimation(receivedItems,numberOfItems)}),2e3);var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked=!1,tabApp.loadPage(page)}),15e3)}circusAnimation(popup,width,height,receivedItems,numberOfItems){this.setButtonsInvisible(),this.showPopup(popup,"playAction");var random=[Math.floor(4*Math.random())+1,Math.floor(4*Math.random())+1];random[0]==random[1]&&(4==random[0]&&(random[0]=2),random[0]++);for(var ponies=[[],[]],i=0;i<2;i++)for(var j=1;j<=7;j++)ponies[i].push(this.el.appendChild(this.loadImg("pony"+random[i]+j,450,100)));if(ponies[0][0].style.display="block",1==random[1]||2==random[1]){var shortSound=new Boolean(!1);this.timer=window.setTimeout((function(){GenericSoundsInstance.circus()}),1e3)}else{shortSound=new Boolean(!0);this.timer=window.setTimeout((function(){GenericSoundsInstance.circus2()}),1e3)}this.ponyAnimation(450,ponies[0][0],ponies[0][1],ponies[0][2],ponies[0][3],ponies[0][4],ponies[0][5],ponies[0][6]);var act=this;this.timer=window.setTimeout((function(){act.ponyAnimation(450,ponies[1][0],ponies[1][1],ponies[1][2],ponies[1][3],ponies[1][4],ponies[1][5],ponies[1][6])}),3e3);act=this;if(this.timer=window.setTimeout((function(){act.itemAppearAnimation(receivedItems,numberOfItems)}),3e3),shortSound){var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked=!1,tabApp.loadPage(page)}),14500)}else{tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked=!1,tabApp.loadPage(page)}),27500)}}ponyAnimation(xDistance,p,p1,p2,p3,p4,p5,p6){var pony=p,pony1=p1,pony2=p2,pony3=p3,pony4=p4,pony5=p5,pony6=p6,x=xDistance;if(pony6.style.display="none",pony.style.left=x+"px",pony.style.display="block",this.timer=window.setTimeout((function(){pony1.style.left=x+"px",pony1.style.display="block",pony.style.display="none"}),100),this.timer=window.setTimeout((function(){x-=3,pony2.style.left=x+"px",pony2.style.display="block",pony1.style.display="none"}),200),this.timer=window.setTimeout((function(){x-=8,pony3.style.left=x+"px",pony3.style.display="block",pony2.style.display="none"}),300),this.timer=window.setTimeout((function(){x-=6,pony4.style.left=x+"px",pony4.style.display="block",pony3.style.display="none"}),400),this.timer=window.setTimeout((function(){x-=4,pony5.style.left=x+"px",pony5.style.display="block",pony4.style.display="none"}),500),this.timer=window.setTimeout((function(){x-=7,pony6.style.left=x+"px",pony6.style.display="block",pony5.style.display="none"}),600),x>150){var act=this;this.timer=window.setTimeout((function(){act.ponyAnimation(x,pony,pony1,pony2,pony3,pony4,pony5,pony6)}),600)}else this.timer=window.setTimeout((function(){pony6.style.display="none"}),600)}shoppingAnimation(popup,width,height,receivedItems,numberOfItems){GenericSoundsInstance.shoppingMall(),this.setButtonsInvisible(),this.showPopup(popup,"playAction"),this.el.querySelector(".outerPopup").querySelector("img").style.visibility="hidden";var gift=this.el.appendChild(this.loadImg("gift1",200,40));gift.style.display="block";var gift1=this.el.appendChild(this.loadImg("gift2",200,40)),gift2=this.el.appendChild(this.loadImg("gift3",200,40)),gift3=this.el.appendChild(this.loadImg("gift4",200,40)),gift4=this.el.appendChild(this.loadImg("gift5",200,40)),gift5=this.el.appendChild(this.loadImg("gift6",200,40));gift.style.display="block",this.timer=window.setTimeout((function(){gift1.style.display="block",gift.style.display="none"}),350),this.timer=window.setTimeout((function(){gift2.style.display="block",gift1.style.display="none"}),450),this.timer=window.setTimeout((function(){gift3.style.display="block",gift2.style.display="none"}),550),this.timer=window.setTimeout((function(){gift4.style.display="block",gift3.style.display="none"}),650),this.timer=window.setTimeout((function(){gift5.style.display="block",gift4.style.display="none"}),750);var act=this;this.timer=window.setTimeout((function(){act.itemAppearAnimation(receivedItems,numberOfItems)}),1e3);var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked=!1,tabApp.loadPage(page)}),17500)}treasureHuntAnimation(popup,width,height,receivedItems,numberOfItems){this.setButtonsInv
119isible(),this.showPopup(popup,"playAction"),this.el.querySelector(".outerPopup").querySelector("img").style.visibility="hidden";var treasure=this.el.appendChild(this.loadImg("treasureChest1",200,40));treasure.style.display="block";var treasure1=this.el.appendChild(this.loadImg("treasureChest2",200,40)),treasure2=this.el.appendChild(this.loadImg("treasureChest3",200,40)),treasure3=this.el.appendChild(this.loadImg("treasureChest4",200,40)),treasure4=this.el.appendChild(this.loadImg("treasureChest5",200,40));treasure.style.display="block",this.timer=window.setTimeout((function(){treasure1.style.display="block",treasure.style.display="none"}),350),this.timer=window.setTimeout((function(){treasure2.style.display="block",treasure1.style.display="none"}),550),this.timer=window.setTimeout((function(){treasure3.style.display="block",treasure2.style.display="none"}),750),this.timer=window.setTimeout((function(){treasure4.style.display="block",treasure3.style.display="none"}),950);var act=this;this.timer=window.setTimeout((function(){act.itemAppearAnimation(receivedItems,numberOfItems)}),1e3);var tabApp=this.el.closest(".tabbedApplication").attachedObj,page=this.pageUrl;this.timer=window.setTimeout((function(){tabApp.blocked=!1,tabApp.loadPage(page)}),11e3)}itemAppearAnimation(receivedItems,numberOfItems){var items=receivedItems;const timeline=gsap.timeline();switch(numberOfItems){case 5:var item5=new Image;item5.src=items.substring(items.lastIndexOf(";")+1),item5.style.position="absolute",item5.style.left="500px",item5.style.top="350px",item5.style.width="80px",item5.style.height="80px",item5.style.display="none",this.el.appendChild(item5),timeline.add(LegacyEffects.appear(item5,{duration:2})),items=items.substring(0,items.lastIndexOf(";"));case 4:var item4=new Image;item4.src=items.substring(items.lastIndexOf(";")+1),item4.style.position="absolute",item4.style.left="400px",item4.style.top="350px",item4.style.width="80px",item4.style.height="80px",item4.style.display="none",this.el.appendChild(item4),timeline.add(LegacyEffects.appear(item4,{duration:2}),0),items=items.substring(0,items.lastIndexOf(";"));case 3:var item3=new Image;item3.src=items.substring(items.lastIndexOf(";")+1),item3.style.position="absolute",item3.style.left="300px",item3.style.top="350px",item3.style.width="80px",item3.style.height="80px",item3.style.display="none",this.el.appendChild(item3),timeline.add(LegacyEffects.appear(item3,{duration:2}),0),items=items.substring(0,items.lastIndexOf(";"));case 2:var item2=new Image;item2.src=items.substring(items.lastIndexOf(";")+1),item2.style.position="absolute",item2.style.left="200px",item2.style.top="350px",item2.style.width="80px",item2.style.height="80px",item2.style.display="none",this.el.appendChild(item2),timeline.add(LegacyEffects.appear(item2,{duration:2}),0),items=items.substring(0,items.lastIndexOf(";"));case 1:var item1=new Image;item1.src=items.substring(items.lastIndexOf(";")+1),item1.style.position="absolute",item1.style.left="100px",item1.style.top="350px",item1.style.width="80px",item1.style.height="80px",item1.style.display="none",this.el.appendChild(item1),timeline.add(LegacyEffects.appear(item1,{duration:2}),0),items=items.substring(0,items.lastIndexOf(";"));break;case 0:var scoopImage=new Image;scoopImage.src=this.options.pictures.scoops,scoopImage.style.position="absolute",scoopImage.style.left="300px",scoopImage.style.top="350px",scoopImage.style.display="none",this.el.appendChild(scoopImage),timeline.add(LegacyEffects.appear(scoopImage,{duration:2})),items=items.substring(0,items.lastIndexOf(";"))}}setButtonsInvisible(){this.el.closest(".GNOMApplication").querySelector(".prevBtn").style.display="none",this.el.closest(".GNOMApplication").querySelector(".nextBtn").style.display="none"}}
120class GNOMStatBox extends DOMAttached{constructor(el,options){super(el,options),this.linkEl=this.el.querySelector("a"),null!=this.linkEl&&null!=this.options.link&&this.safeObserve(this.linkEl,"click",this.onClick.bind(this))}onClick(ev){this.el.closest(".tabbedApplication").attachedObj.findAndLoadTab(this.options.link),ev.preventDefault(),ev.stopPropagation()}}
121class GNOMRefreshingStatBox extends DOMAttached{constructor(el,options){super(el,options),null!=this.options.hatchTR&&(this.el.closest(".tabbedApplication").querySelector(".eggHatchDesc").innerHTML=this.options.hatchTR);var timer=setTimeout(this.onTimer.bind(this),1e4);this.el.closest(".tabbedApplication").attachedObj.registerTimer(timer),null!=this.options.petPageUrl&&this.el.closest(".tabbedApplication").attachedObj.activatePlaceholder("petTab",this.el.querySelector(".gnomName").innerHTML,this.options.petPageUrl),setTimeout(this.onPopupTimer.bind(this),0)}onPopupTimer(){if(null!=this.options.hatching&&("None"!=this.options.hatching?this.el.closest(".tabbedApplication").querySelector(".imageBox .hatch").style.display="block":this.el.closest(".tabbedApplication").querySelector(".imageBox .hatch").style.display="none"),null!=this.options.hatchPopupUrl&&(this.el.closest(".GNOMApplication").querySelector(".popupContainer").attachedObj.isPopupVisible()||this.el.closest(".GNOMApplication").querySelector(".popupContainer").attachedObj.showPopup(this.options.hatchPopupUrl)),null!=this.options.petNamePopup&&(this.el.closest(".GNOMApplication").querySelector(".popupContainer").attachedObj.isPopupVisible()||this.el.closest(".GNOMApplication").querySelector(".popupContainer").attachedObj.showPopup(this.options.petNamePopup)),null!=this.options.timer){var actionTimer=this.el.closest(".tabbedApplication").querySelector(".actionTimer");null!=actionTimer&&actionTimer.attachedObj.setTime(this.options.timer)}}onTimer(){axios(this.options.url,{method:"get"}).then((response=>{this.onBoxLoaded(response)}))}onBoxLoaded(req){try{var json=req.data}catch(e){return}json.success&&replaceElement(this.el,json.box)}}
122class GNOMPetImageBox extends DOMAttached{constructor(el,options){super(el,options),this.el.zIndex=300,this.link=options.link,""!=this.link&&(this.safeObserve(this.el,"click",this.onClick.bind(this)),this.safeObserve(this.el,"mouseover",this.onMouseOver.bind(this)),this.el.classList.add("clickable"))}onClick(ev){GenericSoundsInstance.pickUpSound(),this.el.closest(".GNOMApplication").querySelector(".popupContainer").attachedObj.showPopup(this.link)}onMouseOver(ev){}}
123var marBottom,height,width;class GNOMListItem extends DOMAttached{constructor(el,options){super(el,options),this.behaviour=options.behaviour,this.link=options.link,this.locked=!1,this.el.querySelector(".petImageContainer")&&"None"!=this.behaviour?this.safeObserve(this.el.querySelector(".petImageContainer"),"click",this.onClick.bind(this)):this.el.querySelector("img")&&"None"!=this.behaviour&&this.safeObserve(this.el.querySelector("img"),"click",this.onClick.bind(this))}onClick(ev){if(null!=this.el.closest(".GNOMApplication")&&!this.el.closest(".GNOMApplication").querySelector(".tabbedApplication").attachedObj.blocked){if(this.locked)return;if(null!=this.el.closest(".GNOMPage")&&this.el.closest(".GNOMPage").classList.contains("deactivated"))return;switch(this.behaviour){case"MultiSelect":this.el.classList.contains("selected")?this.el.classList.remove("selected"):this.el.classList.add("selected");break;case"Popup":GenericSoundsInstance.pickUpSound(),this.el.closest(".GNOMApplication").querySelector(".popupContainer").attachedObj.showPopup(this.link);break;case"Link":GenericSoundsInstance.clickSound(),this.el.closest(".tabbedApplication").attachedObj.loadPage(this.link);break;case"CallbackSelect":this.el.classList.contains("shared")?this.el.classList.remove("shared"):this.el.classList.add("shared");var list=this.el.closest(".gnomList").attachedObj;this.locked=!0,list.loadPage(list.options.currentPage,this.options.link.replace("PLH_switch",this.el.classList.contains("shared")));break;case"Animation":this.el.closest(".GNOMApplication").querySelector(".animationContainer").attachedObj.loadAnimation(this.link,ev.clientX)}}}onLoadPage(pageEl){this.locked=!1}onMouseOver(ev){this.height=this.el.querySelector("img").height,this.width=this.el.querySelector("img").width,this.el.closest(".GNOMApplication").querySelector(".tabbedApplication").attachedObj.blocked||(this.el.querySelector("img").style.width=this.width+7+"px",this.el.querySelector("img").style.height=this.height+7+"px",this.marBottom=this.window.getComputedStyle(el).getPropertyValue("marginBottom"),"18px"==this.marBottom&&(this.el.style.marginBottom="11px"))}onMouseOut(ev){this.el.querySelector("img").style.width=this.width+"px",this.el.querySelector("img").style.height=this.height+"px",this.el.style.marginBottom=this.marBottom}}
124class GNOMActionTimer extends DOMAttached{constructor(el,options){super(el,options),this.el.attachedObj=this,this.popup=this.el.closest(".GNOMPage").querySelector(".outerPopup2"),this.time=options.start,this.printTime(),this.time>0&&(this.el.closest(".GNOMPage").classList.add("deactivated"),this.setVisible()),this.timer=setInterval(this.onTimer.bind(this),1e3),this.el.closest(".tabbedApplication").attachedObj.registerInterval(this.timer)}onTimer(){if(this.time<=0)return clearInterval(this.timer),this.setInVisible(),void this.el.closest(".GNOMPage").classList.remove("deactivated");this.time--,this.printTime()}printTime(){this.el.innerHTML=Math.floor(this.time/60)+":"+(this.time%60<10?"0":"")+this.time%60}setVisible(){this.popup.style.display="inline"}setInVisible(){this.popup.style.display="none"}setTime(val){clearInterval(this.timer),this.time=val,this.printTime(),this.time>0&&this.setVisible(),this.timer=setInterval(this.onTimer.bind(this),1e3),this.el.closest(".tabbedApplication").attachedObj.registerInterval(this.timer)}}
125class FriendshipRequestButton extends DOMAttached{constructor(el,options){super(el,options),this.options=options,this.el=document.getElementById(el),this.acceptBtn=document.getElementById(this.options.acceptBtn),this.conReqLit=document.getElementById(this.options.conReqLit),this.responseMsg=document.getElementById(this.options.responseMessage),this.responseMsg&&(this.responseMsg.style.display="none"),this.acceptBtn&&this.safeObserve(this.acceptBtn,"click",this.onAccept.bind(this))}onAccept(event){event.preventDefault(),event.stopPropagation(),this.acceptBtn.style.display="none",this.responseMsg.style.display="",axios(new UrlTemplate(this.options.acceptLink).url,{method:"get"}).then(this.onResponse.bind(this))}onResponse(req){var json=req.data;this.conReqLit.innerHTML=json.status,this.conReqLit.style.display=""}}
126class FriendshipRequest extends DOMAttached{constructor(el,options){super(el,options),this.options=options,this.el=document.getElementById(el),this.triggerOK=document.getElementById(this.options.triggerOK),this.triggerClose=document.getElementById(this.options.triggerClose),this.statusfield=document.getElementById(this.options.statusfield),this.inputCode=document.getElementById(this.options.inputCode),this.pbody=document.getElementById(this.options.pbody),this.overlay=document.getElementById(this.options.overlay),this.safeObserve(this.triggerOK,"click",this.onConfirm.bind(this)),null!=this.options.inputCodeShowTrigger&&(this.inputCodeShowTrigger=document.getElementById(this.options.inputCodeShowTrigger),this.safeObserve(this.inputCodeShowTrigger,"click",this.showCodeInput.bind(this)))}
126showCodeInput(event){this.inputCode.style.display="block",this.inputCodeShowTrigger.style.display="none"}onConfirm(event){var icode="";null!=this.inputCode&&null!=this.inputCode&&(null!=(icode=this.inputCode.querySelector("input").value)&&""!=icode||null!=this.inputCodeShowTrigger||(icode="invalid"));axios(new UrlTemplate(this.options.link).r("PLH_friendcode",icode).url,{method:"post",headers:{"content-type":"application/x-www-form-urlencoded"}}).then(this.onResponse.bind(this))}onResponse(req){var json=req.data;json.end&&(this.pbody.innerHTML="",json.reload&&this.safeObserve(this.triggerClose,"click",this.onClose.bind(this))),this.statusfield.innerHTML=json.ret,this.overlay.position()}onClose(req){window.location.reload()}}
127var FilterableBox={initializeFilterableBox:function(tagName){this.filterTagName=tagName,this.filterBtnDiv=this.el.querySelector(".filterBtns"),null!=this.filterBtnDiv&&this.setupFilterBtns()},setupFilterBtns:function(opacityOnly){this.filterBtnDiv.querySelectorAll(this.filterTagName).forEach((btn=>{this.options.memberFilter==btn.getAttribute("class")?btn.classList.add("selected"):btn.classList.remove("selected"),opacityOnly||(this.safeObserve(btn,"click",this.onFilterBtnClick.bind(this)),this.safeObserve(btn,"mouseover",this.onFilterBtnOver.bind(this)),this.safeObserve(btn,"mouseout",this.onFilterBtnOut.bind(this)))}))},onFilterBtnClick:function(ev){if(ev.preventDefault(),ev.stopPropagation(),!this.requestRunning&&!this.disablePaging){var btn=ev.target.closest(this.filterTagName);this.options.memberFilter!=btn.getAttribute("class").replace(/\s*selected\s*/,"")&&(this.options.memberFilter=btn.getAttribute("class").replace(/\s*selected\s*/,""),this.setupFilterBtns(!0),this.options.currentPage=0,this.refresh())}},onFilterBtnOver:function(ev){var btn=ev.target.closest(this.filterTagName);btn.hover||(btn.hover=!0,btn.classList.add("selected"))},onFilterBtnOut:function(ev){var btn=ev.target.closest(this.filterTagName);btn.hover=!1,this.options.memberFilter==btn.getAttribute("class").replace(/\s*selected\s*/,"")?btn.classList.add("selected"):btn.classList.remove("selected")}};
128class FeedStatusMessage extends DOMAttached{constructor(el,options){super(el,options),this.commentBox=this.el.querySelector(".newComment"),this.textbox=this.el.querySelector(".newComment").querySelector("textarea"),this.showCommentBoxLink=this.el.closest(".mia-FeedEntry").querySelector("div.mia-timespan a"),this.safeObserve(this.el.querySelector(".newComment .button"),"click",this.onSubmitClick.bind(this)),this.safeObserve(this.showCommentBoxLink,"click",this.onCommentClick.bind(this)),this.loadMoreComments=this.el.querySelector(".loadMoreComments"),this.progressIndicator=new ProgressIndicator(this.el);window.createVueApplication("legacy-smiley-selector").mount(this.el.querySelector(".mia-smileySelectorWrapper")),null!=this.loadMoreComments&&this.safeObserve(this.loadMoreComments,"click",this.loadMore.bind(this)),0==this.el.getElementsByClassName("feedComment").length?this.el.style.display="none":this.showCommentBoxLink.style.display="none"}onCommentClick(ev){ev.preventDefault(),ev.stopPropagation(),this.showCommentBoxLink.style.display="none",this.el.style.display="none"===this.el.style.display?"":"none"}onSubmitClick(ev){ev.preventDefault(),ev.stopPropagation();var text=this.textbox.value;""!=text.trim()?text.length>this.options.maxLength?confirmAI(this.options.errorTooLongText,(function(){}),(function(){}),!0,!1):(this.progressIndicator.showProgressIndicator(),axios(new UrlTemplate(this.options.addUrl).r("PLH_text",this.textbox.value).url,{method:"get"}).then(this.onLoaded.bind(this))):confirmAI(this.options.errorEmptyText,(function(){}),(function(){}),!0,!1)}onLoadException(ex){console.log(ex.message),this.progressIndicator.hideProgressIndicator()}onLoaded(res){this.progressIndicator.hideProgressIndicator();var json=res.data;if(json.success){if(json.hideLastComment){var commentContainer=this.commentBox.previousElementSibling;if(commentContainer){var lastComment=jQuery(commentContainer).find(".feedComment").last();lastComment&&lastComment.hide()}}var newComment=document.createElement("div");this.commentBox.parentNode.insertBefore(newComment,this.commentBox),jQuery(newComment).html(json.comment),this.textbox.value=""}else confirmAI(json.errorMessage,(function(){}),(function(){}),!0,!1)}loadMore(ev){ev.preventDefault(),ev.stopPropagation();axios(this.options.feedCommentsUrl,{method:"get"}).then(this.onResponse.bind(this))}onResponse(req){var json;try{json=req.data}catch(e){this.write(e)}var div=document.createElement("div");div.innerHTML=json.comments,this.el.insertBefore(div,this.el.firstChild.nextSibling),this.options.feedCommentsUrl=json.feedCommentsUrl,json.more
128Comments?this.el.firstChild.innerHTML=json.moreCommentsString:this.loadMoreComments.style.display="none";for(var scripts=div.getElementsByTagName("script"),ix=0;ix<scripts.length;ix++)eval(scripts[ix].text)}}
129class FeedLoader extends DOMAttached{constructor(el,options){super(el,options);var node=document.getElementById("feedControl"),img=document.createElement("img");img.setAttribute("src",this.options.imageSource),img.setAttribute("alt",this.options.loadingTR),node.appendChild(img),this.loadFeed()}write(text){document.getElementById("feedControl").innerHTML=text}loadFeed(){axios(this.options.feedUrl,{method:"get"}).then(this.onResponse.bind(this))}onResponse(req){var json;try{json=req.data}catch(e){this.write(e)}this.write(json.feed);for(var scripts=document.getElementById("feedControl").getElementsByTagName("script"),ix=0;ix<scripts.length;ix++)eval(scripts[ix].text);0!=json.unreadcomments&&null!=document.getElementById("unreadcomments")&&(document.getElementById("unreadcomments").innerHTML=json.unreadcomments,document.getElementById("unreadcomments").style.display="block")}}
130class FeedComment extends DOMAttached{constructor(el,options){super(el,options),this.deleteButton=this.el.querySelector(".deleteBtn"),null!=this.deleteButton&&this.safeObserve(this.deleteButton,"click",(ev=>this.onDeleteClick(ev,this.el)))}onDeleteClick(ev,comment){ev.preventDefault(),ev.stopPropagation(),this.dialogComment=comment,confirmAI(this.options.trReallyDelete,this.onDeleteConfirm.bind(this),this.onDeleteCancel.bind(this),!0,!0)}onDeleteConfirm(){var id=this.dialogComment.querySelector(".id").innerHTML;axios(new UrlTemplate(this.options.deleteUrl).r("PLH_smsgc",id).url,{method:"get"}).then((response=>{this.onDeleted(this.dialogComment,response)}))}onDeleteCancel(){}onDeleted(comment,res){res.data.success&&comment.remove()}}
131class FeatureLevelSelector extends DOMAttached{constructor(el,options){super(el,options),this.selector=null,this.triggeringControl=null,this.triggeringControlEventHandle=null,this.previousValue=null,this.selector=document.getElementById(el).querySelector(".featureLevelSelector"),this.selector.addEventListener("change",this.onValueChange.bind(this)),this.previousValue=this.selector.value,void 0!==this.options.warningTriggeringControl&&(this.triggeringControl=document.getElementById(this.options.warningTriggeringControl),this.triggeringControlEventHandle=this.triggeringControl.addEventListener("click",this.onTriggeringControlClicked.bind(this)))}onValueChange(event){this.selector.value!=this.options.fullSocialEnumValue&&(this.previousValue=this.selector.value)}onTriggeringControlClicked(event){this.selector.value==this.options.fullSocialEnumValue&&(event.preventDefault(),event.stopPropagation(),confirmAI(this.options.warningTR,this.onConfirm.bind(this),this.onCancel.bind(this),!0,!0))}onConfirm(){var link=document.getElementById(this.triggeringControl).querySelector("a");link?window.location.href=document.getElementById(link).getAttribute("href"):(this.triggeringControlEventHandle.preventDefault(),this.triggeringControlEventHandle.stopPropagation(),this.triggeringControl.simulate("click"))}onCancel(){this.selector.value=this.previousValue}}
132class ExternalHyperLink extends DOMAttached{constructor(el){super(el),this.safeObserve(this.el,"click",this.onClick.bind(this))}onClick(ev){window.open(this.el.getAttribute("href")),ev.preventDefault(),ev.stopPropagation()}}
133class EnhancedButton extends DOMAttached{constructor(el,options){super(el,options),this.oneClickOnly=this.options.oneClickOnly,this.safeObserve(this.el,"click",this.onclick.bind(this)),this.safeObserve(this.el,"mousedown",this.onMouseDown.bind(this)),this.safeObserve(this.el,"mouseup",this.onMouseUp.bind(this)),this.safeObserve(this.el,"mouseout",this.onMouseUp.bind(this))}onclick(ev){this.oneClickOnly&&setTimeout(function(){this.el.disabled=!0}.bind(this),0)}onMouseDown(ev){this.el.disabled||this.el.classList.add("pushed")}onMouseUp(ev){this.el.classList.remove("pushed")}}
134var DragonWorldServerInterface=null;class DragonWorld extends DOMAttached{constructor(el,options){super(el,options),this.hatchedDragonType="PLH_hatchedDragonType",this.dragonHatID="PLH_dragonHatID",this.dragonBeardID="PLH_dragonBeardID",this.dragonColorID="PLH_dragonColorID",this.dragonStat1="PLH_dragonStat1",this.dragonStat2="PLH_dragonStat2",this.dragonStat3="PLH_dragonStat3",this.dragonStat4="PLH_dragonStat4",this.dragonStat5="PLH_dragonStat5",this.items="PLH_dragonWorldItemList",this.currentChallengePosition="PLH_dragonWorldCurrentChallengePosition",this.gold="PLH_gold",this.goldTag="PLH_goldTag",this.score="PLH_score",this.miniGameID="PLH_dragonWorldMinigameID",this.gameId="PLH_gameId",this.categoryNameTRKey="PLH_categoryNameTRKey",this.trophyId="PLH_trophyId",this.trophyColor="PLH_trophyColor",DragonWorldServerInterface=this}resetHatchingCounterAndAddHatchedDragon(type){axios(new UrlTemplate(this.options.hatchedDragonUrl).r(this.hatchedDragonType,type).url,{method:"get"})}customizeDragon(hatID,beardID,colorID){axios(new UrlTemplate(this.options.customizeUrl).r(this.dragonHatID,hatID).r(this.dragonBeardID,beardID).r(this.dragonColorID,colorID).url,{method:"get"})}saveDragonStatsAndIncreaseHatchingCounter(stat1,stat2,stat3,stat4,stat5){axios(new UrlTemplate(this.options.statsUrl).r(this.dragonStat1,stat1).r(this.dragonStat2,stat2).r(this.dragonStat3,stat3).r(this.dragonStat4,stat4).r(this.dragonStat5,stat5).url,{method:"get"})}storeItems(items){axios(new UrlTemplate(this.options.itemUrl).r(this.items,items).url,{method:"get"})}storeCurrentChallengePosition(currentChallengePosition){axios(new UrlTemplate(this.options.storeCurrentChallengePositionUrl).r(this.currentChallengePosition,currentChallengePosition).url,{method:"get"})}hasMemberEnoughMoney(amount,onTrueCallback,onFalseCallback){axios(new UrlTemplate(this.options.checkGoldUrl).r(this.gold,amount).url,{method:"get"}).then((response=>{response.data.success?onTrueCallback():onFalseCallback()}))}callForMoneyTransaction(amount,tag){axios(new UrlTemplate(this.options.callForMoneyTransactionUrl).r(this.gold,amount).r(this.goldTag,tag).url,{method:"get"})}saveHighscore(score,miniGameID){axios(new UrlTemplate(this.options.saveHighScoreUrl).r(this.score,score).r(this.miniGameID,miniGameID).url,{method:"get"})}getGameContent(gameId,callback){axios(new UrlTemplate(this.options.getGameContentUrl).r(this.gameId,gameId).url,{method:"get"}).then((response=>{callback(response.data.gameContent)}))}setGamePassed(gameId){axios(new UrlTemplate(this.options.setGamePassedUrl).r(this.gameId,gameId).url,{method:"get"})}resetGamesPassedInCategory(categoryNameTRKey){axios(new UrlTemplate(this.options.resetGamesPassedInCategoryUrl).r(this.categoryNameTRKey,categoryNameTRKey).url,{method:"get"})}awardTrophy(trophy,color){void 0===color&&(color=0),axios(new UrlTemplate(this.options.giveTrophyUrl).r(this.trophyId,trophy.id).r(this.trophyColor,color).url,{method:"get"})}}
135class DragonChoose extends DOMAttached{constructor(el,options){super(el,options),this.options=options,this.el=document.getElementById(el),this.okButton=document.getElementById(this.options.okButton),this.safeObserve(this.okButton,"click",this.onConfirm.bind(this))}onConfirm(event){var first_color,second_color;event.preventDefault(),event.stopPropagation();for(var first_dragons=document.getElementsByName("firstDragon"),i=0;i<first_dragons.length;i++)1==first_dragons[i].checked&&(first_color=first_dragons[i].value);for(var second_dragons=document.getElementsByName("secondDragon"),j=0;j<second_dragons.length;j++)1==second_dragons[j].checked&&(second_color=second_dragons[j].value);var colors=[first_color,second_color];first_color==second_color?confirmAI(this.options.trSameDragons,(function(){}),(function(){}),!0,!1):axios(new UrlTemplate(this.options.link).r("PLH_CDragonColor",colors).url,{method:"post",headers:{"content-type":"application/x-www-form-urlencoded"}}).then(this.onResponse.bind(this))}onResponse(){window.location.reload()}}
136class DesignstudioEditor extends DOMAttached{constructor(el,options){super(el,options),this.progressIndicator=new ProgressIndicator(this.el),this.progressIndicator.showProgressIndicator();var svgPath=options.svgPath;""!=svgPath&&jQuery.get(svgPath,(function(data){var svgContent=(new XMLSerializer).serializeToString(data.documentElement);initializeDesignStudio(options,svgContent)})),this.progressIndicator.hideProgressIndicator()}}
137class DeleteMessageDesign extends PopupEmailPreview{constructor(el,options){super(el,options),this.subjectBox=document.getElementById(options.subjectBox),this.messageBox=document.getElementById(options.messageBox),this.itemId=options.itemId,this.emailAddress=options.emailAddress}getParameters(){return{PLH_subject:this.subjectBox.value,PLH_message:this.messageBox.value}}}
138class ControlSwitcher extends DOMAttached{constructor(el,options){super(el,options),this.initiallyShownControl
138=document.getElementById(options.initiallyShownControl),this.initiallyHiddenControl=document.getElementById(options.initiallyHiddenControl),this.clickableControl=document.getElementById(options.clickableControl),this.safeObserve(this.clickableControl,"click",this.onClick.bind(this))}onClick(ev){ev.preventDefault(),this.initiallyShownControl.style.display="none",this.initiallyHiddenControl.style.display="block"}}
139class Collapser extends DOMAttached{constructor(el,options){super(el,options),this.collapsedIds=this.options.collapsedIds.split(" "),this.afterwardsIds=this.options.afterwardsIds.split(" "),this.link=this.el.querySelector(".collapserLink"),this.safeObserve(this.link,"click",this.onClick.bind(this))}onClick(ev){this.afterwardsIds.forEach((function(id){document.getElementById(id).style.display="none"})),this.collapsedIds.forEach((function(id){document.getElementById(id).style.display="block"}))}}
140class CloseButton extends DOMAttached{constructor(el,options){super(el,options),this.safeObserve(this.el.querySelector(".TriggerControl"),"click",this.onClick.bind(this))}onClick(ev){if(this.options.showLink)location.href=this.options.url;else for(var ids=this.options.ids.split(","),i=0;i<ids.length;i++){document.getElementById(ids[i]).style.display="none"}}}
141var BusinessSimulationServerInterface=null;class BusinessSimulation extends DOMAttached{constructor(el,options){super(el,options),this.itemId="PLH_itemId",this.itemIsOnSale="PLH_isOnSale",this.machine="PLH_machine",this.gold="PLH_gold",this.goldTag="PLH_goldTag",this.rangeStart="PLH_rangeStart",this.amountToLoad="PLH_amountToLoad",this.objectCategory="PLH_ObjectCategory",BusinessSimulationServerInterface=this}redirectToAdvertising(){window.location.href=this.options.advertisingUrl}setItemOnSale(itemId){axios(new UrlTemplate(this.options.salesUrl).r(this.itemId,parseInt(itemId)).r(this.itemIsOnSale,!0).url,{method:"get"})}setItemOffSale(itemId){axios(new UrlTemplate(this.options.salesUrl).r(this.itemId,parseInt(itemId)).r(this.itemIsOnSale,!1).url,{method:"get"})}buyMachine(itemId,machine){axios(new UrlTemplate(this.options.machineUrl).r(this.itemId,parseInt(itemId)).r(this.machine,parseInt(machine)).url,{method:"get"})}callForMoneyTransaction(amount,tag){axios(new UrlTemplate(this.options.callForMoneyTransactionUrl).r(this.gold,amount).r(this.goldTag,tag).url,{method:"get"})}checkForGold(amount,onTrueCallback,onFalseCallback){axios(new UrlTemplate(this.options.checkGoldUrl).r(this.gold,amount).url,{method:"get"}).then((response=>{response.data.success?onTrueCallback():onFalseCallback()}))}loadItems(category,onTrueCallback){axios(new UrlTemplate(this.options.loadItemsUrl).r(this.objectCategory,category).url,{method:"get"}).then((response=>{onTrueCallback(response.data.items)}))}loadItemGraphInformation(itemId,onTrueCallback){axios(new UrlTemplate(this.options.loadItemInfoUrl).r(this.itemId,itemId).url,{method:"get"}).then((response=>{onTrueCallback(response.data.stats)}))}}
142class AwardScoops extends DOMAttached{constructor(el,options){super(el,options),this.messageSelector=this.el.querySelector(".messageSelector"),this.messageInput=this.el.querySelector(".messageInput").querySelector("input"),this.safeObserve(this.messageSelector,"change",this.onMessageSelected.bind(this))}onMessageSelected(ev){0!=this.messageSelector.selectedIndex&&(this.messageInput.value=this.messageSelector.options[this.messageSelector.selectedIndex].value,this.messageSelector.selectedIndex=0)}}
143class Animation extends DOMAttached{constructor(el,options){super(el,options),this.nextFrame=1,this.increment=1,this.timer=null,this.timer=setInterval(this.fadeIn.bind(this),100),setInterval(function(){var posX=this.nextFrame*this.options.width;this.el.style.backgroundPosition="-"+posX+"px 0px",this.nextFrame+=this.increment,(this.nextFrame>=this.options.tilecount||this.nextFrame<0)&&(this.options.rewind?(this.increment=-this.increment,this.nextFrame+=this.increment):this.nextFrame=0)}.bind(this),this.options.speed)}fadeIn(){this.el.querySelector(".hiddenimg").complete&&(this.el.style.visibility="visible",clearInterval(this.timer))}}
144class ActiveRatingBar extends DOMAttached{constructor(el,options){super(el,options),this.options.showDescription&&(this.desc=this.el.querySelector("ul").querySelectorAll("li")),this.stars=this.el.querySelectorAll("span.star"),this.rating=this.el.querySelector(".ratingValue"),this.safeObserve(this.el,"mouseover",this.onMouseOver.bind(this)),this.safeObserve(this.el,"mouseout",this.onMouseOut.bind(this)),this.safeObserve(this.el,"click",this.onClick.bind(this))}onMouseOver(ev){ev.preventDefault(),ev.stopPropagation();var star=ev.target.closest("span");null!=star&&star.classList.contains("star")&&this.updateStars(star)}onMouseOut(ev){ev.preventDefault(),ev.stopPropagation();var _star=ev.target.closest("span");if(null!=_star&&_star.classList.contains("star")){var rating=this.rating.value,star=null;
144this.stars.forEach((function(el){0==--rating&&(star=el)})),this.updateStars(star)}}updateStars(star){var count=0,starMode=null!=star?"On":"Off";this.stars.forEach((function(el){"On"==starMode?(++count,el.style.background="url("+this.options.starOnSrc+") top left no-repeat"):el.style.background="url("+this.options.starOffSrc+") top left no-repeat",star==el&&(starMode="Off")})),this.options.showDescription&&this.desc.forEach((function(el){-1==--count?"none"==window.getComputedStyle(el).getPropertyValue("display")&&(el.style.display=block):"none"!=window.getComputedStyle(el).getPropertyValue("display")&&(el.style.display=none)}))}onClick(ev){ev.preventDefault(),ev.stopPropagation();var star=ev.target.closest("span");if(null!=star&&star.classList.contains("star")){var count;for(count=0;count<this.stars.length&&this.stars[count]!=star;++count);this.rating.value=count+1}}}
145//# sourceMappingURL=maps/website-js.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.