// source --> https://mindset-wins.cash/wp-content/plugins/wplms_plugin/includes/../assets/js/singleunit.js?ver=1.9.3 
!function(e){var t={};function n(i){if(t[i])return t[i].exports;var a=t[i]={i:i,l:!1,exports:{}};return e[i].call(a.exports,a,a.exports,n),a.l=!0,a.exports}n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(i,a,function(t){return e[t]}.bind(null,a));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=1)}([function(e,t,n){e.exports=function(){"use strict";(function(){for(var e=0,t=["ms","moz","webkit","o"],n=0;n<t.length&&!window.requestAnimationFrame;++n)window.requestAnimationFrame=window[t[n]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[t[n]+"CancelAnimationFrame"]||window[t[n]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(t,n){var i=(new Date).getTime(),a=Math.max(0,16-(i-e)),r=window.setTimeout((function(){t(i+a)}),a);return e=i+a,r}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})})(),function(){if("function"==typeof window.CustomEvent)return!1;function e(e,t){t=t||{bubbles:!1,cancelable:!1,detail:void 0};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n}e.prototype=window.Event.prototype,window.CustomEvent=e}(),function(e){try{return new CustomEvent("test"),!1}catch(e){}function t(t,n){n=n||{bubbles:!1,cancelable:!1};var i=document.createEvent("MouseEvent");return i.initMouseEvent(t,n.bubbles,n.cancelable,e,0,0,0,0,0,!1,!1,!1,!1,0,null),i}t.prototype=Event.prototype,e.MouseEvent=t}(window);var e=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},t=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}(),n=function e(t,n,i){null===t&&(t=Function.prototype);var a=Object.getOwnPropertyDescriptor(t,n);if(void 0===a){var r=Object.getPrototypeOf(t);return null===r?void 0:e(r,n,i)}if("value"in a)return a.value;var s=a.get;return void 0!==s?s.call(i):void 0},i=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},a=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],i=!0,a=!1,r=void 0;try{for(var s,o=e[Symbol.iterator]();!(i=(s=o.next()).done)&&(n.push(s.value),!t||n.length!==t);i=!0);}catch(e){a=!0,r=e}finally{try{!i&&o.return&&o.return()}finally{if(a)throw r}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")},r=function t(n,i,a,r){e(this,t);var s=this;function o(e){e.stopPropagation(),document.removeEventListener("mouseup",o),document.removeEventListener("mousemove",l),s.eventBus.dispatchEvent(new CustomEvent("handleend",{detail:{handle:s}}))}function l(e){e.stopPropagation(),s.eventBus.dispatchEvent(new CustomEvent("handlemove",{detail:{mouseX:e.clientX,mouseY:e.clientY}}))}this.position=n,this.constraints=i,this.cursor=a,this.eventBus=r,this.el=document.createElement("div"),this.el.className="croppr-handle",this.el.style.cursor=a,this.el.addEventListener("mousedown",(function(e){e.stopPropagation(),document.addEventListener("mouseup",o),document.addEventListener("mousemove",l),s.eventBus.dispatchEvent(new CustomEvent("handlestart",{detail:{handle:s}}))}))},s=function(){function n(t,i,a,r){e(this,n),this.x1=t,this.y1=i,this.x2=a,this.y2=r}return t(n,[{key:"set",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return this.x1=null==e?this.x1:e,this.y1=null==t?this.y1:t,this.x2=null==n?this.x2:n,this.y2=null==i?this.y2:i,this}},{key:"width",value:function(){return Math.abs(this.x2-this.x1)}},{key:"height",value:function(){return Math.abs(this.y2-this.y1)}},{key:"resize",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[0,0],i=this.x1+this.width()*n[0],a=this.y1+this.height()*n[1];return this.x1=i-e*n[0],this.y1=a-t*n[1],this.x2=this.x1+e,this.y2=this.y1+t,this}},{key:"scale",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0,0],n=this.width()*e,i=this.height()*e;return this.resize(n,i,t),this}},{key:"move",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=this.width(),i=this.height();return e=null===e?this.x1:e,t=null===t?this.y1:t,this.x1=e,this.y1=t,this.x2=e+n,this.y2=t+i,this}},{key:"getRelativePoint",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0],t=this.width()*e[0],n=this.height()*e[1];return[t,n]}},{key:"getAbsolutePoint",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0],t=this.x1+this.width()*e[0],n=this.y1+this.height()*e[1];return[t,n]}},{key:"constrainToRatio",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0,0],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"height";if(null!==e){switch(this.width(),this.height(),n){case"height":this.resize(this.width(),this.width()*e,t);break;case"width":this.resize(1*this.height()/e,this.height(),t);break;default:this.resize(this.width(),this.width()*e,t)}return this}}},{key:"constrainToBoundary",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[0,0],i=this.getAbsolutePoint(n),r=a(i,2),s=r[0],o=r[1],l=s,c=o,d=e-s,u=t-o,p=-2*n[0]+1,m=-2*n[1]+1,h=null,_=null;switch(p){case-1:h=l;break;case 0:h=2*Math.min(l,d);break;case 1:h=d}switch(m){case-1:_=c;break;case 0:_=2*Math.min(c,u);break;case 1:_=u}if(this.width()>h){var w=h/this.width();this.scale(w,n)}if(this.height()>_){var v=_/this.height();this.scale(v,n)}return this}},{key:"constrainToSize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[0,0],r=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null;if(r&&(r>1?(e=1*t/r,i*=r):r<1&&(t=e*r,n=1*i/r)),e&&this.width()>e){var s=e,o=null===r?this.height():t;this.resize(s,o,a)}if(t&&this.height()>t){var l=null===r?this.width():e,c=t;this.resize(l,c,a)}if(n&&this.width()<n){var d=n,u=null===r?this.height():i;this.resize(d,u,a)}if(i&&this.height()<i){var p=null===r?this.width():n,m=i;this.resize(p,m,a)}return this}}]),n}();function o(e){e.preventDefault();var t=e.changedTouches[0];t.target.dispatchEvent(new MouseEvent({touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup"}[e.type],{bubbles:!0,cancelable:!0,view:window,clientX:t.clientX,clientY:t.clientY,screenX:t.screenX,screenY:t.screenY}))}var l=[{position:[0,0],constraints:[1,0,0,1],cursor:"nw-resize"},{position:[.5,0],constraints:[1,0,0,0],cursor:"n-resize"},{position:[1,0],constraints:[1,1,0,0],cursor:"ne-resize"},{position:[1,.5],constraints:[0,1,0,0],cursor:"e-resize"},{position:[1,1],constraints:[0,1,1,0],cursor:"se-resize"},{position:[.5,1],constraints:[0,0,1,0],cursor:"s-resize"},{position:[0,1],constraints:[0,0,1,1],cursor:"sw-resize"},{position:[0,.5],constraints:[0,0,0,1],cursor:"w-resize"}];function c(e,t){return Number(Math.round(e+"e"+t)+"e-"+t)}return function(a){function r(t,n){var a=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return e(this,r),i(this,(r.__proto__||Object.getPrototypeOf(r)).call(this,t,n,a))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(r,a),t(r,[{key:"getValue",value:function(e){return n(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"getValue",this).call(this,e)}},{key:"setImage",value:function(e){return n(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"setImage",this).call(this,e)}},{key:"destroy",value:function(){return n(r.prototype.__proto__||Object.getPrototypeOf(r.prototype),"destroy",this).call(this)}},{key:"moveTo",value:function(e,t){return this.box.move(e,t),this.redraw(),null!==this.options.onCropEnd&&this.options.onCropEnd(this.getValue()),this}},{key:"resizeTo",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[.5,.5];return this.box.resize(e,t,n),this.redraw(),null!==this.options.onCropEnd&&this.options.onCropEnd(this.getValue()),this}},{key:"scaleBy",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[.5,.5];return this.box.scale(e,t),this.redraw(),null!==this.options.onCropEnd&&this.options.onCropEnd(this.getValue()),this}},{key:"reset",value:function(){return this.box=this.initializeBox(this.options),this.redraw(),null!==this.options.onCropEnd&&this.options.onCropEnd(this.getValue()),this}}]),r}(function(){function n(t,i){var a=this,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(e(this,n),this.options=n.parseOptions(i||{}),!t.nodeName&&null==(t=document.querySelector(t)))throw"Unable to find element.";if(!t.getAttribute("src"))throw"Image src not provided.";this._initialized=!1,this._restore={parent:t.parentNode,element:t},r||(0===t.width||0===t.height?t.onload=function(){a.initialize(t)}:this.initialize(t))}return t(n,[{key:"initialize",value:function(e){this.createDOM(e),this.options.convertToPixels(this.cropperEl),this.attachHandlerEvents(),this.attachRegionEvents(),this.attachOverlayEvents(),this.box=this.initializeBox(this.options),this.redraw(),this._initialized=!0,null!==this.options.onInitialize&&this.options.onInitialize(this)}},{key:"createDOM",value:function(e){var t;this.containerEl=document.createElement("div"),this.containerEl.className="croppr-container",this.eventBus=this.containerEl,(t=this.containerEl).addEventListener("touchstart",o),t.addEventListener("touchend",o),t.addEventListener("touchmove",o),this.cropperEl=document.createElement("div"),this.cropperEl.className="croppr",this.imageEl=document.createElement("img"),this.imageEl.setAttribute("src",e.getAttribute("src")),this.imageEl.setAttribute("alt",e.getAttribute("alt")),this.imageEl.className="croppr-image",this.imageClippedEl=this.imageEl.cloneNode(),this.imageClippedEl.className="croppr-imageClipped",this.regionEl=document.createElement("div"),this.regionEl.className="croppr-region",this.overlayEl=document.createElement("div"),this.overlayEl.className="croppr-overlay";var n=document.createElement("div");n.className="croppr-handleContainer",this.handles=[];for(var i=0;i<l.length;i++){var a=new r(l[i].position,l[i].constraints,l[i].cursor,this.eventBus);this.handles.push(a),n.appendChild(a.el)}this.cropperEl.appendChild(this.imageEl),this.cropperEl.appendChild(this.imageClippedEl),this.cropperEl.appendChild(this.regionEl),this.cropperEl.appendChild(this.overlayEl),this.cropperEl.appendChild(n),this.containerEl.appendChild(this.cropperEl),e.parentElement.replaceChild(this.containerEl,e)}},{key:"setImage",value:function(e){var t=this;return this.imageEl.onload=function(){t.box=t.initializeBox(t.options),t.redraw()},this.imageEl.src=e,this.imageClippedEl.src=e,this}},{key:"destroy",value:function(){this._restore.parent.replaceChild(this._restore.element,this.containerEl)}},{key:"initializeBox",value:function(e){var t=e.startSize.width,n=e.startSize.height,i=new s(0,0,t,n);i.constrainToRatio(e.aspectRatio,[.5,.5]);var a=e.minSize,r=e.maxSize;i.constrainToSize(r.width,r.height,a.width,a.height,[.5,.5],e.aspectRatio);var o=this.cropperEl.offsetWidth,l=this.cropperEl.offsetHeight;i.constrainToBoundary(o,l,[.5,.5]);var c=this.cropperEl.offsetWidth/2-i.width()/2,d=this.cropperEl.offsetHeight/2-i.height()/2;return i.move(c,d),i}},{key:"redraw",value:function(){var e=this,t=Math.round(this.box.width()),n=Math.round(this.box.height()),i=Math.round(this.box.x1),a=Math.round(this.box.y1),r=Math.round(this.box.x2),s=Math.round(this.box.y2);window.requestAnimationFrame((function(){e.regionEl.style.transform="translate("+i+"px, "+a+"px)",e.regionEl.style.width=t+"px",e.regionEl.style.height=n+"px",e.imageClippedEl.style.clip="rect("+a+"px, "+r+"px, "+s+"px, "+i+"px)";for(var o=e.box.getAbsolutePoint([.5,.5]),l=o[0]-e.cropperEl.offsetWidth/2>>31,c=o[1]-e.cropperEl.offsetHeight/2>>31,d=-2*((l^c)+c+c+4)+8,u=0;u<e.handles.length;u++){var p=e.handles[u],m=p.el.offsetWidth,h=p.el.offsetHeight,_=i+t*p.position[0]-m/2,w=a+n*p.position[1]-h/2;p.el.style.transform="translate("+Math.round(_)+"px, "+Math.round(w)+"px)",p.el.style.zIndex=d==u?5:4}}))}},{key:"attachHandlerEvents",value:function(){var e=this.eventBus;e.addEventListener("handlestart",this.onHandleMoveStart.bind(this)),e.addEventListener("handlemove",this.onHandleMoveMoving.bind(this)),e.addEventListener("handleend",this.onHandleMoveEnd.bind(this))}},{key:"attachRegionEvents",value:function(){var e=this.eventBus;function t(t){t.stopPropagation(),e.dispatchEvent(new CustomEvent("regionmove",{detail:{mouseX:t.clientX,mouseY:t.clientY}}))}function n(i){i.stopPropagation(),document.removeEventListener("mouseup",n),document.removeEventListener("mousemove",t),e.dispatchEvent(new CustomEvent("regionend",{detail:{mouseX:i.clientX,mouseY:i.clientY}}))}this.regionEl.addEventListener("mousedown",(function(i){i.stopPropagation(),document.addEventListener("mouseup",n),document.addEventListener("mousemove",t),e.dispatchEvent(new CustomEvent("regionstart",{detail:{mouseX:i.clientX,mouseY:i.clientY}}))})),e.addEventListener("regionstart",this.onRegionMoveStart.bind(this)),e.addEventListener("regionmove",this.onRegionMoveMoving.bind(this)),e.addEventListener("regionend",this.onRegionMoveEnd.bind(this))}},{key:"attachOverlayEvents",value:function(){var e=this,t=null;function n(t){t.stopPropagation(),e.eventBus.dispatchEvent(new CustomEvent("handlemove",{detail:{mouseX:t.clientX,mouseY:t.clientY}}))}function i(a){a.stopPropagation(),document.removeEventListener("mouseup",i),document.removeEventListener("mousemove",n),1!==e.box.width()||1!==e.box.height()?e.eventBus.dispatchEvent(new CustomEvent("handleend",{detail:{mouseX:a.clientX,mouseY:a.clientY}})):e.box=t}this.overlayEl.addEventListener("mousedown",(function(a){a.stopPropagation(),document.addEventListener("mouseup",i),document.addEventListener("mousemove",n);var r=e.cropperEl.getBoundingClientRect(),o=a.clientX-r.left,l=a.clientY-r.top;t=e.box,e.box=new s(o,l,o+1,l+1),e.eventBus.dispatchEvent(new CustomEvent("handlestart",{detail:{handle:e.handles[4]}}))}))}},{key:"onHandleMoveStart",value:function(e){var t=e.detail.handle,n=[1-t.position[0],1-t.position[1]],i=this.box.getAbsolutePoint(n),r=a(i,2),s=r[0],o=r[1];this.activeHandle={handle:t,originPoint:n,originX:s,originY:o},null!==this.options.onCropStart&&this.options.onCropStart(this.getValue())}},{key:"onHandleMoveMoving",value:function(e){var t=e.detail,n=t.mouseX,i=t.mouseY,a=this.cropperEl.getBoundingClientRect();n-=a.left,i-=a.top,n<0?n=0:n>a.width&&(n=a.width),i<0?i=0:i>a.height&&(i=a.height);var r=this.activeHandle.originPoint.slice(),o=this.activeHandle.originX,l=this.activeHandle.originY,c=this.activeHandle.handle,d=1===c.constraints[0],u=1===c.constraints[1],p=1===c.constraints[2],m=1===c.constraints[3],h=(m||u)&&(d||p),_=m||u?o:this.box.x1,w=m||u?o:this.box.x2,v=d||p?l:this.box.y1,f=d||p?l:this.box.y2;_=m?n:_,w=u?n:w,v=d?i:v,f=p?i:f;var g=!1,y=!1;if((m||u)&&(g=m?n>o:n<o),(d||p)&&(y=d?i>l:i<l),g){var b=_;_=w,w=b,r[0]=1-r[0]}if(y){var x=v;v=f,f=x,r[1]=1-r[1]}var k=new s(_,v,w,f);if(this.options.aspectRatio){var E=this.options.aspectRatio,S=!1;h?S=i>k.y1+E*k.width()||i<k.y2-E*k.width():(d||p)&&(S=!0);var q=S?"width":"height";k.constrainToRatio(E,r,q)}var C=this.options.minSize,N=this.options.maxSize;k.constrainToSize(N.width,N.height,C.width,C.height,r,this.options.aspectRatio);var O=this.cropperEl.offsetWidth,M=this.cropperEl.offsetHeight;k.constrainToBoundary(O,M,r),this.box=k,this.redraw(),null!==this.options.onCropMove&&this.options.onCropMove(this.getValue())}},{key:"onHandleMoveEnd",value:function(e){null!==this.options.onCropEnd&&this.options.onCropEnd(this.getValue())}},{key:"onRegionMoveStart",value:function(e){var t=e.detail,n=t.mouseX,i=t.mouseY,a=this.cropperEl.getBoundingClientRect();n-=a.left,i-=a.top,this.currentMove={offsetX:n-this.box.x1,offsetY:i-this.box.y1},null!==this.options.onCropStart&&this.options.onCropStart(this.getValue())}},{key:"onRegionMoveMoving",value:function(e){var t=e.detail,n=t.mouseX,i=t.mouseY,a=this.currentMove,r=a.offsetX,s=a.offsetY,o=this.cropperEl.getBoundingClientRect();n-=o.left,i-=o.top,this.box.move(n-r,i-s),this.box.x1<0&&this.box.move(0,null),this.box.x2>o.width&&this.box.move(o.width-this.box.width(),null),this.box.y1<0&&this.box.move(null,0),this.box.y2>o.height&&this.box.move(null,o.height-this.box.height()),this.redraw(),null!==this.options.onCropMove&&this.options.onCropMove(this.getValue())}},{key:"onRegionMoveEnd",value:function(e){null!==this.options.onCropEnd&&this.options.onCropEnd(this.getValue())}},{key:"getValue",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if(null===e&&(e=this.options.returnMode),"real"==e){var t=this.imageEl.naturalWidth,n=this.imageEl.naturalHeight,i=this.imageEl.getBoundingClientRect(),a=i.width,r=i.height,s=t/a,o=n/r;return{x:Math.round(this.box.x1*s),y:Math.round(this.box.y1*o),width:Math.round(this.box.width()*s),height:Math.round(this.box.height()*o)}}if("ratio"==e){var l=this.imageEl.getBoundingClientRect(),d=l.width,u=l.height;return{x:c(this.box.x1/d,3),y:c(this.box.y1/u,3),width:c(this.box.width()/d,3),height:c(this.box.height()/u,3)}}if("raw"==e)return{x:Math.round(this.box.x1),y:Math.round(this.box.y1),width:Math.round(this.box.width()),height:Math.round(this.box.height())}}}],[{key:"parseOptions",value:function(e){var t=null,n={width:null,height:null},i={width:null,height:null},a={width:100,height:100,unit:"%"},r="real",s=null,o=null,l=null,c=null,d=null;void 0!==e.aspectRatio&&("number"==typeof e.aspectRatio?d=e.aspectRatio:e.aspectRatio instanceof Array&&(d=e.aspectRatio[1]/e.aspectRatio[0]));var u=null;void 0!==e.maxSize&&null!==e.maxSize&&(u={width:e.maxSize[0]||null,height:e.maxSize[1]||null,unit:e.maxSize[2]||"px"});var p=null;void 0!==e.minSize&&null!==e.minSize&&(p={width:e.minSize[0]||null,height:e.minSize[1]||null,unit:e.minSize[2]||"px"});var m=null;void 0!==e.startSize&&null!==e.startSize&&(m={width:e.startSize[0]||null,height:e.startSize[1]||null,unit:e.startSize[2]||"%"});var h=null;"function"==typeof e.onInitialize&&(h=e.onInitialize);var _=null;"function"==typeof e.onCropStart&&(_=e.onCropStart);var w=null;"function"==typeof e.onCropEnd&&(w=e.onCropEnd);var v=null;"function"==typeof e.onUpdate&&(console.warn("Croppr.js: `onUpdate` is deprecated and will be removed in the next major release. Please use `onCropMove` or `onCropEnd` instead."),v=e.onUpdate),"function"==typeof e.onCropMove&&(v=e.onCropMove);var f=null;if(void 0!==e.returnMode){var g=e.returnMode.toLowerCase();if(-1===["real","ratio","raw"].indexOf(g))throw"Invalid return mode.";f=g}var y=function(e,t){return null!==e?e:t};return{aspectRatio:y(d,t),maxSize:y(u,n),minSize:y(p,i),startSize:y(m,a),returnMode:y(f,r),onInitialize:y(h,s),onCropStart:y(_,o),onCropMove:y(v,l),onCropEnd:y(w,c),convertToPixels:function(e){for(var t=e.offsetWidth,n=e.offsetHeight,i=["maxSize","minSize","startSize"],a=0;a<i.length;a++){var r=i[a];null!==this[r]&&("%"==this[r].unit&&(null!==this[r].width&&(this[r].width=this[r].width/100*t),null!==this[r].height&&(this[r].height=this[r].height/100*n)),delete this[r].unit)}}}}}]),n}())}()},function(e,t,n){"use strict";n.r(t);const{createElement:i,render:a}=wp.element;var r=e=>i("div",{class:"lds-ellipsis"},i("div",null),i("div",null),i("div",null),i("div",null));const{Component:s,createElement:o,render:l,useState:c,useEffect:d,Fragment:u}=wp.element;var p=e=>{const[t,n]=c(e.duration),[i,a]=c({d:0,h:0,m:0,s:0});d(()=>{if(e.start){setTimeout(()=>{let i=t-1;i<=-1?e.update(e.quiz_id,"expired"):i>=0&&(n(i),r())},1e3)}else n(e.duration),r()},[t,e.start,e.duration]);const r=()=>{let e={...i},n=t;n>86400?(e.d=Math.floor(n/86400),n-=86400*e.d):e.d=0,n>3600?(e.h=Math.floor(n/3600),n-=3600*e.h):e.h=0,n>60?(e.m=Math.floor(n/60),n-=60*e.m):e.m=0,e.s=n,a(e)};return o("div",{className:"driptimer_wrapper"},o("div",{className:"driptimer"},o("span",{className:"timer_amount"},i.d?o(u,null,o("span",null,i.d),o("span",null,":")):"",i.h?o(u,null,o("span",null,i.h),o("span",null,":")):"",i.m?o(u,null,o("span",null,i.m),o("span",null,":")):"",o("span",null,i.s)),o("span",{className:"timer_unit"},i.d?o(u,null,o("span",null,window.wplms_course_data.translations.days),o("span",null)):"",i.h?o(u,null,o("span",null,window.wplms_course_data.translations.hours),o("span",null)):"",i.m?o(u,null,o("span",null,window.wplms_course_data.translations.minutes),o("span",null)):"",o("span",null,window.wplms_course_data.translations.seconds))))},m=n(0),h=n.n(m);const{createElement:_,useState:w,useEffect:v,useRef:f,Fragment:g,render:y}=wp.element,{dispatch:b,select:x}=wp.data,k=Math.round(100*Math.random());var E=e=>{const t=f(null),[n,i]=w(!1),[a,r]=w(!1),[s,o]=w(""),[l,c]=w(""),[d,u]=w(""),[p,m]=w(""),[g,y]=w({x:0,y:0,width:0,height:0,type:"image"}),[b,x]=w(""),[E,S]=w(window.wplms_course_data.translations.select_image);v(()=>{e.hasOwnProperty("crop")&&e.crop&&i(!0)},[]),v(()=>{if(a&&b&&n)new h.a(b,{returnMode:"ratio",onCropEnd:function(t){let n={...g};n.x=100*t.x,n.y=100*t.y,n.height=100*t.height,n.width=100*t.width,y(n);let i={x:b.naturalWidth*t.x,y:b.naturalHeight*t.y,width:b.naturalWidth*t.width,height:b.naturalHeight*t.height};e.update(p,i)}})},[a,b]);g.x,g.y,g.width,g.height;return _("div",{className:"uploader"},_("label",{for:"fileupload_"+k,className:"upload_file"},E,"image"==e.type?_("input",{id:"fileupload_"+k,"data-type":e.type,ref:t,type:"file",accept:"image/*",onChange:n=>{t.current.files[0].size<window.wplms_course_data.settings.upload_limit?(o(window.URL.createObjectURL(t.current.files[0])),m(t.current.files[0]),e.update(t.current.files[0],{...g,key:"image"})):(S(window.wplms_course_data.translations.image_size_error),setTimeout(()=>{S(window.wplms_course_data.translations.select_image)},3500))}}):"video"==e.type?_("input",{id:"fileupload_"+k,"data-type":e.type,ref:t,type:"file",accept:"video/*",onChange:n=>{t.current.files[0].size<window.wplms_course_data.settings.upload_limit?(c(window.URL.createObjectURL(t.current.files[0])),m(t.current.files[0]),e.update(t.current.files[0],{...g,key:"video"})):(S(window.wplms_course_data.translations.image_size_error),setTimeout(()=>{S(window.wplms_course_data.translations.select_image)},3500))}}):_("input",{id:"fileupload_"+k,"data-type":e.type,ref:t,type:"file",onChange:n=>{t.current.files&&t.current.files[0]&&(t.current.files[0].size<e.args.allowed_file_size?-1!==e.args.allowed_mime_types.indexOf(t.current.files[0].type)?(u(window.URL.createObjectURL(t.current.files[0])),m(t.current.files),e.update(t.current.files,{...g,key:"attachment"})):(S(window.wplms_course_data.translations.image_type_error),setTimeout(()=>{S(window.wplms_course_data.translations.select_image)},3500)):(S(window.wplms_course_data.translations.image_size_error),setTimeout(()=>{S(window.wplms_course_data.translations.select_image)},3500)))}})))};const{Component:S,createElement:q,render:C,useState:N,useEffect:O,Fragment:M}=wp.element;var z=e=>{const[t,n]=N(e.duration),[i,a]=N({d:0,h:0,m:0,s:0});O(()=>{if(e.start){setTimeout(()=>{let i=t-1;i<=-1?e.update(e.quiz_id,"expired"):i>=0&&(n(i),r())},1e3)}else n(e.duration),r()},[t,e.start,e.duration]);const r=()=>{let e={...i},n=t;n>86400?(e.d=Math.floor(n/86400),n-=86400*e.d):e.d=0,n>3600?(e.h=Math.floor(n/3600),n-=3600*e.h):e.h=0,n>60?(e.m=Math.floor(n/60),n-=60*e.m):e.m=0,e.s=n,a(e)};let s="c100 p0 big";if(t>-1){let n=Math.floor((e.duration-t)/e.duration*100);n<=0&&(n=1),s="c100 p"+n+" big"}return q("div",{className:"quiztimer"},q(M,null,q("div",{className:"circle_timer"},q("div",{className:s},q("span",null,q("span",{className:"timer_amount"},i.d?q(M,null,q("span",null,i.d),q("span",null,":")):"",i.h?q(M,null,q("span",null,i.h),q("span",null,":")):"",i.m?q(M,null,q("span",null,i.m),q("span",null,":")):"",q("span",null,i.s)),q("span",{className:"timer_unit"},i.d?q(M,null,q("span",null,window.wplms_course_data.translations.days),q("span",null)):"",i.h?q(M,null,q("span",null,window.wplms_course_data.translations.hours),q("span",null)):"",i.m?q(M,null,q("span",null,window.wplms_course_data.translations.minutes),q("span",null)):"",q("span",null,window.wplms_course_data.translations.seconds))),q("div",{className:"slice"},q("div",{className:"bar"}),q("div",{className:"fill"}))))))};const{createContext:P}=wp.element;var I=P({course:{},activeTab:"create_course",update:e=>{}});const{createElement:L,render:T,useState:A,useEffect:B,useContext:H,Fragment:R,RawHTML:D}=wp.element;var F=e=>{const[t,n]=A(e.field),[i,a]=(H(I),A({post_content:"",raw:{}})),[r,s]=A(Math.round(1e5*Math.random()));B(()=>{if(e.field&&e.field.id){var t=new CustomEvent("load_vibe_editor",{detail:{selector:".vibe_"+e.field.id+r+"_editor",content:e.field.hasOwnProperty("value")?e.field.value:"",raw:e.field.hasOwnProperty("raw")?e.field.raw:"",components:e.field.components?e.field.components:"",updater:e.field.id+r}});document.dispatchEvent(t)}},[e.field]),B(()=>(e.field&&e.field.id&&document.addEventListener("vibe_editor_content_update_"+e.field.id+r,o,!1),()=>{e.field&&e.field.id&&document.removeEventListener("vibe_editor_content_update_"+e.field.id+r,o)}));const o=t=>{a({post_content:t.detail.raw_html,raw:t.detail.editor_content});let i={...e.field};i.value=t.detail.raw_html,i.raw=t.detail.editor_content,JSON.stringify(i.raw)!==JSON.stringify(e.field.raw)&&(n(i),e.update(i,e.fieldIndex,"fieldvaluechanged"))};return L("div",{className:"vibev_editor"},L("div",{className:"vibe_"+t.id+r+"_editor"},L("textarea",{value:t.value})))};const{createContext:j}=wp.element;var X=j({courseStatus:{},current_unit_key:0,update:e=>{}});var Y=function(e){if(void 0===e)return!0;if("undefined"===e)return!0;if(null==e)return!0;if("number"==typeof e)return!1;if(Array.isArray(e)||"string"==typeof e||e instanceof String)return 0===e.length;for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};const{createElement:U,useState:J,useEffect:$,Fragment:W,render:V,useContext:K}=wp.element,{dispatch:G,select:Q}=wp.data;var Z=e=>{const[t,n]=J(!0),[i,a]=J({}),[s,o]=J([]),[l,c]=J(""),[d,u]=J(!1);K(X);let p=Q("vibebp").getUser();p.token=Q("vibebp").getToken(),$(()=>{n(!0);let t=`${window.wplms_course_data.api_url}/user/content/assignmentId/${e.assignment.id}`;e.hasOwnProperty("force")&&e.force&&(t+="?force"),fetch(t,{method:"post",headers:window.vibebp.xnonce?{"X-WP-Nonce":window.vibebp.xnonce}:{},body:JSON.stringify({token:p.token})}).then(e=>e.ok?e.json():{status:0,message:window.wplms_course_data.translations.error_loading_data}).then(e=>{if(e){if(e.hasOwnProperty("remaining"))e.duration=e.remaining;else if(e.hasOwnProperty("start")&&!0!==e.start&&e.start){let t=parseInt(e.duration)+parseInt(e.start),n=Math.round((new Date).getTime()/1e3);e.duration=t>n?t-n:0}e.hasOwnProperty("comment_content")&&c(e.comment_content),a(e),n(!1),document.dispatchEvent(new Event("VibeBP_Editor_Content"))}}).catch(e=>{n(!1),console.error("Uh oh, an error!",e),G("vibebp").addNotification({text:window.wplms_course_data.translations.error_loading_data})}),document.addEventListener("wplms_assignment_custom_upload",({detail:e})=>{if(e.hasOwnProperty("data")&&e.data.hasOwnProperty("Key")&&e.data.Key.length){let t=[...s],n=e.data.Key.split("/");t.push({...e.data,name:n[n.length-1]}),o(t)}})},[e.assignment]);const m=(t=null)=>{let n=l;if(!t&&i&&i.type&&"upload"==i.type){if(!s||s.length<=0)return G("vibebp").addNotification({text:window.wplms_course_data.translations.upload_a_file}),!1;Y(n)&&(n=i.title+" - "+(p.displayname?p.displayname:p.name?p.name:""))}else if(t&&Y(n)&&(n=i.title+" - "+(p.displayname?p.displayname:p.name?p.name:"")),!n||n.length<=3)return G("vibebp").addNotification({text:window.wplms_course_data.translations.error}),!1;u(!0);var r=new FormData;r.append("body",JSON.stringify({comment:n,attachments:s,token:Q("vibebp").getToken()})),s.length&&s.map((e,t)=>{e instanceof File?r.append("files_"+t,e):r.append("files_"+t,JSON.stringify(e))}),fetch(`${window.wplms_course_data.api_url}/user/upload/assignmentId/${e.assignment.id}?post`,{method:"post",headers:window.vibebp.xnonce?{"X-WP-Nonce":window.vibebp.xnonce}:{},body:r}).then(e=>e.ok?e.json():{status:0,message:window.wplms_course_data.translations.error_loading_data}).then(t=>{if(u(!1),t){let n={...i};if(t.attachment_urls&&t.attachment_urls.length&&(n.attachment_urls=t.attachment_urls),t.comment_id){n.flag=1,n.already_submitted=!0,e.hasOwnProperty("unitIndex")?e.update({unitIndex:e.unitIndex,assignmentIndex:e.assignmentIndex},"complete"):e.update({},"submitassignment");let t=`${window.wplms_course_data.api_url}/user/content/assignmentId/${e.assignment.id}`;"undefined"!=typeof localforage&&window.vibebp.api.sw_enabled&&localforage.getItem(t).then(e=>{e&&e.length&&(e=JSON.parse(e)).hasOwnProperty("duration")&&(e=n,localforage.setItem(t,JSON.stringify(e)))});let i=window.wplms_course_data.api_url+"/student/assignments";h(i)}if(a(n),t.hasOwnProperty("message")&&G("vibebp").addNotification({text:t.message}),t.status){let t=e.course,n=e.assignment.id;document.dispatchEvent(new CustomEvent("course_item_completed",{detail:{course_id:t,item_id:n}}))}}}).catch(e=>{u(!1),console.error("Uh oh, an error!",e),G("vibebp").addNotification({text:window.wplms_course_data.translations.error_loading_data})})},h=(e,t)=>"undefined"!=typeof localforage&&window.vibebp.api.sw_enabled&&navigator.onLine?t?localforage.removeItem(e):localforage.iterate((function(t,n,i){e.length&&n.length&&n.includes(e)&&localforage.removeItem(n)})):new Promise(e=>{e(1)});let _={allowed_mime_types:i.permit_mime,allowed_file_size:parseInt(i.permit_size)};return t?U(r,null):U("div",{className:"course_assignment_wrapper"},U("div",{className:"course_assignment"},U("div",{className:"assignment_details"},U("div",{className:"assignment_marks"},U("span",null,i.total_marks),U("span",null,window.wplms_course_data.translations.total_marks)),U(z,{duration:i.duration,update:(e,t)=>{"expired"==t&&(i.already_submitted||m(!0))},quiz_id:i.id,start:i.start})),U("div",{className:"assignment_content_wrapper"},U("div",{className:"assignment_content",dangerouslySetInnerHTML:{__html:i.content}}),i.type&&"upload"==i.type&&i&&i.permit_extension&&i.permit_extension.length&&i.flag<=2?U("div",{className:"allowed_file_extenstions"},U("label",null,window.wplms_course_data.translations.allowed_file_extenstions),i.permit_extension.map(e=>U("span",null,e))):"",i.start?"":U("a",{className:"assignment_start_button button is-primary",onClick:()=>{fetch(`${window.wplms_course_data.api_url}/user/start/assignmentId/${e.assignment.id}?post`,{method:"post",headers:window.vibebp.xnonce?{"X-WP-Nonce":window.vibebp.xnonce}:{},body:JSON.stringify({token:Q("vibebp").getToken()})}).then(e=>e.ok?e.json():{status:0,message:window.wplms_course_data.translations.error_loading_data}).then(t=>{if(t){let n={...i};n.start=Math.round((new Date).getTime()/1e3),a(n);let r=`${window.wplms_course_data.api_url}/user/content/assignmentId/${e.assignment.id}`,s=window.wplms_course_data.api_url+"/student/assignments";h(s,!0),"undefined"!=typeof localforage&&window.vibebp.api.sw_enabled&&localforage.getItem(r).then(e=>{e&&e.length&&(e=JSON.parse(e)).hasOwnProperty("duration")&&(e.start=n.start,localforage.setItem(r,JSON.stringify(e)))}),t.hasOwnProperty("message")&&G("vibebp").addNotification({text:t.message})}}).catch(e=>{console.error("Uh oh, an error!",e),G("vibebp").addNotification({text:window.wplms_course_data.translations.error_loading_data})})}},window.wplms_course_data.translations.start_assigmment),i.start&&i.flag<=2?U(W,null,i.already_submitted?U(W,null,i.attachment_urls&&i.attachment_urls.length?U(W,null,window.wplms_course_data.translations.uploaded_files,U("div",{className:"assignment_attachments"},i.attachment_urls.map((e,t)=>e.hasOwnProperty("url")?U("div",null,U("a",null,e.name)):U("div",null,U("a",{href:e.url,target:"_blank",download:!0},e.name))))):"",i.hasOwnProperty("flag")&&1==i.flag&&i.duration>0?U("div",{className:"resubmit ",onClick:()=>{(()=>{let t={...i};t.already_submitted=!1,t.flag=0,e.hasOwnProperty("unitIndex")?e.update({unitIndex:e.unitIndex,assignmentIndex:e.assignmentIndex},"retake"):e.update({},"retookassignment"),a(t)})()}},U("a",{className:"button is-primary"},window.wplms_course_data.translations.resubmit,U("span",{className:"vicon vicon-close"}))):""):"",i.type&&"upload"==i.type&&!i.already_submitted?U("div",{className:"upload_assignment"},i.hasOwnProperty("custom_upload")&&i.custom_upload?U("div",null,(w=new CustomEvent("custom_assignment_upload",{detail:{data:i}}),document.dispatchEvent(w),U("div",{className:"custom_assignment_upload",id:i.custom_upload}))):U(E,{type:1,update:(e,t)=>{let n=[...s];n.push(new File([e[0]],e[0].name)),o(n)},args:_}),s?U("div",{className:"assignment_attachments"},s.map((e,t)=>U("div",null,U("span",null,e.name),U("span",{className:"vicon vicon-close",onClick:()=>{(e=>{let t=[...s];t.splice(e,1),o(t)})(t)}})))):"",U(F,l?{field:{id:"assignment_text",value:l,components:["editor"]},update:(e,t,n)=>{c(e.value)}}:{field:{id:"assignment_text",components:["editor"]},update:(e,t,n)=>{c(e.value)}})):"",!i.hasOwnProperty("type")||i.type&&"textarea"==i.type?U(F,{field:l?{id:"assignment_text",value:l,components:["editor"]}:{id:"assignment_text",components:["editor"]},update:(e,t,n)=>{c(e.value)}}):""):"",i.flag&&i.hasOwnProperty("marks")&&i.flag>1?U("div",{className:"assigment_evaluated"},i.message?U("span",null,i.message):"",i.marks?U("span",null,window.wplms_course_data.translations.marks_obtained," : ",i.marks):"",i.hasOwnProperty("instructor_remarks")?U("div",{className:"remarks"},U("h3",null,window.wplms_course_data.translations.instructor_remarks," "),U("div",{dangerouslySetInnerHTML:{__html:i.instructor_remarks}})):""):"")),i.start&&!i.already_submitted?U("a",{className:d?"button is-primary is-loading":"button is-primary",onClick:()=>{m()}},window.wplms_course_data.translations.submit_assignment):"");var w};const{createElement:ee,render:te,useState:ne,useEffect:ie,useContext:ae,Fragment:re,RawHTML:se}=wp.element,{dispatch:oe,select:le}=wp.data;var ce=e=>{const[t,n]=ne(e.timestamp),[i,a]=ne(0);let r=Math.floor(Date.now()/1e3);ie(()=>{if(n(parseInt(e.timestamp)),e.timestamp)if(e.hasOwnProperty("notimediff"))a(parseInt(e.timestamp));else{let t=e.timestamp;if(e.timestamp.toString().includes("-")){t=new Date(t).getTime()/1e3;let e=(new Date).getTimezoneOffset();e*=60,parseInt(e)>0?t-=Math.abs(e):t+=Math.abs(e)}parseInt(t)>r?a(parseInt(t)-r):a(r-parseInt(t))}},[e.timestamp]);return ee("span",{className:"friendly_time"},(()=>{if(i<0)return window.wplms_course_data.translations.expired;let t,n,a,r=0,s=0,o=0,l=[{label:window.wplms_course_data.time_labels.year.single,multi:window.wplms_course_data.time_labels.year.multi,value:31536e3},{label:window.wplms_course_data.time_labels.month.single,multi:window.wplms_course_data.time_labels.month.multi,value:2592e3,max:12},{label:window.wplms_course_data.time_labels.week.single,multi:window.wplms_course_data.time_labels.week.multi,value:604800,max:7},{label:window.wplms_course_data.time_labels.day.single,multi:window.wplms_course_data.time_labels.day.multi,value:86400,max:31},{label:window.wplms_course_data.time_labels.hour.single,multi:window.wplms_course_data.time_labels.hour.multi,value:3600,max:24},{label:window.wplms_course_data.time_labels.minute.single,multi:window.wplms_course_data.time_labels.minute.multi,value:60,max:60},{label:window.wplms_course_data.time_labels.second.single,multi:window.wplms_course_data.time_labels.second.multi,value:1,max:60}];if(i>=776736e3)return window.wplms_course_data.translations.unlimited_time;if(i<=0)return e.hasOwnProperty("notimediff")?i+" "+window.wplms_course_data.time_labels.second.multi:window.wplms_course_data.translations.just_now;for(let e=0;e<l.length;e++)if(n=l[e],s=e,n.value<i){r=Math.floor(i/n.value),r>n.max&&(r=n.max);break}return t=r+" "+(r>1?n.multi:n.label),n.value>1&&(a=l[s+1],o=Math.floor(i%n.value/a.value),o&&(t+=", "+o+" "+(o>1?a.multi:a.label))),t})())};const{createElement:de,useState:ue,useEffect:pe,Fragment:me,render:he,useRef:_e}=wp.element,{dispatch:we,select:ve}=wp.data;const{createElement:fe,render:ge,useState:ye,useEffect:be,Fragment:xe,useContext:ke,useRef:Ee}=wp.element,{dispatch:Se,select:qe}=wp.data;var Ce=e=>{const t=Ee(null),[n,i]=ye(Math.round(1e4*Math.random())),[a,r]=ye(!1),[s,o]=ye(!1),l=(e,t)=>{void 0===t&&(t=window.location.href);var n=t.match("[?&]"+e+"=([^&]+)");return n?n[1]:null};be(()=>(d().then(()=>{if(document.querySelector("#item_"+e.index)){let t={};"youtube"==e.provider&&(t.youtube={modestbranding:1}),"vimeo"==e.provider&&(t.vimeo={controls:!0,playsinline:!1}),window.wplms_course_data.course.status.seek_lock&&(t.listeners={seek:e=>{var t=a.currentTime;if(_getTargetTime(a,e)>t)return e.preventDefault(),!1}});let n=null;if(e.hasOwnProperty("video")&&e.video.hasOwnProperty("videotype")&&"360"==e.video.videotype)n=new Plyr(document.querySelector("#item_"+e.index),t),n.mediainfo=n.mediainfo||{},n.mediainfo.projection="360",n.vr({projection:"AUTO",debug:!0,forceCardboard:!1});else{if(e.hasOwnProperty("src")&&"mpd"==e.url.split(".").pop())dashjs.MediaPlayer().create().initialize(document.querySelector("#item_"+e.index),e.url,!0);if(n=new Plyr(document.querySelector("#item_"+e.index),t),e.hasOwnProperty("src")&&"m3u8"==e.url.split(".").pop())if(Hls.isSupported()){const t=new Hls;t.loadSource(e.url),t.attachMedia(document.querySelector("#item_"+e.index))}else document.querySelector("#item_"+e.index).src=e.url}n&&(o(n),n.once("loadeddata",()=>{let t=localStorage.getItem(e.url);t&&(n.currentTime=parseInt(t)),r({plyr:n,url:e.url})}),n.on("timeupdate",()=>{localStorage.setItem(e.url,Math.floor(n.currentTime))}),"youtube"==e.provider&&n.pause(),n.on("ready",()=>{if("youtube"==e.provider){let t=l("t",e.url);if(void 0!==t&&t)n.muted=!0,n.forward(parseInt(t)),n.play();else{let i=localStorage.getItem(e.url);void 0!==t&&i&&(n.muted=!0,n.forward(parseInt(i)),n.play())}}}),n.on("playing",()=>{if("youtube"==e.provider){let t=l("t",e.url);if(void 0!==t&&t)n.seekDone||(n.pause(),n.muted=!1,n.seekDone=!0);else{localStorage.getItem(e.url)&&(n.seekDone||(n.pause(),n.muted=!1,n.seekDone=!0))}}}),n.once("ended",c))}}),()=>{document.querySelector(".video_wrapper")&&document.querySelector(".video_wrapper > div")&&document.querySelector(".video_wrapper > div").remove()}),[e.url]);const c=t=>{e.update("ended",{index:e.index,src:e.url,event:t})},d=()=>{if(document.querySelector(".video_wrapper")&&document.querySelector(".video_wrapper > div")&&document.querySelector(".video_wrapper > div").remove(),"youtube"==e.provider)return localforage.getItem(e.url).then(t=>{if(t){var n=document.createElement("div"),i=document.createElement("video");i.setAttribute("id","item_"+e.index);var a=document.createElement("source");a.setAttribute("src",URL.createObjectURL(t)),a.setAttribute("type",t.type),i.appendChild(a),n.appendChild(i),document.querySelector(".video_wrapper").appendChild(n)}else{(n=document.createElement("div")).setAttribute("id","item_"+e.index),n.setAttribute("data-plyr-provider","youtube"),n.setAttribute("data-plyr-embed-id",e.embed_id),document.querySelector(".video_wrapper").appendChild(n)}});if("vimeo"==e.provider)return new Promise(t=>{var n=document.createElement("div");n.setAttribute("id","item_"+e.index),n.setAttribute("data-plyr-provider","vimeo"),n.setAttribute("data-plyr-embed-id",e.embed_id),document.querySelector(".video_wrapper").appendChild(n),t()});var t=document.createElement("div"),n=document.createElement("video");n.setAttribute("id","item_"+e.index);var i=document.createElement("source");return localforage.getItem(e.url).then(t=>{t?(i.setAttribute("src",URL.createObjectURL(t)),i.setAttribute("type",t.type)):(i.setAttribute("src",e.url),i.setAttribute("type",e.mime_type))}).then(()=>{n.appendChild(i),t.appendChild(n),document.querySelector(".video_wrapper").appendChild(t)})};return fe("div",{className:"video_wrapper item_player_"+n},"youtube"==e.provider?fe("div",{ref:t,id:"item_"+e.index,"data-plyr-provider":"youtube","data-plyr-embed-id":e.embed_id}):"vimeo"==e.provider?fe("div",{ref:t,id:"item_"+e.index,"data-plyr-provider":"vimeo","data-plyr-embed-id":e.embed_id}):"local"==e.provider?fe("div",null,fe("video",{className:"activity_meta video",ref:t,id:"item_"+e.index},fe("source",{src:e.url,type:e.mime_type}))):"")};const{createElement:Ne,render:Oe,useState:Me,useEffect:ze,Fragment:Pe}=wp.element;var Ie=e=>{const[t,n]=Me({});ze(()=>{n(e.question)},[e.question]);let i="";t.hasOwnProperty("marked_answer")&&(i=t.marked_answer);let a="";return t.hasOwnProperty("usercorrect")&&t.show_correct_answer&&(a="question_incorrect",t.usercorrect>0&&(a="question_correct")),Ne(Pe,null,Ne("div",{className:"question_content",dangerouslySetInnerHTML:{__html:t&&t.content?t.content:""}}),Ne("input",{type:"text",className:a,value:i,onChange:t=>{let i={...e.question};i.marked_answer=t.target.value,n(i),e.update(i,e.index,"changed")}}))};const{createElement:Le,render:Te,useState:Ae,useEffect:Be,Fragment:He}=wp.element;var Re=e=>{const[t,n]=Ae({}),[i,a]=Ae([]);Be(()=>{if(n(e.question),e.question.hasOwnProperty("options")&&e.question.options.length&&Array.isArray(e.question.options)){let t=[...e.question.options];window.wplms_course_data.question_option_rearrange&&r(t),a(t)}},[e.question.correct_indexes]);const r=e=>{for(var t=e.length-1;t>0;t--){var n=Math.floor(Math.random()*(t+1)),i=e[t];e[t]=e[n],e[n]=i}};let s="";return t.hasOwnProperty("marked_answer")&&(s=t.marked_answer),Le(He,null,Le("div",{className:"question_content",dangerouslySetInnerHTML:{__html:t&&t.content?t.content:""}}),t.options&&t.options.length?Le(He,null,(t=>i.map((function(i,a){let r=t.options.findIndex(e=>e==i);return Le("div",{className:"question_option radio "+(t.show_correct_answer&&t.correct_indexes?t.correct_indexes&&t.correct_indexes.length&&t.correct_indexes.includes(r)?"question_correct":"question_incorrect":"")},Le("input",{type:"radio",name:e.quiz_id+"_"+t.id,value:r,id:e.quiz_id+"_"+t.id+r,checked:parseInt(t.marked_answer)===r,onChange:t=>{let i={...e.question};i.marked_answer=t.target.value,n(i),e.update(i,e.index,"changed")}}),Le("label",{for:e.quiz_id+"_"+t.id+r,dangerouslySetInnerHTML:{__html:i}}))})))(t),t.attempted?"":Le("span",{className:"resetq_answer button",onClick:t=>{let i={...e.question};i.marked_answer=null,n(i),e.update(i,e.index,"changed")}},Le("i",{class:"vicon vicon-trash"}))):"")};const{createElement:De,render:Fe,useState:je,useEffect:Xe,Fragment:Ye}=wp.element;var Ue=e=>{const[t,n]=je({});Xe(()=>{n(e.question)},[e.question]);const i=(t,i)=>{let a={...e.question};a.marked_answer&&a.marked_answer.length||(a.marked_answer=[]),a.marked_answer[i]=t,n(a),e.update(a,e.index,"changed")},a=(t,n)=>De(Ye,null,De("span",{className:t.show_correct_answer&&t.correct_indexes?t.correct_indexes&&t.correct_indexes.length&&t.correct_indexes.includes(n)?"question_correct":"question_incorrect":""},De("select",{name:e.quiz_id+"_"+t.id,id:e.quiz_id+"_"+t.id,onChange:e=>{i(e.target.value,n)}},De("option",null,window.wplms_course_data.translations.select_option),((e,t)=>e.options.map((function(n,i){return e.hasOwnProperty("options_arr")&&e.options_arr&&e.options_arr.length&&e.options_arr[t]&&e.options_arr[t].length?e.options_arr[t].includes((i+1).toString())||e.options_arr[t].includes(i+1)?De("option",{value:i,selected:e.marked_answer&&e.marked_answer.length&&e.marked_answer[t]&&parseInt(e.marked_answer[t])===i,dangerouslySetInnerHTML:{__html:n}}):void 0:De("option",{value:i,selected:e.marked_answer&&e.marked_answer.length&&e.marked_answer[t]&&parseInt(e.marked_answer[t])===i,dangerouslySetInnerHTML:{__html:n}})})))(t,n))),t.attempted?"":De("span",{className:"resetq_answer button",onClick:e=>{i(null,n)}},De("i",{class:"vicon vicon-trash"})));return De(Ye,null,t&&t.extra_content&&Array.isArray(t.extra_content)?De("div",{className:"question_content"},t.extra_content.map((function(e,n){return De(Ye,null,De("span",{className:"select_question_content",dangerouslySetInnerHTML:{__html:e}}),t.options&&t.options.length&&n<t.extra_content.length-1?De(Ye,null,a(t,n)):"")}))):"")};const{createElement:Je,render:$e,useState:We,useEffect:Ve,Fragment:Ke}=wp.element;var Ge=e=>{const[t,n]=We({}),[i,a]=We([]);"undefined"!=e.question.marked_answer&&null!=e.question.marked_answer||(e.question.marked_answer=[]),Ve(()=>{if(n(e.question),e.question.hasOwnProperty("options")&&e.question.options.length&&Array.isArray(e.question.options)){let t=[...e.question.options];window.wplms_course_data.question_option_rearrange&&r(t),a(t)}},[e.question.correct_indexes]);const r=e=>{for(var t=e.length-1;t>0;t--){var n=Math.floor(Math.random()*(t+1)),i=e[t];e[t]=e[n],e[n]=i}};return Je(Ke,null,Je("div",{className:"question_content",dangerouslySetInnerHTML:{__html:t&&t.content?t.content:""}}),t.options&&t.options.length?Je(Ke,null,(t=>{if(i&&i.length)return i.map((function(i,a){let r=t.options.findIndex(e=>e==i);return Je("div",{className:"question_option checkbox "+(t.show_correct_answer&&t.correct_indexes?t.correct_indexes&&t.correct_indexes.length&&t.correct_indexes.includes(r)?"question_correct":"question_incorrect":"")},Je("input",{type:"checkbox",name:e.quiz_id+"_"+t.id,value:r,id:e.quiz_id+"_"+t.id+r,checked:e.question.marked_answer&&e.question.marked_answer.length&&e.question.marked_answer.includes(r),onChange:t=>{let i={...e.question};if(i.marked_answer.includes(r)){let e=i.marked_answer.indexOf(r);e>-1&&i.marked_answer.splice(e,1)}else i.marked_answer.push(r);n(i),e.update(i,e.index,"changed")}}),Je("label",{for:e.quiz_id+"_"+t.id+r,dangerouslySetInnerHTML:{__html:i}}))}))})(t),t.attempted?"":Je("span",{className:"resetq_answer button",onClick:t=>{let i={...e.question};i.marked_answer=null,n(i),e.update(i,e.index,"changed")}},Je("i",{class:"vicon vicon-trash"}))):"")};const{createElement:Qe,render:Ze,useState:et,useEffect:tt,Fragment:nt}=wp.element;var it=e=>{const[t,n]=et("120"),[i,a]=et(()=>{let t="";return e.marked_answer&&e.marked_answer.length&&(t=e.marked_answer[e.index]),t});tt(()=>{void 0!==i&&i&&i.length>15&&n(8*i.length)},[i]);let r="";i&&(r=i);return Qe(nt,null,Qe("div",{className:"fillblank_area"},Qe("input",{type:"text",value:r,onChange:t=>{let n=i;n=t.target.value,a(n),e.update(n,e.index,"changed")},style:{width:t+"px"}})))};const{createElement:at,render:rt,useState:st,useEffect:ot,Fragment:lt}=wp.element;var ct=e=>{const[t,n]=st({});ot(()=>{n(e.question)},[]);let i="";t.hasOwnProperty("marked_answer")&&(i=t.marked_answer);const a=(i,a,r)=>{if("changed"==r){let r={...t};r.marked_answer&&t.marked_answer.length||(r.marked_answer=[]),r.marked_answer[a]=i,n(r),e.update(r,e.index,"changed")}};return at(lt,null,t&&t.extra_content&&Array.isArray(t.extra_content)?at("div",{className:"question_content"},t.extra_content.map((function(e,n){return at(lt,null,at("span",{className:"select_question_content",dangerouslySetInnerHTML:{__html:e}}),n<t.extra_content.length-1?at("div",{className:"fillblank_area "+(t.show_correct_answer&&t.correct_indexes?t.correct_indexes&&t.correct_indexes.length&&t.correct_indexes.includes(n)?"question_correct":"question_incorrect":"")},at(it,{update:a,index:n,marked_answer:t.marked_answer})):"")}))):"")};const{createElement:dt,render:ut,useState:pt,useEffect:mt,Fragment:ht}=wp.element;var _t=e=>{const[t,n]=pt([]),[i,a]=pt(!1),[r,s]=pt([]),[o,l]=pt([]),[c,d]=pt([]),[u,p]=pt([]);mt(()=>{s(e.items)},[e.items]);let m="droppable";i&&(m+=" active");const h=e=>{let t="";return i===r[e]&&(t="dragging"),t};return dt("div",{className:m},r.map((m,_)=>dt("div",{key:_,onDragStart:e=>{r[_]&&a(r[_])},onDragEnd:()=>{a(!1)},onDragOver:t=>{t.preventDefault(),((t,n)=>{if(!i)return;let a=r[n];if(i===a)return;let o=[...r];o=o.filter(e=>e!=i),o.splice(n,0,i),s(o),e.update(o,"changed")})(0,_)},ref:e=>{((e,i)=>{if(e){let a=t;a[i]||(a[i]=e),n(a)}})(e,_)},draggable:"true",style:u[_],onTouchStart:e=>{let n=[...c];t.map((e,t)=>{let i=e.getBoundingClientRect();n[t]=i}),d(n),r[_]&&a(r[_])},onTouchMove:e=>{e.preventDefault();let t=[];if("touchmove"===e.type){let n=[...u];n[_]={transform:"translateY("+Math.floor(e.touches[0].clientY-c[_].top)+"px)"},p(n),t.push(r[_]);let i=[];if(e.touches[0].clientY&&c.map((n,a)=>{n.top+n.height/2>e.touches[0].clientY&&r[a]!==r[_]&&t.push(r[a]),n.bottom-n.height/2<e.touches[0].clientY&&r[a]!==r[_]&&i.push(r[a])}),i.length)for(let e=i.length-1;e>=0;e--)t.unshift(i[e]);l(t)}},onTouchEnd:t=>{s(o),e.update(o,"changed"),d([]),p([]),a(!1),l([])},className:h(_)+" "+(e.question.show_correct_answer&&e.question.correct_indexes?e.question.correct_indexes&&e.question.correct_indexes.length&&e.question.correct_indexes.includes(_)?"question_correct":"question_incorrect":"")},dt("div",{dangerouslySetInnerHTML:{__html:m}}))))};const{createElement:wt,render:vt,useState:ft,useEffect:gt,Fragment:yt}=wp.element;var bt=e=>{e.question.id,e.quiz_id;const[t,n]=ft({}),[i,a]=ft(!1);gt(()=>{let t=e.question;if(!i&&t&&t.marked_answer&&t.marked_answer.length&&"undefined"!=t.marked_answer){let e=[];t.marked_answer.map((n,i)=>{e.push(t.original_options[parseInt(n)-1])}),t.options=e,n(t),a(!0)}n(t)},[t]);return wt(yt,null,wt("div",{className:"question_content",dangerouslySetInnerHTML:{__html:t&&t.content?t.content:""}}),t.options&&t.options.length?wt(yt,null,wt(_t,{items:t.options,original_items:t.original_options,update:(i,a)=>{if("changed"==a){let a=t;a.marked_answer=[],i.map((e,t)=>{let n=a.original_options.indexOf(e);a.marked_answer.push(n+1)}),n(a),e.update(a,e.index,"changed")}},question:t}),t.attempted?"":wt("span",{className:"resetq_answer button",onClick:i=>{let a={...t};a.marked_answer=null,a.options=a.original_options,n(a),e.update(a,e.index,"changed")}},wt("i",{class:"vicon vicon-trash"}))):"")};const{createElement:xt,render:kt,useState:Et,useEffect:St,Fragment:qt}=wp.element;function Ct(e){if(null==e)return!0;if(void 0===e)return!0;if("number"==typeof e)return!1;if(Array.isArray(e)||"string"==typeof e||e instanceof String)return 0===e.length;for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}var Nt=e=>{const[t,n]=Et([]),[i,a]=Et(!1),[r,s]=Et([]),[o,l]=Et(""),[c,d]=Et([]),[u,p]=Et(e.matches),[m,h]=Et([]),[_,w]=Et([]),[v,f]=Et([]),[g,y]=Et({}),[b,x]=Et([]),[k,E]=Et([]),[S,q]=Et([]),[C,N]=Et({x:0,y:0}),[O,M]=Et([]);St(()=>{let t=[...e.items];e.question&&e.question.marked_answer&&e.question.marked_answer.length&&e.question.marked_answer.map(n=>{n&&"NaN"!=typeof n&&(t=t.filter(t=>t!=e.question.original_options[n-1]))}),d(t);let n=[];e.question&&e.question.marked_answer&&e.question.marked_answer.length&&e.question.marked_answer.map(e=>{parseFloat(e)-1>=0?n.push(e-1):n.push(null)}),q(n),e.update(!1,"reset")},[e.items,e.reset]);let z="droppable";i&&(z+=" active");const P=e=>{let t="";return i===c[e]&&(t="dragging"),t};return xt("div",{className:"match_playground"},xt("div",{className:"match_options"},u&&u.length?u.map((n,l)=>xt("div",{key:l,className:"match_option "+(e.question.show_correct_answer&&e.question.correct_indexes?e.question.correct_indexes&&e.question.correct_indexes.length&&e.question.correct_indexes.includes(l)?"question_correct":"question_incorrect":""),onDrop:t=>{((t,n)=>{if(!i)return;if(O.index===n)return;let a=[...c],r=[...S];if(!r[n]&&0!==r[n]){a=a.filter(e=>e!=i);let t=e.original_items.indexOf(i);u&&u.length&&u.map((e,t)=>{Ct(r[t])&&(r[t]=null)}),Ct(n)||(r[n]=t),q(r),d(a),e.update(r,"changed")}})(0,l)},onDragOver:e=>{e.preventDefault()},ref:e=>{((e,t)=>{if(e){let n=r;n[t]||(n[t]=e),s(n)}})(e,l)}},xt("div",{dangerouslySetInnerHTML:{__html:n}}),xt("div",{className:"children"},e.original_items&&null!=S[l]&&e.original_items[S[l]]?xt("div",{key:"droppablediv"+l,draggable:"true",onDragStart:t=>{e.original_items[S[l]]&&(a(e.original_items[S[l]]),M({index:l,source:"droppablediv"}))},onDragEnd:()=>{a(!1),M({})},onDragOver:e=>{e.preventDefault()},className:P(l),style:k[S[l]],onTouchStart:n=>{let i=[..._];t.map((e,t)=>{let n=e.getBoundingClientRect();i[t]=n}),w(i);let s=[...v];r.map((e,t)=>{let n=e.getBoundingClientRect();s[t]=n}),f(s),y(o.getBoundingClientRect()),e.original_items[S[l]]&&(a(e.original_items[S[l]]),M({index:l,source:"droppablediv"})),M({})},onTouchMove:e=>{if(e&&(e.preventDefault(),"touchmove"===e.type)){let t=[...k];t[S[l]]={position:"fixed",top:Math.floor(e.touches[0].clientY)+"px",left:Math.floor(e.touches[0].clientX)+"px"},E(t),N({x:e.touches[0].clientX,y:e.touches[0].clientY})}},onTouchEnd:t=>{let n=[...c],r=[...S];g.top<C.y&&g.top+g.height>C.y&&g.left<C.x&&g.left+g.width>C.x&&(n.push(i),r.map((e,t)=>{e==S[l]&&(r[t]=null)})),f([]),y({}),a(!1),E([]),x([]),d(n),q(r),e.update(r,"changed"),N({x:0,y:0})}},xt("div",{dangerouslySetInnerHTML:{__html:e.original_items[S[l]]}})):""))):""),xt("div",{className:z,onDragOver:e=>{e.preventDefault()},onDrop:t=>{(t=>{if("droppablediv"!==O.source)return;if(!i)return;let n=[...c],a=[...S];n.includes(i)||n.push(i),d(n),Ct(O.index)||(a[O.index]=null),q(a),e.update(a,"changed")})()},ref:e=>{var t;(t=e)&&l(t)}},c&&c.length?c.map((i,s)=>xt("div",{key:"draggablediv"+s,onDragStart:e=>{c[s]&&a(c[s]),M({})},onDragEnd:()=>{a(!1),M({})},onDragOver:e=>{e.preventDefault()},ref:e=>{((e,i)=>{if(e){let a=t;a[i]||(a[i]=e),n(a)}})(e,s)},draggable:"true",style:b[s],onTouchStart:e=>{let n=[..._];t.map((e,t)=>{let i=e.getBoundingClientRect();n[t]=i}),w(n);let s=[...v];r.map((e,t)=>{let n=e.getBoundingClientRect();s[t]=n}),f(s),i&&a(i),M({})},onTouchMove:e=>{if(e.preventDefault(),"touchmove"===e.type){let t=[...b];t[s]={position:"fixed",top:Math.floor(e.touches[0].clientY)+"px",left:Math.floor(e.touches[0].clientX)+"px"},x(t),N({x:e.touches[0].clientX,y:e.touches[0].clientY})}},onTouchEnd:t=>{x([]);let n=[...c],r=[...S];v.map((t,a)=>{if(t.top<C.y&&t.top+t.height>C.y&&t.left<C.x&&t.left+t.width>C.x){let t=e.original_items.indexOf(i);t>=0&&!r[a]&&0!==r[a]&&(r[a]=t,n=n.filter(e=>e!=i))}}),f([]),a(!1),d(n),q(r),e.update(r,"changed"),N({x:0,y:0})},className:P(s)},xt("div",{dangerouslySetInnerHTML:{__html:i}}))):""))};const{createElement:Ot,render:Mt,useState:zt,useEffect:Pt,Fragment:It}=wp.element;var Lt=e=>{e.question.id,e.quiz_id;const[t,n]=zt({}),[i,a]=zt(!1);Pt(()=>{n(e.question)},[t]);return Ot(It,null,Ot("div",{className:"question_content"},Ot("div",{className:"question_statement",dangerouslySetInnerHTML:{__html:t&&t.extra_content&&t.extra_content.statement?t.extra_content.statement:""}}),t.options&&t.options.length&&t.content.match&&t.content.match.length?Ot(Nt,{matches:t.extra_content.match,original_matches:t.extra_content.match,items:t.options,original_items:t.original_options,update:(i,r)=>{if("changed"==r){let a={...t};a.marked_answer=[],i.map(e=>{a.marked_answer.push(parseInt(e)+1)}),n(a),e.update(a,e.index,"changed")}"reset"==r&&a(!1)},reset:i,question:t}):"",Ot("div",{className:"question_end",dangerouslySetInnerHTML:{__html:t&&t.content&&t.content.end?t.content.end:""}})),t.attempted?"":Ot("span",{className:"resetq_answer button",onClick:i=>{a(!0);let r={...t};r.marked_answer=null,r.options=r.original_options,n(r),e.update(r,e.index,"changed")}},Ot("i",{class:"vicon vicon-trash"})))};const{createElement:Tt,render:At,useState:Bt,useEffect:Ht,Fragment:Rt}=wp.element;var Dt=e=>{const[t,n]=Bt(e.question);let i="";return t.hasOwnProperty("marked_answer")&&(i=t.marked_answer),Tt(Rt,null,Tt("div",{className:"question_content",dangerouslySetInnerHTML:{__html:t&&t.content?t.content:""}}),t.options&&t.options.length?Tt(Rt,null,(t=>t.options.map((function(i,a){return Tt("div",{className:"question_option radio "+(t.show_correct_answer&&t.correct_indexes?t.correct_indexes&&t.correct_indexes.length&&t.correct_indexes.includes(a)?"question_correct":"question_incorrect":"")},Tt("input",{type:"radio",name:e.quiz_id+"_"+t.id,value:a,id:e.quiz_id+"_"+t.id+a,checked:parseInt(t.marked_answer)===a,onChange:t=>{let i={...e.question};i.marked_answer=t.target.value,n(i),e.update(i,e.index,"changed")}}),Tt("label",{for:e.quiz_id+"_"+t.id+a,dangerouslySetInnerHTML:{__html:i}}))})))(t),t.attempted?"":Tt("span",{className:"resetq_answer button",onClick:t=>{let i={...e.question};i.marked_answer=null,n(i)}},Tt("i",{class:"vicon vicon-trash"}))):"")};const{createElement:Ft,render:jt,useState:Xt,useEffect:Yt,Fragment:Ut}=wp.element;var Jt,$t,Wt=e=>{const[t,n]=Xt({});Yt(()=>{n(e.question)},[e.question]);let i="";t.hasOwnProperty("marked_answer")&&(i=t.marked_answer);let a="";return t.hasOwnProperty("usercorrect")&&t.show_correct_answer&&(a="question_incorrect",t.usercorrect>0&&(a="question_correct")),Ft(Ut,null,Ft("div",{className:"question_content",dangerouslySetInnerHTML:{__html:t&&t.content?t.content:""}}),Ft("textarea",{className:a,type:"text",onChange:t=>{let i={...e.question};i.marked_answer=t.target.value,n(i),e.update(i,e.index,"changed")},value:i},i))},Vt=Vt||function(e,t){var n={},i=n.lib={},a=function(){},r=i.Base={extend:function(e){a.prototype=this;var t=new a;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=i.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||l).stringify(this)},concat:function(e){var t=this.words,n=e.words,i=this.sigBytes;if(e=e.sigBytes,this.clamp(),i%4)for(var a=0;a<e;a++)t[i+a>>>2]|=(n[a>>>2]>>>24-a%4*8&255)<<24-(i+a)%4*8;else if(65535<n.length)for(a=0;a<e;a+=4)t[i+a>>>2]=n[a>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],i=0;i<t;i+=4)n.push(4294967296*e.random()|0);return new s.init(n,t)}}),o=n.enc={},l=o.Hex={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],i=0;i<e;i++){var a=t[i>>>2]>>>24-i%4*8&255;n.push((a>>>4).toString(16)),n.push((15&a).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],i=0;i<t;i+=2)n[i>>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new s.init(n,t/2)}},c=o.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],i=0;i<e;i++)n.push(String.fromCharCode(t[i>>>2]>>>24-i%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],i=0;i<t;i++)n[i>>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new s.init(n,t)}},d=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},u=i.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,i=n.words,a=n.sigBytes,r=this.blockSize,o=a/(4*r);if(t=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*r,a=e.min(4*t,a),t){for(var l=0;l<t;l+=r)this._doProcessBlock(i,l);l=i.splice(0,t),n.sigBytes-=a}return new s.init(l,a)},clone:function(){var e=r.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});i.Hasher=u.extend({cfg:r.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){u.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,n){return new e.init(n).finalize(t)}},_createHmacHelper:function(e){return function(t,n){return new p.HMAC.init(e,n).finalize(t)}}});var p=n.algo={};return n}(Math);$t=(Jt=Vt).lib.WordArray,Jt.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,i=this._map;e.clamp(),e=[];for(var a=0;a<n;a+=3)for(var r=(t[a>>>2]>>>24-a%4*8&255)<<16|(t[a+1>>>2]>>>24-(a+1)%4*8&255)<<8|t[a+2>>>2]>>>24-(a+2)%4*8&255,s=0;4>s&&a+.75*s<n;s++)e.push(i.charAt(r>>>6*(3-s)&63));if(t=i.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,n=this._map;(i=n.charAt(64))&&-1!=(i=e.indexOf(i))&&(t=i);for(var i=[],a=0,r=0;r<t;r++)if(r%4){var s=n.indexOf(e.charAt(r-1))<<r%4*2,o=n.indexOf(e.charAt(r))>>>6-r%4*2;i[a>>>2]|=(s|o)<<24-a%4*8,a++}return $t.create(i,a)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,n,i,a,r,s){return((e=e+(t&n|~t&i)+a+s)<<r|e>>>32-r)+t}function n(e,t,n,i,a,r,s){return((e=e+(t&i|n&~i)+a+s)<<r|e>>>32-r)+t}function i(e,t,n,i,a,r,s){return((e=e+(t^n^i)+a+s)<<r|e>>>32-r)+t}function a(e,t,n,i,a,r,s){return((e=e+(n^(t|~i))+a+s)<<r|e>>>32-r)+t}for(var r=Vt,s=(l=r.lib).WordArray,o=l.Hasher,l=r.algo,c=[],d=0;64>d;d++)c[d]=4294967296*e.abs(e.sin(d+1))|0;l=l.MD5=o.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,r){for(var s=0;16>s;s++){var o=e[l=r+s];e[l]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}s=this._hash.words;var l=e[r+0],d=(o=e[r+1],e[r+2]),u=e[r+3],p=e[r+4],m=e[r+5],h=e[r+6],_=e[r+7],w=e[r+8],v=e[r+9],f=e[r+10],g=e[r+11],y=e[r+12],b=e[r+13],x=e[r+14],k=e[r+15],E=t(E=s[0],C=s[1],q=s[2],S=s[3],l,7,c[0]),S=t(S,E,C,q,o,12,c[1]),q=t(q,S,E,C,d,17,c[2]),C=t(C,q,S,E,u,22,c[3]);E=t(E,C,q,S,p,7,c[4]),S=t(S,E,C,q,m,12,c[5]),q=t(q,S,E,C,h,17,c[6]),C=t(C,q,S,E,_,22,c[7]),E=t(E,C,q,S,w,7,c[8]),S=t(S,E,C,q,v,12,c[9]),q=t(q,S,E,C,f,17,c[10]),C=t(C,q,S,E,g,22,c[11]),E=t(E,C,q,S,y,7,c[12]),S=t(S,E,C,q,b,12,c[13]),q=t(q,S,E,C,x,17,c[14]),E=n(E,C=t(C,q,S,E,k,22,c[15]),q,S,o,5,c[16]),S=n(S,E,C,q,h,9,c[17]),q=n(q,S,E,C,g,14,c[18]),C=n(C,q,S,E,l,20,c[19]),E=n(E,C,q,S,m,5,c[20]),S=n(S,E,C,q,f,9,c[21]),q=n(q,S,E,C,k,14,c[22]),C=n(C,q,S,E,p,20,c[23]),E=n(E,C,q,S,v,5,c[24]),S=n(S,E,C,q,x,9,c[25]),q=n(q,S,E,C,u,14,c[26]),C=n(C,q,S,E,w,20,c[27]),E=n(E,C,q,S,b,5,c[28]),S=n(S,E,C,q,d,9,c[29]),q=n(q,S,E,C,_,14,c[30]),E=i(E,C=n(C,q,S,E,y,20,c[31]),q,S,m,4,c[32]),S=i(S,E,C,q,w,11,c[33]),q=i(q,S,E,C,g,16,c[34]),C=i(C,q,S,E,x,23,c[35]),E=i(E,C,q,S,o,4,c[36]),S=i(S,E,C,q,p,11,c[37]),q=i(q,S,E,C,_,16,c[38]),C=i(C,q,S,E,f,23,c[39]),E=i(E,C,q,S,b,4,c[40]),S=i(S,E,C,q,l,11,c[41]),q=i(q,S,E,C,u,16,c[42]),C=i(C,q,S,E,h,23,c[43]),E=i(E,C,q,S,v,4,c[44]),S=i(S,E,C,q,y,11,c[45]),q=i(q,S,E,C,k,16,c[46]),E=a(E,C=i(C,q,S,E,d,23,c[47]),q,S,l,6,c[48]),S=a(S,E,C,q,_,10,c[49]),q=a(q,S,E,C,x,15,c[50]),C=a(C,q,S,E,m,21,c[51]),E=a(E,C,q,S,y,6,c[52]),S=a(S,E,C,q,u,10,c[53]),q=a(q,S,E,C,f,15,c[54]),C=a(C,q,S,E,o,21,c[55]),E=a(E,C,q,S,w,6,c[56]),S=a(S,E,C,q,k,10,c[57]),q=a(q,S,E,C,h,15,c[58]),C=a(C,q,S,E,b,21,c[59]),E=a(E,C,q,S,p,6,c[60]),S=a(S,E,C,q,g,10,c[61]),q=a(q,S,E,C,d,15,c[62]),C=a(C,q,S,E,v,21,c[63]);s[0]=s[0]+E|0,s[1]=s[1]+C|0,s[2]=s[2]+q|0,s[3]=s[3]+S|0},_doFinalize:function(){var t=this._data,n=t.words,i=8*this._nDataBytes,a=8*t.sigBytes;n[a>>>5]|=128<<24-a%32;var r=e.floor(i/4294967296);for(n[15+(a+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),n[14+(a+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,i=0;4>i;i++)a=n[i],n[i]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8);return t},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}}),r.MD5=o._createHelper(l),r.HmacMD5=o._createHmacHelper(l)}(Math),function(){var e,t=Vt,n=(e=t.lib).Base,i=e.WordArray,a=(e=t.algo).EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=(o=this.cfg).hasher.create(),a=i.create(),r=a.words,s=o.keySize,o=o.iterations;r.length<s;){l&&n.update(l);var l=n.update(e).finalize(t);n.reset();for(var c=1;c<o;c++)l=n.finalize(l),n.reset();a.concat(l)}return a.sigBytes=4*s,a}});t.EvpKDF=function(e,t,n){return a.create(n).compute(e,t)}}(),Vt.lib.Cipher||function(e){var t=(m=Vt).lib,n=t.Base,i=t.WordArray,a=t.BufferedBlockAlgorithm,r=m.enc.Base64,s=m.algo.EvpKDF,o=t.Cipher=a.extend({cfg:n.extend(),createEncryptor:function(e,t){return this.create(this._ENC_XFORM_MODE,e,t)},createDecryptor:function(e,t){return this.create(this._DEC_XFORM_MODE,e,t)},init:function(e,t,n){this.cfg=this.cfg.extend(n),this._xformMode=e,this._key=t,this.reset()},reset:function(){a.reset.call(this),this._doReset()},process:function(e){return this._append(e),this._process()},finalize:function(e){return e&&this._append(e),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(e){return{encrypt:function(t,n,i){return("string"==typeof n?h:p).encrypt(e,t,n,i)},decrypt:function(t,n,i){return("string"==typeof n?h:p).decrypt(e,t,n,i)}}}});t.StreamCipher=o.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var l=m.mode={},c=function(e,t,n){var i=this._iv;i?this._iv=void 0:i=this._prevBlock;for(var a=0;a<n;a++)e[t+a]^=i[a]},d=(t.BlockCipherMode=n.extend({createEncryptor:function(e,t){return this.Encryptor.create(e,t)},createDecryptor:function(e,t){return this.Decryptor.create(e,t)},init:function(e,t){this._cipher=e,this._iv=t}})).extend();d.Encryptor=d.extend({processBlock:function(e,t){var n=this._cipher,i=n.blockSize;c.call(this,e,t,i),n.encryptBlock(e,t),this._prevBlock=e.slice(t,t+i)}}),d.Decryptor=d.extend({processBlock:function(e,t){var n=this._cipher,i=n.blockSize,a=e.slice(t,t+i);n.decryptBlock(e,t),c.call(this,e,t,i),this._prevBlock=a}}),l=l.CBC=d,d=(m.pad={}).Pkcs7={pad:function(e,t){for(var n,a=(n=(n=4*t)-e.sigBytes%n)<<24|n<<16|n<<8|n,r=[],s=0;s<n;s+=4)r.push(a);n=i.create(r,n),e.concat(n)},unpad:function(e){e.sigBytes-=255&e.words[e.sigBytes-1>>>2]}},t.BlockCipher=o.extend({cfg:o.cfg.extend({mode:l,padding:d}),reset:function(){o.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=t.createEncryptor;else n=t.createDecryptor,this._minBufferSize=1;this._mode=n.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var u=t.CipherParams=n.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),p=(l=(m.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?i.create([1398893684,1701076831]).concat(e).concat(t):t).toString(r)},parse:function(e){var t=(e=r.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=i.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return u.create({ciphertext:e,salt:n})}},t.SerializableCipher=n.extend({cfg:n.extend({format:l}),encrypt:function(e,t,n,i){i=this.cfg.extend(i);var a=e.createEncryptor(n,i);return t=a.finalize(t),a=a.cfg,u.create({ciphertext:t,key:n,iv:a.iv,algorithm:e,mode:a.mode,padding:a.padding,blockSize:e.blockSize,formatter:i.format})},decrypt:function(e,t,n,i){return i=this.cfg.extend(i),t=this._parse(t,i.format),e.createDecryptor(n,i).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),m=(m.kdf={}).OpenSSL={execute:function(e,t,n,a){return a||(a=i.random(8)),e=s.create({keySize:t+n}).compute(e,a),n=i.create(e.words.slice(t),4*n),e.sigBytes=4*t,u.create({key:e,iv:n,salt:a})}},h=t.PasswordBasedCipher=p.extend({cfg:p.cfg.extend({kdf:m}),encrypt:function(e,t,n,i){return n=(i=this.cfg.extend(i)).kdf.execute(n,e.keySize,e.ivSize),i.iv=n.iv,(e=p.encrypt.call(this,e,t,n.key,i)).mixIn(n),e},decrypt:function(e,t,n,i){return i=this.cfg.extend(i),t=this._parse(t,i.format),n=i.kdf.execute(n,e.keySize,e.ivSize,t.salt),i.iv=n.iv,p.decrypt.call(this,e,t,n.key,i)}})}(),function(){for(var e=Vt,t=e.lib.BlockCipher,n=e.algo,i=[],a=[],r=[],s=[],o=[],l=[],c=[],d=[],u=[],p=[],m=[],h=0;256>h;h++)m[h]=128>h?h<<1:h<<1^283;var _=0,w=0;for(h=0;256>h;h++){var v=(v=w^w<<1^w<<2^w<<3^w<<4)>>>8^255&v^99;i[_]=v,a[v]=_;var f=m[_],g=m[f],y=m[g],b=257*m[v]^16843008*v;r[_]=b<<24|b>>>8,s[_]=b<<16|b>>>16,o[_]=b<<8|b>>>24,l[_]=b,b=16843009*y^65537*g^257*f^16843008*_,c[v]=b<<24|b>>>8,d[v]=b<<16|b>>>16,u[v]=b<<8|b>>>24,p[v]=b,_?(_=f^m[m[m[y^f]]],w^=m[m[w]]):_=w=1}var x=[0,1,2,4,8,16,32,64,128,27,54];n=n.AES=t.extend({_doReset:function(){for(var e=(n=this._key).words,t=n.sigBytes/4,n=4*((this._nRounds=t+6)+1),a=this._keySchedule=[],r=0;r<n;r++)if(r<t)a[r]=e[r];else{var s=a[r-1];r%t?6<t&&4==r%t&&(s=i[s>>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s]):(s=i[(s=s<<8|s>>>24)>>>24]<<24|i[s>>>16&255]<<16|i[s>>>8&255]<<8|i[255&s],s^=x[r/t|0]<<24),a[r]=a[r-t]^s}for(e=this._invKeySchedule=[],t=0;t<n;t++)r=n-t,s=t%4?a[r]:a[r-4],e[t]=4>t||4>=r?s:c[i[s>>>24]]^d[i[s>>>16&255]]^u[i[s>>>8&255]]^p[i[255&s]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,r,s,o,l,i)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,c,d,u,p,a),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,i,a,r,s,o){for(var l=this._nRounds,c=e[t]^n[0],d=e[t+1]^n[1],u=e[t+2]^n[2],p=e[t+3]^n[3],m=4,h=1;h<l;h++){var _=i[c>>>24]^a[d>>>16&255]^r[u>>>8&255]^s[255&p]^n[m++],w=i[d>>>24]^a[u>>>16&255]^r[p>>>8&255]^s[255&c]^n[m++],v=i[u>>>24]^a[p>>>16&255]^r[c>>>8&255]^s[255&d]^n[m++];p=i[p>>>24]^a[c>>>16&255]^r[d>>>8&255]^s[255&u]^n[m++],c=_,d=w,u=v}_=(o[c>>>24]<<24|o[d>>>16&255]<<16|o[u>>>8&255]<<8|o[255&p])^n[m++],w=(o[d>>>24]<<24|o[u>>>16&255]<<16|o[p>>>8&255]<<8|o[255&c])^n[m++],v=(o[u>>>24]<<24|o[p>>>16&255]<<16|o[c>>>8&255]<<8|o[255&d])^n[m++],p=(o[p>>>24]<<24|o[c>>>16&255]<<16|o[d>>>8&255]<<8|o[255&u])^n[m++],e[t]=_,e[t+1]=w,e[t+2]=v,e[t+3]=p},keySize:8});e.AES=t._createHelper(n)}();var Kt=Vt,Gt={stringify:function(e){var t={ct:e.ciphertext.toString(Kt.enc.Base64)};return e.iv&&(t.iv=e.iv.toString()),e.salt&&(t.s=e.salt.toString()),JSON.stringify(t).replace(/\s/g,"")},parse:function(e){var t=JSON.parse(e),n=Kt.lib.CipherParams.create({ciphertext:Kt.enc.Base64.parse(t.ct)});return t.iv&&(n.iv=Kt.enc.Hex.parse(t.iv)),t.s&&(n.salt=Kt.enc.Hex.parse(t.s)),n}};var Qt=e=>{let t="";if(!e.type)return t;if(!e.marked||"undefined"==e.marked)return t;switch(e.type){case"truefalse":case"single":case"survey":t=e.options[parseInt(e.marked)];break;case"multiple":if(t="",(n=e.marked.split(",")).length)for(let i=0;i<n.length;i++)t+=e.options[parseInt(n[i])]+(i+1<n.length?" , ":"");break;case"sort":case"match":if((n=e.marked.split(",")).length)for(let i=0;i<n.length;i++)"undefined"!==e.original_options[parseInt(n[i])-1]&&null!=e.original_options[parseInt(n[i])-1]&&""!=e.original_options[parseInt(n[i])-1]||(e.original_options[parseInt(n[i])-1]="____"),t+=e.original_options[parseInt(n[i])-1]+(i+1<n.length?" , ":"");break;case"select":if(t="",(n=e.marked.split("|")).length)for(let i=0;i<n.length;i++)t+=e.options[parseInt(n[i])]+(i+1<n.length?" , ":"");break;case"fillblank":case"text":var n;if(t="",(n=e.marked.split("|")).length)for(let e=0;e<n.length;e++)t+=n[e]+(e+1<n.length?" , ":"");break;case"largetext":case"smalltext":t=e.marked}return t};var Zt=e=>{let t="";if(!e.type)return"";switch(e.type){case"truefalse":t=e.correct?window.wplms_course_data.translations.true:window.wplms_course_data.translations.false;break;case"single":case"survey":t=e.options[parseInt(e.correct)-1];break;case"multiple":if(t="",(n=e.correct.split(",")).length)for(let i=0;i<n.length;i++)t+=e.options[parseInt(n[i])-1]+(i+1<n.length?" , ":"");break;case"sort":case"match":if(t="",(n=e.correct.split(",")).length)for(let i=0;i<n.length;i++)t+=e.original_options[parseInt(n[i])-1]+(i+1<n.length?" , ":"");break;case"select":if(t="",(n=e.correct.split("|")).length)for(let i=0;i<n.length;i++)t+=e.options[parseInt(n[i])-1]+(i+1<n.length?" , ":"");break;case"fillblank":case"text":case"largetext":case"smalltext":var n;if(t="",(n=e.correct.split("|")).length)for(let e=0;e<n.length;e++)t+=n[e]+(e+1<n.length?" , ":"")}return t};function en(e){if(null==e)return!0;if(void 0===e)return!0;if("number"==typeof e)return!1;if(Array.isArray(e)||"string"==typeof e||e instanceof String)return 0===e.length;for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}var tn=(e,t=null,n=null,i=null,a=!0)=>{i&&(i=parseFloat(i)),n||(i=null);let r=0,s=[],o=0;e.user_marks=0;let l=0,c=null;en(e.correct)||(c=JSON.parse(Kt.AES.decrypt(e.correct,e.key,{format:Gt}).toString(Kt.enc.Utf8))),e.correct=c,e.marked_answer&&"undefined"!=e.marked_answer||(e.marked_answer=null);let d=e.marked_answer;switch(e.type){case"truefalse":e.marked=d,e.correct=parseInt(c),d==c?(e.user_marks=e.marks,r=1):e.user_marks=0,s.push(c);break;case"single":e.marked=d,d==c-1?(e.user_marks=e.marks,r=1):e.user_marks=0,s.push(c-1);break;case"multiple":en(d)&&(d=[]);var u=d;e.marked=d.join(",").slice();var p=c.split(",");if(s=p,t){if(u.length)for(let e=0;e<u.length;e++){let t=u[e]+1;t=t.toString(),-1!==p.indexOf(t)?o++:l++}r=o/p.length,e.user_marks=Math.round(e.marks*r*100)/100}else if(u.length==p.length)for(let t=0;t<u.length;t++){e.user_marks=e.marks,r=1;let n=u[t]+1;if(n=n.toString(),-1==p.indexOf(n)){e.user_marks=0,r=0;break}}break;case"match":case"sort":en(d)&&(d=[]),e.marked=d.join(",").slice();let n=d,i=c.split(","),a=0;if(n&&n.length){for(let t=0;t<n.length;t++){e.user_marks=e.marks,r=1;let c="";en(n[t])||(c=n[t].toString()),i[t]!=c?(r&&(e.user_marks=0,r=0,a=1),l++):(o++,s.push(t))}t?(r=o/i.length,e.user_marks=Math.round(e.marks*r*100)/100):a&&(e.user_marks=0,r=0)}break;case"fillblank":en(d)&&(d=[]),d.map((e,t)=>{d[t]=e.toLowerCase()}),e.marked=d.join("|").slice(),c=c.toLowerCase();let m=c.split("|");if(e.user_marks=0,d.length){e.user_marks=e.marks,r=1;for(let t=0;t<d.length;t++){let n="";en(d[t])||(n=d[t].toString());let i=[];en(m[t])||Array.isArray(m[t])||(i=m[t].split(",")),-1==i.indexOf(n)?(r&&(e.user_marks=0,r=0),l++):(o++,s.push(t))}t?(r=o/m.length,e.user_marks=Math.round(e.marks*r*100)/100):d.length!==m.length&&(e.user_marks=0,r=0)}break;case"select":en(d)&&(d=[]),e.marked=d.join("|").slice();let h=c.split("|");if(e.user_marks=0,d&&d.length){e.user_marks=e.marks,r=1;for(let t=0;t<d.length;t++){let n="";n=(parseInt(d[t])+1).toString(),n!=h[t]?(r&&(e.user_marks=0,r=0),l++):(o++,s.push(t))}t?(r=o/h.length,e.user_marks=Math.round(e.marks*r*100)/100):d.length!==h.length&&(e.user_marks=0,r=0)}break;case"smalltext":case"largetext":e.marked=d,d&&c&&d.toLowerCase()==c.toLowerCase()?(e.user_marks=e.marks,r=1):e.user_marks=0}if(!en(d)&&i&&(t&&l>0?e.user_marks=e.user_marks-l*i:r||(e.user_marks=e.user_marks-i)),e.auto||a||(e.user_marks=0,e.show_correct_answer=0),s&&s.length)for(var m=s.length-1;m>=0;m--)"multiple"==e.type?s[m]=parseInt(s[m]-1):s[m]=parseInt(s[m]);return e.correct_indexes=s,e.auto&&(e.usercorrect=r,e.attempted=!0),e.marked=Qt(e),e.correct=Zt(e),e};const{createElement:nn,render:an,useState:rn,useEffect:sn,Fragment:on,RawHTML:ln}=wp.element;var cn=e=>{const[t,n]=rn({}),[i,a]=rn(!1);sn(()=>{n(e.question),setTimeout(()=>{a(!0)},200)},[]);let r="incorrect",s="checked_answer incorrect";return t.hasOwnProperty("user_marks")&&t.user_marks&&parseFloat(t.user_marks)>0&&(r="correct",s="checked_answer correct"),nn(on,null,t.show_correct_answer&&void 0!==t.correct&&t.correct.length?nn("div",{className:s},nn("strong",null,window.wplms_course_data.translations.correct_answer,nn(ln,null,t.correct))):"",nn("div",{className:i?"question_wrapper loaded":"question_wrapper"},nn("div",{className:"result"},nn("div",{className:r},nn("span",null),nn("strong",null,t.user_marks)))))};const{createElement:dn,render:un,useState:pn,useEffect:mn,Fragment:hn}=wp.element;var _n=e=>{let t="",n="";return mn(()=>{},[e.question]),e.question.hasOwnProperty("show_hint")&&e.question.show_hint?(n="question_hint_content message show",t="question_hint show"):(e.question.show_hint=0,n="question_hint_content message",t="question_hint"),dn(hn,null,e.question.hint?dn("span",{className:t,onClick:t=>{e.question.show_hint=!e.question.show_hint,e.update({...e.question},e.index,"changed")}}):"",e.question.hint?dn("span",{className:n,dangerouslySetInnerHTML:{__html:e.question.hint}}):"")};const{createElement:wn,render:vn,useState:fn,useEffect:gn,Fragment:yn}=wp.element,{dispatch:bn,select:xn}=wp.data;var kn=e=>{const[t,n]=fn({}),[i,a]=fn(!1),[s,o]=fn(null);gn(()=>{n(e.question),a(!0)},[e.question]);const l=(e,i=0,a)=>{let r={...t};"changed"==a&&(r=e,n(r),!function(e){if(null==e)return!0;if("number"==typeof e)return!0;if(Array.isArray(e)||"string"==typeof e||e instanceof String)return 0===e.length;for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}(e.marked_answer)?"object"==typeof e.marked_answer||Array.isArray(e.marked_answer)?localStorage.setItem(e.id,JSON.stringify(e.marked_answer)):localStorage.setItem(e.id,e.marked_answer):null==e.marked_answer&&localStorage.removeItem(e.id))};return i?t?wn(yn,null,wn("div",{className:"incourse"},wn("div",{className:"quiz_questions_content"},wn("div",{className:"question_cwrapper"},wn("div",{className:"question","data-i":e.i},wn(_n,{question:t,update:l}),(e=>{switch(e.type){case"smalltext":return wn(Ie,{question:e,update:l});case"single":return wn(Re,{question:e,update:l,quiz_id:e.id});case"select":return wn(Ue,{question:e,update:l,quiz_id:e.id});case"multiple":return wn(Ge,{question:e,update:l,quiz_id:e.id});case"fillblank":return wn(ct,{question:e,update:l,quiz_id:e.id});case"sort":return wn(bt,{question:e,update:l,quiz_id:e.id});case"match":return wn(Lt,{question:e,update:l,quiz_id:e.id});case"truefalse":return wn(Dt,{question:e,update:l,quiz_id:e.id});case"largetext":return wn(Wt,{question:e,update:l,quiz_id:e.id})}})({...t}),t.attempted?"":wn("div",{className:"quiz_check_answer button",onClick:e=>{(e=>{let t={...e};a(!1),t=tn(t,null,null,null,!0),t.attempted=!0,a(!0),n(t)})(t)}},window.wplms_course_data.translations.check_answer),t.attempted?wn(cn,{question:t}):"",t.attempted&&t.explanation.length?wn("div",{className:"explanation"},wn("strong",null,window.wplms_course_data.translations.question_explanation),wn("div",{dangerouslySetInnerHTML:{__html:t.explanation}})):"")),t.attempted&&window.wplms_course_data.question_retries?wn("div",{className:"quiz_check_answer button",onClick:e=>{(()=>{let e={...t};if(e.hasOwnProperty("original")){let t=e;e=t.original,e.original=t.original,n(e)}})()}},wn("span",{className:"vicon vicon-reload"}),window.wplms_course_data.translations.retry):""))):"":wn(r,null)};const{createElement:En,render:Sn,useState:qn,useEffect:Cn,Fragment:Nn}=wp.element,{dispatch:On,select:Mn}=wp.data;function zn(e){if(null==e)return!0;if("number"==typeof e)return!0;if(Array.isArray(e)||"string"==typeof e||e instanceof String)return 0===e.length;for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}var Pn=e=>{const[t,n]=qn([]),[i,a]=qn(!1),[s,o]=qn(0);Cn(()=>{l()},[e.questions,s]);const l=()=>{a(!1);let t=`${window.wplms_course_data.api_url}/course/questions/?client_id=${window.wplms_course_data.client_id}`;e.hasOwnProperty("force")&&e.force&&(t+="?force"),fetch(t,{method:"post",headers:window.vibebp.xnonce?{"X-WP-Nonce":window.vibebp.xnonce}:{},body:JSON.stringify({questions:e.questions,page:s+1,per_page:window.wplms_course_data.practice_questions})}).then(e=>e.ok?e.json():{status:0,message:window.wplms_course_data.translations.error_loading_data}).then(e=>{if(e.status){if(e.questions){let t=[];e.questions.map(e=>{let n=localStorage.getItem(e.id);!zn(n)&&zn(e.marked_answer)&&(!function(e){try{JSON.parse(e)}catch(e){return!1}return!0}(n)?e.marked_answer=n:e.marked_answer=JSON.parse(n)),t.push(e)}),n(t)}a(!0)}else console.log(e)}).catch(e=>{a(!0),console.error("Uh oh, an error!",e),On("vibebp").addNotification({text:window.wplms_course_data.translations.error_loading_data})})};return En("div",{className:"practice_questions"},i?t.filter((e,t)=>t<(s+1)*window.wplms_course_data.practice_questions).map(e=>En(kn,{question:e,i:s*window.wplms_course_data.practice_questions+t.indexOf(e)+1})):En(r,null),e.questions.length>window.wplms_course_data.practice_questions?En("div",{className:"buttons has-addons"},s>0?En("span",{className:"button vicon vicon-angle-left",onClick:()=>{i&&o(s-1)}}):"",s<Math.floor(e.questions.length/window.wplms_course_data.practice_questions)?En("span",{className:"button vicon vicon-angle-right",onClick:()=>{i&&o(s+1)}}):""):"")};const{createElement:In,render:Ln,useState:Tn,useEffect:An,Fragment:Bn,useContext:Hn}=wp.element,{dispatch:Rn,select:Dn}=wp.data;var Fn=e=>{const[t,n]=Tn(null),[i,a]=Tn(e.curriculumItem),[r,s]=Tn(!1),[o,l]=Tn(!1),[c,d]=Tn(!1),[u,m]=Tn(!1);Hn(X);An(()=>{a({...e.curriculumItem})},[e.curriculumItem]),An(()=>{var e;if(document.querySelector(".wp-playlist.wp-video-playlist")&&(void 0!==(e=JSON.parse(document.querySelector(".wp-playlist-script").innerHTML))&&e&&e.hasOwnProperty("tracks")&&e.tracks.length)){document.querySelector(".wp-playlist video")&&document.querySelector(".wp-playlist video").remove(),(n=document.createElement("div")).classList.add("wplms-playlist");var t=document.createElement("video");n.appendChild(t),document.querySelector(".wp-playlist.wp-video-playlist").parentNode.appendChild(n),setTimeout(()=>{new Plyr(".wplms-playlist video").source={type:"video",sources:e.tracks};var t=document.createElement("div");t.classList.add("wplms_playlist");let n=document.createElement("div");n.classList.add("prevnextbuttonsdiv");let i=document.createElement("span");i.classList.add("wp-playlist-prev-button");let a=document.createElement("span");a.classList.add("wp-playlist-next-button"),n.appendChild(i),n.appendChild(a),document.querySelector(".wp-playlist.wp-video-playlist").parentNode.prepend(n),a.onclick=e=>{h(e,"forward","video")},i.onclick=e=>{h(e,"backward","video")},e.tracks.map((e,n)=>{var i=document.createElement("span");i.classList.add("track"),i.setAttribute("data-url",e.src),i.innerHTML=e.title,n<1&&i.classList.add("active"),i.onclick=t=>{t.preventDefault(),document.querySelector(".wplms_playlist .track")&&document.querySelectorAll(".wplms_playlist .track").forEach((e,t)=>{e.classList.remove("active")}),t.target.classList.add("active"),document.querySelector(".wplms-playlist video")&&document.querySelector(".wplms-playlist video").remove();var n=document.createElement("div");n.classList.add("wplms-playlist");var i=document.createElement("video");n.appendChild(i),document.querySelector(".wp-playlist.wp-video-playlist").parentNode.appendChild(n),setTimeout(()=>{new Plyr(".wplms-playlist video").source={type:"video",sources:[e]}},200)},t.appendChild(i)}),document.querySelector(".wp-playlist.wp-video-playlist").appendChild(t)},200)}if(document.querySelector(".wp-playlist.wp-audio-playlist")&&(void 0!==(e=JSON.parse(document.querySelector(".wp-playlist-script").innerHTML))&&e&&e.hasOwnProperty("tracks")&&e.tracks.length)){var n;document.querySelector(".wp-playlist audio")&&document.querySelector(".wp-playlist audio").remove(),document.querySelector(".wp-playlist-current-item")&&document.querySelector(".wp-playlist-current-item").remove(),(n=document.createElement("div")).classList.add("wplms-playlist");t=document.createElement("audio");n.appendChild(t),document.querySelector(".wp-playlist.wp-audio-playlist").parentNode.appendChild(n),setTimeout(()=>{new Plyr(".wplms-playlist audio").source={type:"audio",sources:e.tracks};var t=document.createElement("div");t.classList.add("wplms_playlist");let n=document.createElement("div");n.classList.add("prevnextbuttonsdiv");let i=document.createElement("span");i.classList.add("wp-playlist-prev-button");let a=document.createElement("span");a.classList.add("wp-playlist-next-button"),n.appendChild(i),n.appendChild(a),document.querySelector(".wp-playlist.wp-audio-playlist").parentNode.prepend(n),a.onclick=e=>{h(e,"forward","audio")},i.onclick=e=>{h(e,"backward","audio")},e.tracks.map((e,n)=>{var i=document.createElement("span");i.classList.add("track"),i.setAttribute("data-url",e.src),i.innerHTML=e.title,n<1&&i.classList.add("active"),i.onclick=t=>{t.preventDefault(),document.querySelector(".wplms_playlist .track")&&document.querySelectorAll(".wplms_playlist .track").forEach((e,t)=>{e.classList.remove("active")}),t.target.classList.add("active"),document.querySelector(".wplms-playlist")&&document.querySelector(".wplms-playlist").remove();var n=document.createElement("div");n.classList.add("wplms-playlist");var i=document.createElement("audio");n.appendChild(i),document.querySelector(".wp-playlist.wp-audio-playlist").parentNode.appendChild(n),setTimeout(()=>{let t=new Plyr(".wplms-playlist audio");t.source={type:"audio",sources:[e]},t.play()},200)},t.appendChild(i)}),document.querySelector(".wp-playlist.wp-audio-playlist").appendChild(t)},200)}},[i]);const h=(e,t,n)=>{if("forward"==t){for(let e=0;e<document.querySelectorAll(".wp-"+n+"-playlist .wplms_playlist .track").length;e++)if(document.querySelectorAll(".wp-"+n+"-playlist .wplms_playlist .track")[e].classList.contains("active")&&e<document.querySelectorAll(".wp-"+n+"-playlist .wplms_playlist .track").length-1){document.querySelector(".wplms_playlist .track")&&document.querySelectorAll(".wplms_playlist .track").forEach((e,t)=>{e.classList.remove("active")}),document.querySelectorAll(".wp-"+n+"-playlist .wplms_playlist .track")[e+1].classList.add("active"),document.querySelector(".wplms-playlist")&&document.querySelector(".wplms-playlist").remove();let t=document.createElement("div");t.classList.add("wplms-playlist");let i=document.createElement(n);t.appendChild(i),document.querySelector(".wp-playlist.wp-"+n+"-playlist").parentNode.appendChild(t),setTimeout(()=>{let t=new Plyr(".wplms-playlist "+n);t.source={type:n,sources:[{src:document.querySelectorAll(".wp-"+n+"-playlist .wplms_playlist .track")[e+1].getAttribute("data-url")}]},t.play()},200);break}}else for(let e=document.querySelectorAll(".wp-"+n+"-playlist .wplms_playlist .track").length-1;e>=0;e--)if(document.querySelectorAll(".wp-"+n+"-playlist .wplms_playlist .track")[e].classList.contains("active")&&0!=e){document.querySelector(".wplms_playlist .track")&&document.querySelectorAll(".wplms_playlist .track").forEach((e,t)=>{e.classList.remove("active")}),document.querySelectorAll(".wp-"+n+"-playlist .wplms_playlist .track")[e-1].classList.add("active"),document.querySelector(".wplms-playlist")&&document.querySelector(".wplms-playlist").remove();var i=document.createElement("div");i.classList.add("wplms-playlist");var a=document.createElement(n);i.appendChild(a),document.querySelector(".wp-playlist.wp-"+n+"-playlist").parentNode.appendChild(i),setTimeout(()=>{let t=new Plyr(".wplms-playlist "+n);t.source={type:n,sources:[{src:document.querySelectorAll(".wp-"+n+"-playlist .wplms_playlist .track")[e-1].getAttribute("data-url")}]},t.play()},200);break}};let _="";if(i.meta.hasOwnProperty("video")&&"object"==typeof i.meta.video&&"video"==i.meta.video.type){let e=i.meta.video.url.split(".");switch(e[e.length-1]){case"mov":_="video/mp4";break;default:_="video/"+e[e.length-1]}}if(i.meta.hasOwnProperty("audio")&&"object"==typeof i.meta.audio&&"audio"==i.meta.audio.type){let e=i.meta.audio.url.split(".");switch(e[e.length-1]){case"m4a":_="audio/mp4";break;case"oga":_="audio/ogg";break;default:_="audio/"+e[e.length-1]}}const w=async(t,n,a=null)=>{if(t){let o={};window.wplms_course_data.course.status.seek_lock&&(o.listeners={seek:e=>{var t=r.currentTime;if(((e,t)=>"object"!=typeof t||"input"!==t.type&&"change"!==t.type?Number(t):t.target.value/t.target.max*e.media.duration)(r,e)>t)return e.preventDefault(),!1}});const l=await localforage.getItem(n);l&&document.querySelector(".media_video_meta"+a+" source")&&document.querySelector(".media_video_meta"+a+" source").setAttribute("src",URL.createObjectURL(l));let c=new Plyr(t,o);c.once("loadeddata",()=>{let e=localStorage.getItem(n);e&&e<=c.duration&&(c.currentTime=e),s({plyr:c,url:n})}),null===a||i.status||c.once("ended",t=>{e.update({index:a,src:n,event:t},"videosended")})}};((e,t,n=[])=>{const i=_e(Date.now());pe(()=>{const n=setTimeout((function(){Date.now()-i.current>=t&&(e(),i.current=Date.now())}),t-(Date.now()-i.current));return()=>{clearTimeout(n)}},[t,...n])})(()=>{void 0!==r.player&&r.player.on("playing",()=>{localStorage.setItem(r.url,r.player.currentTime)})},500,[r,o]);const v=(e,t)=>{let n={...i};n.meta.hasOwnProperty("assignments")&&n.meta.assignments.length&&n.meta.assignments[t]&&(n.meta.assignments[t].show=e),a(n)},f=(t,n)=>{"complete"==n&&e.update({assignmentIndex:t.assignmentIndex},"completeUnitAssigmnent"),"retake"==n&&e.update({assignmentIndex:t.assignmentIndex},"retakeUnitAssigmnent")};window.scorm_page_type="unit",window.hasOwnProperty("scorm_wplms_data")||(window.scorm_wplms_data={}),window.scorm_wplms_data.module_id=i.id,window.scorm_wplms_data.type="unit";const g=e=>{e&&!t&&n(e)},y=(t,n)=>{e.update(n,"mediaended")};let b=[],x=[];if(i.meta.hasOwnProperty("video")&&"object"==typeof i.meta.video){if("youtube"==i.meta.video.type){let e=i.meta.video.url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&|?]+)/);e&&e.length&&(b=e[1])}"vimeo"==i.meta.video.type&&(x=i.meta.video.url.match(/(http|https)?:\/\/(www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|)(\d+)(?:|\/\?)/))}return In("div",{className:"course_content_content"},e.hasOwnProperty("noLabels")&&e.noLabels?"":In(Bn,null,In("span",{className:"lesson_info"},In("span",null,window.wplms_course_data.reports.module.unit+" ",e.item_number+"/"+e.total_item_count),In("span",null," "),In(ce,{timestamp:i.duration,notimediff:1})),In("h2",{dangerouslySetInnerHTML:{__html:i.title}})),In("div",null,i.meta.hasOwnProperty("access")&&i.meta.access||!i.meta.hasOwnProperty("drip_time")?i.meta.hasOwnProperty("video")&&"object"==typeof i.meta.video&&!Array.isArray(i.meta.video)?"youtube"==i.meta.video.type?In("div",null,b&&b.length?In(Ce,{provider:"youtube",index:e.index,embed_id:b,url:i.meta.video.url,update:y}):""):"vimeo"==i.meta.video.type&&void 0!==x&&x&&void 0!==x[4]&&x[4]?In("div",null,In(Ce,{provider:"vimeo",index:e.index,embed_id:x[4],url:i.meta.video.url,update:y})):In("div",null,In(Ce,{provider:"local",index:e.index,src:i.meta.video.url,mime_type:_,url:i.meta.video.url,video:i.meta.video,update:y})):i.meta.hasOwnProperty("audio")&&"object"==typeof i.meta.audio&&!Array.isArray(i.meta.audio)&&i.meta.audio.url.length?In("div",null,In("div",null,In("audio",{className:"activity_meta audio",ref:e=>{w(e,i.meta.audio.url)}},In("source",{src:i.meta.audio.url,type:_})))):i.meta.hasOwnProperty("package")?In("div",{className:"unit_iframe_wrapper"},In("iframe",{src:i.meta.package.src,width:"100%",height:"100%",frameborder:"0",allowfullscreen:"allowfullscreen"})):In("div",{className:i.type+""+i.id}):In(p,{start:!0,duration:i.meta.drip_time,update:(t,n)=>{"expired"==n&&e.update({index:e.index},"loadunit")},quiz_id:e.index})),i.meta&&i.meta.hasOwnProperty("access")&&i.meta.access&&i.meta.hasOwnProperty("video")&&i.meta.video.length?In("div",{className:"unit_videos"},i.meta.video.map((e,t)=>In("div",{className:"video_wrapper"},In("video",{className:"activity_meta video media_video_meta"+t,ref:n=>w(n,e,t)},In("source",{src:e,type:"video/mp4"}))))):"",i.meta&&i.meta.hasOwnProperty("access")&&i.meta.access&&i.meta.hasOwnProperty("audio")&&i.meta.audio.length?In("div",{className:"unit_videos"},i.meta.audio.map((e,t)=>In("div",{className:"video_wrapper"},In("audio",{className:"activity_meta video media_video_meta"+t,ref:n=>w(n,e,t)},In("source",{src:e,type:"audio/mpeg"}))))):"",i.meta&&i.meta.hasOwnProperty("access")&&i.meta.access&&i.meta.hasOwnProperty("iframes")&&i.meta.iframes.length?In("div",{className:"unit_iframes"},i.meta.iframes.map((e,t)=>"object"==typeof e&&e.hasOwnProperty("value")?In("div",{className:"unit_iframe_wrapper "+e.shortcode},In("iframe",{src:e.value,width:"560",height:"315",frameborder:"0",allowfullscreen:"allowfullscreen"})):In("div",{className:"unit_iframe_wrapper"},In("iframe",{src:e,width:"560",height:"315",frameborder:"0",allowfullscreen:"allowfullscreen"})))):"",i.hasOwnProperty("unit_type")&&"elementor"===i.unit_type?(()=>{if(i.hasOwnProperty("meta")&&i.meta.hasOwnProperty("link")&&i.meta.link.length){let e=i.meta.link;return e.includes("?")?e+="&token="+Dn("vibebp").getToken():e+="?token="+Dn("vibebp").getToken(),In("div",{className:"wplms_iframe_wrapper"},In("iframe",{src:e,width:"100%"}))}return In("div",{dangerouslySetInnerHTML:{__html:i.content},ref:g})})():In("div",{dangerouslySetInnerHTML:{__html:i.content},ref:g}),i.meta&&i.meta.hasOwnProperty("access")&&i.meta.access&&i.meta.attachments&&i.meta.attachments.length?In("div",{className:"unit_attachments"},In("h3",null,window.wplms_course_data.translations.attachments),i.meta.attachments.map((e,t)=>{return In("div",{className:"attachment"},In("span",null,"application/pdf"==(n=e.type)?In("span",{className:"attachment_icon",dangerouslySetInnerHTML:{__html:window.wplms_course_data.course.attachment_types["application/pdf"]}}):"image/jpeg"==n?In("span",{className:"attachment_icon",dangerouslySetInnerHTML:{__html:window.wplms_course_data.course.attachment_types["image/jpeg"]}}):"video/mp4"==n?In("span",{className:"attachment_icon",dangerouslySetInnerHTML:{__html:window.wplms_course_data.course.attachment_types["video/mp4"]}}):"application/pdf"==n||"application/pdf"==n?"":In("span",{className:"attachment_icon",dangerouslySetInnerHTML:{__html:window.wplms_course_data.course.attachment_types.default}}),In("strong",{dangerouslySetInnerHTML:{__html:e.name}})),In("a",{href:e.link,download:e.link.substring(e.link.lastIndexOf("/")+1),target:"_blank",className:"vicon vicon-download"}));var n})):"",i.meta&&i.meta.hasOwnProperty("access")&&i.meta.access&&i.meta.attachments&&i.meta.assignments.length?In("div",{className:"unit_assignments"},In("h3",null,window.wplms_course_data.translations.assignments),i.meta.assignments.map((t,n)=>In("div",{className:"assignment"},In("div",{className:"assignment_heading"},In("span",null,t.title),In("div",{className:"assignment_meta"},t&&t.hasOwnProperty("show")&&t.show?In("a",{className:"vicon vicon-minus",onClick:()=>{v(!1,n)}}):In("a",{className:"vicon vicon-plus",onClick:()=>{v(!0,n)}}))),t.show?In("div",{className:"assignment_content_wrapper"},In(Z,{assignment:t,assignmentIndex:n,index:n,unitIndex:e.index,update:f})):""))):"",i.meta.hasOwnProperty("pratice_questions")&&i.meta.pratice_questions.length?In("div",{className:"pratice_questions"},In(Pn,{questions:i.meta.pratice_questions})):"")};const{createElement:jn,render:Xn,useState:Yn,useEffect:Un,Fragment:Jn}=wp.element,{dispatch:$n,select:Wn}=wp.data,Vn=e=>{const[t,n]=Yn(!1),[i,a]=Yn(!1);return Un(()=>{fetch(`${window.wplms_course_data.api_url}/course/single-unit/${e.unitid}?client_id=${window.wplms_course_data.client_id}&force`,{method:"post",body:JSON.stringify({id:e.unitid,type:"unit"})}).then(e=>e.ok?e.json():{status:0,message:window.wplms_course_data.translations.error_loading_data}).then(e=>{if(e&&e.hasOwnProperty("meta")){n(e),e.meta.hasOwnProperty("scorm_type")&&e.meta.scorm_type&&setTimeout(()=>{var e=new CustomEvent("unit_content_loaded",{detail:{coursestatus:{}}});document.dispatchEvent(e)},200);var t=new CustomEvent("unit_loaded",{detail:{coursestatus:{}}});document.dispatchEvent(t),document.dispatchEvent(new Event("VibeBP_Editor_Content"))}a(!0)}).catch(e=>{a(!0),console.error("Uh oh, an error!",e),$n("vibebp").addNotification({text:window.wplms_course_data.translations.error_loading_data})})},[e.unitid]),i?jn(Jn,null,jn("div",{className:"unit_content"},t?jn(Fn,{curriculumItem:t,noLabels:!0}):"")):jn(r,null)},Kn=e=>{const[t,n]=Yn(!1),[i,a]=Yn(!1);return Un(()=>{fetch(`${window.wplms_course_data.api_url}/course/single-unit/${e.unitid}?client_id=${window.wplms_course_data.client_id}?force`,{method:"post",body:JSON.stringify({id:e.unitid,type:"unit",token:Wn("vibebp").getToken()})}).then(e=>e.ok?e.json():{status:0,message:window.wplms_course_data.translations.error_loading_data}).then(e=>{if(e&&e.hasOwnProperty("meta")){n(e),e.meta.hasOwnProperty("scorm_type")&&e.meta.scorm_type&&setTimeout(()=>{var e=new CustomEvent("unit_content_loaded",{detail:{coursestatus:{}}});document.dispatchEvent(e)},200);var t=new CustomEvent("unit_loaded",{detail:{coursestatus:{}}});document.dispatchEvent(t),document.dispatchEvent(new Event("VibeBP_Editor_Content"))}a(!0)}).catch(e=>{a(!0),console.error("Uh oh, an error!",e),$n("vibebp").addNotification({text:window.wplms_course_data.translations.error_loading_data})})},[e.unitid]),i?jn(Jn,null,jn("div",{className:"unit_content"},t?jn(Fn,{curriculumItem:t,noLabels:!0}):"")):jn(r,null)};window.addEventListener("DOMContentLoaded",e=>{document.querySelector(".single_unit")&&Xn(jn(Vn,{unitid:document.querySelector(".single_unit").getAttribute("data-id")}),document.querySelector(".single_unit"))}),document.addEventListener("userLoaded",e=>{document.querySelector(".single_unit")&&Xn(jn(Kn,{unitid:document.querySelector(".single_unit").getAttribute("data-id")}),document.querySelector(".single_unit"))})}]);
// source --> https://mindset-wins.cash/wp-content/plugins/wplms_plugin/includes/vibe-shortcodes/js/scorm2.js?ver=1.9.3 
document.addEventListener("unit_content_loaded", (e)=>{
        //e.target.removeEventListener(e.type, arguments.callee);

(function(){
    

    

    this._VERSION = "2.2.20130225";
    
    /*
     * WplmsSimpleAPI for SCORM 1.2
     * --------------------------------------------------
    */
       
    // Should we skip the automatic manifest check?
    this.skipManifestCheck = false;

    // The SCO's *default* launch file
    this.launchFile = 'default.htm';

    // The *default* name of the cookie to be used within this session
    this.cookieName = 'WplmsSimpleAPI_Data_'+_VERSION;

    // Should the *default* cookie name use the name of the parent folder instead?
    this.useParentFolderAsCookieName = true;

    // Shall we close SCO on LMSFinish?
    this.closeOnFinish = true;

    // The width of the SCO window when launched
    this.wWidth = 1024;

    // The height of the SCO window when launched
    this.wHeight = 768;

    // SCO window default features
    this.wToolbar = false;
    this.wTitlebar = false;
    this.wLocation = true;
    this.wStatus = true;
    this.wScrollbars = true;
    this.wResizable = true;
    this.wMenubar = false;

    this.WPLMSLastSaved = new Date().getTime();
    // Default value for the search string option
    this.defaultSearchString = '?embedded=true';

    // Default values for the custom API key/value pair injection option
    this.defaultCustomApiKey = 'SomeCustomKey';
    this.defaultCustomApiValue = 'SomeCustomValue';

    // Default state of the SCORM API if one cannot be pulled from the
    // data cookie.  Change values below if you wish to test a SCO
    // being launched in a specific state.  Ensure you reset it back
    // to the defaults already present below when finished testing
    // to avoid the appearance of unexpected behaviors within the SCO
    // in subsequent tests...

    //initialise from WPLMS <---
    this.initialState = {
        'cmi.core._children':'student_id,student_name,lesson_status,lesson_location,lesson_mode,score,credit,entry,exit,session_time,total_time',
        'cmi.core.score._children':'raw',
        'cmi.core.student_id':(!isEmpty(window.scorm_wplms_data))?scorm_wplms_data.user_email:'SAMPLE0001',
        'cmi.core.student_name':(!isEmpty(window.scorm_wplms_data))?scorm_wplms_data.user_name:'SAMPLE0001',
        'cmi.core.lesson_status':'not attempted',
        'cmi.core.score.raw':'',
        'cmi.core.lesson_location':'',
        'cmi.suspend_data':'',
        'cmi.core.session_time':'0000:00:00.00',
        'cmi.core.credit':'credit', /* "credit" or "no-credit" */
        'cmi.core.entry':'ab-initio', /* "resume" or "ab-initio" */
        'cmi.core.lesson_mode':'normal', /* "browse",  "normal" or "review" */
        'cmi.core.exit':'' /* "time-out", "suspend" or "logout" */
    };

    /*
     * Do not touch anything below
     * --------------------------------------------------
     */
    this.scoWin;
    this.API;
    this.hasTerminated = false;
    this.hasInitialized = false;
    this.optionsOpen = true;
    this.initTimeoutMax = 20000;
    this.initTimeout = 0;
    this.fullPath = document.location.href.substr(0,document.location.href.lastIndexOf('/'))
    this.parentFolder = fullPath.substr(fullPath.lastIndexOf('/')+1,fullPath.length);
    this.timeoutErrorDisplayed = false;
    this.launchWithEmbeddedParam = false;
    this.launchWithCustomApiProperty = false;
    this.storageObject;

    this.WplmsSimpleAPI = function(cookiename,api,initData)
    {
        this.api = api;
        this.initData = initData;
        this.__data = null;
        this.cookiename = cookiename;
        this.initialized = false;
        this.terminated = false;
        this.lastError = "0";
        this.lastCmd = '';

        this.logCommand=function()
        {
            Utils.log(this.lastCmd,'entry');
            var lasterr = this.api.LMSGetLastError();
            if (lasterr != '0')
            {
                var errorstr = this.api.LMSGetErrorString(lasterr);
                var diag = this.api.LMSGetDiagnostic(lasterr);
                var msg = "Error Calling: " + this.lastCmd + "<br>";
                msg += "LMSGetLastError() = " + lasterr + "<br>";
                msg += "LMSGetErrorString('" + lasterr + "') = " + errorstr + "<br>";
                msg += "LMSGetDiagnostic('" + lasterr + "') = " + diag;
                Utils.log(msg,'error');
            }
        };

        // LMSInitialize
        this.LMSInitialize=function(arg)
        {
            var success = this.api.LMSInitialize(arg);
            this.lastCmd = "LMSInitialize('" + arg + "') = " + success;
            this.logCommand();
            this.initialized = (success === 'true') ? true : false;
            if(this.initialized)
            {
                this.terminated = false;
                hasInitialized = true;
                for(var o in this.api)
                {
                    if(typeof this.api[o] != 'function')
                    {
                        this[o] = this.api[o];
                    }
                }

                this.__data = Utils.getInitAPIData(this.initData);
                for(var el in this.__data)
                {
                    loadDataIntoModel(el,this.__data[el]);
                }
            }
            return success;
        };
        this.Initialize = this.LMSInitialize;
        // LMSFinish
        this.LMSFinish=function(arg)
        {
            var success = this.api.LMSFinish(arg);
            this.lastCmd = "LMSFinish('" + arg + "') = " + success;
            this.logCommand();
            if(success === 'true')
            {
                this.initialized = false;
                this.terminated = true;
                hasTerminated = true;
                if(this.__data['cmi.core.session_time'] && (this.__data['cmi.core.session_time'].length > 0))
                {
                    if(this.__data['cmi.core.total_time'] == null || this.__data['cmi.core.total_time'] == '')
                    {
                        this.__data['cmi.core.total_time'] = '0000:00:00.00';
                    }
                    var totalTime = Utils.addTime(this.__data['cmi.core.total_time'], this.__data['cmi.core.session_time']);
                    this.__data['cmi.core.total_time'] = totalTime;
                    
                    var cdata = JSON.stringify(this.__data);
                    storageObject.persist(this.cookiename,cdata,365);

                    Utils.log('Total Time (cmi.core.total_time): '+totalTime,'info');
                }

                if(closeOnFinish)
                {
                    if(scoWin && !scoWin.closed)
                    {
                        Utils.closeSCO();
                    }
                }
                if(!isEmpty(window.scorm_wplms_data) ){
                 
                  switch(window.scorm_wplms_data.type){
                    case 'unit':
                        if(document.getElementById('mark-complete')){
                            document.getElementById('mark-complete').click();
                        }
                        
                       if(!isEmpty(this.__data['cmi.core.score.raw']) && !isEmpty(this.__data['cmi.core.score.max'])){
                        document.dispatchEvent(new Event('unitfinished',{"detail":
                            {   
                                unit_id:window.scorm_wplms_data.module_id,
                                course_id:window.scorm_wplms_data.course_id,
                            }
                        }));
                       }
                    break;
                    case 'quiz':
                      
                      //handle quiz submit here

                      if(!isEmpty(this.__data['cmi.core.score.raw']) && !isEmpty(this.__data['cmi.core.score.max'])){
                        var nonce = window.scorm_wplms_data.security_nonce,
                        xhr = new XMLHttpRequest();

                        xhr.open('POST', window.wplms_course_data.api_url+'/scorm/finish?nocache');
                        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                        xhr.onload = function() {
                            if (xhr.status === 200 && xhr.responseText !== nonce) {
                                let data = JSON.parse(xhr.responseText);
                                
                                //means data set
                                if(data && data.status){
                                    if(data.hasOwnProperty('continue') && data.continue){
                                        document.dispatchEvent(new Event('scormquizsubmitted',{"detail":
                                            {   
                                                data:data,
                                                quiz_id:window.scorm_wplms_data.module_id,
                                                course_id:window.scorm_wplms_data.course_id,
                                            }
                                        }));
                                    }
                                }
                                
                            }
                            else if (xhr.status !== 200) {
                                console.log('Something went wrong.Request failed.' + xhr.status);
                                
                            }
                        };
                        xhr.send(encodeURI('token='+window.scorm_wplms_data.token+'&is_take_course='+window.is_take_course+'&key='+this.cookiename+'&data='+this.__data+'&module_id='+window.scorm_wplms_data.module_id+'&course_id='+window.scorm_wplms_data.course_id+'&type='+window.scorm_wplms_data.type+'&total_marks='+this.__data['cmi.core.score.max']+'&user_marks='+this.__data['cmi.core.score.raw']));
                      }
                    break;
                    case 'course':

                    if(!isEmpty(this.__data['cmi.core.score.raw']) && !isEmpty(this.__data['cmi.core.score.max'])){
                      var nonce = window.scorm_wplms_data.security_nonce,
                      xhr = new XMLHttpRequest();

                      xhr.open('POST', window.wplms_course_data.api_url+'/scorm/finish?nocache');
                      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                      xhr.setRequestHeader('Authorization', window.scorm_wplms_data.token);
                      xhr.onload = function() {
                          if (xhr.status === 200 && xhr.responseText !== nonce) {
                              let data = JSON.parse(xhr.responseText);
                              if(document.querySelector('input[name="submit_course"]') && data && data.status){
                                document.querySelector('input[name="submit_course"]').click();
                              }
                              
                          }
                          else if (xhr.status !== 200) {
                              console.log('Something went wrong.Request failed.' + xhr.status);
                          }
                      };
                      xhr.send(encodeURI('token='+window.scorm_wplms_data.token+'&key='+this.cookiename+'&data='+this.__data+'&course_id='+window.scorm_wplms_data.course_id+'&type='+window.scorm_wplms_data.type+'&total_marks='+this.__data['cmi.core.score.max']+'&user_marks='+this.__data['cmi.core.score.raw']));
                    }
                    break;
                    default:
                    var postevent = new CustomEvent('socrmfinishtrigger', { "detail":{scorm_wplms_data:window.scorm_wplms_data,data:this.__data}});
                    document.dispatchEvent(postevent);  
                    break;
                  }
                }
                
            }
            /*console.log(this.__data['cmi.core.score.raw']+'/'+this.__data['cmi.core.score.max']);
            console.log('FINSIHED PACKAGE');*/

            return success;
        };
        this.Finish = this.LMSFinish;
        // LMSGetValue
        this.LMSGetValue=function(name)
        {
            var value = unescape(this.api.LMSGetValue(name));
            this.lastCmd = "LMSGetValue('" + name + "') = " + value;
            this.logCommand();
            return value;
        };

        this.GetValue = this.LMSGetValue;

        // LMSSetValue
        this.LMSSetValue=function(name, value)
        {
            var success = this.api.LMSSetValue(name, escape(value));
            this.lastCmd = "LMSSetValue('" + name + "','" + value + "') = " + success;
            this.logCommand();

            if(success === 'true')
            {
                this.__data[name] = value;


                if(!isEmpty(window.scorm_wplms_data) && name == 'cmi.suspend_data' && !isEmpty(value)){
                  //if(new Date().getTime() > (this.WPLMSLastSaved+15000)){
                    var nonce = window.scorm_wplms_data.security_nonce,
                    xhr = new XMLHttpRequest();

                    xhr.open('POST', window.wplms_course_data.api_url+'/scorm/scormdata/update?nocache');
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.onload = function() {
                        if (xhr.status === 200 && xhr.responseText !== nonce) {
                            let data = JSON.parse(xhr.responseText);
                            //means data set
                            if(data && data.status){
                                if(window.scorm_wplms_data.type=='quiz' && data.hasOwnProperty('continue') && data.continue){
                                    document.dispatchEvent(new Event('scormquizsubmitted',{"detail":
                                        {   
                                            data:data,
                                            quiz_id:window.scorm_wplms_data.module_id,
                                            course_id:window.scorm_wplms_data.course_id,
                                        }
                                    }));
                                }
                            }
                            
                        }
                        else if (xhr.status !== 200) {
                            console.log('Something went wrong.Request failed.' + xhr.status);
                            
                        }
                    };
                    xhr.send(encodeURI('token='+window.scorm_wplms_data.token+'&action=save_scorm_data&security='+nonce+'&key='+this.cookiename+'&data='+value+'&module_id='+window.scorm_wplms_data.module_id+'&course_id='+window.scorm_wplms_data.course_id+'&type='+window.scorm_wplms_data.type+'&type='+window.scorm_wplms_data.type+'&total_marks='+this.__data['cmi.core.score.max']+'&user_marks='+(typeof this.__data['cmi.core.score.raw']!=='undefined' && this.__data['cmi.core.score.raw']?this.__data['cmi.core.score.raw']:0)));

                    this.WPLMSLastSaved = new Date().getTime();
                  //}

                }

            }
            
            return success;
        };

        this.SetValue = this.LMSSetValue;

        // LMSCommit
        this.LMSCommit=function(arg)
        {
            var success = this.api.LMSCommit(arg);
            this.lastCmd = "LMSCommit('" + arg + "') = " + success;
            this.logCommand();

            if(success === 'true')
            {
                var cdata = JSON.stringify(this.__data);


                //API call

                
                storageObject.persist(this.cookiename,cdata,365);
            }
            
            return success;
        };

        this.Commit = this.LMSCommit;

        // LMSGetErrorString
        this.LMSGetErrorString=function(arg)
        {
            var errorstr = this.api.LMSGetErrorString(arg);
            Utils.log("LMSGetErrorString('" + arg + "') = " + errorstr,'entry');
            return errorstr;
        };
        this.GetErrorString= this.LMSGetErrorString;
        // LMSGetLastError
        this.LMSGetLastError=function()
        {
            var lasterr = this.api.LMSGetLastError();
            Utils.log("LMSGetLastError() = " + lasterr,'entry');
            return lasterr;
        };
        this.GetLastError = this.LMSGetLastError;
        // LMSGetDiagnostic
        this.LMSGetDiagnostic=function(arg)
        {
            var diag = this.api.LMSGetDiagnostic(arg);
            Utils.log("LMSGetDiagnostic('" + arg + "') = " + diag,'entry');
            return diag;
        };
        this.GetDiagnostic = this.LMSGetDiagnostic;
    };

    // Utilities
    // ----------------------------------------------------------------------------
    this.Utils = {
        getInitAPIData:function(initData)
        {   
            if(storageObject.retrieve(API.cookiename) !== null && storageObject.retrieve(API.cookiename) !== undefined)
            { 

                return JSON.parse(storageObject.retrieve(API.cookiename));
            }
            else
            {
                return initData;
            }
        },
        dumpAPI:function()
        {
            if(API.__data)
            {
                Utils.log('<b>Dumping API object:</b> <blockquote> ' + this.formatAPIData(JSON.stringify(API.__data)) + '</blockquote>','info');
            }
            else
            {
                Utils.log('ERROR: API object contains no data.','error');
            }
        },

        dumpExistingAPIData:function()
        {
            if(storageObject.retrieve(cookieName) !== undefined && storageObject.retrieve(cookieName) !== null)
            {
                var existingData = storageObject.retrieve(cookieName);
                Utils.log('<b>Existing API Data (from '+storageObject.toString()+' &quot;'+cookieName+'&quot; - To be used in API during initialization):</b> <blockquote> ' + this.formatAPIData(existingData) + '</blockquote>','info');
            }
            else
            {
                Utils.log('No Existing API data found in &quot;'+cookieName+'&quot;. Will use default init data.','info');
            }
        },

        formatAPIData:function(str)
        {
            var html;
            html = this.replaceAll(str, '{"', '{<br>"');
            html = this.replaceAll(html, '"}', '"<br>}');
            html = this.replaceAll(html, '","', '",<br>"');

            return html;
        },

        replaceAll:function(text, strA, strB)
        {
            return text.replace( new RegExp(strA,"g"), strB );    
        },

        addTime:function(first, second)
        {
            var sFirst = first.split(":");
            var sSecond = second.split(":");
            var cFirst = sFirst[2].split(".");
            var cSecond = sSecond[2].split(".");
            var change = 0;

            FirstCents = 0;  //Cents
            if (cFirst.length > 1) {
                FirstCents = parseInt(cFirst[1],10);
            }
            SecondCents = 0;
            if (cSecond.length > 1) {
                SecondCents = parseInt(cSecond[1],10);
            }
            var cents = FirstCents + SecondCents;
            change = Math.floor(cents / 100);
            cents = cents - (change * 100);
            if (Math.floor(cents) < 10) {
                cents = "0" + cents.toString();
            }

            var secs = parseInt(cFirst[0],10)+parseInt(cSecond[0],10)+change;  //Seconds
            change = Math.floor(secs / 60);
            secs = secs - (change * 60);
            if (Math.floor(secs) < 10) {
                secs = "0" + secs.toString();
            }

            mins = parseInt(sFirst[1],10)+parseInt(sSecond[1],10)+change;   //Minutes
            change = Math.floor(mins / 60);
            mins = mins - (change * 60);
            if (mins < 10) {
                mins = "0" + mins.toString();
            }

            hours = parseInt(sFirst[0],10)+parseInt(sSecond[0],10)+change;  //Hours
            if (hours < 10) {
                hours = "0" + hours.toString();
            }

            if (cents != '0') {
                return hours + ":" + mins + ":" + secs + '.' + cents;
            } else {
                return hours + ":" + mins + ":" + secs;
            }
        },
        openWindow:function(winURL,winName,winW,winH,winOpts)
        {
            winOptions = winOpts+",width=" + winW + ",height=" + winH;
            newWin = window.open(winURL,winName,winOptions);
            newWin.moveTo(0,0);
            newWin.focus();
            return newWin;
        },
        log:function(status,style)
        {
            var timeFix=function(time)
            {
                return (time<10) ? '0'+time : time;
            };
            var d = new Date();
            var hrs = timeFix(d.getHours());
            var min = timeFix(d.getMinutes());
            var sec = timeFix(d.getSeconds());
            var tmp = (style) ? '<div class="'+style+'">' : '<div class="entry">';
            tmp += '&gt; '+hrs+':'+min+':'+sec+' ';
            tmp += status;
            tmp += '</div>';

        },
        clearCookieData:function()
        {
            

            
          if(storageObject.retrieve(cookieName))
          {
              storageObject.remove(cookieName);
              Utils.log(storageObject.toString()+'"'+cookieName+'" Cleared','info');
          }
          else
          {
              Utils.log(storageObject.toString()+'"'+cookieName+'" Not Found','error');
          }
            
        },
        genNewSessionName:function()
        {
            var d = new Date();
            var hrs = d.getHours();
            var min = d.getMinutes();
            var sec = d.getSeconds();

            if(useParentFolderAsCookieName)
            {
                var tmp = parentFolder+'_';
            }
            else
            {
                var tmp = 'WplmsSimpleAPI_Data_';
            }
            
            tmp += hrs+'.'+min+'.'+sec;

            $('cookieNameAlt').value = tmp;
        },
        watchWin:function()
        {  
            if(scoWin && !scoWin.closed)
            {
                initTimeout += 1000;
                if(initTimeout >= initTimeoutMax)
                {   
                    if(!API.initialized && !timeoutErrorDisplayed)
                    {
                        this.log('ERROR: LMSInitialize not called within 20 seconds from launching.', 'error');
                        timeoutErrorDisplayed = true;
                    }
                }
                setTimeout(function(){Utils.watchWin()},1000);
            }
            else
            {
                
                this.log('SCO Closed','info');
                if(!hasInitialized)
                {
                    this.log('ERROR: LMSInitialize was never called.', 'error');
                }
                if(!hasTerminated)
                {
                    this.log('ERROR: LMSFinish was never called.', 'error');
                }
            }
        },
        launchSCO:function()
        {
            // Reset the WplmsSimpleAPI
            hasTerminated = false;
            hasInitialized = false;
            API.terminated = false;
            API.initialized = false;
            initTimeout = 0;
            timeoutErrorDisplayed = false;


            if(launchWithCustomApiProperty)
            {
                try
                {
                    var key = $('customApiKey').value;
                    var val = $('customApiValue').value;
                    if(key && val)
                    {
                        API[key] = val;
                    }
                    Utils.log('Injected custom key/value into API object: '+key+'='+val,'info');
                }
                catch(e)
                {
                    Utils.log('ERROR: Cannot inject custom key/value into API object: '+key+'='+val+ '('+e+')','error');
                }
            }

            try
            {
                var w = (($('winW').value != "") && ($('winW').value > 0)) ? $('winW').value : wWidth;
                var h = (($('winH').value != "") && ($('winH').value > 0)) ? $('winH').value : wHeight;
                var embedParam = '';
                if(launchWithEmbeddedParam)
                {
                    try
                    {
                        embedParam = $('searchString').value;
                        Utils.log('Appending search string to launch file: '+$('searchString').value,'info');
                    }
                    catch(e)
                    {
                        embedParam = '';
                    }
                }
                else
                {
                    embedParam = '';
                }

                var opts = '';
                opts += (wToolbar) ? 'toolbar=yes,' : '';
                opts += (wTitlebar) ? 'titlebar=yes,' : '';
                opts += (wLocation) ? 'location=yes,' : '';
                opts += (wStatus) ? 'status=yes,' : '';
                opts += (wScrollbars) ? 'scrollbars=yes,' : '';
                opts += (wResizable) ? 'resizable=yes,' : '';
                opts += (wMenubar) ? 'menubar=yes,' : '';
                opts = opts.substring(0, opts.length-1)
                
                Utils.log("Launching SCO win with options: "+opts)
                scoWin = document.getElementsByTagName("iframe")[0].contentWindow;
                //scoWin = this.openWindow(launchFile+embedParam,"SCOwindow",w,h,opts);
            }
            catch (e)
            {
                Utils.log('ERROR: '+e.description, 'error');
            }
            
            if(scoWin !== null)
            {
                try
                {
                    Utils.log('SCO Launched','info');
                    scoWin.focus();
                    this.watchWin();
                }
                catch (e)
                {
                    Utils.log('ERROR: '+err.description,'error');
                }
            }
            else
            {
                Utils.log('ERROR: SCO windows unable to open.  Please disable any popup blockers you might have enabled and ensure the launch file path is correct.', 'error');
            }
        },
        closeSCO:function()
        {
            try
            {
                if(scoWin && !scoWin.closed)
                {
                    Utils.log('Attempting to close SCO window...','info');

                    
                    scoWin.close();
                }
            }
            catch(e)
            {
                Utils.log('ERROR: Unable to close SCO window ('+e.description+')','error');
            }
        },
        
        toggleCloseOnFinishOption:function(chkd)
        {
            closeOnFinish = chkd;
        },
        toggleEmbeddedParam:function(chkd)
        {
            launchWithEmbeddedParam = chkd;
            $('searchString').disabled = !chkd;

        },
        toggleCustomKeyValueOption:function(chkd)
        {
            launchWithCustomApiProperty = chkd;
            $('customApiKey').disabled = !chkd;
            $('customApiValue').disabled = !chkd;
        },
        toggleWindowOption:function(prop,el)
        {
            window[prop] = el.checked;
        },
        enableAllWindowOptions:function()
        {
            wToolbar = true;
            wTitlebar = true;
            wLocation = true;
            wStatus = true;
            wScrollbars = true;
            wResizable = true;
            wMenubar = true;
            $('wToolbarOption').checked = true;
            $('wTitlebarOption').checked = true;
            $('wLocationOption').checked = true;
            $('wStatusOption').checked = true;
            $('wScrollbarsOption').checked = true;
            $('wResizableOption').checked = true;
            $('wMenubarOption').checked = true;
        },
        disableAllWindowOptions:function()
        {
            wToolbar = false;
            wTitlebar = false;
            wLocation = false;
            wStatus = false;
            wScrollbars = false;
            wResizable = false;
            wMenubar = false;
            $('wToolbarOption').checked = false;
            $('wTitlebarOption').checked = false;
            $('wLocationOption').checked = false;
            $('wStatusOption').checked = false;
            $('wScrollbarsOption').checked = false;
            $('wResizableOption').checked = false;
            $('wMenubarOption').checked = false;
        },
        loadManifest:function()
        {
            var xmlDoc = null;
            var file = fullPath+"/imsmanifest.xml";

            var useManifest=function()
            {
                try
                {
                    var m = xmlDoc.getElementsByTagName("manifest")[0];
                    
                    var orgs = xmlDoc.getElementsByTagName("organizations")[0];
                    var org = orgs.getElementsByTagName("organization")[0];
                    var orgTitle = org.getElementsByTagName("title")[0].firstChild.nodeValue;
                    
                    var items = org.getElementsByTagName("item");
                    var item = items[0];
                    var itemTitle = item.getElementsByTagName("title")[0].firstChild.nodeValue;
                    var itemMasteryScore = item.getElementsByTagName("adlcp:masteryscore")[0].firstChild.nodeValue;
                    var itemIdentifier = item.getAttribute("identifier");
                    var itemIdentifierRef = item.getAttribute("identifierref");

                    var resources = xmlDoc.getElementsByTagName("resources")[0];
                    var resource = resources.getElementsByTagName("resource");
                    var itemResource = null;
                    for(var i=0;i<resource.length;i++)
                    {
                        var id = resource[i].getAttribute("identifier");
                        var scormtype = resource[i].getAttribute("adlcp:scormtype");
                        if(id == itemIdentifierRef && scormtype.toLowerCase() == "sco")
                        {
                            itemResource = resource[i];
                        }
                    }
                    var itemResourceHref = itemResource.getAttribute("href");
                    
                    Utils.log('IMS Manifest: Organization Title = &quot;'+orgTitle+'&quot;','entry');
                    if(items.length > 1)
                    {
                        Utils.log('IMS Manifest: WplmsSimpleAPI detected multiple SCO references - Only the first will be launched.','entry');
                    }
                    Utils.log('IMS Manifest: First SCO Item = &quot;'+itemTitle+'&quot; (Mastery Score: '+itemMasteryScore+' / Identifier: &quot;'+itemIdentifier+'&quot;)','entry');
                    Utils.log('IMS Manifest: Resource &quot;'+itemIdentifierRef+'&quot; HREF for Item &quot;'+itemIdentifier+'&quot; = &quot;'+itemResourceHref+'&quot;');

                    var obj = {};
                    obj.id = m.getAttribute("identifier");
                    obj.orgTitle = orgTitle;
                    obj.itemTitle = itemTitle;
                    obj.itemMasteryScore = itemMasteryScore;
                    obj.itemResourceHref = itemResourceHref;

                    $('launchFileAlt').value = itemResourceHref;

                    return obj;
                }
                catch(e)
                {
                    error=e.message;
                    Utils.log('IMS Manifest: Cannot locate or parse manifest - '+error,'error');
                    return false;
                }
            };

            /* - For Webkit - Not now though...
            // Check for the various File API support.
            if (window.File && window.FileReader) {
              alert('Great success! All the File APIs are supported.');
            } else {
              alert('The File APIs are not fully supported in this browser.');
            }
            */

            
            try //Internet Explorer
            {
                xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async=false;
                xmlDoc.onreadystatechange = function()
                {
                    if(xmlDoc.readyState == 4)
                    {
                        useManifest();
                    }
                }
                var success = xmlDoc.load(file);
            }
            catch(e)
            {
                try //Firefox, Mozilla, Opera, etc.
                {
                    xmlDoc=document.implementation.createDocument("","",null);
                    xmlDoc.async=false;
                    xmlDoc.onload = function()
                    {
                        useManifest();
                    };
                    var success = xmlDoc.load(file);
                }
                catch(e)
                {
                    try //Google Chrome
                    {
                        var xmlhttp = new window.XMLHttpRequest();
                        xmlhttp.open("GET",file,false);
                        xmlhttp.send(null);
                        xmlDoc = xmlhttp.responseXML.documentElement;
                        //alert(success);
                    }
                    catch(e)
                    {
                        error=e.message;
                        Utils.log('IMS Manifest: Cannot locate or parse manifest - '+error,'error');

                        return false;
                    }
                }
            }
        }
    };

    // General/Global
    // ----------------------------------------------------------------------------
    this.init=function()
    {

     
        let src = document.getElementsByTagName("iframe")[0].getAttribute('data-src');
        fullPath = src.substr(0,src.lastIndexOf('/'));
        parentFolder = fullPath.substr(fullPath.lastIndexOf('/')+1,fullPath.length);
        scoWin = null;
        var manifestObj = null;

        if(!skipManifestCheck)
        {
          
            var manifestObj = Utils.loadManifest();
        }

        if(!manifestObj)
        { 
            if(useParentFolderAsCookieName)
            {
              
                cookieName = src;
            }
        }
        else
        {
            if(manifestObj.id)
            {
              
                cookieName = manifestObj.id;
            }
            
            if(manifestObj.itemResourceHref)
            {
                $('launchFileAlt').value = manifestObj.itemResourceHref;
            }
        }
        
        var api = new GenericAPIAdaptor();
        API = new WplmsSimpleAPI(cookieName,api,initialState);
        
        // test for localStorage
        if(typeof(Storage) !== "undefined")
        {
            try {
              if (('localStorage' in window) && window['localStorage'] && window.localStorage !== null)
              {
                storageObject = localStorageObject;
              }
              else
              {
                storageObject = cookieStorageObject;
              }
            } catch(e) {
              storageObject = cookieStorageObject;
            }
        }
        else
        {
            storageObject = cookieStorageObject;
        }

        /*$('cookieNameAlt').value = cookieName;

        $('winW').value = wWidth;
        $('winH').value = wHeight;

        $('wToolbarOption').checked = wToolbar;
        $('wTitlebarOption').checked = wTitlebar;
        $('wLocationOption').checked = wLocation;
        $('wStatusOption').checked = wStatus;
        $('wScrollbarsOption').checked = wScrollbars;
        $('wResizableOption').checked = wResizable;
        $('wMenubarOption').checked = wMenubar;*/

 


        launchWithEmbeddedParam = true;
        launchWithCustomApiProperty = false;
        
        /*
        $('searchString').disabled = !launchWithEmbeddedParam;
        $('customApiKey').disabled = !launchWithCustomApiProperty;
        $('customApiValue').disabled = !launchWithCustomApiProperty;


        $('searchString').value = defaultSearchString;
        $('customApiKey').value = defaultCustomApiKey;
        $('customApiValue').value = defaultCustomApiValue;*/

        Utils.log('Storage type will be: '+storageObject.toString(),'info');

        Utils.dumpExistingAPIData();
    };

    this.sendSimApi=function(simAPI,title,totalToInclude,totalIncorrect,incStepNumberList)
    {
        Utils.log('Sim API Object: '+simAPI,'info');
        Utils.log('Sim Title: '+title,'info');
    };

   /* this.$=function(id)
    {
        var el = document.getElementById(id);
        return el;
    };*/

    // Cookie Object interface
    this.cookieStorageObject={
        persist:function(name,data,lifetime)
        {
            saveCookie(name,data,lifetime)
        },
        retrieve:function(name)
        {
            return readCookie(name);
        },
        remove:function(name)
        {
            deleteCookie(name);
        },
        toString:function()
        {
            return "Cookie";
        }
    };

    // LocalStorage Interface
    this.localStorageObject={
        persist: function(name,data,lifetime)
        {    
            //make api call to save all the data here 
            

            localStorage[name] = data;
        },
        retrieve:function(name)
        {
            return localStorage[name];
        },
        remove:function(name)
        {
            delete localStorage[name];
        },
        toString:function()
        {
            return "LocalStorage";
        }
    };
    //if(window.is_take_course){
     window.onload=function()
      {
          this.init();
      };
    //}else{
      setTimeout(function (){
        this.init();
      },500);
   
      
      
    //}
    
})();


// Cookie Functions
// ----------------------------------------------------------------------------
// save/read/delete cookie functions for storing small chunks of data in the browser
// 19990326

// Copyright (C) 1999 Dan Steinman
// Distributed under the terms of the GNU Library General Public License
// Available at http://www.dansteinman.com/dynapi/

// thanks to: Jesee Chisholm <JCHISHOLM@SENSORMATIC-VPD.com>

function saveCookie(name,value,days)
{
    if(days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else
    {
        expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i<ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function deleteCookie(name)
{
    saveCookie(name,"",-1);
}

// JSON
// ----------------------------------------------------------------------------
/*
    json.js
    2006-11-09

    This file adds these methods to JavaScript:

        array.wplmsscormtoJSONString()
        boolean.wplmsscormtoJSONString()
        date.wplmsscormtoJSONString()
        number.wplmsscormtoJSONString()
        object.wplmsscormtoJSONString()
        string.wplmsscormtoJSONString()
            These method produces a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a wplmsscormtoJSONString method to any date object to get a different
            representation.

        string.wplmsscormparseJSON()
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2007.
*/


/**
 *  RELOAD TOOLS
 *
 *  Copyright (c) 2003 Oleg Liber, Bill Olivier, Phillip Beauvoir, Paul Sharples
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *  Project Management Contact:
 *
 *  Oleg Liber
 *  Bolton Institute of Higher Education
 *  Deane Road
 *  Bolton BL3 5AB
 *  UK
 *
 *  e-mail:   o.liber@bolton.ac.uk
 *
 *
 *  Technical Contact:
 *
 *  Phillip Beauvoir
 *  e-mail:   p.beauvoir@bolton.ac.uk
 *
 *  Paul Sharples
 *  e-mail:   p.sharples@bolton.ac.uk
 *
 *  Web:      http://www.reload.ac.uk
 *
 * @author Paul Sharples
 * @version $Id: ReloadAPIAdaptor.js,v 1.3 2004/07/25 13:04:59 ps3com Exp $
 *
 */
/*
* -----------------------------------------------------------------------------------------------
*  Convenience Methods needed for SCO communication
* -----------------------------------------------------------------------------------------------
*/

var looseChecking ="false";

/*
* Function to initially load the server model CMI elements into the javascript
* model, when this page first loads.
*/
function loadDataIntoModel(element, value){
  if (element != "cmi.interactions._count" && element != "cmi.interactions._count"){
        if (element.indexOf("cmi.objectives") != -1){
             dealWithSettingObjectives(element, value);
        }
        else if (element.indexOf("cmi.interactions") != -1){
             dealWithSettingInteractions(element, value);
        }
        else{
           var result = eval ("API."+element);
           if (result != null){
                result.cmivalue = value;
           }
        }
  }
}

/*
*  Object ServerScoSettings()
*  Used to store server specific settings and error codes etc..
*  Is accessed as an object inside this implementation of the API object.
*/
function ServerScoSettings(){
    this.isInitialized = "false";
    this.lastError = "0";
    this.checkDataTypeAndVocab = scoCheckDataTypeAndVocab;
}

/*
* A CMIComponent holds properties for each CMI element in the model.
* Here we keep the element name, it current value, its read/write status
* and finally it CMI datatype
*/
function CMIComponent(thename, thevalue, readstatus, datatype){
    this.cminame=thename;
    this.cmivalue=thevalue;
    this.cmireadStatus=readstatus;
    this.cmidatatype=datatype;
}

/*
* Top level object to hold complete CMI data model and API methods
*/
function GenericAPIAdaptor(){
    this.cmi = new CMIModel;
    this.LMSInitialize = LMSInitializeMethod;
    this.LMSGetValue = LMSGetValueMethod;
    this.LMSSetValue = LMSSetValueMethod;
    this.LMSCommit = LMSCommitMethod;
    this.LMSFinish = LMSFinishMethod;
    this.LMSGetLastError = LMSGetLastErrorMethod;
    this.LMSGetErrorString = LMSGetErrorStringMethod;
    this.LMSGetDiagnostic = LMSGetDiagnosticMethod;
    this.ServerSco = new ServerScoSettings;
}

/*
* ---------------------------------------------------------------------------------------------
*   API Javascript Functions
* ---------------------------------------------------------------------------------------------
*/

/*
* LMSInitialize. Initialize this sco (if it is one)
*/
function LMSInitializeMethod(parameter){

    //Login check in WPLMS
    //Progress , Quiz results , course status

    // check that this has been called with an empty string...
    if (parameter != ""){
        this.ServerSco.lastError = "201"
        return "false";
    }
    // check that we are not already initialized...
    if(this.ServerSco.isInitialized == "false"){
        this.ServerSco.isInitialized = "true";
        this.ServerSco.lastError = "0"
        return "true";
    }
    else{
        this.ServerSco.lastError = "101"
        return "false";
    }
}

/*
* LMSFinish. Finish this sco session.
*/
function LMSFinishMethod(parameter){
    // check that this has been called with an empty string...
    if (parameter != ""){
        this.ServerSco.lastError = "201";
        return "false";
    }
    // make sure that the server is initialized...
    if (this.ServerSco.isInitialized=="true"){
            this.ServerSco.isInitialized = "false";
            this.ServerSco.lastError = "0";
            return "true";
    }
    else{
        // not initialized
        this.ServerSco.lastError = "301";
        return "false";
    }
}



/*
* LMSCommit.  Method to update/persist any changed items in the CMI datamodel
*/
function LMSCommitMethod(parameter){
    // check that this has been called with an empty string...
    if (parameter!=""){
        this.ServerSco.lastError = "201"
        return "false";
    }
    if (this.ServerSco.isInitialized == "true"){
            this.ServerSco.lastError = "0";
            return "true";
    }
    else{
        // not initialized
        this.ServerSco.lastError = "301";
        return "false";
    }
}

function dealWithGettingObjectives(element){
    // RETURN _CHILDREN
    if (element == "cmi.objectives._children"){
        API.ServerSco.lastError = "0";
        return API.cmi.objectives._children.cmivalue;
    }

    // RETURN _COUNT
    if (element == "cmi.objectives._count"){
        API.ServerSco.lastError = "0";
        return API.cmi.objectives._count.cmivalue;
    }

    // ELSE CHECK THAT THE ELEMENT IS VALID AND HAS AT LEAST 3 PARAMS
    var cmiArray = element.split(".");
    if (cmiArray.length < 3){
        API.ServerSco.lastError = "201";
        return "";
    }

    var theCount = API.cmi.objectives._count.cmivalue;

    // IF 3RD ARG IS NOT A NUMBER THEN THROW ERROR
    // need to check cmiArray[2] to see if its a number
    if (isNaN(cmiArray[2])){
        API.ServerSco.lastError = "401";
        return "";
    }

    // IF ITS A NUMBER MAKE SURE ITS IN THE ARRAY BOUNDS
    if(cmiArray[2] >= theCount){
        // call to array is out of bounds
        API.ServerSco.lastError = "201";
        return "";
    }
    else{   // WEVE GOT TO THE POINT OF VALIDATING cmi.objective.n
        // does this element exist in the objectives array? - sanity check...
        var mystr = "API."+cmiArray[0] + "." + cmiArray[1] + ".objArray(" + cmiArray[2] + ");";
        ans = eval(mystr);
        //if it doesn't exist
        if (ans == null){
            API.ServerSco.lastError = "201";
            return "";
        }
        else{
            // we need to see if the call is asking for a valid element under cmi.objectives.n
            // we can trust the element parameter now to call the following...
            subelementstr = "ans";
            for (i=3;i<cmiArray.length;i++){
                subelementstr = subelementstr + "." + cmiArray[i];
            }

            var objTest = eval(subelementstr);
            if (objTest == null){
                API.ServerSco.lastError = "201";
                return "false";
            }

            subelementstr = subelementstr + ".cmivalue;";
            res = eval(subelementstr);
            if (res == null){
                API.ServerSco.lastError = "201";
                return "";
            }
            else{
                API.ServerSco.lastError = "0";
                return res;
            }
        }
    }
}

function dealWithGettingInteractions(element){
    // RETURN _CHILDREN
    if (element == "cmi.interactions._children"){
        API.ServerSco.lastError = "0";
        return API.cmi.interactions._children.cmivalue;
    }

    // RETURN _COUNT
    if (element == "cmi.interactions._count"){
        API.ServerSco.lastError = "0";
        return API.cmi.interactions._count.cmivalue;
    }

    // ELSE CHECK THAT THE ELEMENT IS VALID AND HAS AT LEAST 3 PARAMS, DOESNT HAVE
    // MORE THAN 6 PARAMS  - IF SO, ITS ILLEGAL
    var cmiArray = element.split(".");
    if (cmiArray.length < 3 || cmiArray.length > 6){
        API.ServerSco.lastError = "201";
        return "";
    }

    var theCount = API.cmi.interactions._count.cmivalue;

    // IF 3RD ARG IS NOT A NUMBER THEN THROW ERROR
    // need to check cmiArray[2] to see if its a number
    if (isNaN(cmiArray[2])){
        API.ServerSco.lastError = "401";
        return "";
    }

    // IF ITS A NUMBER MAKE SURE ITS IN THE ARRAY BOUNDS
    if(cmiArray[2] >= theCount){
        // call to array is out of bounds
        API.ServerSco.lastError = "201";
        return "";
    }
    else{   // WEVE GOT TO THE POINT OF VALIDATING cmi.interactions.n
        // does this element exist in the interactions array? - sanity check...
        //
        // We are checking that 'cmi.interactions.n' exists
        var mystr = "API."+cmiArray[0] + "." + cmiArray[1] + ".intArray(" + cmiArray[2] + ")";
        ans = eval(mystr);
        //if it doesn't exist
        if (ans==null){
            API.ServerSco.lastError = "201";
            return "";
        }
        else{
            // if theres 4 bits to the element path then try to see if object exists
            if (cmiArray.length == 4){
                strleaf = "ans."+ cmiArray[3] + ";";
                var doesLeafExist = eval (strleaf);
                if (doesLeafExist == null){
                    API.ServerSco.lastError = "201";
                    return "";
                }
                else{
                    // NEXT CHECK THAT THIS ELEMENT IS NOT WRITEONLY
                    strleafstatus = mystr + "."+ cmiArray[3] + ".cmireadStatus;";
                    var leafstatus = eval(strleafstatus);
                    if (leafstatus == "writeonly"){
                        API.ServerSco.lastError = "404";
                        return "";
                    }

                    // WE CAN NOW TRY TO GET THE FULL OBJECT REFERENCE
                    var strleafval = mystr + "."+ cmiArray[3] + ".cmivalue;";
                    var leafVal = eval(strleafval);
                    if (leafVal == null){
                        // IT FAILED AT THE FINAL HURDLE...
                        API.ServerSco.lastError = "201";
                        return "";
                    }
                    else{
                        API.ServerSco.lastError = "0";
                        return leafVal;
                    }

                }
            }
            // if theres 5 bits to the element path then try to see if object exists
            if (cmiArray.length == 5){
                // check object exists
                strbranch = "ans."+ cmiArray[3] + ";";
                var doesLeafExist = eval (strbranch);
                if (doesLeafExist == null){
                    API.ServerSco.lastError = "201";
                    return "";
                }

                // check final object exists in the array list...
                nextstrbranch = "ans."+ cmiArray[3] + "." + cmiArray[4] + ";";
                var doesLeafExist = eval (nextstrbranch);
                if (doesLeafExist == null){
                    API.ServerSco.lastError = "201";
                    return "";
                }

                // check for write only
                strread = "ans."+ cmiArray[3] + "." + cmiArray[4] + ".cmireadStatus;";
                var isWriteOnly = eval (strread);
                if (isWriteOnly == "writeonly"){
                    API.ServerSco.lastError = "404";
                    return "";
                }

                // see if value exists
                strleaf = "ans."+ cmiArray[3] + "." + cmiArray[4] + ".cmivalue;";
                var doesLeafExist = eval (strleaf);
                if (doesLeafExist == null){
                    API.ServerSco.lastError = "201";
                    return "";
                }
                else{
                    API.ServerSco.lastError = "0";
                    return doesLeafExist;
                }

            }
            // if theres 6 bits to the element path then try to see if object exists
            if (cmiArray.length == 6){
                // check object exists
                strbranch = "ans."+ cmiArray[3];
                var doesBranchExist = eval (strbranch);
                if (doesBranchExist == null){
                    API.ServerSco.lastError = "201";
                    return "";
                }
                // The fifth argument should be an array reference, so do some checking...

                // IF 5TH ARG IS NOT A NUMBER THEN THROW ERROR
                // need to check cmiArray[4] to see if its a number
                if (isNaN(cmiArray[4])){
                    API.ServerSco.lastError = "401";
                    return "";
                }

                // check to see if this element has a _count
                // If it hasn't we'll have to throw an error here
                // because we need the correct array index for array #2...
                var theCount = "ans." + cmiArray[3] + "._count.cmivalue;";
                var hasCount = eval(theCount);
                // CANT FIND _COUNT FOR THIS ELEMENT, SO THROW AN ERROR...
                if (hasCount == null){
                    API.ServerSco.lastError = "201";
                    return "";
                }
                // next need to check to see if array ref is in array bounds
                if(cmiArray[4] >= hasCount || cmiArray[4] < 0){
                    // call to array is out of bounds
                    API.ServerSco.lastError = "201";
                    return "";
                }
                // make sure that array index 4 is either 'objectives' or 'correct_responses'
                if (cmiArray[3] == "objectives"){
                    // next check that there is an object here at this array index...
                    var arrayIndex2Check = eval("ans." + cmiArray[3] + ".objectivesInteractionArray(" + cmiArray[4] + ")");
                    // check for null
                    if (arrayIndex2Check == null){
                        API.ServerSco.lastError = "201";
                        return "";
                    }
                    else{
                        // next check that the last element is valid...
                        finalObjectCheck = eval ("arrayIndex2Check." + cmiArray[5]);
                        if (finalObjectCheck == null){
                            API.ServerSco.lastError = "201";
                            return "";
                        }
                        else{
                            // call must be to a valid element in the model so...
                            // check it for writeonly...
                            isWriteonly = eval ("finalObjectCheck.cmireadStatus");
                            if (isWriteonly == "writeonly"){
                                API.ServerSco.lastError = "404";
                                return "";
                            }
                            else{
                                API.ServerSco.lastError = "0";
                                return eval ("finalObjectCheck.cmivalue");
                            }
                        }
                    }
                }
                else if (cmiArray[3] == "correct_responses"){
                    // next check that there is an object here at this array index...
                    var arrayIndex2Check = eval("ans." + cmiArray[3] + ".correctResponsesInteractionArray(" + cmiArray[4] + ")");
                    // check for null
                    if (arrayIndex2Check == null){
                        API.ServerSco.lastError = "201";
                        return "";
                    }
                    else{
                        // next check that the last element is valid...
                        finalObjectCheck = eval ("arrayIndex2Check." + cmiArray[5]);
                        if (finalObjectCheck == null){
                            API.ServerSco.lastError = "201";
                            return "";
                        }
                        else{
                            // call must be to a valid element in the model so...
                            // check it for writeonly...
                            isWriteonly = eval ("finalObjectCheck.cmireadStatus");
                            if (isWriteonly == "writeonly"){
                                API.ServerSco.lastError = "404";
                                return "";
                            }
                            else{
                                API.ServerSco.lastError = "0";
                                return eval ("finalObjectCheck.cmivalue");
                            }
                        }
                    }
                }
                else {
                    // throw an error becuase 4th arg was not either
                    // objectives or correct_responses
                    API.ServerSco.lastError = "201";
                    return "";
                }
            }
        }
    }
}

function dealWithSettingObjectives(element, value){
    //  _CHILDREN ARE READONLY
    if (element == "cmi.objectives._children"){
        API.ServerSco.lastError = "402";
        return "false";
    }

    //  _COUNT IS READ ONLY
    if (element == "cmi.objectives._count"){
        API.ServerSco.lastError = "402";
        return "false";
    }

    // ELSE CHECK THAT THE ELEMENT IS VALID AND HAS AT LEAST 3 PARAMS
    var cmiArray = element.split(".");
    if (cmiArray.length < 3){
        API.ServerSco.lastError = "201";
        return "false";
    }

    // IF 3RD ARG IS NOT A NUMBER THEN THROW ERROR
    // need to check cmiArray[2] to see if its a number
    if (isNaN(cmiArray[2])){
        API.ServerSco.lastError = "401";
        return "false";
    }


    var theCount = API.cmi.objectives._count.cmivalue;

    // IF ITS A NUMBER MAKE SURE ITS IN THE ARRAY BOUNDS
    if(cmiArray[2] > theCount || cmiArray[2] < 0){
        // call to array is out of bounds
        API.ServerSco.lastError = "201";
        return "false";
    }
    else if(cmiArray[2] == theCount || cmiArray[2]  < theCount){

        //create a new one
        var existingObjectiveHandle = API.cmi.objectives.objArray(cmiArray[2]);
        if (existingObjectiveHandle == null){
            API.ServerSco.lastError = "101";
            return "false";
        }
        else{
            // we need to see if the call is asking for a valid element under cmi.objectives.n
            // we can trust the element parameter now to call the following...
            subelementstr = "existingObjectiveHandle";
            for (i=3;i<cmiArray.length;i++){
                subelementstr = subelementstr + "." + cmiArray[i];
            }

            var objTest = eval(subelementstr);
            if (objTest == null){
                API.ServerSco.lastError = "201";
                return "false";

            }

            var subelementstrWithoutLeaf = subelementstr;
            subelementstr = subelementstr + ".cmireadStatus;";
            res = eval(subelementstr);
            if (res == null){
                API.ServerSco.lastError = "101";
                return "false";
            }
            else{
                if (res == "readonly"){
                    API.ServerSco.lastError = "403";
                    return "false";
                }
                else{

                    // check the datatype and vocabulary...
                    var datatype = objTest.cmidatatype;
                    res = API.ServerSco.checkDataTypeAndVocab(element, value, datatype);

                    if (res == "true"){
                        // correct datatype...
                        // WE CAN NOW TRY TO SET THE FULL OBJECT REFERENCE
                        var strleafval = "objTest.cmivalue =\"" + value + "\";";
                        var leafVal = eval(strleafval);
                        if (leafVal == null){
                            // IT FAILED AT THE FINAL HURDLE...
                            API.ServerSco.lastError = "201";
                            return "false";
                       }
                       else{
                            API.ServerSco.lastError = "0";
                            return "true";
                       }
                   }
                   else{
                       // incorrect data type...
                       API.ServerSco.lastError = "405";
                       return "false";
                   }

                }
            }
        }
    }
}

function dealWithSettingInteractions(element, value){
    //  _CHILDREN ARE READONLY
    if (element == "cmi.interactions._children"){
        API.ServerSco.lastError = "402";
        return "false";
    }

    //  _COUNT IS READ ONLY
    if (element == "cmi.interactions._count"){
        API.ServerSco.lastError = "402";
        return "false";
    }

    // ELSE CHECK THAT THE ELEMENT IS VALID AND HAS AT LEAST 3 PARAMS, DOESNT HAVE
    // MORE THAN 6 PARAMS  - ALL ILLEGAL
    var cmiArray = element.split(".");
    if (cmiArray.length < 3 || cmiArray.length > 6){
        API.ServerSco.lastError = "201";
        return "false";
    }

    var theCount = API.cmi.interactions._count.cmivalue;

    // IF 3RD ARG IS NOT A NUMBER THEN THROW ERROR
    // need to check cmiArray[2] to see if its a number
    if (isNaN(cmiArray[2])){
        API.ServerSco.lastError = "401";
        return "false";
    }

    var theCount = API.cmi.interactions._count.cmivalue;

    // IF ITS A NUMBER MAKE SURE ITS IN THE ARRAY BOUNDS
    if(cmiArray[2] > theCount || cmiArray[2] < 0){
        // call to array is out of bounds
        API.ServerSco.lastError = "201";
        return "false";
    }
    else if(cmiArray[2] <= theCount){

        //create a new one or get existing object
        var existingObjectiveHandle = API.cmi.interactions.intArray(cmiArray[2]);
        if (existingObjectiveHandle == null){
            API.ServerSco.lastError = "101";
            return "false";
        }
        else{
            // we now have a reference to cmi.interactions.n
            // if theres 4 bits to the element path then try to see if object exists

            if (cmiArray.length == 4){
                strleaf = "existingObjectiveHandle." + cmiArray[3];
                var doesLeafExist = eval (strleaf);
                if (doesLeafExist == null){
                    API.ServerSco.lastError = "201";
                    return "false";
                }
                else{

                    // NEXT CHECK THAT THIS ELEMENT IS NOT READONLY
                    strleafstatus = "doesLeafExist.cmireadStatus";
                    var leafstatus = eval(strleafstatus);
                    if (leafstatus == "readonly"){
                        API.ServerSco.lastError = "403";
                        return "false";
                    }

                    // check the datatype and vocabulary...
                    var datatype = doesLeafExist.cmidatatype;
                    res = API.ServerSco.checkDataTypeAndVocab(element, value, datatype);
                    if (res == "true"){
                        // correct datatype...
                        // WE CAN NOW TRY TO SET THE FULL OBJECT REFERENCE
                        var strleafval = "doesLeafExist.cmivalue =\"" + value + "\";";
                        var leafVal = eval(strleafval);
                        if (leafVal == null){
                            // IT FAILED AT THE FINAL HURDLE...
                            API.ServerSco.lastError = "201";
                            return "false";
                       }
                       else{
                            API.ServerSco.lastError = "0";
                            return "true";
                       }
                   }
                   else{
                       // incorrect data type...
                       API.ServerSco.lastError = "405";
                       return "false";
                   }
                }
            }
            if (cmiArray.length == 5){
                // check object exists
                strbranch = "existingObjectiveHandle."+ cmiArray[3] + ";";
                var doesLeafExist = eval (strbranch);
                if (doesLeafExist == null){
                    API.ServerSco.lastError = "201";
                    return "false";
                }

                // check final object exists in the array list...
                nextstrbranch = "existingObjectiveHandle."+ cmiArray[3] + "." + cmiArray[4] + ";";
                var doesLeafExist = eval (nextstrbranch);
                if (doesLeafExist == null){
                    API.ServerSco.lastError = "201";
                    return "false";
                }

                // check for write only
                strread = "existingObjectiveHandle."+ cmiArray[3] + "." + cmiArray[4] + ".cmireadStatus;";
                var isWriteOnly = eval (strread);
                if (isWriteOnly == "readonly"){
                    API.ServerSco.lastError = "403";
                    return "false";
                }

                // see if value exists
                strleaf = "existingObjectiveHandle."+ cmiArray[3] + "." + cmiArray[4] + ".cmivalue;";
                var doesLeafExist = eval (strleaf);
                if (doesLeafExist == null){
                    API.ServerSco.lastError = "201";
                    return "false";
                }
                else{
                    // check the datatype and vocabulary...
                    var datatype = doesLeafExist.cmidatatype;
                    res = API.ServerSco.checkDataTypeAndVocab(element, value, datatype);
                    if (res == "true"){
                        // correct datatype...
                        // WE CAN NOW TRY TO SET THE FULL OBJECT REFERENCE
                        var strleafval = "doesLeafExist.cmivalue =\"" + value + "\";";
                        var leafVal = eval(strleafval);
                        if (leafVal == null){
                            // IT FAILED AT THE FINAL HURDLE...
                            API.ServerSco.lastError = "201";
                            return "false";
                        }
                        else{
                            API.ServerSco.lastError = "0";
                            return "true";
                        }
                    }
                    else{
                       // incorrect data type...
                       API.ServerSco.lastError = "405";
                       return "false";
                    }
                }
            }
            if (cmiArray.length == 6){
                // check object exists
                strbranch = "existingObjectiveHandle."+ cmiArray[3];
                var doesBranchExist = eval (strbranch);
                if (doesBranchExist == null){
                    API.ServerSco.lastError = "201";
                    return "false";
                }
                // The fifth argument should be an array reference, so do some checking...

                // IF 5TH ARG IS NOT A NUMBER THEN THROW ERROR
                // need to check cmiArray[4] to see if its a number
                if (isNaN(cmiArray[4])){
                    API.ServerSco.lastError = "401";
                    return "false";
                }

                // check to see if this element has a _count
                // If it hasn't we'll have to throw an error here
                // because we need the correct array index for array #2...
                var theCount = "existingObjectiveHandle." + cmiArray[3] + "._count.cmivalue;";
                var hasCount = eval(theCount);
                // CANT FIND _COUNT FOR THIS ELEMENT, SO THROW AN ERROR...
                if (hasCount == null){
                    API.ServerSco.lastError = "201";
                    return "false";
                }
                // next need to check to see if array ref is in array bounds
                if(cmiArray[4] > hasCount || cmiArray[4] < 0){
                    // call to array is out of bounds
                    API.ServerSco.lastError = "201";
                    return "false";
                }

                // make sure that array index 4 is either 'objectives' or 'correct_responses'
                if (cmiArray[3] == "objectives"){
                    // next check that there is an object here at this array index...
                    var arrayIndex2Check = eval("existingObjectiveHandle." + cmiArray[3] + ".objectivesInteractionArray(" + cmiArray[4] + ")");
                    // check for null
                    if (arrayIndex2Check == null){
                        API.ServerSco.lastError = "201";
                        return "false";
                    }
                    else{
                        // next check that the last element is valid...
                        finalObjectCheck = eval ("arrayIndex2Check." + cmiArray[5]);
                        if (finalObjectCheck == null){
                            API.ServerSco.lastError = "201";
                            return "false";
                        }
                        else{
                            // call must be to a valid element in the model so...
                            // check it for readonly...
                            isWriteonly = eval ("finalObjectCheck.cmireadStatus");
                            if (isWriteonly == "readonly"){
                                API.ServerSco.lastError = "403";
                                return "false";
                            }
                            else{

                                // check the datatype and vocabulary...
                                var datatype = finalObjectCheck.cmidatatype;
                                res = API.ServerSco.checkDataTypeAndVocab(element, value, datatype);
                                if (res == "true"){
                                    // correct datatype...
                                    // WE CAN NOW TRY TO SET THE FULL OBJECT REFERENCE
                                    var strleafval = "finalObjectCheck.cmivalue =\"" + value + "\";";
                                    var leafVal = eval(strleafval);
                                    if (leafVal == null){
                                        // IT FAILED AT THE FINAL HURDLE...
                                        API.ServerSco.lastError = "201";
                                        return "false";
                                    }
                                    else{
                                       API.ServerSco.lastError = "0";
                                       return "true";
                                    }
                               }
                               else{
                                   // incorrect data type...
                                   API.ServerSco.lastError = "405";
                                   return "false";
                               }
                            }
                        }
                    }
                }
                else if (cmiArray[3] == "correct_responses"){
                    // next check that there is an object here at this array index...
                    var arrayIndex2Check = eval("existingObjectiveHandle." + cmiArray[3] + ".correctResponsesInteractionArray(" + cmiArray[4] + ")");
                    // check for null
                    if (arrayIndex2Check == null){
                        API.ServerSco.lastError = "201";
                        return "false";
                    }
                    else{
                        // next check that the last element is valid...
                        finalObjectCheck = eval ("arrayIndex2Check." + cmiArray[5]);
                        if (finalObjectCheck == null){
                            API.ServerSco.lastError = "201";
                            return "false";
                        }
                        else{
                            // call must be to a valid element in the model so...
                            // check it for readonly...
                            isWriteonly = eval ("finalObjectCheck.cmireadStatus");
                            if (isWriteonly == "readonly"){
                                API.ServerSco.lastError = "403";
                                return "false";
                            }
                            else{
                                                               // check the datatype and vocabulary...
                                                               var datatype = finalObjectCheck.cmidatatype;
                                                               res = API.ServerSco.checkDataTypeAndVocab(element, value, datatype);
                                                               if (res == "true"){
                                                                   // correct datatype...
                                                       // WE CAN NOW TRY TO SET THE FULL OBJECT REFERENCE
                                                                   var strleafval = "finalObjectCheck.cmivalue =\"" + value + "\";";
                                               var leafVal = eval(strleafval);
                                               if (leafVal == null){
                                               // IT FAILED AT THE FINAL HURDLE...
                                               API.ServerSco.lastError = "201";
                                               return "false";
                                                                   }
                                               else{
                                               API.ServerSco.lastError = "0";
                                                                       return "true";
                                               }
                                                               }
                                                               else{
                                                                       // incorrect data type...
                                                           API.ServerSco.lastError = "405";
                                                                       return "false";
                                                               }

                            }
                        }
                    }
                }
                else {
                    // throw an error because 4th arg was not either
                    // objectives or correct_responses
                    API.ServerSco.lastError = "201";
                    return "false";
                }

            }

        }
    }

}

/*
* LMSGetValue.  Method to allow sco to read/access CMI datamodel elements
*/
function LMSGetValueMethod(element){
    if(this.ServerSco.isInitialized=="true"){
        var invalid = "false";
        var cannotHaveChildren = "false";
        var isNotAnArray = "false";

        // this checks to make sure there is at least one dot in the value
        if (element.indexOf(".")== -1){
            invalid = "true";
        }

        // dont bother doing this if we have already found an error...
        if (invalid != "true"){
            // we then loop around the children, making sure they exist one, by one...
            var cmiArray = element.split(".");
            var teststring = "this";
            for(i=0;i<cmiArray.length;i++){
                doesExist = eval(teststring + "." + cmiArray[i]+ ";");
                if(doesExist == null){
                    invalid="true";
                    // check for invalid _children call
                    if (cmiArray[i]=="_children"){
                        cannotHaveChildren = "true";
                    }
                    // check for invalid _count call
                    if (cmiArray[i]=="_count"){
                        isNotAnArray = "true";
                    }
                    break;
                }
                else{
                    teststring = teststring + "." + cmiArray[i];
                    // WE NEED TO TRAP THE OBJECTIVES...
                    if (teststring=="this.cmi.objectives"){
                        return dealWithGettingObjectives(element);
                    }
                    // WE NEED TO TRAP THE INTERACTIONS...
                    if (teststring=="this.cmi.interactions"){
                        return dealWithGettingInteractions(element);
                    }
                }
            }
        }

        // user tried to call _count on a non-array value
        if (isNotAnArray=="true"){
            this.ServerSco.lastError = "203";
            return "";
        }

        // user tried to call _children on an element that didnt support it
        if (cannotHaveChildren=="true"){
            this.ServerSco.lastError = "202";
            return "";
        }

        // if there was some kind of error found above, then...
        if (invalid == "true"){
            this.ServerSco.lastError = "401";
            return "";
        }
        else{
            // otherwise its a valid model reference...
            elementObj = eval ("this."+element);
        }

        // next we will check to make sure this element is not writeonly..
        if (elementObj.cmireadStatus == "writeonly"){
            this.ServerSco.lastError = "404";
            return "";
        }
        else{
            // its okay and user can read it...
            this.ServerSco.lastError = "0";
            return elementObj.cmivalue;
        }
    }
    else{
        // not initialized...
        this.ServerSco.lastError = "301";
        return "";
    }
}



/*
* LMSSetValue.  Method to allow sco to write data to CMI datamodel
*/
function LMSSetValueMethod(element, value){
     value = unescape(value)  ;
     if (this.ServerSco.isInitialized == "true"){
        var invalid = "false";
        var cannotHaveChildren = "false";
        var isNotAnArray = "false";

                // check for sco trying to set _children & _count
                //element is a keyword, cannot set...
                if (element.indexOf("._children") != -1 || element.indexOf("._count") != -1){
                        this.ServerSco.lastError = "402";
                        return "false";
                }

        // this checks to make sure there is at least one dot in the value
                // if it doesnt, then it cant be a valid CMI model reference
        if (element.indexOf(".")== -1){
            invalid = "true";
        }

        // dont bother doing this if we have already found an error...
        if (invalid != "true"){
            // we then loop around the children, making sure they exist one, by one...
            var cmiArray = element.split(".");
            var teststring = "this";
            for(i=0;i<cmiArray.length;i++){
                doesExist = eval(teststring + "." + cmiArray[i]+ ";");
                if(doesExist == null){
                    invalid="true";
                    // check for invalid _children call
                    if (cmiArray[i]=="_children"){
                        cannotHaveChildren = "true";
                    }
                    // check for invalid _count call
                    if (cmiArray[i]=="_count"){
                        isNotAnArray = "true";
                    }
                    break;
                }
                else{
                    teststring = teststring + "." + cmiArray[i];
                    // WE NEED TO TRAP THE OBJECTIVES...
                    if (teststring=="this.cmi.objectives"){
                        return dealWithSettingObjectives(element, value);
                    }
                    // WE NEED TO TRAP THE INTERACTIONS...
                    if (teststring=="this.cmi.interactions"){
                        return dealWithSettingInteractions(element, value);
                    }
                }
            }
        }

        // user tried to call _count on a non-array value
        if (isNotAnArray=="true"){
            this.ServerSco.lastError = "203";
            return "false";
        }

        // user tried to call _children on an element that didnt support it
        if (cannotHaveChildren=="true"){
            this.ServerSco.lastError = "202";
            return "false";
        }

        // if there was some kind of error found above, then...
        if (invalid=="true"){
            this.ServerSco.lastError = "401";
            return "false";
        }
        else{
            // otherwise its a valid model reference...
            elementObj = eval ("this."+element);
        }

        // check that its writeable...
        if (elementObj.cmireadStatus == "readonly"){
            this.ServerSco.lastError = "403";
            return "false";
        }
        else{
            // check the datatype and vocabulary...
            var datatype = elementObj.cmidatatype;
            res = this.ServerSco.checkDataTypeAndVocab(element, value, datatype);
                if (res == "true"){
                    // correct datatype...
                    // cmi.comments need to be appended...
                    if (element == "cmi.comments"){
                        pre = this.LMSGetValue("cmi.comments");
                        pre = pre.replace(/"/g,'\'');
                        value = value.replace(/"/g,'\'');
                        setString = "this." + element + ".cmivalue =\"" + pre + value + "\";";
                    }
                    else{
                        value = value.replace(/"/g,'\'');
                        setString = "this." + element + ".cmivalue =\"" + value + "\";";
                    }
                    var result = eval(setString);
                    this.ServerSco.lastError = "0";
                    return "true";
                }
                else{
                    // incorrect data type...
                    this.ServerSco.lastError = "405";
                    return "false";
               }
        }
    }
    else{
        // not initialized...
        this.ServerSco.lastError = "301";
        return "false";
    }
}

function LMSGetErrorStringMethod(errorCode){
    switch (errorCode)
    {
        case "0":   { return "No error"; break }
        case "101": { return "General exception"; break  }
        case "201": { return "Invalid argument error"; break }
        case "202": { return "Element cannot have children"; break  }
        case "203": { return "Element not an array - Cannot have count"; break  }
        case "301": { return "Not initialized"; break  }
        case "401": { return "Not implemented error"; break  }
        case "402": { return "Invalid set value, element is a keyword"; break  }
        case "403": { return "Element is read only"; break  }
        case "404": { return "Element is write only"; break  }
        case "405": { return "Incorrect Data Type"; break  }
        default:    { return ""; break }
    }
    // just to be safe...
    return;
}

function LMSGetLastErrorMethod(){
    return this.ServerSco.lastError;
}

function LMSGetDiagnosticMethod(errorCode){
    if (errorCode==""){
        errorCode=this.ServerSco.lastError;
    }
    switch (errorCode)
    {
        case "0":   { return "No error. No errors were encountered. Successful API call."; break }
        case "101": { return "General exception. An unexpected error was encountered."; break  }
        case "201": { return "Invalid argument error. A call was made to a DataModel element that does not exist."; break }
        case "202": { return "Element cannot have children. A call was made to an Element that does not support _children"; break  }
        case "203": { return "Element is not an array.  Cannot have count. A call was made to an Element that does not support _count."; break  }
        case "301": { return "Not initialized. The SCO has not yet been initialized.  It needs to call LMSInitialize() first."; break  }
        case "401": { return "Not implemented error.  A call was made to a DataModel element that is not supported."; break  }
        case "402": { return "Invalid set value, element is a keyword.  Keyword values cannot be changed"; break  }
        case "403": { return "Element is read only.  A call was made to set the value of a read-only element."; break  }
        case "404": { return "Element is write only.  A call was made to get the value of a write-only element."; break  }
        case "405": { return "Incorrect Data Type.  The syntax of a call to change an element was incorrect."; break  }
        default:    { return ""; break }
    }
}

/*
* --------------------------------------------------------------------------------------------------
*   Datatype and vocabulary checking
* --------------------------------------------------------------------------------------------------
*/

/*
* Method to check the datatype and vocabulary of an element
* returns true or false...
*/
function scoCheckDataTypeAndVocab (element, value, datatype){
    switch (datatype)
    {
        case "CMIBlank":   { return checkCMIBlank(value); break }
        case "CMIBoolean": { return checkCMIBoolean(value); break  }
        case "CMIDecimal": { return checkCMIDecimal(value); break }
        case "CMIFeedback": { return  checkCMIFeedback(element, value); break  }
        case "CMIIdentifier": { return  checkCMIIdentifier(value); break  }
        case "CMIInteger": { return checkCMIInteger(value); break  }
        case "CMISInteger": { return checkCMISInteger(element, value); break  }
        case "CMIString255": { return checkCMIString255(value); break  }
        case "CMIString4096": { return checkCMIString4096(value); break  }
        case "CMITime": { return checkCMITime(value); break  }
        case "CMITimespan": { return checkCMITimespan(value); break  }
        case "CMIVocabularyCredit": { return checkCMIVocabularyCredit(value); break  }
        case "CMIVocabularyStatus": { return checkCMIVocabularyStatus(element, value); break  }
        case "CMIVocabularyEntry": { return checkCMIVocabularyEntry(value); break  }
        case "CMIVocabularyMode": { return checkCMIVocabularyMode(value); break  }
        case "CMIVocabularyExit": { return checkCMIVocabularyExit(value); break  }
        case "CMIVocabularyTimeLimitAction": { return checkCMIVocabularyTimeLimitAction(value); break  }
        case "CMIVocabularyInteraction": { return checkCMIVocabularyInteraction(value); break  }
        case "CMIVocabularyResult": { return checkCMIVocabularyResult(value); break  }
        case "CMIDecimalOrCMIBlank": { return checkCMIDecimalOrCMIBlank(value); break  }
        default:    { return "true"; break }
    }
}

function checkCMIDecimalOrCMIBlank(value){

    var isBlank = checkCMIBlank(value);
    var isCMIDecimal = checkCMIDecimal(value);
    if (isBlank == "true" || isCMIDecimal == "true"){
        if (value > 100 || value < 0){
            return "false";
        }
        else{
            return "true";
        }
    }else{
        return "false";
    }
}

function checkCMIVocabularyResult(value){
    var ans = checkCMIDecimal(value);
    if (ans == "true"){
        return "true";
    }
    if (value == "correct" || value == "wrong" ||
        value == "unanticipated" || value == "neutral"){
        return "true";
    }
    else{
        return "false";
    }
}


function checkCMIVocabularyInteraction(value){
    if (value == "true-false" || value == "choice" ||
        value == "fill-in" || value == "matching" ||
        value == "performance" || value == "likert" ||
        value == "sequencing" || value == "numeric"){
        return "true";
    }
    else{
        return "false";
    }
}

function checkCMIVocabularyTimeLimitAction(value){
    if (value == "exit,message" || value == "exit,no message" ||
        value == "continue,message" || value == "continue,no message"){
        return "true";
    }
    else{
        return "false";
    }
}

function checkCMIVocabularyExit(value){
    if (value == "time-out" || value == "suspend" ||
        value == "logout" || value == ""){
        return "true";
    }
    else{
        return "false";
    }
}

function checkCMIVocabularyMode(value){
    if (value == "normal" || value == "review" || value == "browse"){
        return "true";
    }
    else{
        return "false";
    }
}

function checkCMIVocabularyEntry(value){
    if (value == "ab-initio" || value == "resume" || value == ""){
        return "true";
    }
    else{
        return "false";
    }
}

function checkCMIVocabularyStatus(element, value){
    // sco cannot set lesson_status to not attempted
    if (element == "cmi.core.lesson_status" && value == "not attempted"){
        return false;
    }
    if (value == "passed" || value == "completed" ||
        value == "failed" || value == "incomplete" ||
        value == "browsed" || value == "not attempted"){
        return "true";
    }
    else{
        return "false";
    }
}

function checkCMIVocabularyCredit(value){
    if (value == "credit" || value == "no-credit"){
        return "true";
    }
    else{
        return "false";
    }
}


function checkCMITimespan(value){
   // must have some colons...
   if (value.indexOf(":") == -1){
       return "false";
   }
   // must contain at least 2 colons, giving 3 array elements...
   var cmiArray = value.split(":");
   if (cmiArray.length < 3){
      return "false";
   }
   // hours must be 4,3 or 2 digits...
   if (cmiArray[0].length < 2 || cmiArray[0].length > 4  ){
      return "false";
   }
   // minutes must be 2 digits...
   if (cmiArray[1].length != 2){
      return "false";
   }
   // must be numbers...
   if (isNaN(cmiArray[0]) || isNaN(cmiArray[1]) || isNaN(cmiArray[2])){
      return "false";
   }
   // 24hr clock for hours...
   if (parseInt(cmiArray[0]) < 0){
      return "false";
   }
   // parse minutes
   // NOTE: Seems illegal to have 99 minutes, but ADL 1.2
   // SCORM Conformance Test Suite does this? I'll do the same...
   // if (parseInt(cmiArray[1]) < 0 || parseInt(cmiArray[1]) > 59){
   if (parseInt(cmiArray[1]) < 0){
      return "false";
   }
   // check for decimal place...
   if (cmiArray[2].indexOf(".") != -1){
       var cmiDecArray = cmiArray[2].split(".");
       // can only be 2 values here...
       if (cmiDecArray.length != 2){
           return "false";
       }
       // again they must be numbers...
       if (isNaN(cmiDecArray[0]) || isNaN(cmiDecArray[1])){
           return "false";
       }
       // only two digits allowed for seconds...
       if (cmiDecArray[0].length != 2){
           return "false";
       }
       // make sure there is less than 60 seconds here...
       if (parseInt(cmiDecArray[0]) > 59 ){
          return "false";
       }
       // only one or two digits allowed for milliseconds...
       if (cmiDecArray[1].length > 2){
           return "false";
       }
   }
   else{
       // no dots, so must be no milliseconds...
       // make sure length is 2
       if (cmiArray[2].length != 2){
           return "false";
       }
       // make sure there is less than 60 seconds here...
       if (parseInt(cmiArray[2]) > 59 ){
          return "false";
       }
   }
   // got up to here, then value okay...
   return "true";
}

function checkCMITime(value){

   // must have some colons...
   if (value.indexOf(":") == -1){
       return "false";
   }
   // must contain at least 2 colons, giving 3 array elements...
   var cmiArray = value.split(":");
   if (cmiArray.length < 3){
      return "false";
   }
   // hours & minutes must be 2 digits...
   if (cmiArray[0].length != 2 || cmiArray[1].length != 2){
      return "false";
   }
   // must be numbers...
   if (isNaN(cmiArray[0]) || isNaN(cmiArray[1]) || isNaN(cmiArray[2])){
      return "false";
   }
   // 24hr clock for hours...
   if (parseInt(cmiArray[0]) < 0 || parseInt(cmiArray[0]) > 23){
      return "false";
   }
   // parse minutes
   if (parseInt(cmiArray[1]) < 0 || parseInt(cmiArray[1]) > 59){
      return "false";
   }
   // check for decimal place...
   if (cmiArray[2].indexOf(".") != -1){
       var cmiDecArray = cmiArray[2].split(".");
       // can only be 2 values here...
       if (cmiDecArray.length != 2){
           return "false";
       }
       // again they must be numbers...
       if (isNaN(cmiDecArray[0]) || isNaN(cmiDecArray[1])){
           return "false";
       }
       // only two digits allowed for seconds...
       if (cmiDecArray[0].length != 2){
           return "false";
       }
       // make sure there is less than 60 seconds here...
       if (parseInt(cmiDecArray[0]) > 59 ){
          return "false";
       }
       // only one or two digits allowed for milliseconds...
       if (cmiDecArray[1].length > 2){
           return "false";
       }
   }
   else{
       // no dots, so must be no milliseconds...
       // make sure length is 2
       if (cmiArray[2].length != 2){
           return "false";
       }
       // make sure there is less than 60 seconds here...
       if (parseInt(cmiArray[2]) > 59 ){
          return "false";
       }
   }
   // got up to here, then value okay...
   return "true";
}


function checkCMIString4096(value){
    if (value.length <= 4096){
       return "true";
    }
    else{
       return "false";
    }
}

function checkCMIString255(value){
    if (value.length <= 255){
       return "true";
    }
    else{
       return "false";
    }
}

function checkCMISInteger(element, value){
    if(isNaN(value)){
        return "false";
    }
    else{
        var num = parseInt(value);
        if (num >= -32768 && num <= 32768){
            if (element == "cmi.student_preference.audio"){
                if (num < -1 || num > 100){
                    return "false";
                }
                else{
                    return "true";
                }
            }
            else if (element == "cmi.student_preference.speed"){
                if (num < -100 || num > 100){
                    return "false";
                }
                else{
                    return "true";
                }
            }
            else if (element == "cmi.student_preference.text"){
                if (num < -1 || num > 1){
                    return "false";
                }
                else{
                    return "true";
                }
            }
            else{
                return "true";
            }
        }
        else{
            return "false";
        }
    }
}

function checkCMIInteger(value){
    if(isNaN(value)){
        return "false";
    }
    else{
        var num = parseInt(value);
        if (num >= 0 && num <= 65536){
            return "true";
        }
        else{
            return "false";
        }
    }
}

function checkCMIIdentifier(value){
    var SPACE = ' ';
    var TAB = '\t';
    var CRETURN = '\r';
    var LINEFEED = '\n';
    if (value.indexOf(SPACE) == -1 && value.indexOf(TAB) == -1
     && value.indexOf(CRETURN) == -1 && value.indexOf(LINEFEED) == -1){
        if (value.length > 0 && value.length < 256){
            return "true";
        }
        else{
            return "false";
        }
    }
    else{
        return "false";
    }
}



function checkCMIFeedback(element, value){
    // allow user to edit var at top of page to disable this checking...
    if (looseChecking == "false"){
        // need to find the type (if its set)
        var cmiArray = element.split(".");
        // need to check cmiArray[2] to see if its a number
        if (isNaN(cmiArray[2])){
            // this should be a number. However, Err on the side of caution...
            return "false";
        }
        // make sure that this interaction already exists...
        var res = API.LMSGetValue("cmi.interactions._count");
        if (parseInt(cmiArray[2]) >= parseInt(res)){
            // then this interaction does not exist.. However, Err on the side of caution...
            return "false";
        }
        // Up to here? - then get the type
        var theType = "cmi.interactions.intArray("+cmiArray[2]+").type";
        elementObj = eval("API."+theType+";");
        if (elementObj == null){
            return "false";
        }
        datatype = elementObj.cmivalue;

        if (datatype == null){
            return "false";
        }
        // its not null, so it equals something, so...
        switch (datatype)
        {
            case "true-false":   { return checkTrueFalse(value); break }
            case "choice":   { return checkChoice(value); break }
            case "fill-in":   { return checkFillIn(value); break }
            case "numeric":   { return checkCMIDecimal(value); break }
            case "likert":   { return checkLikert(value); break }
            case "matching":   { return checkMatching(value); break }
            case "performance":   { return checkCMIString255(value); break }
            case "sequencing":   { return checkSequencing(value); break }
            // if its not been set then we should return false.  That would mean
            // that a cmi.interaction.n.type MUST have a value and cannot be empty
            default:   { return "false"; break }
        }
    }
    else{
        return "true";
    }

}

function checkMatching(value){
  // check for n.n
  var TEST_VAL = /^[a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1}$/;
  // check for n.n,n.n,n.n etc
  var TEST_VAL2 = /^[a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1},{1}([a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1},{1})*[a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1}$/;
  // check for {n.n,n.n,n.n etc }
  // Bugfix Mozilla firebird didnt like this line below
  // var TEST_VAL3 = /^{[a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1},{1}([a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1},{1})*[a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1}}$/;
  var TEST_VAL3 = /^[a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1},{1}([a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1},{1})*[a-z,A-Z,0-9]{1}.{1}[a-z,A-Z,0-9]{1}$/;
  if (TEST_VAL.test(value)) {
      return "true";
  }
  else if (TEST_VAL2.test(value)) {
      return "true";
  }
  else if (TEST_VAL3.test(value)) {
      return "true";
  }
  else{
      return "false";
  }
}


function checkSequencing(value){

  // test for single a-z 0-9
  var TEST_VAL = /^[a-z,A-Z,0-9]{1}$/;

  // test for format 1,2,3,a,b,c
  var TEST_VAL2 = /^[a-z,A-Z,0-9]{1},{1}([a-z,A-Z,0-9],)*[a-z,A-Z,0-9]{1}$/;

  if (TEST_VAL.test(value)) {
      return "true";
  }
  else if (TEST_VAL2.test(value)) {
      return "true";
  }
  else{
      return "false";
  }
}

function checkChoice(value){
  // test for single a-z 0-9
  var TEST_VAL = /^[a-z,A-Z,0-9]{1}$/;

  // test for format 1,2,3,a,b,c
  var TEST_VAL2 = /^[a-z,A-Z,0-9]{1},{1}([a-z,A-Z,0-9],)*[a-z,A-Z,0-9]{1}$/;

  // test for format {1,2,3,a,b,c}
  // Bugfix Mozilla firebird didnt like this line below
  //var TEST_VAL3 = /^{[a-z,A-Z,0-9]{1},{1}([a-z,A-Z,0-9],)*[a-z,A-Z,0-9]{1}}$/;
  var TEST_VAL3 = /^[a-z,A-Z,0-9]{1},{1}([a-z,A-Z,0-9],)*[a-z,A-Z,0-9]{1}$/;
  
  if (TEST_VAL.test(value)) {
      return "true";
  }
  else if (TEST_VAL2.test(value)) {
      return "true";
  }
  else if (TEST_VAL3.test(value)) {
      return "true";
  }
  else{
      return "false";
  }
}


function checkFillIn(value){
    return checkCMIString255(value);
}


function checkTrueFalse(value){
    if (value == "0" || value == "1" || value == "t" || value == "f" || value == "T" || value == "F"){
        return "true";
    }
    else{
        return "false";
    }
}


function checkLikert(value){
  if (value.length == 0){
      return "true";
  }
  if (value.length > 1){
      return "false";
  }
  var TEST_VAL = /^[a-z,A-Z,0-9]{1}$/;
  if (TEST_VAL.test(value)) {
      return "true";
  }
  else{
      return "false";
  }
}


function checkCMIDecimal(value){
   if (isNaN(value)){
        return "false";
   }
   else{
        return "true";
   }
}

function checkCMIBoolean(value){
   if (value == "true" || value == "false"){
        return "true";
   }
   else{
        return "false";
   }
}

function checkCMIBlank(value){
   if (value != ""){
       return "false";
   }
   else{
       return "true";
   }
}


/*
* ----------------------------------------------------------------------------------------------------
*
*   The CMI Client side data models
*
* ----------------------------------------------------------------------------------------------------
*/



function CMIModel (){
    this._version = new CMIComponent("_version", "3.4", "readonly", "");
    this.core = new CMICoreModel;
    this.suspend_data = new CMIComponent("suspend_data", "", "both", "CMIString4096");
    this.launch_data = new CMIComponent("launch_data","","readonly", "CMIString4096");
    this.comments = new CMIComponent("comments","","both", "CMIString4096");
    this.comments_from_lms = new CMIComponent("comments_from_lms","","readonly", "CMIString4096");
    this.objectives = new ObjectivesModel;
    this.student_data = new StudentDataModel;
    this.student_preference = new StudentPreferenceModel;
    this.interactions = new InteractionsModel;
}


function CMICoreModel(){
    this._children = new CMIComponent("_children", "student_id,student_name,lesson_location,credit,lesson_status,entry,score,total_time,lesson_mode,exit,session_time", "readonly", "CMIString255");
    this.student_id = new CMIComponent("student_id", "", "readonly", "CMIIdentifier");
    this.student_name = new CMIComponent("student_name", "", "readonly", "CMIString255");
    this.lesson_location = new CMIComponent("lesson_location", "", "both", "CMIString255");
    this.credit = new CMIComponent("credit", "", "readonly", "CMIVocabularyCredit");
    this.lesson_status = new CMIComponent("lesson_status", "", "both", "CMIVocabularyStatus");
    this.entry = new CMIComponent("entry","","readonly", "CMIVocabularyEntry");
    this.score = new CMIScore;
    this.total_time = new CMIComponent("total_time", "", "readonly", "CMITimespan");
    this.lesson_mode = new CMIComponent("lesson_mode", "", "readonly", "CMIVocabularyMode");
    this.exit = new CMIComponent("exit", "", "writeonly", "CMIVocabularyExit");
    this.session_time = new CMIComponent("session_time", "", "writeonly", "CMITimespan");
}


function CMIScore(){
    this._children = new  CMIComponent("_children", "raw,min,max", "readonly", "CMIString255");
    this.raw = new CMIComponent("raw", "", "both", "CMIDecimalOrCMIBlank");
    this.max = new CMIComponent("max", "", "both", "CMIDecimalOrCMIBlank");
    this.min = new CMIComponent("min", "", "both", "CMIDecimalOrCMIBlank");
}


function StudentPreferenceModel(){
    this._children = new CMIComponent("_children", "audio,language,speed,text", "readonly", "CMIString255");
    this.audio = new CMIComponent("audio", "0", "both", "CMISInteger");
    this.language = new CMIComponent("language", "", "both", "CMIString255");
    this.speed = new CMIComponent("speed", "0", "both", "CMISInteger");
    this.text = new CMIComponent("text", "0", "both", "CMISInteger");
}


function StudentDataModel(){
    this._children = new CMIComponent("_count", "mastery_score,max_time_allowed,time_limit_action", "readonly", "CMIString255");
    this.mastery_score = new CMIComponent("mastery_score", "", "readonly", "CMIDecimal");
    this.max_time_allowed = new CMIComponent("max_time_allowed", "", "readonly", "CMITimespan");
    this.time_limit_action = new CMIComponent("time_limit_action", "", "readonly", "CMIVocabularyTimeLimitAction");
}



/*
*  The CMI objectives model
*/

function ObjectivesModel(){
    this._children = new CMIComponent("_children", "id,score,status", "readonly", "CMIString255");
    this._count = new CMIComponent("_count", 0, "readonly", "CMIInteger");
    this.objArray = ObjectiveArrayModel;
    this.objArr = new Array();
}

function ObjectiveArrayModel(index){
    if(index>this._count.cmivalue-1){
        if (index == this._count.cmivalue){
            // then create new one...
            this.objArr[index] = new singleObjectiveModel();
            this._count.cmivalue = this._count.cmivalue + 1;
            return this.objArr[index];
        }
        else{
            return "false";
        }
    }
    else{
        // we must be talking about this one so return object..
        return this.objArr[index];
    }
}


function singleObjectiveModel(){
    this.id = new CMIComponent("id", "", "both", "CMIIdentifier");
    this.score = new objectiveScoreModel;
    this.status = new CMIComponent("status", "", "both", "CMIVocabularyStatus");
}

function objectiveScoreModel(){
    this._children = new CMIComponent("_children", "raw,min,max", "readonly", "CMIString255");
    this.raw = new CMIComponent("raw", "", "both", "CMIDecimalOrCMIBlank");
    this.min = new CMIComponent("min", "", "both", "CMIDecimalOrCMIBlank");
    this.max = new CMIComponent("max", "", "both", "CMIDecimalOrCMIBlank");
}



/*
*  The CMI interactions model
*/

function InteractionsModel(){
    this._children = new CMIComponent("_children", "id,objectives,time,type,correct_responses,weighting,student_response,result,latency", "readonly", "CMIString255");
    this._count = new CMIComponent("_count", 0, "readonly", "CMIInteger");
    this.intArray = InteractionsArrayModel;
    this.intArr = new Array();
}


function InteractionsArrayModel(index){

    if(index>this._count.cmivalue-1){
        if (index == this._count.cmivalue){
            // then create new one...
            this.intArr[index] = new singleInteractionModel();
            this._count.cmivalue = this._count.cmivalue + 1;
            return this.intArr[index];
        }
        else{
            return "false";
        }
    }
    else{
        // we must be talking about this one so return object..
        return this.intArr[index];
    }
}


function singleInteractionModel(){
    this.id = new CMIComponent("id", "", "writeonly", "CMIIdentifier");
    this.objectives = new ObjectivesInteractionModel;
    this.time = new CMIComponent("time", "", "writeonly", "CMITime");
    this.type = new CMIComponent("type", "", "writeonly", "CMIVocabularyInteraction");
    this.correct_responses = new CorrectResponsesInteractionModel;
    this.weighting = new CMIComponent("weighting", "", "writeonly", "CMIDecimal");
    this.student_response = new CMIComponent("student_response", "", "writeonly", "CMIFeedback");
    this.result = new CMIComponent("result", "", "writeonly", "CMIVocabularyResult");
    this.latency = new CMIComponent("latency", "", "writeonly", "CMITimespan");
}


function ObjectivesInteractionModel(){
    this._count = new CMIComponent("_count", 0, "readonly", "CMIInteger");
    this.objectivesInteractionArray = SingleObjectivesInteractionModel;
    this.objectivesInteractionArr = new Array();
}


function SingleObjectivesInteractionModel(index){
    if(index>this._count.cmivalue-1){
        if (index == this._count.cmivalue){
            // then create new one...
            this.objectivesInteractionArr[index] = new SingleItemObjectivesInteractionModel();
            this._count.cmivalue = this._count.cmivalue + 1;
            return this.objectivesInteractionArr[index];
        }
        else{
            return "false";
        }
    }
    else{
        // we must be talking about this one so return object..
        return this.objectivesInteractionArr[index];
    }
}


function SingleItemObjectivesInteractionModel(){
    this.id = new CMIComponent("id", "", "writeonly", "CMIIdentifier");
}



function CorrectResponsesInteractionModel(){
    this._count = new CMIComponent("_count", 0, "readonly", "CMIInteger");
    this.correctResponsesInteractionArray = SingleCorrectResponsesInteractionModel;
    this.correctResponsesInteractionArr = new Array();
}


function SingleCorrectResponsesInteractionModel(index){
    if(index>this._count.cmivalue-1){
        if (index == this._count.cmivalue){
            // then create new one...
            this.correctResponsesInteractionArr[index] = new SingleItemCorrectResponsesInteractionModel();
            this._count.cmivalue = this._count.cmivalue + 1;
            return this.correctResponsesInteractionArr[index];
        }
        else{
            return "false";
        }
    }
    else{
        // we must be talking about this one so return object..
        return this.correctResponsesInteractionArr[index];
    }
}


function SingleItemCorrectResponsesInteractionModel(){
    this.pattern = new CMIComponent("pattern", "", "writeonly", "CMIFeedback");
}

/*
*
*
*/
function showCurrentModelState(infoOrForm){

    var divider = "";
    var titles = "";
    if (infoOrForm == "info"){
        divider = "\n";
                equals = "=";
        titles = "Current client CMI Datamodel\n\n";
    }
    else{
                equals = "~r@l@ad~";
        divider = "^r@l@ad^";
        titles = "";
    }

    a = "cmi.core.student_id" + equals + API.cmi.core.student_id.cmivalue + divider;
    b = "cmi.core.student_name" + equals + API.cmi.core.student_name.cmivalue + divider;
    c = "cmi.core.lesson_location" + equals + API.cmi.core.lesson_location.cmivalue + divider;
    d = "cmi.core.credit" + equals + API.cmi.core.credit.cmivalue + divider;
    e = "cmi.core.lesson_status" + equals + API.cmi.core.lesson_status.cmivalue + divider;
    f = "cmi.core.entry" + equals + API.cmi.core.entry.cmivalue + divider;
    g = "cmi.core.score.raw" + equals + API.cmi.core.score.raw.cmivalue + divider;
    h = "cmi.core.score.max" + equals + API.cmi.core.score.max.cmivalue + divider;
    i = "cmi.core.score.min" + equals + API.cmi.core.score.min.cmivalue + divider;
    j = "cmi.core.total_time" + equals + API.cmi.core.total_time.cmivalue + divider;
    k = "cmi.core.lesson_mode" + equals + API.cmi.core.lesson_mode.cmivalue + divider;
    l = "cmi.core.exit" + equals + API.cmi.core.exit.cmivalue + divider;
    m = "cmi.core.session_time" + equals + API.cmi.core.session_time.cmivalue + divider;
    n = "cmi.suspend_data" + equals + API.cmi.suspend_data.cmivalue + divider;
    o = "cmi.launch_data" + equals + API.cmi.launch_data.cmivalue + divider;
    p = "cmi.comments" + equals + API.cmi.comments.cmivalue + divider;
    q = "cmi.comments_from_lms" + equals + API.cmi.comments_from_lms.cmivalue + divider;
    r = "cmi.objectives._count" + equals + API.cmi.objectives._count.cmivalue + divider;

    var s = "";
    var objectivesCount = API.cmi.objectives._count.cmivalue;
    for (count=0; count < objectivesCount; count++){
        objHandle = API.cmi.objectives.objArray(count);
        idval = objHandle.id.cmivalue;
        scoreRaw = objHandle.score.raw.cmivalue;
        scoreMax = objHandle.score.max.cmivalue;
        scoreMin = objHandle.score.min.cmivalue;
                statval = objHandle.status.cmivalue;
        s = s + "cmi.objectives." + count + ".id" + equals + idval + divider;
        s = s + "cmi.objectives." + count + ".score.raw" + equals + scoreRaw + divider;
        s = s + "cmi.objectives." + count + ".score.max" + equals + scoreMax + divider;
        s = s + "cmi.objectives." + count + ".score.min" + equals + scoreMin + divider;
                s = s + "cmi.objectives." + count + ".status" + equals + statval + divider;
    }


    v = "cmi.student_data.mastery_score" + equals + API.cmi.student_data.mastery_score.cmivalue + divider;
    w = "cmi.student_data.max_time_allowed" + equals + API.cmi.student_data.max_time_allowed.cmivalue + divider;
    x = "cmi.student_data.time_limit_action" + equals + API.cmi.student_data.time_limit_action.cmivalue + divider;

    y = "cmi.student_preference.audio" + equals + API.cmi.student_preference.audio.cmivalue + divider;
    z = "cmi.student_preference.language" + equals + API.cmi.student_preference.language.cmivalue + divider;
    zz = "cmi.student_preference.speed" + equals + API.cmi.student_preference.speed.cmivalue + divider;
    zzz = "cmi.student_preference.text" + equals + API.cmi.student_preference.text.cmivalue + divider;

    t = "cmi.interactions._count" + equals + API.cmi.interactions._count.cmivalue + divider;

    var u = "";
    var interactionsCount = API.cmi.interactions._count.cmivalue
    for (intcount=0; intcount < interactionsCount; intcount++){
        intHandle = API.cmi.interactions.intArray(intcount);

        idval = intHandle.id.cmivalue;
        u = u + "cmi.interactions." + intcount + ".id" + equals + idval + divider;

        interObjCount = intHandle.objectives._count.cmivalue;
        u = u + "cmi.interactions." + intcount + ".objectives._count" + equals + interObjCount + divider;

        for (objcount=0; objcount < interObjCount; objcount++){
             interactionObjectiveHandle = intHandle.objectives.objectivesInteractionArray(objcount);
             objid = interactionObjectiveHandle.id.cmivalue;
             u = u + "cmi.interactions." + intcount + ".objectives." + objcount + ".id" + equals + objid + divider;
        }

        srCount = intHandle.correct_responses._count.cmivalue;
        u = u + "cmi.interactions." + intcount + ".correct_responses._count" + equals + srCount + divider;

        for (objcount=0; objcount < srCount; objcount++){
             interactionSRHandle = intHandle.correct_responses.correctResponsesInteractionArray(objcount);
             patternid = interactionSRHandle.pattern.cmivalue;
             u = u + "cmi.interactions." + intcount + ".correct_responses." + objcount + ".pattern" + equals + patternid + divider;
        }


        timeval = intHandle.time.cmivalue;
        u = u + "cmi.interactions." + intcount + ".time" + equals + timeval + divider;

        typeval = intHandle.type.cmivalue;
        u = u + "cmi.interactions." + intcount + ".type" + equals + typeval + divider;

        weightingval = intHandle.weighting.cmivalue;
        u = u + "cmi.interactions." + intcount + ".weighting" + equals + weightingval + divider;

        student_responseval = intHandle.student_response.cmivalue;
        u = u + "cmi.interactions." + intcount + ".student_response" + equals + student_responseval + divider;

        resultval = intHandle.result.cmivalue;
        u = u + "cmi.interactions." + intcount + ".result" + equals + resultval + divider;

        latencyval = intHandle.latency.cmivalue;
        u = u + "cmi.interactions." + intcount + ".latency" + equals + latencyval + divider;
    }

    var alertString = titles+a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+v+w+x+y+z+zz+zzz+t+u;
    return alertString;

}

/*
* a function used in debug mode to see the current cmi model
*/
function viewModel(){
    return showCurrentModelState("info");
}

function load_scorm_lms_api(){
  //xhr here
  let src = document.getElementsByTagName("iframe")[0].getAttribute('data-src');
  var skey = src;

  var value = localStorage.getItem(skey);
  if(!isEmpty(window.scorm_wplms_data)){
    document.getElementsByTagName("iframe")[0].setAttribute('src',src);
    Utils.launchSCO();
  }else{
    document.getElementsByTagName("iframe")[0].setAttribute('src',src);
    Utils.launchSCO();
  }
}


function fetchWPLMSSCORMData(){
  return new Promise(function(resolve) {
    let src = document.getElementsByTagName("iframe")[0].getAttribute('data-src');
    var skey = src;

    var value = localStorage.getItem(skey);
    if(!isEmpty(value) && !isEmpty(window.scorm_wplms_data)){
      var nonce = window.scorm_wplms_data.security_nonce,
      xhr = new XMLHttpRequest();
      xhr.open('POST', window.wplms_course_data.api_url+'/scorm/scormdata/get?force');
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.onload = function() {
          if (xhr.status === 200 && xhr.responseText !== nonce) {
              let data = JSON.parse(xhr.responseText);
              //means data set
              if(data && data.status && data.data){
                value['cmi.suspend_data'] = data.data;
                localStorage.setItem(skey,value);
                resolve();
              }else{
                localStorage.removeItem(skey);
                resolve();
              }
              
          }
          else if (xhr.status !== 200) {
              console.log('Something went wrong.Request failed.' + xhr.status);
              resolve();
          }
          
      };
      xhr.send(encodeURI('action=save_scorm_data&token='+window.scorm_wplms_data.token+'&security=' + nonce+'&key='+skey+'&data='+value+'&module_id='+window.scorm_wplms_data.module_id+'&course_id='+window.scorm_wplms_data.course_id+'&type='+window.scorm_wplms_data.type));
    }else{
      resolve();
    }
  }); 
};

fetchWPLMSSCORMData().then(function(){
  setTimeout(function(){
    load_scorm_lms_api();
  },500);
  window.addEventListener("load",function(event) {
    load_scorm_lms_api();
  });
});  




function isEmpty(obj){
    if (obj == null) return true;
    if(typeof obj == 'number' && obj != 0) return false;
    if (Array.isArray(obj) || typeof obj === 'string' || obj instanceof String) return obj.length === 0;
    for (var key in obj) if (obj.hasOwnProperty(key)) return false;
    return true;
}


function wplms_send_xhr(type,headers,data,url){
  return new Promise(function(resolve, reject) {
    if(!isEmpty(window.scorm_wplms_data)){
      var nonce = window.scorm_wplms_data.security_nonce,
      xhr = new XMLHttpRequest();

      xhr.open(type+'?nocache', url);
      if(headers){
        for (var key in headers) {
            if (headers.hasOwnProperty(key)) {
                xhr.setRequestHeader(key, headers[key]);
            }
        }
      }
      xhr.onload = function() {
          if (xhr.status === 200 && xhr.responseText !== nonce) {
              let resp = JSON.parse(xhr.responseText);
              //means data set
              resolve(resp);
              
          }
          else if (xhr.status !== 200) {
              console.log('Something went wrong.Request failed.' + xhr.status);
              resolve();
          }
      };
      xhr.send(encodeURI(data));
    }else{
      resolve();
    }
  });
}
});