· 5 years ago · May 23, 2020, 04:40 AM
1(function(){"use strict";var XModule={};XModule.Descriptor=function(){var Descriptor=function(element){this.element=element;this.update=_.bind(this.update,this)};Descriptor.prototype.onUpdate=function(callback){if(!this.callbacks){this.callbacks=[]}this.callbacks.push(callback)};Descriptor.prototype.update=function(){var data,callbacks,i,length;data=this.save();callbacks=this.callbacks;length=callbacks.length;$.each(callbacks,function(index,callback){callback(data)})};Descriptor.prototype.save=function(){return{}};return Descriptor}();this.XBlockToXModuleShim=function(runtime,element,initArgs){var moduleType,module;if(initArgs){moduleType=initArgs["xmodule-type"]}if(!moduleType){moduleType=$(element).data("type")}if(moduleType==="None"){return}try{module=new window[moduleType](element);if($(element).hasClass("xmodule_edit")){$(document).trigger("XModule.loaded.edit",[element,module])}if($(element).hasClass("xmodule_display")){$(document).trigger("XModule.loaded.display",[element,module])}return module}catch(error){console.error("Unable to load "+moduleType+": "+error.message)}};this.XModule=XModule}).call(this);(function(){"use strict";this.JavascriptLoader=function(){function JavascriptLoader(){}JavascriptLoader.executeModuleScripts=function(el,callback){var callbackCalled,completed,completionHandlerGenerator,loaded,placeholders;if(!callback){callback=null}placeholders=el.find(".script_placeholder");if(placeholders.length===0){if(callback!==null){callback()}return[]}completed=function(){var i,ref,results;results=[];for(i=1,ref=placeholders.length;ref>=1?i<=ref:i>=ref;ref>=1?++i:--i){results.push(false)}return results}();callbackCalled=false;completionHandlerGenerator=function(index){return function(){var allComplete,flag,i,len;allComplete=true;completed[index]=true;for(i=0,len=completed.length;i<len;i++){flag=completed[i];if(!flag){allComplete=false;break}}if(allComplete&&!callbackCalled){callbackCalled=true;if(callback!==null){return callback()}}return undefined}};loaded={};return placeholders.each(function(index,placeholder){var s,src;src=$(placeholder).attr("data-src");if(!(src in loaded)){loaded[src]=true;s=document.createElement("script");s.setAttribute("src",src);s.setAttribute("type","text/javascript");s.onload=completionHandlerGenerator(index);$("head")[0].appendChild(s)}else{completionHandlerGenerator(index)()}return $(placeholder).remove()})};return JavascriptLoader}()}).call(this);(function(){"use strict";this.LTI=function(element){var dataAttrs=$(element).find(".lti").data(),askToSendUsername=dataAttrs.askToSendUsername==="True",askToSendEmail=dataAttrs.askToSendEmail==="True";$(element).on("click",".link_lti_new_window",function(){if(askToSendUsername&&askToSendEmail){return confirm(gettext("Click OK to have your username and e-mail address sent to a 3rd party application.\n\nClick Cancel to return to this page without sending your information."))}else if(askToSendUsername){return confirm(gettext("Click OK to have your username sent to a 3rd party application.\n\nClick Cancel to return to this page without sending your information."))}else if(askToSendEmail){return confirm(gettext("Click OK to have your e-mail address sent to a 3rd party application.\n\nClick Cancel to return to this page without sending your information."))}else{return true}})}}).call(this);(function(){this.Conditional=function(){function Conditional(element,callerElId){var dependencies;this.el=$(element).find(".conditional-wrapper");this.callerElId=callerElId;if(callerElId!==void 0){dependencies=this.el.data("depends");if(typeof dependencies==="string"&&dependencies.length>0&&dependencies.indexOf(callerElId)===-1){return}}this.url=this.el.data("url");if(this.url){this.render(element)}}Conditional.prototype.render=function(element){var _this=this;return $.postWithPrefix(""+this.url+"/conditional_get",function(response){var i,parentEl,parentId,_i,_len,_ref;_this.el.html("");_ref=response.html;for(_i=0,_len=_ref.length;_i<_len;_i++){i=_ref[_i];_this.el.append(i)}parentEl=$(element).parent();parentId=parentEl.attr("id");if(response.message===false){if(parentEl.hasClass("vert")){parentEl.hide()}else{$(element).hide()}}else{if(parentEl.hasClass("vert")){parentEl.show()}else{$(element).show()}}return XBlock.initializeBlocks(_this.el)})};return Conditional}()}).call(this);(function(undefined){"use strict";this.Time={format:format,formatFull:formatFull,convert:convert};return;function format(time,formatFull){var hours,minutes,seconds;if(!_.isFinite(time)||time<0){time=0}seconds=Math.floor(time);minutes=Math.floor(seconds/60);hours=Math.floor(minutes/60);seconds=seconds%60;minutes=minutes%60;if(formatFull){return""+_pad(hours)+":"+_pad(minutes)+":"+_pad(seconds%60)}else if(hours){return""+hours+":"+_pad(minutes)+":"+_pad(seconds%60)}else{return""+minutes+":"+_pad(seconds%60)}}function formatFull(time){return format(time,true)}function convert(time,oldSpeed,newSpeed){return(time*oldSpeed/newSpeed).toFixed(3)}function _pad(number){if(number<10){return"0"+number}else{return""+number}}}).call(this);(function(){this.HTMLModule=function(){function HTMLModule(element){this.element=element;this.el=$(this.element);JavascriptLoader.executeModuleScripts(this.el);Collapsible.setCollapsibles(this.el);if(typeof MathJax!=="undefined"&&MathJax!==null){MathJax.Hub.Queue(["Typeset",MathJax.Hub,this.el[0]])}if(typeof setupFullScreenModal!=="undefined"&&setupFullScreenModal!==null){setupFullScreenModal()}}HTMLModule.prototype.$=function(selector){return $(selector,this.el)};return HTMLModule}()}).call(this);(function(){"use strict";this.Sequence=function(){function Sequence(element){var self=this;this.removeBookmarkIconFromActiveNavItem=function(event){return Sequence.prototype.removeBookmarkIconFromActiveNavItem.apply(self,[event])};this.addBookmarkIconToActiveNavItem=function(event){return Sequence.prototype.addBookmarkIconToActiveNavItem.apply(self,[event])};this._change_sequential=function(direction,event){return Sequence.prototype._change_sequential.apply(self,[direction,event])};this.selectPrevious=function(event){return Sequence.prototype.selectPrevious.apply(self,[event])};this.selectNext=function(event){return Sequence.prototype.selectNext.apply(self,[event])};this.goto=function(event){return Sequence.prototype.goto.apply(self,[event])};this.toggleArrows=function(){return Sequence.prototype.toggleArrows.apply(self)};this.addToUpdatedProblems=function(problemId,newContentState,newState){return Sequence.prototype.addToUpdatedProblems.apply(self,[problemId,newContentState,newState])};this.hideTabTooltip=function(event){return Sequence.prototype.hideTabTooltip.apply(self,[event])};this.displayTabTooltip=function(event){return Sequence.prototype.displayTabTooltip.apply(self,[event])};this.arrowKeys={LEFT:37,UP:38,RIGHT:39,DOWN:40};this.updatedProblems={};this.requestToken=$(element).data("request-token");this.el=$(element).find(".sequence");this.path=$(".path");this.contents=this.$(".seq_contents");this.content_container=this.$("#seq_content");this.sr_container=this.$(".sr-is-focusable");this.num_contents=this.contents.length;this.id=this.el.data("id");this.ajaxUrl=this.el.data("ajax-url");this.nextUrl=this.el.data("next-url");this.prevUrl=this.el.data("prev-url");this.keydownHandler($(element).find("#sequence-list .tab"));this.base_page_title=($("title").data("base-title")||"").trim();this.bind();this.render(parseInt(this.el.data("position"),10))}Sequence.prototype.$=function(selector){return $(selector,this.el)};Sequence.prototype.bind=function(){this.$("#sequence-list .nav-item").click(this.goto);this.$("#sequence-list .nav-item").keypress(this.keyDownHandler);this.el.on("bookmark:add",this.addBookmarkIconToActiveNavItem);this.el.on("bookmark:remove",this.removeBookmarkIconFromActiveNavItem);this.$("#sequence-list .nav-item").on("focus mouseenter",this.displayTabTooltip);this.$("#sequence-list .nav-item").on("blur mouseleave",this.hideTabTooltip)};Sequence.prototype.previousNav=function(focused,index){var $navItemList,$sequenceList=$(focused).parent().parent();if(index===0){$navItemList=$sequenceList.find("li").last()}else{$navItemList=$sequenceList.find("li:eq("+index+")").prev()}$sequenceList.find(".tab").removeClass("visited").removeClass("focused");$navItemList.find(".tab").addClass("focused").focus()};Sequence.prototype.nextNav=function(focused,index,total){var $navItemList,$sequenceList=$(focused).parent().parent();if(index===total){$navItemList=$sequenceList.find("li").first()}else{$navItemList=$sequenceList.find("li:eq("+index+")").next()}$sequenceList.find(".tab").removeClass("visited").removeClass("focused");$navItemList.find(".tab").addClass("focused").focus()};Sequence.prototype.keydownHandler=function(element){var self=this;element.keydown(function(event){var key=event.keyCode,$focused=$(event.currentTarget),$sequenceList=$focused.parent().parent(),index=$sequenceList.find("li").index($focused.parent()),total=$sequenceList.find("li").size()-1;switch(key){case self.arrowKeys.LEFT:event.preventDefault();self.previousNav($focused,index);break;case self.arrowKeys.RIGHT:event.preventDefault();self.nextNav($focused,index,total);break}})};Sequence.prototype.displayTabTooltip=function(event){$(event.currentTarget).find(".sequence-tooltip").removeClass("sr")};Sequence.prototype.hideTabTooltip=function(event){$(event.currentTarget).find(".sequence-tooltip").addClass("sr")};Sequence.prototype.updatePageTitle=function(){var currentSectionTitle,positionLink=this.link_for(this.position);if(positionLink&&positionLink.data("page-title")){currentSectionTitle=positionLink.data("page-title")+" | "+this.base_page_title;if(currentSectionTitle!==document.title){document.title=currentSectionTitle}}};Sequence.prototype.hookUpContentStateChangeEvent=function(){var self=this;return $(".problems-wrapper").bind("contentChanged",function(event,problemId,newContentState,newState){return self.addToUpdatedProblems(problemId,newContentState,newState)})};Sequence.prototype.addToUpdatedProblems=function(problemId,newContentState,newState){if(!this.anyUpdatedProblems(this.position)){this.updatedProblems[this.position]={}}this.updatedProblems[this.position][problemId]=[newContentState,newState]};Sequence.prototype.anyUpdatedProblems=function(position){return typeof this.updatedProblems[position]!=="undefined"};Sequence.prototype.enableButton=function(buttonClass,buttonAction){this.$(buttonClass).removeClass("disabled").removeAttr("disabled").click(buttonAction)};Sequence.prototype.disableButton=function(buttonClass){this.$(buttonClass).addClass("disabled").attr("disabled",true)};Sequence.prototype.updateButtonState=function(buttonClass,buttonAction,isAtBoundary,boundaryUrl){if(isAtBoundary&&boundaryUrl==="None"){this.disableButton(buttonClass)}else{this.enableButton(buttonClass,buttonAction)}};Sequence.prototype.toggleArrows=function(){var isFirstTab,isLastTab,nextButtonClass,previousButtonClass;this.$(".sequence-nav-button").unbind("click");isFirstTab=this.position===1;previousButtonClass=".sequence-nav-button.button-previous";this.updateButtonState(previousButtonClass,this.selectPrevious,isFirstTab,this.prevUrl);isLastTab=this.position>=this.contents.length;nextButtonClass=".sequence-nav-button.button-next";this.updateButtonState(nextButtonClass,this.selectNext,isLastTab,this.nextUrl)};Sequence.prototype.render=function(newPosition){var bookmarked,currentTab,modxFullUrl,sequenceLinks,self=this;if(this.position!==newPosition){if(this.position){this.mark_visited(this.position);modxFullUrl=""+this.ajaxUrl+"/goto_position";$.postWithPrefix(modxFullUrl,{position:newPosition})}this.el.trigger("sequence:change");this.mark_active(newPosition);currentTab=this.contents.eq(newPosition-1);bookmarked=this.el.find(".active .bookmark-icon").hasClass("bookmarked");this.content_container.html(currentTab.text()).attr("aria-labelledby",currentTab.attr("aria-labelledby")).data("bookmarked",bookmarked);if(this.anyUpdatedProblems(newPosition)){$.each(this.updatedProblems[newPosition],function(problemId,latestData){var latestContent,latestResponse;latestContent=latestData[0];latestResponse=latestData[1];self.content_container.find("[data-problem-id='"+problemId+"']").data("content",latestContent).data("problem-score",latestResponse.current_score).data("problem-total-possible",latestResponse.total_possible).data("attempts-used",latestResponse.attempts_used)})}XBlock.initializeBlocks(this.content_container,this.requestToken);window.update_schematics();this.position=newPosition;this.toggleArrows();this.hookUpContentStateChangeEvent();this.updatePageTitle();sequenceLinks=this.content_container.find("a.seqnav");sequenceLinks.click(this.goto);edx.HtmlUtils.setHtml(this.path,edx.HtmlUtils.template($("#sequence-breadcrumbs-tpl").text())({courseId:this.el.parent().data("course-id"),blockId:this.id,pathText:this.el.find(".nav-item.active").data("path"),unifiedCourseView:this.path.data("unified-course-view")}));this.sr_container.focus();this.el.trigger("sequence:change_finished")}};Sequence.prototype.goto=function(event){var alertTemplate,alertText,isBottomNav,newPosition,widgetPlacement;event.preventDefault();if($(event.currentTarget).hasClass("seqnav")){newPosition=$(event.currentTarget).attr("href")}else{newPosition=$(event.currentTarget).data("element")}if(newPosition>=1&&newPosition<=this.num_contents){isBottomNav=$(event.target).closest('nav[class="sequence-bottom"]').length>0;if(isBottomNav){widgetPlacement="bottom"}else{widgetPlacement="top"}Logger.log("edx.ui.lms.sequence.tab_selected",{current_tab:this.position,target_tab:newPosition,tab_count:this.num_contents,id:this.id,widget_placement:widgetPlacement});if(window.queuePollerID){window.clearTimeout(window.queuePollerID);delete window.queuePollerID}this.render(newPosition)}else{alertTemplate=gettext("Sequence error! Cannot navigate to %(tab_name)s in the current SequenceModule. Please contact the course staff.");alertText=interpolate(alertTemplate,{tab_name:newPosition},true);alert(alertText)}};Sequence.prototype.selectNext=function(event){this._change_sequential("next",event)};Sequence.prototype.selectPrevious=function(event){this._change_sequential("previous",event)};Sequence.prototype._change_sequential=function(direction,event){var analyticsEventName,isBottomNav,newPosition,offset,targetUrl,widgetPlacement;if(direction!=="previous"&&direction!=="next"){return}event.preventDefault();analyticsEventName="edx.ui.lms.sequence."+direction+"_selected";isBottomNav=$(event.target).closest('nav[class="sequence-bottom"]').length>0;if(isBottomNav){widgetPlacement="bottom"}else{widgetPlacement="top"}if(direction==="next"&&this.position>=this.contents.length){targetUrl=this.nextUrl}else if(direction==="previous"&&this.position===1){targetUrl=this.prevUrl}Logger.log(analyticsEventName,{id:this.id,current_tab:this.position,tab_count:this.num_contents,widget_placement:widgetPlacement}).always(function(){if(targetUrl){window.location.href=targetUrl}});if(!targetUrl){if(isBottomNav){$.scrollTo(0,150)}offset={next:1,previous:-1};newPosition=this.position+offset[direction];this.render(newPosition)}};Sequence.prototype.link_for=function(position){return this.$("#sequence-list .nav-item[data-element="+position+"]")};Sequence.prototype.mark_visited=function(position){var element=this.link_for(position);element.attr({tabindex:"-1","aria-selected":"false","aria-expanded":"false"}).removeClass("inactive").removeClass("active").removeClass("focused").addClass("visited")};Sequence.prototype.mark_active=function(position){var element=this.link_for(position);element.attr({tabindex:"0","aria-selected":"true","aria-expanded":"true"}).removeClass("inactive").removeClass("visited").removeClass("focused").addClass("active");this.$(".sequence-list-wrapper").focus()};Sequence.prototype.addBookmarkIconToActiveNavItem=function(event){event.preventDefault();this.el.find(".nav-item.active .bookmark-icon").removeClass("is-hidden").addClass("bookmarked");this.el.find(".nav-item.active .bookmark-icon-sr").text(gettext("Bookmarked"))};Sequence.prototype.removeBookmarkIconFromActiveNavItem=function(event){event.preventDefault();this.el.find(".nav-item.active .bookmark-icon").removeClass("bookmarked").addClass("is-hidden");this.el.find(".nav-item.active .bookmark-icon-sr").text("")};return Sequence}()}).call(this);window.Poll=function(el){RequireJS.require(["PollMain"],function(PollMain){new PollMain(el)})};(function(){var _this=this;this.Annotatable=function(){Annotatable.prototype._debug=false;Annotatable.prototype.wrapperSelector=".annotatable-wrapper";Annotatable.prototype.toggleAnnotationsSelector=".annotatable-toggle-annotations";Annotatable.prototype.toggleInstructionsSelector=".annotatable-toggle-instructions";Annotatable.prototype.instructionsSelector=".annotatable-instructions";Annotatable.prototype.sectionSelector=".annotatable-section";Annotatable.prototype.spanSelector=".annotatable-span";Annotatable.prototype.replySelector=".annotatable-reply";Annotatable.prototype.problemXModuleSelector=".xmodule_CapaModule";Annotatable.prototype.problemSelector="div.problem";Annotatable.prototype.problemInputSelector="div.problem .annotation-input";Annotatable.prototype.problemReturnSelector="div.problem .annotation-return";function Annotatable(el){var _this=this;this.onMoveTip=function(event,api,position){return Annotatable.prototype.onMoveTip.apply(_this,arguments)};this.onShowTip=function(event,api){return Annotatable.prototype.onShowTip.apply(_this,arguments)};this.onClickReturn=function(e){return Annotatable.prototype.onClickReturn.apply(_this,arguments)};this.onClickReply=function(e){return Annotatable.prototype.onClickReply.apply(_this,arguments)};this.onClickToggleInstructions=function(e){return Annotatable.prototype.onClickToggleInstructions.apply(_this,arguments)};this.onClickToggleAnnotations=function(e){return Annotatable.prototype.onClickToggleAnnotations.apply(_this,arguments)};if(this._debug){console.log("loaded Annotatable")}this.el=el;this.$el=$(el);this.init()}Annotatable.prototype.$=function(selector){return $(selector,this.el)};Annotatable.prototype.init=function(){this.initEvents();return this.initTips()};Annotatable.prototype.initEvents=function(){var _ref;_ref=[false,false],this.annotationsHidden=_ref[0],this.instructionsHidden=_ref[1];this.$(this.toggleAnnotationsSelector).bind("click",this.onClickToggleAnnotations);this.$(this.toggleInstructionsSelector).bind("click",this.onClickToggleInstructions);this.$el.on("click",this.replySelector,this.onClickReply);return $(document).on("click",this.problemReturnSelector,this.onClickReturn)};Annotatable.prototype.initTips=function(){var _this=this;return this.$(this.spanSelector).each(function(index,el){return $(el).qtip(_this.getSpanTipOptions(el))})};Annotatable.prototype.getSpanTipOptions=function(el){return{content:{title:{text:this.makeTipTitle(el)},text:this.makeTipContent(el)},position:{my:"bottom center",at:"top center",target:$(el),container:this.$(this.wrapperSelector),adjust:{y:-5}},show:{event:"click mouseenter",solo:true},hide:{event:"click mouseleave",delay:500,fixed:true},style:{classes:"ui-tooltip-annotatable"},events:{show:this.onShowTip,move:this.onMoveTip}}};Annotatable.prototype.onClickToggleAnnotations=function(e){return this.toggleAnnotations()};Annotatable.prototype.onClickToggleInstructions=function(e){return this.toggleInstructions()};Annotatable.prototype.onClickReply=function(e){return this.replyTo(e.currentTarget)};Annotatable.prototype.onClickReturn=function(e){return this.returnFrom(e.currentTarget)};Annotatable.prototype.onShowTip=function(event,api){if(this.annotationsHidden){return event.preventDefault()}};Annotatable.prototype.onMoveTip=function(event,api,position){var adjust_y,container,container_offset,focus_rect,is_non_overlapping,offset_left,offset_top,rect_center,rect_top,rects,target,tip,tip_height,tip_left,tip_top,tip_width,win_width,_ref,_ref1,_ref2;tip=api.elements.tooltip;adjust_y=((_ref=api.options.position)!=null?(_ref1=_ref.adjust)!=null?_ref1.y:void 0:void 0)||0;container=((_ref2=api.options.position)!=null?_ref2.container:void 0)||$("body");target=api.elements.target;rects=$(target).get(0).getClientRects();is_non_overlapping=(rects!=null?rects.length:void 0)===2&&rects[0].left>rects[1].right;if(is_non_overlapping){focus_rect=rects[0].width>rects[1].width?rects[0]:rects[1]}else{focus_rect=rects[0]}rect_center=focus_rect.left+focus_rect.width/2;rect_top=focus_rect.top;tip_width=$(tip).width();tip_height=$(tip).height();container_offset=$(container).offset();offset_left=-container_offset.left;offset_top=$(document).scrollTop()-container_offset.top;tip_left=offset_left+rect_center-tip_width/2;tip_top=offset_top+rect_top-tip_height+adjust_y;win_width=$(window).width();if(tip_left<offset_left){tip_left=offset_left}else if(tip_left+tip_width>win_width+offset_left){tip_left=win_width+offset_left-tip_width}return $.extend(position,{left:tip_left,top:tip_top})};Annotatable.prototype.getSpanForProblemReturn=function(el){var problem_id;problem_id=$(this.problemReturnSelector).index(el);return this.$(this.spanSelector).filter("[data-problem-id='"+problem_id+"']")};Annotatable.prototype.getProblem=function(el){var problem_id;problem_id=this.getProblemId(el);return $(this.problemInputSelector).eq(problem_id)};Annotatable.prototype.getProblemId=function(el){return $(el).data("problem-id")};Annotatable.prototype.toggleAnnotations=function(){var hide;hide=this.annotationsHidden=!this.annotationsHidden;this.toggleAnnotationButtonText(hide);this.toggleSpans(hide);return this.toggleTips(hide)};Annotatable.prototype.toggleTips=function(hide){var visible;visible=this.findVisibleTips();return this.hideTips(visible)};Annotatable.prototype.toggleAnnotationButtonText=function(hide){var buttonText;if(hide){buttonText=gettext("Show Annotations")}else{buttonText=gettext("Hide Annotations")}return this.$(this.toggleAnnotationsSelector).text(buttonText)};Annotatable.prototype.toggleInstructions=function(){var hide;hide=this.instructionsHidden=!this.instructionsHidden;this.toggleInstructionsButton(hide);return this.toggleInstructionsText(hide)};Annotatable.prototype.toggleInstructionsButton=function(hide){var cls,txt;if(hide){txt=gettext("Expand Instructions")}else{txt=gettext("Collapse Instructions")}cls=hide?["expanded","collapsed"]:["collapsed","expanded"];return this.$(this.toggleInstructionsSelector).text(txt).removeClass(cls[0]).addClass(cls[1])};Annotatable.prototype.toggleInstructionsText=function(hide){var slideMethod;slideMethod=hide?"slideUp":"slideDown";return this.$(this.instructionsSelector)[slideMethod]()};Annotatable.prototype.toggleSpans=function(hide){return this.$(this.spanSelector).toggleClass("hide",hide,250)};Annotatable.prototype.replyTo=function(buttonEl){var el,offset;offset=-20;el=this.getProblem(buttonEl);if(el.length>0){return this.scrollTo(el,this.afterScrollToProblem,offset)}else{if(this._debug){return console.log("problem not found. event: ",e)}}};Annotatable.prototype.returnFrom=function(buttonEl){var el,offset;offset=-200;el=this.getSpanForProblemReturn(buttonEl);if(el.length>0){return this.scrollTo(el,this.afterScrollToSpan,offset)}else{if(this._debug){return console.log("span not found. event:",e)}}};Annotatable.prototype.scrollTo=function(el,after,offset){var _this=this;if(offset==null){offset=-20}if($(el).length>0){return $("html,body").scrollTo(el,{duration:500,onAfter:this._once(function(){return after!=null?after.call(_this,el):void 0}),offset:offset})}};Annotatable.prototype.afterScrollToProblem=function(problem_el){return problem_el.effect("highlight",{},500)};Annotatable.prototype.afterScrollToSpan=function(span_el){return span_el.addClass("selected",400,"swing",function(){return span_el.removeClass("selected",400,"swing")})};Annotatable.prototype.makeTipContent=function(el){var _this=this;return function(api){var comment,problem_id,reply,text;text=$(el).data("comment-body");comment=_this.createComment(text);problem_id=_this.getProblemId(el);reply=_this.createReplyLink(problem_id);return $(comment).add(reply)}};Annotatable.prototype.makeTipTitle=function(el){var _this=this;return function(api){var title;title=$(el).data("comment-title");if(title){return title}else{return gettext("Commentary")}}};Annotatable.prototype.createComment=function(text){return $('<div class="annotatable-comment">'+text+"</div>")};Annotatable.prototype.createReplyLink=function(problem_id){var linktxt;linktxt=gettext("Reply to Annotation");return $('<a class="annotatable-reply" href="javascript:void(0);" data-problem-id="'+problem_id+'">'+linktxt+"</a>")};Annotatable.prototype.findVisibleTips=function(){var visible;visible=[];this.$(this.spanSelector).each(function(index,el){var api,tip;api=$(el).qtip("api");tip=$(api!=null?api.elements.tooltip:void 0);if(tip.is(":visible")){return visible.push(el)}});return visible};Annotatable.prototype.hideTips=function(elements){return $(elements).qtip("hide")};Annotatable.prototype._once=function(fn){var done,_this=this;done=false;return function(){if(!done){fn.call(_this)}return done=true}};return Annotatable}()}).call(this);(function(define){"use strict";define("video/00_component.js",[],function(){var inherit=Object.create||function(){var F=function(){};return function(o){if(arguments.length>1){throw Error("Second argument not supported")}if(_.isNull(o)||_.isUndefined(o)){throw Error("Cannot set a null [[Prototype]]")}if(!_.isObject(o)){throw TypeError("Argument must be an object")}F.prototype=o;return new F}}();var Component=function(){if($.isFunction(this.initialize)){return this.initialize.apply(this,arguments)}};Component.extend=function(protoProps,staticProps){var Parent=this,Child=function(){if($.isFunction(this.initialize)){return this.initialize.apply(this,arguments)}};Child.prototype=inherit(Parent.prototype);Child.constructor=Parent;Child.__super__=Parent.prototype;if(protoProps){$.extend(Child.prototype,protoProps)}$.extend(Child,Parent,staticProps);return Child};return Component})})(RequireJS.define);(function(){"use strict";var indexOfHelper=[].indexOf||function(item){var i,len;for(i=0,len=this.length;i<len;i++){if(i in this&&this[i]===item){return i}}return-1};this.Problem=function(){function Problem(element){var that=this;this.hint_button=function(){return Problem.prototype.hint_button.apply(that,arguments)};this.enableSubmitButtonAfterTimeout=function(){return Problem.prototype.enableSubmitButtonAfterTimeout.apply(that,arguments)};this.enableSubmitButtonAfterResponse=function(){return Problem.prototype.enableSubmitButtonAfterResponse.apply(that,arguments)};this.enableSubmitButton=function(enable,changeText){if(changeText===null||changeText===undefined){changeText=true}return Problem.prototype.enableSubmitButton.apply(that,arguments)};this.disableAllButtonsWhileRunning=function(operationCallback,isFromCheckOperation){return Problem.prototype.disableAllButtonsWhileRunning.apply(that,arguments)};this.submitAnswersAndSubmitButton=function(bind){if(bind===null||bind===undefined){bind=false}return Problem.prototype.submitAnswersAndSubmitButton.apply(that,arguments)};this.refreshAnswers=function(){return Problem.prototype.refreshAnswers.apply(that,arguments)};this.updateMathML=function(jax,el){return Problem.prototype.updateMathML.apply(that,arguments)};this.refreshMath=function(event,el){return Problem.prototype.refreshMath.apply(that,arguments)};this.save_internal=function(){return Problem.prototype.save_internal.apply(that,arguments)};this.save=function(){return Problem.prototype.save.apply(that,arguments)};this.gentle_alert=function(msg){return Problem.prototype.gentle_alert.apply(that,arguments)};this.clear_all_notifications=function(){return Problem.prototype.clear_all_notifications.apply(that,arguments)};this.show=function(){return Problem.prototype.show.apply(that,arguments)};this.reset_internal=function(){return Problem.prototype.reset_internal.apply(that,arguments)};this.reset=function(){return Problem.prototype.reset.apply(that,arguments)};this.get_sr_status=function(contents){return Problem.prototype.get_sr_status.apply(that,arguments)};this.submit_internal=function(){return Problem.prototype.submit_internal.apply(that,arguments)};this.submit=function(){return Problem.prototype.submit.apply(that,arguments)};this.submit_fd=function(){return Problem.prototype.submit_fd.apply(that,arguments)};this.focus_on_save_notification=function(){return Problem.prototype.focus_on_save_notification.apply(that,arguments)};this.focus_on_hint_notification=function(){return Problem.prototype.focus_on_hint_notification.apply(that,arguments)};this.focus_on_submit_notification=function(){return Problem.prototype.focus_on_submit_notification.apply(that,arguments)};this.focus_on_notification=function(type){return Problem.prototype.focus_on_notification.apply(that,arguments)};this.scroll_to_problem_meta=function(){return Problem.prototype.scroll_to_problem_meta.apply(that,arguments)};this.submit_save_waitfor=function(callback){return Problem.prototype.submit_save_waitfor.apply(that,arguments)};this.setupInputTypes=function(){return Problem.prototype.setupInputTypes.apply(that,arguments)};this.poll=function(prevTimeout,focusCallback){return Problem.prototype.poll.apply(that,arguments)};this.queueing=function(focusCallback){return Problem.prototype.queueing.apply(that,arguments)};this.forceUpdate=function(response){return Problem.prototype.forceUpdate.apply(that,arguments)};this.updateProgress=function(response){return Problem.prototype.updateProgress.apply(that,arguments)};this.renderProgressState=function(){return Problem.prototype.renderProgressState.apply(that,arguments)};this.bind=function(){return Problem.prototype.bind.apply(that,arguments)};this.el=$(element).find(".problems-wrapper");this.id=this.el.data("problem-id");this.element_id=this.el.attr("id");this.url=this.el.data("url");this.content=this.el.data("content");this.has_timed_out=false;this.has_response=false;this.render(this.content)}Problem.prototype.$=function(selector){return $(selector,this.el)};Problem.prototype.bind=function(){var problemPrefix,that=this;if(typeof MathJax!=="undefined"&&MathJax!==null){this.el.find(".problem > div").each(function(index,element){return MathJax.Hub.Queue(["Typeset",MathJax.Hub,element])})}window.update_schematics();problemPrefix=this.element_id.replace(/problem_/,"");this.inputs=this.$('[id^="input_'+problemPrefix+'_"]');this.$("div.action button").click(this.refreshAnswers);this.reviewButton=this.$(".notification-btn.review-btn");this.reviewButton.click(this.scroll_to_problem_meta);this.submitButton=this.$(".action .submit");this.submitButtonLabel=this.$(".action .submit .submit-label");this.submitButtonSubmitText=this.submitButtonLabel.text();this.submitButtonSubmittingText=this.submitButton.data("submitting");this.submitButton.click(this.submit_fd);this.hintButton=this.$(".action .hint-button");this.hintButton.click(this.hint_button);this.resetButton=this.$(".action .reset");this.resetButton.click(this.reset);this.showButton=this.$(".action .show");this.showButton.click(this.show);this.saveButton=this.$(".action .save");this.saveNotification=this.$(".notification-save");this.showAnswerNotification=this.$(".notification-show-answer");this.saveButton.click(this.save);this.gentleAlertNotification=this.$(".notification-gentle-alert");this.submitNotification=this.$(".notification-submit");this.$(".clarification").focus(function(ev){var icon;icon=$(ev.target).children("i");return window.globalTooltipManager.openTooltip(icon)});this.$(".clarification").blur(function(){return window.globalTooltipManager.hide()});this.$(".review-btn").focus(function(ev){return $(ev.target).removeClass("sr")});this.$(".review-btn").blur(function(ev){return $(ev.target).addClass("sr")});this.bindResetCorrectness();if(this.submitButton.length){this.submitAnswersAndSubmitButton(true)}Collapsible.setCollapsibles(this.el);this.$("input.math").keyup(this.refreshMath);
2if(typeof MathJax!=="undefined"&&MathJax!==null){this.$("input.math").each(function(index,element){return MathJax.Hub.Queue([that.refreshMath,null,element])})}};Problem.prototype.renderProgressState=function(){var graded,progress,progressTemplate,curScore,totalScore,attemptsUsed;curScore=this.el.data("problem-score");totalScore=this.el.data("problem-total-possible");attemptsUsed=this.el.data("attempts-used");graded=this.el.data("graded");if(graded==="True"&&totalScore!==0){graded=true}else{graded=false}if(curScore===undefined||totalScore===undefined){progressTemplate=""}else if(curScore===null||curScore==="None"){if(graded){progressTemplate=ngettext("%(num_points)s point possible (graded, results hidden)","%(num_points)s points possible (graded, results hidden)",totalScore)}else{progressTemplate=ngettext("%(num_points)s point possible (ungraded, results hidden)","%(num_points)s points possible (ungraded, results hidden)",totalScore)}}else if(attemptsUsed===0||totalScore===0){if(graded){progressTemplate=ngettext("%(num_points)s point possible (graded)","%(num_points)s points possible (graded)",totalScore)}else{progressTemplate=ngettext("%(num_points)s point possible (ungraded)","%(num_points)s points possible (ungraded)",totalScore)}}else{if(graded){progressTemplate=ngettext("%(earned)s/%(possible)s point (graded)","%(earned)s/%(possible)s points (graded)",totalScore)}else{progressTemplate=ngettext("%(earned)s/%(possible)s point (ungraded)","%(earned)s/%(possible)s points (ungraded)",totalScore)}}progress=interpolate(progressTemplate,{earned:curScore,num_points:totalScore,possible:totalScore},true);return this.$(".problem-progress").text(progress)};Problem.prototype.updateProgress=function(response){if(response.progress_changed){this.el.data("problem-score",response.current_score);this.el.data("problem-total-possible",response.total_possible);this.el.data("attempts-used",response.attempts_used);this.el.trigger("progressChanged")}return this.renderProgressState()};Problem.prototype.forceUpdate=function(response){this.el.data("problem-score",response.current_score);this.el.data("problem-total-possible",response.total_possible);this.el.data("attempts-used",response.attempts_used);this.el.trigger("progressChanged");return this.renderProgressState()};Problem.prototype.queueing=function(focusCallback){var that=this;this.queued_items=this.$(".xqueue");this.num_queued_items=this.queued_items.length;if(this.num_queued_items>0){if(window.queuePollerID){window.clearTimeout(window.queuePollerID)}window.queuePollerID=window.setTimeout(function(){return that.poll(1e3,focusCallback)},1e3)}};Problem.prototype.poll=function(previousTimeout,focusCallback){var that=this;return $.postWithPrefix(""+this.url+"/problem_get",function(response){var newTimeout;that.new_queued_items=$(response.html).find(".xqueue");if(that.new_queued_items.length!==that.num_queued_items){edx.HtmlUtils.setHtml(that.el,edx.HtmlUtils.HTML(response.html)).promise().done(function(){return typeof focusCallback==="function"?focusCallback():void 0});JavascriptLoader.executeModuleScripts(that.el,function(){that.setupInputTypes();that.bind()})}that.num_queued_items=that.new_queued_items.length;if(that.num_queued_items===0){that.forceUpdate(response);delete window.queuePollerID}else{newTimeout=previousTimeout*2;if(newTimeout>=6e4){delete window.queuePollerID;that.gentle_alert(gettext("The grading process is still running. Refresh the page to see updates."))}else{window.queuePollerID=window.setTimeout(function(){return that.poll(newTimeout,focusCallback)},newTimeout)}}})};Problem.inputAjax=function(url,inputId,dispatch,data,callback){data.dispatch=dispatch;data.input_id=inputId;return $.postWithPrefix(""+url+"/input_ajax",data,callback)};Problem.prototype.render=function(content,focusCallback){var that=this;if(content){this.el.html(content);return JavascriptLoader.executeModuleScripts(this.el,function(){that.setupInputTypes();that.bind();that.queueing(focusCallback);that.renderProgressState();return typeof focusCallback==="function"?focusCallback():void 0})}else{return $.postWithPrefix(""+this.url+"/problem_get",function(response){that.el.html(response.html);return JavascriptLoader.executeModuleScripts(that.el,function(){that.setupInputTypes();that.bind();that.queueing();return that.forceUpdate(response)})})}};Problem.prototype.setupInputTypes=function(){var that=this;this.inputtypeDisplays={};return this.el.find(".capa_inputtype").each(function(index,inputtype){var classes,cls,id,setupMethod,i,len,results;classes=$(inputtype).attr("class").split(" ");id=$(inputtype).attr("id");results=[];for(i=0,len=classes.length;i<len;i++){cls=classes[i];setupMethod=that.inputtypeSetupMethods[cls];if(setupMethod!=null){results.push(that.inputtypeDisplays[id]=setupMethod(inputtype))}else{results.push(void 0)}}return results})};Problem.prototype.submit_save_waitfor=function(callback){var flag,inp,i,len,ref,that=this;flag=false;ref=this.inputs;for(i=0,len=ref.length;i<len;i++){inp=ref[i];if($(inp).is("input[waitfor]")){try{$(inp).data("waitfor")(function(){that.refreshAnswers();return callback()})}catch(e){if(e.name==="Waitfor Exception"){alert(e.message)}else{alert(gettext("Could not grade your answer. The submission was aborted."))}throw e}flag=true}else{flag=false}}return flag};Problem.prototype.scroll_to_problem_meta=function(){var questionTitle;questionTitle=this.$(".problem-header");if(questionTitle.length>0){$("html, body").animate({scrollTop:questionTitle.offset().top},500);questionTitle.focus()}};Problem.prototype.focus_on_notification=function(type){var notification;notification=this.$(".notification-"+type);if(notification.length>0){notification.focus()}};Problem.prototype.focus_on_submit_notification=function(){this.focus_on_notification("submit")};Problem.prototype.focus_on_hint_notification=function(){this.focus_on_notification("hint")};Problem.prototype.focus_on_save_notification=function(){this.focus_on_notification("save")};Problem.prototype.submit_fd=function(){var abortSubmission,error,errorHtml,errors,fd,fileNotSelected,fileTooLarge,maxFileSize,requiredFilesNotSubmitted,settings,timeoutId,unallowedFileSubmitted,i,len,that=this;if(this.el.find("input:file").length===0){this.submit();return}this.enableSubmitButton(false);if(!window.FormData){alert(gettext("Submission aborted! Sorry, your browser does not support file uploads. If you can, please use Chrome or Safari which have been verified to support file uploads."));this.enableSubmitButton(true);return}timeoutId=this.enableSubmitButtonAfterTimeout();fd=new FormData;maxFileSize=4*1e3*1e3;fileTooLarge=false;fileNotSelected=false;requiredFilesNotSubmitted=false;unallowedFileSubmitted=false;errors=[];this.inputs.each(function(index,element){var allowedFiles,file,maxSize,requiredFiles,loopI,loopLen,ref;if(element.type==="file"){requiredFiles=$(element).data("required_files");allowedFiles=$(element).data("allowed_files");ref=element.files;for(loopI=0,loopLen=ref.length;loopI<loopLen;loopI++){file=ref[loopI];if(allowedFiles.length!==0&&indexOfHelper.call(allowedFiles,file.name)<0){unallowedFileSubmitted=true;errors.push(edx.StringUtils.interpolate(gettext("You submitted {filename}; only {allowedFiles} are allowed."),{filename:file.name,allowedFiles:allowedFiles}))}if(indexOfHelper.call(requiredFiles,file.name)>=0){requiredFiles.splice(requiredFiles.indexOf(file.name),1)}if(file.size>maxFileSize){fileTooLarge=true;maxSize=maxFileSize/(1e3*1e3);errors.push(edx.StringUtils.interpolate(gettext("Your file {filename} is too large (max size: {maxSize}MB)."),{filename:file.name,maxSize:maxSize}))}fd.append(element.id,file)}if(element.files.length===0){fileNotSelected=true;fd.append(element.id,"")}if(requiredFiles.length!==0){requiredFilesNotSubmitted=true;errors.push(edx.StringUtils.interpolate(gettext("You did not submit the required files: {requiredFiles}."),{requiredFiles:requiredFiles}))}}else{fd.append(element.id,element.value)}});if(fileNotSelected){errors.push(gettext("You did not select any files to submit."))}errorHtml="<ul>\n";for(i=0,len=errors.length;i<len;i++){error=errors[i];errorHtml+="<li>"+error+"</li>\n"}errorHtml+="</ul>";this.gentle_alert(errorHtml);abortSubmission=fileTooLarge||fileNotSelected||unallowedFileSubmitted||requiredFilesNotSubmitted;if(abortSubmission){window.clearTimeout(timeoutId);this.enableSubmitButton(true)}else{settings={type:"POST",data:fd,processData:false,contentType:false,complete:this.enableSubmitButtonAfterResponse,success:function(response){switch(response.success){case"submitted":case"incorrect":case"correct":that.render(response.contents);that.updateProgress(response);break;default:that.gentle_alert(response.success)}return Logger.log("problem_graded",[that.answers,response.contents],that.id)}};$.ajaxWithPrefix(""+this.url+"/problem_check",settings)}};Problem.prototype.submit=function(){if(!this.submit_save_waitfor(this.submit_internal)){this.disableAllButtonsWhileRunning(this.submit_internal,true)}};Problem.prototype.submit_internal=function(){var that=this;Logger.log("problem_check",this.answers);return $.postWithPrefix(""+this.url+"/problem_check",this.answers,function(response){switch(response.success){case"submitted":case"incorrect":case"correct":window.SR.readTexts(that.get_sr_status(response.contents));that.el.trigger("contentChanged",[that.id,response.contents,response]);that.render(response.contents,that.focus_on_submit_notification);that.updateProgress(response);break;default:that.saveNotification.hide();that.gentle_alert(response.success)}return Logger.log("problem_graded",[that.answers,response.contents],that.id)})};Problem.prototype.get_sr_status=function(contents){var addedStatus,ariaLabel,element,labeledStatus,parentSection,statusElement,template,i,len;statusElement=$(contents).find(".status");labeledStatus=[];for(i=0,len=statusElement.length;i<len;i++){element=statusElement[i];parentSection=$(element).closest(".wrapper-problem-response");addedStatus=false;if(parentSection){ariaLabel=parentSection.attr("aria-label");if(ariaLabel){template=gettext("{label}: {status}");labeledStatus.push(edx.StringUtils.interpolate(template,{label:ariaLabel,status:$(element).text()}));addedStatus=true}}if(!addedStatus){labeledStatus.push($(element).text())}}return labeledStatus};Problem.prototype.reset=function(){return this.disableAllButtonsWhileRunning(this.reset_internal,false)};Problem.prototype.reset_internal=function(){var that=this;Logger.log("problem_reset",this.answers);return $.postWithPrefix(""+this.url+"/problem_reset",{id:this.id},function(response){if(response.success){that.el.trigger("contentChanged",[that.id,response.html,response]);that.render(response.html,that.scroll_to_problem_meta);that.updateProgress(response);return window.SR.readText(gettext("This problem has been reset."))}else{return that.gentle_alert(response.msg)}})};Problem.prototype.show=function(){var that=this;Logger.log("problem_show",{problem:this.id});return $.postWithPrefix(""+this.url+"/problem_show",function(response){var answers;answers=response.answers;$.each(answers,function(key,value){var answer;if(!$.isArray(value)){answer=that.$("#answer_"+key+", #solution_"+key);edx.HtmlUtils.setHtml(answer,edx.HtmlUtils.HTML(value));Collapsible.setCollapsibles(answer);try{return $(value).find(".detailed-solution")}catch(e){return{}}}});that.el.find(".capa_inputtype").each(function(index,inputtype){var classes,cls,display,showMethod,i,len,results;classes=$(inputtype).attr("class").split(" ");results=[];for(i=0,len=classes.length;i<len;i++){cls=classes[i];display=that.inputtypeDisplays[$(inputtype).attr("id")];showMethod=that.inputtypeShowAnswerMethods[cls];if(showMethod!=null){results.push(showMethod(inputtype,display,answers,response.correct_status_html))}else{results.push(void 0)}}return results});if(typeof MathJax!=="undefined"&&MathJax!==null){that.el.find(".problem > div").each(function(index,element){return MathJax.Hub.Queue(["Typeset",MathJax.Hub,element])})}that.el.find(".show").attr("disabled","disabled");that.updateProgress(response);that.clear_all_notifications();that.showAnswerNotification.show();that.focus_on_notification("show-answer")})};Problem.prototype.clear_all_notifications=function(){this.submitNotification.remove();this.gentleAlertNotification.hide();this.saveNotification.hide();this.showAnswerNotification.hide()};Problem.prototype.gentle_alert=function(msg){edx.HtmlUtils.setHtml(this.el.find(".notification-gentle-alert .notification-message"),edx.HtmlUtils.HTML(msg));this.clear_all_notifications();this.gentleAlertNotification.show();this.gentleAlertNotification.focus()};Problem.prototype.save=function(){if(!this.submit_save_waitfor(this.save_internal)){this.disableAllButtonsWhileRunning(this.save_internal,false)}};Problem.prototype.save_internal=function(){var that=this;Logger.log("problem_save",this.answers);return $.postWithPrefix(""+this.url+"/problem_save",this.answers,function(response){var saveMessage;saveMessage=response.msg;if(response.success){that.el.trigger("contentChanged",[that.id,response.html,response]);edx.HtmlUtils.setHtml(that.el.find(".notification-save .notification-message"),edx.HtmlUtils.HTML(saveMessage));that.clear_all_notifications();that.el.find(".wrapper-problem-response .message").hide();that.saveNotification.show();that.focus_on_save_notification()}else{that.gentle_alert(saveMessage)}})};Problem.prototype.refreshMath=function(event,element){var elid,eqn,jax,mathjaxPreprocessor,preprocessorTag,target;if(!element){element=event.target}elid=element.id.replace(/^input_/,"");target="display_"+elid;preprocessorTag="inputtype_"+elid;mathjaxPreprocessor=this.inputtypeDisplays[preprocessorTag];if(typeof MathJax!=="undefined"&&MathJax!==null&&MathJax.Hub.getAllJax(target)[0]){jax=MathJax.Hub.getAllJax(target)[0];eqn=$(element).val();if(mathjaxPreprocessor){eqn=mathjaxPreprocessor(eqn)}MathJax.Hub.Queue(["Text",jax,eqn],[this.updateMathML,jax,element])}};Problem.prototype.updateMathML=function(jax,element){try{$("#"+element.id+"_dynamath").val(jax.root.toMathML(""))}catch(exception){if(!exception.restart){throw exception}if(typeof MathJax!=="undefined"&&MathJax!==null){MathJax.Callback.After([this.refreshMath,jax],exception.restart)}}};Problem.prototype.refreshAnswers=function(){this.$("input.schematic").each(function(index,element){return element.schematic.update_value()});this.$(".CodeMirror").each(function(index,element){if(element.CodeMirror.save){element.CodeMirror.save()}});this.answers=this.inputs.serialize()};Problem.prototype.submitAnswersAndSubmitButton=function(bind){var answered,atLeastOneTextInputFound,oneTextInputFilled,that=this;if(bind===null||bind===undefined){bind=false}answered=true;atLeastOneTextInputFound=false;oneTextInputFilled=false;this.el.find("input:text").each(function(i,textField){if($(textField).is(":visible")){atLeastOneTextInputFound=true;if($(textField).val()!==""){oneTextInputFilled=true}if(bind){$(textField).on("input",function(){that.saveNotification.hide();that.showAnswerNotification.hide();that.submitAnswersAndSubmitButton()})}}});if(atLeastOneTextInputFound&&!oneTextInputFilled){answered=false}this.el.find(".choicegroup").each(function(i,choicegroupBlock){var checked;checked=false;$(choicegroupBlock).find("input[type=checkbox], input[type=radio]").each(function(j,checkboxOrRadio){if($(checkboxOrRadio).is(":checked")){checked=true}if(bind){$(checkboxOrRadio).on("click",function(){that.saveNotification.hide();that.el.find(".show").removeAttr("disabled");that.showAnswerNotification.hide();that.submitAnswersAndSubmitButton()})}});if(!checked){answered=false}});this.el.find("select").each(function(i,selectField){var selectedOption=$(selectField).find("option:selected").text().trim();if(selectedOption==="Select an option"){answered=false}if(bind){$(selectField).on("change",function(){that.saveNotification.hide();that.showAnswerNotification.hide();that.submitAnswersAndSubmitButton()})}});if(answered){return this.enableSubmitButton(true)}else{return this.enableSubmitButton(false,false)}};Problem.prototype.bindResetCorrectness=function(){var $inputtypes,that=this;$inputtypes=this.el.find(".capa_inputtype").add(this.el.find(".inputtype"));return $inputtypes.each(function(index,inputtype){var bindMethod,classes,cls,i,len,results;classes=$(inputtype).attr("class").split(" ");results=[];for(i=0,len=classes.length;i<len;i++){cls=classes[i];bindMethod=that.bindResetCorrectnessByInputtype[cls];if(bindMethod!=null){results.push(bindMethod(inputtype))}else{results.push(void 0)}}return results})};Problem.prototype.bindResetCorrectnessByInputtype={formulaequationinput:function(element){return $(element).find("input").on("input",function(){var $p;$p=$(element).find("span.status");return $p.parent().removeAttr("class").addClass("unsubmitted")})},choicegroup:function(element){var $element,id;$element=$(element);id=$element.attr("id").match(/^inputtype_(.*)$/)[1];return $element.find("input").on("change",function(){var $status;$status=$("#status_"+id);if($status[0]){$status.removeAttr("class").addClass("status unanswered")}else{$("<span>",{class:"status unanswered",style:"display: inline-block;",id:"status_"+id})}$element.find("label").find("span.status.correct").remove();return $element.find("label").removeAttr("class")})},"option-input":function(element){var $select,id;$select=$(element).find("select");id=$select.attr("id").match(/^input_(.*)$/)[1];return $select.on("change",function(){return $("#status_"+id).removeAttr("class").addClass("unanswered").find(".sr").text(gettext("unsubmitted"))})},textline:function(element){return $(element).find("input").on("input",function(){var $p;$p=$(element).find("span.status");return $p.parent().removeClass("correct incorrect").addClass("unsubmitted")})}};Problem.prototype.inputtypeSetupMethods={"text-input-dynamath":function(element){var data,preprocessor,preprocessorClass,preprocessorClassName;data=$(element).find(".text-input-dynamath_data");preprocessorClassName=data.data("preprocessor");preprocessorClass=window[preprocessorClassName];if(preprocessorClass==null){return false}else{preprocessor=new preprocessorClass;return preprocessor.fn}},cminput:function(container){var CodeMirrorEditor,CodeMirrorTextArea,element,id,linenumbers,mode,spaces,tabsize;element=$(container).find("textarea");tabsize=element.data("tabsize");mode=element.data("mode");linenumbers=element.data("linenums");spaces=Array(parseInt(tabsize,10)+1).join(" ");CodeMirrorEditor=CodeMirror.fromTextArea(element[0],{lineNumbers:linenumbers,indentUnit:tabsize,tabSize:tabsize,mode:mode,matchBrackets:true,lineWrapping:true,indentWithTabs:false,smartIndent:false,extraKeys:{Esc:function(){$(".grader-status").focus();return false},Tab:function(cm){cm.replaceSelection(spaces,"end");return false}}});id=element.attr("id").replace(/^input_/,"");CodeMirrorTextArea=CodeMirrorEditor.getInputField();CodeMirrorTextArea.setAttribute("id","cm-textarea-"+id);CodeMirrorTextArea.setAttribute("aria-describedby","cm-editor-exit-message-"+id+" status_"+id);return CodeMirrorEditor}};Problem.prototype.inputtypeShowAnswerMethods={choicegroup:function(element,display,answers,correctStatusHtml){var answer,choice,inputId,i,len,results,$element,$inputLabel,$inputStatus;$element=$(element);inputId=$element.attr("id").replace(/inputtype_/,"");answer=answers[inputId];results=[];for(i=0,len=answer.length;i<len;i++){choice=answer[i];$inputLabel=$element.find("#input_"+inputId+"_"+choice).parent("label");$inputStatus=$inputLabel.find("#status_"+inputId);if($inputStatus.hasClass("unanswered")){$inputStatus.removeAttr("class").addClass("status correct");$inputLabel.addClass("choicegroup_correct")}else if(!$inputLabel.hasClass("choicegroup_correct")){edx.HtmlUtils.append($inputLabel,edx.HtmlUtils.HTML(correctStatusHtml));results.push($inputLabel.addClass("choicegroup_correct"))}}return results},choicetextgroup:function(element,display,answers){var answer,choice,inputId,i,len,results,$element;$element=$(element);inputId=$element.attr("id").replace(/inputtype_/,"");answer=answers[inputId];results=[];for(i=0,len=answer.length;i<len;i++){choice=answer[i];results.push($element.find("section#forinput"+choice).addClass("choicetextgroup_show_correct"))}return results},imageinput:function(element,display,answers){var canvas,container,id,types,context,$element;types={rectangle:function(ctx,coords){var rects,reg;reg=/^\(([0-9]+),([0-9]+)\)-\(([0-9]+),([0-9]+)\)$/;rects=coords.replace(/\s*/g,"").split(/;/);$.each(rects,function(index,rect){var abs,height,points,width;abs=Math.abs;points=reg.exec(rect);if(points){width=abs(points[3]-points[1]);height=abs(points[4]-points[2]);ctx.rect(points[1],points[2],width,height)}});ctx.stroke();return ctx.fill()},regions:function(ctx,coords){var parseCoords;parseCoords=function(coordinates){var reg;reg=JSON.parse(coordinates);if(typeof reg[0][0][0]==="undefined"){reg=[reg]}return reg};return $.each(parseCoords(coords),function(index,region){ctx.beginPath();$.each(region,function(idx,point){if(idx===0){return ctx.moveTo(point[0],point[1])}else{return ctx.lineTo(point[0],point[1])}});ctx.closePath();ctx.stroke();return ctx.fill()})}};$element=$(element);id=$element.attr("id").replace(/inputtype_/,"");container=$element.find("#answer_"+id);canvas=document.createElement("canvas");canvas.width=container.data("width");canvas.height=container.data("height");if(canvas.getContext){context=canvas.getContext("2d")}else{console.log("Canvas is not supported.")}context.fillStyle="rgba(255,255,255,.3)";context.strokeStyle="#FF0000";context.lineWidth="2";if(answers[id]){$.each(answers[id],function(key,value){if(types[key]!==null&&types[key]!==undefined&&value){types[key](context,value)}});container.html(canvas)}else{console.log("Answer is absent for image input with id="+id)}}};Problem.prototype.disableAllButtonsWhileRunning=function(operationCallback,isFromCheckOperation){var that=this;var allButtons=[this.resetButton,this.saveButton,this.showButton,this.hintButton,this.submitButton];var initiallyEnabledButtons=allButtons.filter(function(button){return!button.attr("disabled")});this.enableButtons(initiallyEnabledButtons,false,isFromCheckOperation);return operationCallback().always(function(){return that.enableButtons(initiallyEnabledButtons,true,isFromCheckOperation)})};Problem.prototype.enableButtons=function(buttons,enable,changeSubmitButtonText){var that=this;buttons.forEach(function(button){if(button.hasClass("submit")){that.enableSubmitButton(enable,changeSubmitButtonText)}else if(enable){button.removeAttr("disabled")}else{button.attr({disabled:"disabled"})}})};Problem.prototype.enableSubmitButton=function(enable,changeText){var submitCanBeEnabled;if(changeText===null||changeText===undefined){changeText=true}if(enable){submitCanBeEnabled=this.submitButton.data("should-enable-submit-button")==="True";if(submitCanBeEnabled){this.submitButton.removeAttr("disabled")}if(changeText){this.submitButtonLabel.text(this.submitButtonSubmitText)}}else{this.submitButton.attr({disabled:"disabled"});if(changeText){this.submitButtonLabel.text(this.submitButtonSubmittingText)}}};Problem.prototype.enableSubmitButtonAfterResponse=function(){this.has_response=true;if(!this.has_timed_out){return this.enableSubmitButton(false)}else{return this.enableSubmitButton(true)}};Problem.prototype.enableSubmitButtonAfterTimeout=function(){var enableSubmitButton,that=this;this.has_timed_out=false;this.has_response=false;enableSubmitButton=function(){that.has_timed_out=true;if(that.has_response){that.enableSubmitButton(true)}};return window.setTimeout(enableSubmitButton,750)};Problem.prototype.hint_button=function(){var hintContainer,hintIndex,nextIndex,that=this;hintContainer=this.$(".problem-hint");hintIndex=hintContainer.attr("hint_index");if(hintIndex===void 0){nextIndex=0}else{nextIndex=parseInt(hintIndex,10)+1}return $.postWithPrefix(""+this.url+"/hint_button",{hint_index:nextIndex,input_id:this.id},function(response){var hintMsgContainer;if(response.success){hintMsgContainer=that.$(".problem-hint .notification-message");hintContainer.attr("hint_index",response.hint_index);edx.HtmlUtils.setHtml(hintMsgContainer,edx.HtmlUtils.HTML(response.msg));MathJax.Hub.Queue(["Typeset",MathJax.Hub,hintContainer[0]]);if(response.should_enable_next_hint){that.hintButton.removeAttr("disabled")}else{that.hintButton.attr({disabled:"disabled"})}that.el.find(".notification-hint").show();that.focus_on_hint_notification()}else{that.gentle_alert(response.msg)}})};return Problem}.call(this)}).call(this);(function(undefined){"use strict";this.Collapsible={setCollapsibles:setCollapsibles,toggleFull:toggleFull,toggleHint:toggleHint};return;function setCollapsibles(el){var linkBottom,linkTop,short_custom;linkTop='<a href="#" class="full full-top">See full output</a>';linkBottom='<a href="#" class="full full-bottom">See full output</a>';el.find(".longform").hide();el.find(".shortform").append(linkTop,linkBottom);short_custom=el.find(".shortform-custom");short_custom.each(function(index,elt){var close_text,open_text;open_text=$(elt).data("open-text");close_text=$(elt).data("close-text");$(elt).append("<a href='#' class='full-custom'>"+open_text+"</a>");$(elt).find(".full-custom").click(function(event){Collapsible.toggleFull(event,open_text,close_text)})});el.find(".collapsible header + section").hide();el.find(".full").click(function(event){Collapsible.toggleFull(event,"See full output","Hide output")});el.find(".collapsible header a").click(Collapsible.toggleHint)}function toggleFull(event,open_text,close_text){var el,new_text,parent;event.preventDefault();parent=$(event.target).parent();parent.siblings().slideToggle();parent.parent().toggleClass("open");if($(event.target).text()===open_text){new_text=close_text}else{new_text=open_text}if($(event.target).hasClass("full")){el=parent.find(".full")}else{el=$(event.target)}el.text(new_text)}function toggleHint(event){event.preventDefault();$(event.target).parent().siblings().slideToggle();$(event.target).parent().parent().toggleClass("open")}}).call(this);var setupFullScreenModal=function(){$("a.modal-content").each(function(){var smallImageObject=$(this).children();var largeImageSRC=$(this).attr("href");if(smallImageObject.is("img")&&largeImageSRC){var data={smallHTML:$(this).html(),largeALT:smallImageObject.attr("alt"),largeSRC:largeImageSRC};var html=_.template($("#image-modal-tpl").text())(data);$(this).replaceWith(html)}});$(".wrapper-modal-image .image-wrapper img").each(function(){var draggie=new Draggabilly(this,{containment:true});draggie.disable();$(this).closest(".image-modal").data("draggie",draggie)});$(".wrapper-modal-image .image-link").click(function(){$(this).siblings(".image-modal").addClass("image-is-fit-to-screen");$("body").css("overflow","hidden")});var imageModalImageHover=false;$(".wrapper-modal-image .image-content img, .wrapper-modal-image .image-content .image-controls").hover(function(){imageModalImageHover=true},function(){imageModalImageHover=false});$(".modal-ui-icon").click(function(event){event.preventDefault()});function closeModal(imageModal){imageModal.removeClass("image-is-fit-to-screen").removeClass("image-is-zoomed");$(".wrapper-modal-image .image-content .image-controls .modal-ui-icon.action-zoom-in").removeClass("is-disabled").attr("aria-disabled",false);$(".wrapper-modal-image .image-content .image-controls .modal-ui-icon.action-zoom-out").addClass("is-disabled").attr("aria-disabled",true);var currentDraggie=imageModal.data("draggie");currentDraggie.disable();$("body").css("overflow","auto")}$(".wrapper-modal-image .image-modal").click(function(){if(!imageModalImageHover){closeModal($(this))}});$(".wrapper-modal-image .image-content .action-remove").click(function(){closeModal($(this).closest(".image-modal"))});$(".wrapper-modal-image .image-content .image-controls .modal-ui-icon").click(function(){if(!$(this).hasClass("is-disabled")){var mask=$(this).closest(".image-content");var imageModal=$(this).closest(".image-modal");var img=imageModal.find("img");var currentDraggie=imageModal.data("draggie");if($(this).hasClass("action-zoom-in")){imageModal.removeClass("image-is-fit-to-screen").addClass("image-is-zoomed");var imgWidth=img.width();var imgHeight=img.height();var imgContainerOffsetLeft=imgWidth-mask.width();var imgContainerOffsetTop=imgHeight-mask.height();var imgContainerWidth=imgWidth+imgContainerOffsetLeft;var imgContainerHeight=imgHeight+imgContainerOffsetTop;img.parent().css({left:-imgContainerOffsetLeft,top:-imgContainerOffsetTop,width:imgContainerWidth,height:imgContainerHeight});img.css({top:imgContainerOffsetTop/2,left:imgContainerOffsetLeft/2});currentDraggie.enable()}else if($(this).hasClass("action-zoom-out")){imageModal.removeClass("image-is-zoomed").addClass("image-is-fit-to-screen");currentDraggie.disable()}$(".wrapper-modal-image .image-content .image-controls .modal-ui-icon").toggleClass("is-disabled").attr("aria-disabled",$(this).hasClass("is-disabled"))}})};(function(requirejs,require,define){define("video/00_video_storage.js",[],function(){"use strict";var VideoStorage=function(namespace,id){var setItem=function(name,value,instanceSpecific){if(name){if(instanceSpecific){window[namespace][id][name]=value}else{window[namespace][name]=value}}};var getItem=function(name,instanceSpecific){if(instanceSpecific){return window[namespace][id][name]}else{return window[namespace][name]}};var removeItem=function(name,instanceSpecific){if(instanceSpecific){delete window[namespace][id][name]}else{delete window[namespace][name]}};var clear=function(){window[namespace]={};window[namespace][id]={}};(function initialize(){if(!namespace){namespace="VideoStorage"}if(!id){id=Math.random().toString(36).slice(2)}window[namespace]=window[namespace]||{};window[namespace][id]=window[namespace][id]||{}})();return{clear:clear,getItem:getItem,removeItem:removeItem,setItem:setItem}};return VideoStorage})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(requirejs,require,define){define("PollMain",[],function(){PollMain.prototype={showAnswerGraph:function(poll_answers,total){var _this,totalValue;totalValue=parseFloat(total);if(isFinite(totalValue)===false){return}_this=this;$.each(poll_answers,function(index,value){var numValue,percentValue;numValue=parseFloat(value);if(isFinite(numValue)===false){return}percentValue=numValue/totalValue*100;_this.answersObj[index].statsEl.show();_this.answersObj[index].numberEl.html(""+value+" ("+percentValue.toFixed(1)+"%)");_this.answersObj[index].percentEl.css({width:""+percentValue.toFixed(1)+"%"})})},submitAnswer:function(answer,answerObj){var _this;if(this.questionAnswered===true){return}this.questionAnswered=true;_this=this;console.log("submit answer");answerObj.buttonEl.addClass("answered");$.postWithPrefix(_this.ajax_url+"/"+answer,{},function(response){console.log("success! response = ");console.log(response);_this.showAnswerGraph(response.poll_answers,response.total);if(_this.canReset===true){_this.resetButton.show()}if(_this.wrapperSectionEl!==null){$(_this.wrapperSectionEl).find(".xmodule_ConditionalModule").each(function(index,value){new window.Conditional(value,_this.id.replace(/^poll_/,""))})}})},submitReset:function(){var _this;_this=this;console.log("submit reset");$.postWithPrefix(this.ajax_url+"/"+"reset_poll",{},function(response){console.log("success! response = ");console.log(response);if(response.hasOwnProperty("status")!==true||typeof response.status!=="string"||response.status.toLowerCase()!=="success"){return}_this.questionAnswered=false;_this.questionEl.find(".button.answered").removeClass("answered");_this.questionEl.find(".stats").hide();_this.resetButton.hide();if(_this.wrapperSectionEl!==null){$(_this.wrapperSectionEl).find(".xmodule_ConditionalModule").each(function(index,value){new window.Conditional(value,_this.id.replace(/^poll_/,""))})}})},postInit:function(){var _this;_this=this;if(this.jsonConfig.poll_answer.length>0&&this.jsonConfig.answers.hasOwnProperty(this.jsonConfig.poll_answer)===false){
3this.questionEl.append("<h3>Error!</h3>"+"<p>XML data format changed. List of answers was modified, but poll data was not updated.</p>");return}this.id=this.questionEl.attr("id");this.ajax_url=this.questionEl.data("ajax-url");this.questionHtmlMarkup=$("<div />").html(this.jsonConfig.question).text();this.questionEl.append(this.questionHtmlMarkup);this.questionAnswered=false;this.answersObj={};this.shortVersion=true;$.each(this.jsonConfig.answers,function(index,value){if(value.length>=18){_this.shortVersion=false}});$.each(this.jsonConfig.answers,function(index,value){var answer;answer={};_this.answersObj[index]=answer;answer.el=$('<div class="poll_answer"></div>');answer.questionEl=$('<div class="question"></div>');answer.buttonEl=$('<div class="button"></div>');answer.textEl=$('<div class="text"></div>');answer.questionEl.append(answer.buttonEl);answer.questionEl.append(answer.textEl);answer.el.append(answer.questionEl);answer.statsEl=$('<div class="stats"></div>');answer.barEl=$('<div class="bar"></div>');answer.percentEl=$('<div class="percent"></div>');answer.barEl.append(answer.percentEl);answer.numberEl=$('<div class="number"></div>');answer.statsEl.append(answer.barEl);answer.statsEl.append(answer.numberEl);answer.statsEl.hide();answer.el.append(answer.statsEl);answer.textEl.html(value);if(_this.shortVersion===true){$.each(answer,function(index,value){if(value instanceof jQuery){value.addClass("short")}})}answer.el.appendTo(_this.questionEl);answer.textEl.on("click",function(){_this.submitAnswer(index,answer)});answer.buttonEl.on("click",function(){_this.submitAnswer(index,answer)});if(index===_this.jsonConfig.poll_answer){answer.buttonEl.addClass("answered");_this.questionAnswered=true}});console.log(this.jsonConfig.reset);if(typeof this.jsonConfig.reset==="string"&&this.jsonConfig.reset.toLowerCase()==="true"){this.canReset=true;this.resetButton=$('<div class="button reset-button">Change your vote</div>');if(this.questionAnswered===false){this.resetButton.hide()}this.resetButton.appendTo(this.questionEl);this.resetButton.on("click",function(){_this.submitReset()})}else{this.canReset=false}if(this.questionAnswered===true){this.showAnswerGraph(this.jsonConfig.poll_answers,this.jsonConfig.total)}}};return PollMain;function PollMain(el){var _this;this.questionEl=$(el).find(".poll_question");if(this.questionEl.length!==1){console.log("ERROR: PollMain constructor requires one question DOM element.");return}if(this.questionEl.attr("poll_main_processed")==="true"){console.log("ERROR: PolMain JS constructor was called on a DOM element that has already been processed once.");return}this.questionEl.attr("poll_main_processed","true");_this=this;this.wrapperSectionEl=null;(function(tempEl,c1){while(tempEl.tagName.toLowerCase()!=="body"){tempEl=$(tempEl).parent()[0];c1+=1;if(tempEl.tagName.toLowerCase()==="div"&&$(tempEl).data("block-type")==="wrapper"){_this.wrapperSectionEl=tempEl;break}else if(c1>50){break}}})($(el)[0],0);try{this.jsonConfig=JSON.parse(this.questionEl.children(".poll_question_div").html());$.postWithPrefix(""+this.questionEl.data("ajax-url")+"/"+"get_state",{},function(response){_this.jsonConfig.poll_answer=response.poll_answer;_this.jsonConfig.total=response.total;$.each(response.poll_answers,function(index,value){_this.jsonConfig.poll_answers[index]=value});_this.questionEl.children(".poll_question_div").html(JSON.stringify(_this.jsonConfig));_this.postInit()});return}catch(err){console.log('ERROR: Invalid JSON config for poll ID "'+this.id+'".','Error messsage: "'+err.message+'".');return}}})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(undefined){"use strict";this.Collapsible={setCollapsibles:setCollapsibles,toggleFull:toggleFull,toggleHint:toggleHint};return;function setCollapsibles(el){var linkBottom,linkTop,short_custom;linkTop='<a href="#" class="full full-top">See full output</a>';linkBottom='<a href="#" class="full full-bottom">See full output</a>';el.find(".longform").hide();el.find(".shortform").append(linkTop,linkBottom);short_custom=el.find(".shortform-custom");short_custom.each(function(index,elt){var close_text,open_text;open_text=$(elt).data("open-text");close_text=$(elt).data("close-text");$(elt).append("<a href='#' class='full-custom'>"+open_text+"</a>");$(elt).find(".full-custom").click(function(event){Collapsible.toggleFull(event,open_text,close_text)})});el.find(".collapsible header + section").hide();el.find(".full").click(function(event){Collapsible.toggleFull(event,"See full output","Hide output")});el.find(".collapsible header a").click(Collapsible.toggleHint)}function toggleFull(event,open_text,close_text){var el,new_text,parent;event.preventDefault();parent=$(event.target).parent();parent.siblings().slideToggle();parent.parent().toggleClass("open");if($(event.target).text()===open_text){new_text=close_text}else{new_text=open_text}if($(event.target).hasClass("full")){el=parent.find(".full")}else{el=$(event.target)}el.text(new_text)}function toggleHint(event){event.preventDefault();$(event.target).parent().siblings().slideToggle();$(event.target).parent().parent().toggleClass("open")}}).call(this);(function(window){var slice=Array.prototype.slice;function noop(){}function defineBridget($){if(!$){return}function addOptionMethod(PluginClass){if(PluginClass.prototype.option){return}PluginClass.prototype.option=function(opts){if(!$.isPlainObject(opts)){return}this.options=$.extend(true,this.options,opts)}}var logError=typeof console==="undefined"?noop:function(message){console.error(message)};function bridge(namespace,PluginClass){$.fn[namespace]=function(options){if(typeof options==="string"){var args=slice.call(arguments,1);for(var i=0,len=this.length;i<len;i++){var elem=this[i];var instance=$.data(elem,namespace);if(!instance){logError("cannot call methods on "+namespace+" prior to initialization; "+"attempted to call '"+options+"'");continue}if(!$.isFunction(instance[options])||options.charAt(0)==="_"){logError("no such method '"+options+"' for "+namespace+" instance");continue}var returnValue=instance[options].apply(instance,args);if(returnValue!==undefined){return returnValue}}return this}else{return this.each(function(){var instance=$.data(this,namespace);if(instance){instance.option(options);instance._init()}else{instance=new PluginClass(this,options);$.data(this,namespace,instance)}})}}}$.bridget=function(namespace,PluginClass){addOptionMethod(PluginClass);bridge(namespace,PluginClass)};return $.bridget}if(typeof define==="function"&&define.amd){define("jquery-bridget/jquery.bridget",["jquery"],defineBridget)}else if(typeof exports==="object"){defineBridget(require("jquery"))}else{defineBridget(window.jQuery)}})(window);(function(window){function classReg(className){return new RegExp("(^|\\s+)"+className+"(\\s+|$)")}var hasClass,addClass,removeClass;if("classList"in document.documentElement){hasClass=function(elem,c){return elem.classList.contains(c)};addClass=function(elem,c){elem.classList.add(c)};removeClass=function(elem,c){elem.classList.remove(c)}}else{hasClass=function(elem,c){return classReg(c).test(elem.className)};addClass=function(elem,c){if(!hasClass(elem,c)){elem.className=elem.className+" "+c}};removeClass=function(elem,c){elem.className=elem.className.replace(classReg(c)," ")}}function toggleClass(elem,c){var fn=hasClass(elem,c)?removeClass:addClass;fn(elem,c)}var classie={hasClass:hasClass,addClass:addClass,removeClass:removeClass,toggleClass:toggleClass,has:hasClass,add:addClass,remove:removeClass,toggle:toggleClass};if(typeof define==="function"&&define.amd){define("classie/classie",classie)}else if(typeof exports==="object"){module.exports=classie}else{window.classie=classie}})(window);(function(window){var prefixes="Webkit Moz ms Ms O".split(" ");var docElemStyle=document.documentElement.style;function getStyleProperty(propName){if(!propName){return}if(typeof docElemStyle[propName]==="string"){return propName}propName=propName.charAt(0).toUpperCase()+propName.slice(1);var prefixed;for(var i=0,len=prefixes.length;i<len;i++){prefixed=prefixes[i]+propName;if(typeof docElemStyle[prefixed]==="string"){return prefixed}}}if(typeof define==="function"&&define.amd){define("get-style-property/get-style-property",[],function(){return getStyleProperty})}else if(typeof exports==="object"){module.exports=getStyleProperty}else{window.getStyleProperty=getStyleProperty}})(window);(function(window,undefined){function getStyleSize(value){var num=parseFloat(value);var isValid=value.indexOf("%")===-1&&!isNaN(num);return isValid&&num}function noop(){}var logError=typeof console==="undefined"?noop:function(message){console.error(message)};var measurements=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];function getZeroSize(){var size={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0};for(var i=0,len=measurements.length;i<len;i++){var measurement=measurements[i];size[measurement]=0}return size}function defineGetSize(getStyleProperty){var isSetup=false;var getStyle,boxSizingProp,isBoxSizeOuter;function setup(){if(isSetup){return}isSetup=true;var getComputedStyle=window.getComputedStyle;getStyle=function(){var getStyleFn=getComputedStyle?function(elem){return getComputedStyle(elem,null)}:function(elem){return elem.currentStyle};return function getStyle(elem){var style=getStyleFn(elem);if(!style){logError("Style returned "+style+". Are you running this code in a hidden iframe on Firefox? "+"See http://bit.ly/getsizebug1")}return style}}();boxSizingProp=getStyleProperty("boxSizing");if(boxSizingProp){var div=document.createElement("div");div.style.width="200px";div.style.padding="1px 2px 3px 4px";div.style.borderStyle="solid";div.style.borderWidth="1px 2px 3px 4px";div.style[boxSizingProp]="border-box";var body=document.body||document.documentElement;body.appendChild(div);var style=getStyle(div);isBoxSizeOuter=getStyleSize(style.width)===200;body.removeChild(div)}}function getSize(elem){setup();if(typeof elem==="string"){elem=document.querySelector(elem)}if(!elem||typeof elem!=="object"||!elem.nodeType){return}var style=getStyle(elem);if(style.display==="none"){return getZeroSize()}var size={};size.width=elem.offsetWidth;size.height=elem.offsetHeight;var isBorderBox=size.isBorderBox=!!(boxSizingProp&&style[boxSizingProp]&&style[boxSizingProp]==="border-box");for(var i=0,len=measurements.length;i<len;i++){var measurement=measurements[i];var value=style[measurement];value=mungeNonPixel(elem,value);var num=parseFloat(value);size[measurement]=!isNaN(num)?num:0}var paddingWidth=size.paddingLeft+size.paddingRight;var paddingHeight=size.paddingTop+size.paddingBottom;var marginWidth=size.marginLeft+size.marginRight;var marginHeight=size.marginTop+size.marginBottom;var borderWidth=size.borderLeftWidth+size.borderRightWidth;var borderHeight=size.borderTopWidth+size.borderBottomWidth;var isBorderBoxSizeOuter=isBorderBox&&isBoxSizeOuter;var styleWidth=getStyleSize(style.width);if(styleWidth!==false){size.width=styleWidth+(isBorderBoxSizeOuter?0:paddingWidth+borderWidth)}var styleHeight=getStyleSize(style.height);if(styleHeight!==false){size.height=styleHeight+(isBorderBoxSizeOuter?0:paddingHeight+borderHeight)}size.innerWidth=size.width-(paddingWidth+borderWidth);size.innerHeight=size.height-(paddingHeight+borderHeight);size.outerWidth=size.width+marginWidth;size.outerHeight=size.height+marginHeight;return size}function mungeNonPixel(elem,value){if(window.getComputedStyle||value.indexOf("%")===-1){return value}var style=elem.style;var left=style.left;var rs=elem.runtimeStyle;var rsLeft=rs&&rs.left;if(rsLeft){rs.left=elem.currentStyle.left}style.left=value;value=style.pixelLeft;style.left=left;if(rsLeft){rs.left=rsLeft}return value}return getSize}if(typeof define==="function"&&define.amd){define("get-size/get-size",["get-style-property/get-style-property"],defineGetSize)}else if(typeof exports==="object"){module.exports=defineGetSize(require("desandro-get-style-property"))}else{window.getSize=defineGetSize(window.getStyleProperty)}})(window);(function(window){var docElem=document.documentElement;var bind=function(){};function getIEEvent(obj){var event=window.event;event.target=event.target||event.srcElement||obj;return event}if(docElem.addEventListener){bind=function(obj,type,fn){obj.addEventListener(type,fn,false)}}else if(docElem.attachEvent){bind=function(obj,type,fn){obj[type+fn]=fn.handleEvent?function(){var event=getIEEvent(obj);fn.handleEvent.call(fn,event)}:function(){var event=getIEEvent(obj);fn.call(obj,event)};obj.attachEvent("on"+type,obj[type+fn])}}var unbind=function(){};if(docElem.removeEventListener){unbind=function(obj,type,fn){obj.removeEventListener(type,fn,false)}}else if(docElem.detachEvent){unbind=function(obj,type,fn){obj.detachEvent("on"+type,obj[type+fn]);try{delete obj[type+fn]}catch(err){obj[type+fn]=undefined}}}var eventie={bind:bind,unbind:unbind};if(typeof define==="function"&&define.amd){define("eventie/eventie",eventie)}else if(typeof exports==="object"){module.exports=eventie}else{window.eventie=eventie}})(window);(function(){function EventEmitter(){}var proto=EventEmitter.prototype;var exports=this;var originalGlobalValue=exports.EventEmitter;function indexOfListener(listeners,listener){var i=listeners.length;while(i--){if(listeners[i].listener===listener){return i}}return-1}function alias(name){return function aliasClosure(){return this[name].apply(this,arguments)}}proto.getListeners=function getListeners(evt){var events=this._getEvents();var response;var key;if(evt instanceof RegExp){response={};for(key in events){if(events.hasOwnProperty(key)&&evt.test(key)){response[key]=events[key]}}}else{response=events[evt]||(events[evt]=[])}return response};proto.flattenListeners=function flattenListeners(listeners){var flatListeners=[];var i;for(i=0;i<listeners.length;i+=1){flatListeners.push(listeners[i].listener)}return flatListeners};proto.getListenersAsObject=function getListenersAsObject(evt){var listeners=this.getListeners(evt);var response;if(listeners instanceof Array){response={};response[evt]=listeners}return response||listeners};proto.addListener=function addListener(evt,listener){var listeners=this.getListenersAsObject(evt);var listenerIsWrapped=typeof listener==="object";var key;for(key in listeners){if(listeners.hasOwnProperty(key)&&indexOfListener(listeners[key],listener)===-1){listeners[key].push(listenerIsWrapped?listener:{listener:listener,once:false})}}return this};proto.on=alias("addListener");proto.addOnceListener=function addOnceListener(evt,listener){return this.addListener(evt,{listener:listener,once:true})};proto.once=alias("addOnceListener");proto.defineEvent=function defineEvent(evt){this.getListeners(evt);return this};proto.defineEvents=function defineEvents(evts){for(var i=0;i<evts.length;i+=1){this.defineEvent(evts[i])}return this};proto.removeListener=function removeListener(evt,listener){var listeners=this.getListenersAsObject(evt);var index;var key;for(key in listeners){if(listeners.hasOwnProperty(key)){index=indexOfListener(listeners[key],listener);if(index!==-1){listeners[key].splice(index,1)}}}return this};proto.off=alias("removeListener");proto.addListeners=function addListeners(evt,listeners){return this.manipulateListeners(false,evt,listeners)};proto.removeListeners=function removeListeners(evt,listeners){return this.manipulateListeners(true,evt,listeners)};proto.manipulateListeners=function manipulateListeners(remove,evt,listeners){var i;var value;var single=remove?this.removeListener:this.addListener;var multiple=remove?this.removeListeners:this.addListeners;if(typeof evt==="object"&&!(evt instanceof RegExp)){for(i in evt){if(evt.hasOwnProperty(i)&&(value=evt[i])){if(typeof value==="function"){single.call(this,i,value)}else{multiple.call(this,i,value)}}}}else{i=listeners.length;while(i--){single.call(this,evt,listeners[i])}}return this};proto.removeEvent=function removeEvent(evt){var type=typeof evt;var events=this._getEvents();var key;if(type==="string"){delete events[evt]}else if(evt instanceof RegExp){for(key in events){if(events.hasOwnProperty(key)&&evt.test(key)){delete events[key]}}}else{delete this._events}return this};proto.removeAllListeners=alias("removeEvent");proto.emitEvent=function emitEvent(evt,args){var listeners=this.getListenersAsObject(evt);var listener;var i;var key;var response;for(key in listeners){if(listeners.hasOwnProperty(key)){i=listeners[key].length;while(i--){listener=listeners[key][i];if(listener.once===true){this.removeListener(evt,listener.listener)}response=listener.listener.apply(this,args||[]);if(response===this._getOnceReturnValue()){this.removeListener(evt,listener.listener)}}}}return this};proto.trigger=alias("emitEvent");proto.emit=function emit(evt){var args=Array.prototype.slice.call(arguments,1);return this.emitEvent(evt,args)};proto.setOnceReturnValue=function setOnceReturnValue(value){this._onceReturnValue=value;return this};proto._getOnceReturnValue=function _getOnceReturnValue(){if(this.hasOwnProperty("_onceReturnValue")){return this._onceReturnValue}else{return true}};proto._getEvents=function _getEvents(){return this._events||(this._events={})};EventEmitter.noConflict=function noConflict(){exports.EventEmitter=originalGlobalValue;return EventEmitter};if(typeof define==="function"&&define.amd){define("eventEmitter/EventEmitter",[],function(){return EventEmitter})}else if(typeof module==="object"&&module.exports){module.exports=EventEmitter}else{exports.EventEmitter=EventEmitter}}).call(this);(function(window,factory){if(typeof define=="function"&&define.amd){define("unipointer/unipointer",["eventEmitter/EventEmitter","eventie/eventie"],function(EventEmitter,eventie){return factory(window,EventEmitter,eventie)})}else if(typeof exports=="object"){module.exports=factory(window,require("wolfy87-eventemitter"),require("eventie"))}else{window.Unipointer=factory(window,window.EventEmitter,window.eventie)}})(window,function factory(window,EventEmitter,eventie){function noop(){}function Unipointer(){}Unipointer.prototype=new EventEmitter;Unipointer.prototype.bindStartEvent=function(elem){this._bindStartEvent(elem,true)};Unipointer.prototype.unbindStartEvent=function(elem){this._bindStartEvent(elem,false)};Unipointer.prototype._bindStartEvent=function(elem,isBind){isBind=isBind===undefined?true:!!isBind;var bindMethod=isBind?"bind":"unbind";if(window.navigator.pointerEnabled){eventie[bindMethod](elem,"pointerdown",this)}else if(window.navigator.msPointerEnabled){eventie[bindMethod](elem,"MSPointerDown",this)}else{eventie[bindMethod](elem,"mousedown",this);eventie[bindMethod](elem,"touchstart",this)}};Unipointer.prototype.handleEvent=function(event){var method="on"+event.type;if(this[method]){this[method](event)}};Unipointer.prototype.getTouch=function(touches){for(var i=0,len=touches.length;i<len;i++){var touch=touches[i];if(touch.identifier==this.pointerIdentifier){return touch}}};Unipointer.prototype.onmousedown=function(event){var button=event.button;if(button&&(button!==0&&button!==1)){return}this._pointerDown(event,event)};Unipointer.prototype.ontouchstart=function(event){this._pointerDown(event,event.changedTouches[0])};Unipointer.prototype.onMSPointerDown=Unipointer.prototype.onpointerdown=function(event){this._pointerDown(event,event)};Unipointer.prototype._pointerDown=function(event,pointer){if(this.isPointerDown){return}this.isPointerDown=true;this.pointerIdentifier=pointer.pointerId!==undefined?pointer.pointerId:pointer.identifier;this.pointerDown(event,pointer)};Unipointer.prototype.pointerDown=function(event,pointer){this._bindPostStartEvents(event);this.emitEvent("pointerDown",[event,pointer])};var postStartEvents={mousedown:["mousemove","mouseup"],touchstart:["touchmove","touchend","touchcancel"],pointerdown:["pointermove","pointerup","pointercancel"],MSPointerDown:["MSPointerMove","MSPointerUp","MSPointerCancel"]};Unipointer.prototype._bindPostStartEvents=function(event){if(!event){return}var events=postStartEvents[event.type];var node=event.preventDefault?window:document;for(var i=0,len=events.length;i<len;i++){var evnt=events[i];eventie.bind(node,evnt,this)}this._boundPointerEvents={events:events,node:node}};Unipointer.prototype._unbindPostStartEvents=function(){var args=this._boundPointerEvents;if(!args||!args.events){return}for(var i=0,len=args.events.length;i<len;i++){var event=args.events[i];eventie.unbind(args.node,event,this)}delete this._boundPointerEvents};Unipointer.prototype.onmousemove=function(event){this._pointerMove(event,event)};Unipointer.prototype.onMSPointerMove=Unipointer.prototype.onpointermove=function(event){if(event.pointerId==this.pointerIdentifier){this._pointerMove(event,event)}};Unipointer.prototype.ontouchmove=function(event){var touch=this.getTouch(event.changedTouches);if(touch){this._pointerMove(event,touch)}};Unipointer.prototype._pointerMove=function(event,pointer){this.pointerMove(event,pointer)};Unipointer.prototype.pointerMove=function(event,pointer){this.emitEvent("pointerMove",[event,pointer])};Unipointer.prototype.onmouseup=function(event){this._pointerUp(event,event)};Unipointer.prototype.onMSPointerUp=Unipointer.prototype.onpointerup=function(event){if(event.pointerId==this.pointerIdentifier){this._pointerUp(event,event)}};Unipointer.prototype.ontouchend=function(event){var touch=this.getTouch(event.changedTouches);if(touch){this._pointerUp(event,touch)}};Unipointer.prototype._pointerUp=function(event,pointer){this._pointerDone();this.pointerUp(event,pointer)};Unipointer.prototype.pointerUp=function(event,pointer){this.emitEvent("pointerUp",[event,pointer])};Unipointer.prototype._pointerDone=function(){this.isPointerDown=false;delete this.pointerIdentifier;this._unbindPostStartEvents();this.pointerDone()};Unipointer.prototype.pointerDone=noop;Unipointer.prototype.onMSPointerCancel=Unipointer.prototype.onpointercancel=function(event){if(event.pointerId==this.pointerIdentifier){this._pointerCancel(event,event)}};Unipointer.prototype.ontouchcancel=function(event){var touch=this.getTouch(event.changedTouches);if(touch){this._pointerCancel(event,touch)}};Unipointer.prototype._pointerCancel=function(event,pointer){this._pointerDone();this.pointerCancel(event,pointer)};Unipointer.prototype.pointerCancel=function(event,pointer){this.emitEvent("pointerCancel",[event,pointer])};Unipointer.getPointerPoint=function(pointer){return{x:pointer.pageX!==undefined?pointer.pageX:pointer.clientX,y:pointer.pageY!==undefined?pointer.pageY:pointer.clientY}};return Unipointer});(function(window,factory){if(typeof define=="function"&&define.amd){define("unidragger/unidragger",["eventie/eventie","unipointer/unipointer"],function(eventie,Unipointer){return factory(window,eventie,Unipointer)})}else if(typeof exports=="object"){module.exports=factory(window,require("eventie"),require("unipointer"))}else{window.Unidragger=factory(window,window.eventie,window.Unipointer)}})(window,function factory(window,eventie,Unipointer){function noop(){}function preventDefaultEvent(event){if(event.preventDefault){event.preventDefault()}else{event.returnValue=false}}function getParentLink(elem){while(elem!=document.body){elem=elem.parentNode;if(elem.nodeName=="A"){return elem}}}function Unidragger(){}Unidragger.prototype=new Unipointer;Unidragger.prototype.bindHandles=function(){this._bindHandles(true)};Unidragger.prototype.unbindHandles=function(){this._bindHandles(false)};var navigator=window.navigator;Unidragger.prototype._bindHandles=function(isBind){isBind=isBind===undefined?true:!!isBind;var binderExtra;if(navigator.pointerEnabled){binderExtra=function(handle){handle.style.touchAction=isBind?"none":""}}else if(navigator.msPointerEnabled){binderExtra=function(handle){handle.style.msTouchAction=isBind?"none":""}}else{binderExtra=function(){if(isBind){disableImgOndragstart(handle)}}}var bindMethod=isBind?"bind":"unbind";for(var i=0,len=this.handles.length;i<len;i++){var handle=this.handles[i];this._bindStartEvent(handle,isBind);binderExtra(handle);eventie[bindMethod](handle,"click",this)}};function noDragStart(){return false}var isIE8="attachEvent"in document.documentElement;var disableImgOndragstart=!isIE8?noop:function(handle){if(handle.nodeName=="IMG"){handle.ondragstart=noDragStart}var images=handle.querySelectorAll("img");for(var i=0,len=images.length;i<len;i++){var img=images[i];img.ondragstart=noDragStart}};var allowTouchstartNodes=Unidragger.allowTouchstartNodes={INPUT:true,A:true,BUTTON:true,SELECT:true};Unidragger.prototype.pointerDown=function(event,pointer){this._dragPointerDown(event,pointer);var focused=document.activeElement;if(focused&&focused.blur){focused.blur()}this._bindPostStartEvents(event);this.emitEvent("pointerDown",[event,pointer])};Unidragger.prototype._dragPointerDown=function(event,pointer){this.pointerDownPoint=Unipointer.getPointerPoint(pointer);var targetNodeName=event.target.nodeName;var isTouchstartNode=event.type=="touchstart"&&(allowTouchstartNodes[targetNodeName]||getParentLink(event.target));if(!isTouchstartNode&&targetNodeName!="SELECT"){preventDefaultEvent(event)}};Unidragger.prototype.pointerMove=function(event,pointer){var moveVector=this._dragPointerMove(event,pointer);this.emitEvent("pointerMove",[event,pointer,moveVector]);this._dragMove(event,pointer,moveVector)};Unidragger.prototype._dragPointerMove=function(event,pointer){var movePoint=Unipointer.getPointerPoint(pointer);var moveVector={x:movePoint.x-this.pointerDownPoint.x,y:movePoint.y-this.pointerDownPoint.y};if(!this.isDragging&&this.hasDragStarted(moveVector)){this._dragStart(event,pointer)}return moveVector};Unidragger.prototype.hasDragStarted=function(moveVector){return Math.abs(moveVector.x)>3||Math.abs(moveVector.y)>3};Unidragger.prototype.pointerUp=function(event,pointer){this.emitEvent("pointerUp",[event,pointer]);this._dragPointerUp(event,pointer)};Unidragger.prototype._dragPointerUp=function(event,pointer){if(this.isDragging){this._dragEnd(event,pointer)}else{this._staticClick(event,pointer)}};Unidragger.prototype._dragStart=function(event,pointer){this.isDragging=true;this.dragStartPoint=Unidragger.getPointerPoint(pointer);this.isPreventingClicks=true;this.dragStart(event,pointer)};Unidragger.prototype.dragStart=function(event,pointer){this.emitEvent("dragStart",[event,pointer])};Unidragger.prototype._dragMove=function(event,pointer,moveVector){if(!this.isDragging){return}this.dragMove(event,pointer,moveVector)};Unidragger.prototype.dragMove=function(event,pointer,moveVector){this.emitEvent("dragMove",[event,pointer,moveVector])};Unidragger.prototype._dragEnd=function(event,pointer){this.isDragging=false;var _this=this;setTimeout(function(){delete _this.isPreventingClicks});this.dragEnd(event,pointer)};Unidragger.prototype.dragEnd=function(event,pointer){this.emitEvent("dragEnd",[event,pointer])};Unidragger.prototype.onclick=function(event){if(this.isPreventingClicks){preventDefaultEvent(event)}};Unidragger.prototype._staticClick=function(event,pointer){if(event.target.nodeName=="INPUT"&&event.target.type=="text"){event.target.focus()}this.staticClick(event,pointer)};Unidragger.prototype.staticClick=function(event,pointer){this.emitEvent("staticClick",[event,pointer])};Unidragger.getPointerPoint=function(pointer){return{x:pointer.pageX!==undefined?pointer.pageX:pointer.clientX,y:pointer.pageY!==undefined?pointer.pageY:pointer.clientY}};Unidragger.getPointerPoint=Unipointer.getPointerPoint;return Unidragger});(function(window,factory){if(typeof define=="function"&&define.amd){define("draggabilly",["classie/classie","get-style-property/get-style-property","get-size/get-size","unidragger/unidragger"],function(classie,getStyleProperty,getSize,Unidragger){return factory(window,classie,getStyleProperty,getSize,Unidragger)})}else if(typeof exports=="object"){module.exports=factory(window,require("desandro-classie"),require("desandro-get-style-property"),require("get-size"),require("unidragger"))}else{window.Draggabilly=factory(window,window.classie,window.getStyleProperty,window.getSize,window.Unidragger)}})(window,function factory(window,classie,getStyleProperty,getSize,Unidragger){var document=window.document;function noop(){}function extend(a,b){for(var prop in b){a[prop]=b[prop]}return a}var defView=document.defaultView;var getStyle=defView&&defView.getComputedStyle?function(elem){return defView.getComputedStyle(elem,null)}:function(elem){return elem.currentStyle};var isElement=typeof HTMLElement=="object"?function isElementDOM2(obj){return obj instanceof HTMLElement}:function isElementQuirky(obj){return obj&&typeof obj=="object"&&obj.nodeType==1&&typeof obj.nodeName=="string"};var lastTime=0;var prefixes="webkit moz ms o".split(" ");var requestAnimationFrame=window.requestAnimationFrame;var cancelAnimationFrame=window.cancelAnimationFrame;var prefix;for(var i=0;i<prefixes.length;i++){if(requestAnimationFrame&&cancelAnimationFrame){break}prefix=prefixes[i];requestAnimationFrame=requestAnimationFrame||window[prefix+"RequestAnimationFrame"];cancelAnimationFrame=cancelAnimationFrame||window[prefix+"CancelAnimationFrame"]||window[prefix+"CancelRequestAnimationFrame"]}if(!requestAnimationFrame||!cancelAnimationFrame){requestAnimationFrame=function(callback){var currTime=(new Date).getTime();var timeToCall=Math.max(0,16-(currTime-lastTime));var id=window.setTimeout(function(){callback(currTime+timeToCall)},timeToCall);lastTime=currTime+timeToCall;return id};cancelAnimationFrame=function(id){window.clearTimeout(id)}}var transformProperty=getStyleProperty("transform");var is3d=!!getStyleProperty("perspective");var jQuery=window.jQuery;function Draggabilly(element,options){this.element=typeof element=="string"?document.querySelector(element):element;if(jQuery){this.$element=jQuery(this.element)}this.options=extend({},this.constructor.defaults);this.option(options);this._create()}extend(Draggabilly.prototype,Unidragger.prototype);Draggabilly.defaults={};Draggabilly.prototype.option=function(opts){extend(this.options,opts)};Draggabilly.prototype._create=function(){this.position={};this._getPosition();this.startPoint={x:0,y:0};this.dragPoint={x:0,y:0};this.startPosition=extend({},this.position);var style=getStyle(this.element);if(style.position!="relative"&&style.position!="absolute"){this.element.style.position="relative"}this.enable();this.setHandles()};Draggabilly.prototype.setHandles=function(){this.handles=this.options.handle?this.element.querySelectorAll(this.options.handle):[this.element];this.bindHandles()};Draggabilly.prototype.dispatchEvent=function(type,event,args){var emitArgs=[event].concat(args);this.emitEvent(type,emitArgs);var jQuery=window.jQuery;if(jQuery&&this.$element){if(event){var $event=jQuery.Event(event);$event.type=type;this.$element.trigger($event,args)}else{this.$element.trigger(type,args)}}};Draggabilly.prototype._getPosition=function(){var style=getStyle(this.element);var x=parseInt(style.left,10);var y=parseInt(style.top,10);this.position.x=isNaN(x)?0:x;this.position.y=isNaN(y)?0:y;this._addTransformPosition(style)};Draggabilly.prototype._addTransformPosition=function(style){if(!transformProperty){return}var transform=style[transformProperty];if(transform.indexOf("matrix")!==0){return}var matrixValues=transform.split(",");var xIndex=transform.indexOf("matrix3d")===0?12:4;var translateX=parseInt(matrixValues[xIndex],10);var translateY=parseInt(matrixValues[xIndex+1],10);this.position.x+=translateX;this.position.y+=translateY};Draggabilly.prototype.pointerDown=function(event,pointer){this._dragPointerDown(event,pointer);var focused=document.activeElement;if(focused&&focused.blur){focused.blur()}this._bindPostStartEvents(event);classie.add(this.element,"is-pointer-down");this.dispatchEvent("pointerDown",event,[pointer])};Draggabilly.prototype.pointerMove=function(event,pointer){var moveVector=this._dragPointerMove(event,pointer);this.dispatchEvent("pointerMove",event,[pointer,moveVector]);
4this._dragMove(event,pointer,moveVector)};Draggabilly.prototype.dragStart=function(event,pointer){if(!this.isEnabled){return}this._getPosition();this.measureContainment();this.startPosition.x=this.position.x;this.startPosition.y=this.position.y;this.setLeftTop();this.dragPoint.x=0;this.dragPoint.y=0;this.isDragging=true;classie.add(this.element,"is-dragging");this.dispatchEvent("dragStart",event,[pointer]);this.animate()};Draggabilly.prototype.measureContainment=function(){var containment=this.options.containment;if(!containment){return}this.size=getSize(this.element);var elemRect=this.element.getBoundingClientRect();var container=isElement(containment)?containment:typeof containment=="string"?document.querySelector(containment):this.element.parentNode;this.containerSize=getSize(container);var containerRect=container.getBoundingClientRect();this.relativeStartPosition={x:elemRect.left-containerRect.left,y:elemRect.top-containerRect.top}};Draggabilly.prototype.dragMove=function(event,pointer,moveVector){if(!this.isEnabled){return}var dragX=moveVector.x;var dragY=moveVector.y;var grid=this.options.grid;var gridX=grid&&grid[0];var gridY=grid&&grid[1];dragX=applyGrid(dragX,gridX);dragY=applyGrid(dragY,gridY);dragX=this.containDrag("x",dragX,gridX);dragY=this.containDrag("y",dragY,gridY);dragX=this.options.axis=="y"?0:dragX;dragY=this.options.axis=="x"?0:dragY;this.position.x=this.startPosition.x+dragX;this.position.y=this.startPosition.y+dragY;this.dragPoint.x=dragX;this.dragPoint.y=dragY;this.dispatchEvent("dragMove",event,[pointer,moveVector])};function applyGrid(value,grid,method){method=method||"round";return grid?Math[method](value/grid)*grid:value}Draggabilly.prototype.containDrag=function(axis,drag,grid){if(!this.options.containment){return drag}var measure=axis=="x"?"width":"height";var rel=this.relativeStartPosition[axis];var min=applyGrid(-rel,grid,"ceil");var max=this.containerSize[measure]-rel-this.size[measure];max=applyGrid(max,grid,"floor");return Math.min(max,Math.max(min,drag))};Draggabilly.prototype.pointerUp=function(event,pointer){classie.remove(this.element,"is-pointer-down");this.dispatchEvent("pointerUp",event,[pointer]);this._dragPointerUp(event,pointer)};Draggabilly.prototype.dragEnd=function(event,pointer){if(!this.isEnabled){return}this.isDragging=false;if(transformProperty){this.element.style[transformProperty]="";this.setLeftTop()}classie.remove(this.element,"is-dragging");this.dispatchEvent("dragEnd",event,[pointer])};Draggabilly.prototype.animate=function(){if(!this.isDragging){return}this.positionDrag();var _this=this;requestAnimationFrame(function animateFrame(){_this.animate()})};var translate=is3d?function(x,y){return"translate3d( "+x+"px, "+y+"px, 0)"}:function(x,y){return"translate( "+x+"px, "+y+"px)"};Draggabilly.prototype.setLeftTop=function(){this.element.style.left=this.position.x+"px";this.element.style.top=this.position.y+"px"};Draggabilly.prototype.positionDrag=transformProperty?function(){this.element.style[transformProperty]=translate(this.dragPoint.x,this.dragPoint.y)}:Draggabilly.prototype.setLeftTop;Draggabilly.prototype.staticClick=function(event,pointer){this.dispatchEvent("staticClick",event,[pointer])};Draggabilly.prototype.enable=function(){this.isEnabled=true};Draggabilly.prototype.disable=function(){this.isEnabled=false;if(this.isDragging){this.dragEnd()}};Draggabilly.prototype.destroy=function(){this.disable();if(transformProperty){this.element.style[transformProperty]=""}this.element.style.left="";this.element.style.top="";this.element.style.position="";this.unbindHandles();if(this.$element){this.$element.removeData("draggabilly")}};Draggabilly.prototype._init=noop;if(jQuery&&jQuery.bridget){jQuery.bridget("draggabilly",Draggabilly)}return Draggabilly});(function(requirejs,require,define){define("video/00_resizer.js",[],function(){var Resizer=function(params){var defaults={container:window,element:null,containerRatio:null,elementRatio:null},callbacksList=[],delta={height:0,width:0},module={},mode=null,config;var initialize=function(params){if(!config){config=defaults}config=$.extend(true,{},config,params);if(!config.element){console.log("Required parameter `element` is not passed.")}return module};var getData=function(){var container=$(config.container),containerWidth=container.width()+delta.width,containerHeight=container.height()+delta.height,containerRatio=config.containerRatio,element=$(config.element),elementRatio=config.elementRatio;if(!containerRatio){containerRatio=containerWidth/containerHeight}if(!elementRatio){elementRatio=element.width()/element.height()}return{containerWidth:containerWidth,containerHeight:containerHeight,containerRatio:containerRatio,element:element,elementRatio:elementRatio}};var align=function(){var data=getData();switch(mode){case"height":alignByHeightOnly();break;case"width":alignByWidthOnly();break;default:if(data.containerRatio>=data.elementRatio){alignByHeightOnly()}else{alignByWidthOnly()}break}fireCallbacks();return module};var alignByWidthOnly=function(){var data=getData(),height=data.containerWidth/data.elementRatio;data.element.css({height:height,width:data.containerWidth,top:.5*(data.containerHeight-height),left:0});return module};var alignByHeightOnly=function(){var data=getData(),width=data.containerHeight*data.elementRatio;data.element.css({height:data.containerHeight,width:data.containerHeight*data.elementRatio,top:0,left:.5*(data.containerWidth-width)});return module};var setMode=function(param){if(_.isString(param)){mode=param;align()}return module};var setElement=function(element){config.element=element;return module};var addCallback=function(func){if($.isFunction(func)){callbacksList.push(func)}else{console.error("[Video info]: TypeError: Argument is not a function.")}return module};var addOnceCallback=function(func){if($.isFunction(func)){var decorator=function(){func();removeCallback(func)};addCallback(decorator)}else{console.error("TypeError: Argument is not a function.")}return module};var fireCallbacks=function(){$.each(callbacksList,function(index,callback){callback()})};var removeCallbacks=function(){callbacksList.length=0;return module};var removeCallback=function(func){var index=$.inArray(func,callbacksList);if(index!==-1){return callbacksList.splice(index,1)}};var resetDelta=function(){delta["height"]=delta["width"]=0;return module};var addDelta=function(value,side){if(_.isNumber(value)&&_.isNumber(delta[side])){delta[side]+=value}return module};var substractDelta=function(value,side){if(_.isNumber(value)&&_.isNumber(delta[side])){delta[side]-=value}return module};var destroy=function(){var data=getData();data.element.css({height:"",width:"",top:"",left:""});removeCallbacks();resetDelta();mode=null};initialize.apply(module,arguments);return $.extend(true,module,{align:align,alignByWidthOnly:alignByWidthOnly,alignByHeightOnly:alignByHeightOnly,destroy:destroy,setParams:initialize,setMode:setMode,setElement:setElement,callbacks:{add:addCallback,once:addOnceCallback,remove:removeCallback,removeAll:removeCallbacks},delta:{add:addDelta,substract:substractDelta,reset:resetDelta}})};return Resizer})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);window.ImageInput=function($,undefined){var ImageInput=ImageInputConstructor;ImageInput.prototype={constructor:ImageInputConstructor,clickHandler:clickHandler};return ImageInput;function ImageInputConstructor(elementId){this.el=$("#imageinput_"+elementId);this.crossEl=$("#cross_"+elementId);this.inputEl=$("#input_"+elementId);this.el.on("click",this.clickHandler.bind(this))}function clickHandler(event){var offset=this.el.offset(),posX=event.offsetX?event.offsetX:event.pageX-offset.left,posY=event.offsetY?event.offsetY:event.pageY-offset.top,result="["+Math.round(posX)+","+Math.round(posY)+"]";this.crossEl.css({left:posX-15,top:posY-15,visibility:"visible"});this.inputEl.val(result)}}.call(this,window.jQuery);(function(define){define("video/00_async_process.js",[],function(){"use strict";var AsyncProcess={array:function(list,process){if(!_.isArray(list)){return $.Deferred().reject().promise()}if(!_.isFunction(process)||!list.length){return $.Deferred().resolve(list).promise()}var MAX_DELAY=50,dfd=$.Deferred(),result=[],index=0,len=list.length;var getCurrentTime=function(){return(new Date).getTime()};var handler=function(){var start=getCurrentTime();do{result[index]=process(list[index],index);index++}while(index<len&&getCurrentTime()-start<MAX_DELAY);if(index<len){setTimeout(handler,25)}else{dfd.resolve(result)}};setTimeout(handler,25);return dfd.promise()}};return AsyncProcess})})(RequireJS.define);var cktsim=function(){var T_VOLTAGE=0;var T_CURRENT=1;var v_newt_lim=.3;var v_abstol=1e-6;var i_abstol=1e-12;var eps=1e-12;var dc_max_iters=1e3;var max_tran_iters=20;var time_step_increase_factor=2;var lte_step_decrease_factor=8;var nr_step_decrease_factor=4;var reltol=1e-4;var lterel=10;var res_check_abs=Math.sqrt(i_abstol);var res_check_rel=Math.sqrt(reltol);function Circuit(){this.node_map=[];this.ntypes=[];this.initial_conditions=[];this.devices=[];this.device_map=[];this.voltage_sources=[];this.current_sources=[];this.finalized=false;this.diddc=false;this.node_index=-1;this.periods=1}Circuit.prototype.gnd_node=function(){return-1};Circuit.prototype.node=function(name,ntype,ic){this.node_index+=1;if(name)this.node_map[name]=this.node_index;this.ntypes.push(ntype);this.initial_conditions.push(ic);return this.node_index};Circuit.prototype.finalize=function(){if(!this.finalized){this.finalized=true;this.N=this.node_index+1;for(var i=this.devices.length-1;i>=0;--i)this.devices[i].finalize(this);this.matrix=mat_make(this.N,this.N+1);this.Gl=mat_make(this.N,this.N);this.G=mat_make(this.N,this.N);this.C=mat_make(this.N,this.N);this.soln_max=new Array(this.N);this.abstol=new Array(this.N);this.solution=new Array(this.N);this.rhs=new Array(this.N);for(var i=this.N-1;i>=0;--i){this.soln_max[i]=0;this.abstol[i]=this.ntypes[i]==T_VOLTAGE?v_abstol:i_abstol;this.solution[i]=0;this.rhs[i]=0}for(var i=this.devices.length-1;i>=0;--i){this.devices[i].load_linear(this)}var n_vsrc=this.voltage_sources.length;if(n_vsrc>0){var GV=mat_make(n_vsrc,this.N);for(var i=n_vsrc-1;i>=0;--i){var branch=this.voltage_sources[i].branch;for(var j=this.N-1;j>=0;j--)GV[i][j]=this.Gl[branch][j]}var rGV=mat_rank(GV);if(rGV<n_vsrc){alert("Warning!!! Circuit has a voltage source loop or a source or current probe shorted by a wire, please remove the source or the wire causing the short.");alert("Warning!!! Simulator might produce meaningless results or no result with illegal circuits.");return false}}}return true};Circuit.prototype.load_netlist=function(netlist){for(var i=netlist.length-1;i>=0;--i){var component=netlist[i];var type=component[0];if(type=="g"){var connections=component[3];this.node_map[connections[0]]=this.gnd_node()}}var found_ground=false;for(var i=netlist.length-1;i>=0;--i){var component=netlist[i];var type=component[0];if(type=="view"||type=="w"||type=="g"||type=="s"||type=="L"){continue}var properties=component[2];var name=properties["name"];if(name==undefined||name=="")name="_"+properties["_json_"].toString();var connections=component[3];for(var j=connections.length-1;j>=0;--j){var node=connections[j];var index=this.node_map[node];if(index==undefined)index=this.node(node,T_VOLTAGE);else if(index==this.gnd_node())found_ground=true;connections[j]=index}if(type=="r")this.r(connections[0],connections[1],properties["r"],name);else if(type=="d")this.d(connections[0],connections[1],properties["area"],properties["type"],name);else if(type=="c")this.c(connections[0],connections[1],properties["c"],name);else if(type=="l")this.l(connections[0],connections[1],properties["l"],name);else if(type=="v")this.v(connections[0],connections[1],properties["value"],name);else if(type=="i")this.i(connections[0],connections[1],properties["value"],name);else if(type=="o")this.opamp(connections[0],connections[1],connections[2],connections[3],properties["A"],name);else if(type=="n")this.n(connections[0],connections[1],connections[2],properties["W/L"],name);else if(type=="p")this.p(connections[0],connections[1],connections[2],properties["W/L"],name);else if(type=="a")this.v(connections[0],connections[1],"0",name)}if(!found_ground){alert("Please make at least one connection to ground (inverted T symbol)");return false}return true};Circuit.prototype.find_solution=function(load,maxiters){var soln=this.solution;var rhs=this.rhs;var d_sol=[];var abssum_compare;var converged,abssum_old=0,abssum_rhs;var use_limiting=false;var down_count=0;var thresh;for(var iter=0;iter<maxiters;iter++){load(this,soln,rhs);abssum_rhs=0;for(var i=this.N-1;i>=0;--i)if(this.ntypes[i]==T_VOLTAGE)abssum_rhs+=Math.abs(rhs[i]);if(iter>0&&use_limiting==false&&abssum_old<abssum_rhs){for(var i=this.N-1;i>=0;--i)soln[i]-=d_sol[i];iter-=1;use_limiting=true}else{d_sol=mat_solve_rq(this.matrix,rhs);if(abssum_rhs<abssum_old)down_count+=1;else down_count=0;if(down_count>10){use_limiting=false;down_count=0}abssum_old=abssum_rhs}if(iter==0||abssum_rhs>abssum_compare)abssum_compare=abssum_rhs;if(iter<maxiters-1&&abssum_rhs>res_check_abs+res_check_rel*abssum_compare)converged=false;else converged=true;for(var i=this.N-1;i>=0;--i){if(use_limiting){if(this.ntypes[i]==T_VOLTAGE){d_sol[i]=d_sol[i]>v_newt_lim?v_newt_lim:d_sol[i];d_sol[i]=d_sol[i]<-v_newt_lim?-v_newt_lim:d_sol[i]}}soln[i]+=d_sol[i];thresh=this.abstol[i]+reltol*this.soln_max[i];if(Math.abs(d_sol[i])>thresh){converged=false;this.problem_node=i}}if(converged==true){for(var i=this.N-1;i>=0;--i)if(Math.abs(soln[i])>this.soln_max[i])this.soln_max[i]=Math.abs(soln[i]);return iter+1}}return undefined};Circuit.prototype.dc=function(){if(this.finalize()==false)return undefined;function load_dc(ckt,soln,rhs){mat_v_mult(ckt.Gl,soln,rhs,-1);mat_copy(ckt.Gl,ckt.G);for(var i=ckt.devices.length-1;i>=0;--i)ckt.devices[i].load_dc(ckt,soln,rhs);mat_copy(ckt.G,ckt.matrix)}var iterations=this.find_solution(load_dc,dc_max_iters);if(typeof iterations=="undefined"){if(this.current_sources.length>0){alert("Newton Method Failed, do your current sources have a conductive path to ground?")}else{alert("Newton Method Failed, it may be your circuit or it may be our simulator.")}return undefined}else{this.diddc=true;var result=[];for(var name in this.node_map){var index=this.node_map[name];result[name]=index==-1?0:this.solution[index]}for(var i=this.voltage_sources.length-1;i>=0;--i){var v=this.voltage_sources[i];result["I("+v.name+")"]=this.solution[v.branch]}return result}};Circuit.prototype.tran=function(ntpts,tstart,tstop,probenames,no_dc){function load_tran(ckt,soln,rhs){mat_v_mult(ckt.Gl,soln,ckt.c,-1);mat_copy(ckt.Gl,ckt.G);for(var i=ckt.devices.length-1;i>=0;--i)ckt.devices[i].load_tran(ckt,soln,ckt.c,ckt.time);mat_v_mult(ckt.C,soln,ckt.q,1);for(var i=ckt.N-1;i>=0;--i){var dqdt=ckt.alpha0*ckt.q[i]+ckt.alpha1*ckt.oldq[i]+ckt.alpha2*ckt.old2q[i];rhs[i]=ckt.beta0[i]*ckt.c[i]+ckt.beta1[i]*ckt.oldc[i]-dqdt}mat_scale_add(ckt.G,ckt.C,ckt.beta0,ckt.alpha0,ckt.matrix)}var p=new Array(3);function interp_coeffs(t,t0,t1,t2){var dtt0=t-t0;var dtt1=t-t1;var dtt2=t-t2;var dt0dt1=t0-t1;var dt0dt2=t0-t2;var dt1dt2=t1-t2;p[0]=dtt1*dtt2/(dt0dt1*dt0dt2);p[1]=dtt0*dtt2/(-dt0dt1*dt1dt2);p[2]=dtt0*dtt1/(dt0dt2*dt1dt2);return p}function pick_step(ckt,step_index){var min_shrink_factor=1/lte_step_decrease_factor;var max_growth_factor=time_step_increase_factor;var N=ckt.N;var p=interp_coeffs(ckt.time,ckt.oldt,ckt.old2t,ckt.old3t);var trapcoeff=.5*(ckt.time-ckt.oldt)/(ckt.time-ckt.old3t);var maxlteratio=0;for(var i=ckt.N-1;i>=0;--i){if(ckt.ltecheck[i]){var pred=p[0]*ckt.oldsol[i]+p[1]*ckt.old2sol[i]+p[2]*ckt.old3sol[i];var lte=Math.abs(ckt.solution[i]-pred)*trapcoeff;var lteratio=lte/(lterel*(ckt.abstol[i]+reltol*ckt.soln_max[i]));maxlteratio=Math.max(maxlteratio,lteratio)}}var new_step;var lte_step_ratio=1/Math.pow(maxlteratio,1/3);if(lte_step_ratio<1){lte_step_ratio=Math.max(lte_step_ratio,min_shrink_factor);new_step=(ckt.time-ckt.oldt)*.75*lte_step_ratio;new_step=Math.max(new_step,ckt.min_step)}else{lte_step_ratio=Math.min(lte_step_ratio,max_growth_factor);if(lte_step_ratio>1.2)new_step=(ckt.time-ckt.oldt)*lte_step_ratio/1.2;else new_step=ckt.time-ckt.oldt;new_step=Math.min(new_step,ckt.max_step)}return new_step}no_dc=false;if(this.diddc==false&&no_dc==false){if(this.dc()==undefined){alert("DC failed, trying transient analysis from zero.");this.finalized=false;if(this.finalize()==false)return undefined}}else{if(this.finalize()==false)return undefined}var N=this.N;var response=new Array(N+1);for(var i=N;i>=0;--i)response[i]=[];this.old3sol=new Array(this.N);this.old3q=new Array(this.N);this.old2sol=new Array(this.N);this.old2q=new Array(this.N);this.oldsol=new Array(this.N);this.oldq=new Array(this.N);this.q=new Array(this.N);this.oldc=new Array(this.N);this.c=new Array(this.N);this.alpha0=1;this.alpha1=0;this.alpha2=0;this.beta0=new Array(this.N);this.beta1=new Array(this.N);this.ar=this.algebraic(this.C);this.ltecheck=new Array(this.N);for(var i=N;i>=0;--i)this.ltecheck[i]=this.ar[i]==0;for(var name in this.node_map){var index=this.node_map[name];for(var i=probenames.length;i>=0;--i){if(name==probenames[i]){this.ltecheck[index]=true;break}}}var period=tstop-tstart;for(var i=this.voltage_sources.length-1;i>=0;--i){var per=this.voltage_sources[i].src.period;if(per>0)period=Math.min(period,per)}for(var i=this.current_sources.length-1;i>=0;--i){var per=this.current_sources[i].src.period;if(per>0)period=Math.min(period,per)}this.periods=Math.ceil((tstop-tstart)/period);this.time=tstart;this.max_step=(tstop-tstart)/(this.periods*ntpts);this.min_step=this.max_step/1e8;var new_step=this.max_step/1e6;this.oldt=this.time-new_step;load_tran(this,this.solution,this.rhs);for(var i=N-1;i>=0;--i){this.old3sol[i]=this.solution[i];this.old2sol[i]=this.solution[i];this.oldsol[i]=this.solution[i];this.old3q[i]=this.q[i];this.old2q[i]=this.q[i];this.oldq[i]=this.q[i];this.oldc[i]=this.c[i]}var beta0,beta1;var max_nsteps=this.periods*5e4;for(var step_index=-3;step_index<max_nsteps;step_index++){for(var i=this.N-1;i>=0;--i){if(step_index>=0)response[i].push(this.solution[i]);this.oldc[i]=this.c[i];this.old3sol[i]=this.old2sol[i];this.old2sol[i]=this.oldsol[i];this.oldsol[i]=this.solution[i];this.old3q[i]=this.oldq[i];this.old2q[i]=this.oldq[i];this.oldq[i]=this.q[i]}if(step_index<0){this.old3t=this.old2t-(this.oldt-this.old2t);this.old2t=this.oldt-(tstart-this.oldt);this.oldt=tstart-(this.time-this.oldt);this.time=tstart;beta0=1;beta1=0}else{response[this.N].push(this.time);this.old3t=this.old2t;this.old2t=this.oldt;this.oldt=this.time;if(this.time>=tstop)break;else if(this.time+new_step>tstop)this.time=tstop;else if(this.time+1.5*new_step>tstop)this.time+=2/3*(tstop-this.time);else this.time+=new_step;beta0=.5;beta1=.5}for(var i=this.N-1;i>=0;--i){this.beta0[i]=beta0+this.ar[i]*beta1;this.beta1[i]=(1-this.ar[i])*beta1}while(true){this.alpha0=1/(this.time-this.oldt);this.alpha1=-this.alpha0;this.alpha2=0;if(this.time-this.oldt<1e-4*tstop){for(var i=this.N-1;i>=0;--i){this.beta0[i]=1;this.beta1[i]=0}}var iterations=this.find_solution(load_tran,max_tran_iters);if(iterations!=undefined&&(step_index<=0||this.time-this.oldt<(1+reltol)*this.min_step)){if(step_index>0)new_step=time_step_increase_factor*this.min_step;break}else if(iterations==undefined){this.time=this.oldt+(this.time-this.oldt)/nr_step_decrease_factor}else{new_step=pick_step(this,step_index);if(new_step<(1-reltol)*(this.time-this.oldt)){this.time=this.oldt+new_step}else break}}}var result=[];for(var name in this.node_map){var index=this.node_map[name];result[name]=index==-1?0:response[index]}for(var i=this.voltage_sources.length-1;i>=0;--i){var v=this.voltage_sources[i];result["I("+v.name+")"]=response[v.branch]}result["_time_"]=response[this.N];return result};Circuit.prototype.ac=function(npts,fstart,fstop,source_name){if(this.dc()==undefined){return undefined}var N=this.N;var G=this.G;var C=this.C;var matrixac=mat_make(2*N,2*N+1);if(this.device_map[source_name]===undefined){alert("AC analysis refers to unknown source "+source_name);return"AC analysis failed, unknown source"}this.device_map[source_name].load_ac(this,this.rhs);var response=new Array(2*N+1);for(var i=2*N;i>=0;--i)response[i]=[];var delta_f=Math.exp(Math.LN10/npts);var phase_offset=new Array(N);for(var i=N-1;i>=0;--i)phase_offset[i]=0;var f=fstart;fstop*=1.0001;while(f<=fstop){var omega=2*Math.PI*f;response[2*N].push(f);for(var i=N-1;i>=0;--i){matrixac[i][2*N]=this.rhs[i];matrixac[i+N][2*N]=0;for(var j=N-1;j>=0;--j){matrixac[i][j]=G[i][j];matrixac[i+N][j+N]=G[i][j];matrixac[i][j+N]=-omega*C[i][j];matrixac[i+N][j]=omega*C[i][j]}}var solac=mat_solve(matrixac);for(var i=N-1;i>=0;--i){var mag=Math.sqrt(solac[i]*solac[i]+solac[i+N]*solac[i+N]);response[i].push(mag);var phase=180*(Math.atan2(solac[i+N],solac[i])/Math.PI);var phasei=response[i+N];var L=phasei.length;if(L>1){var phase_jump=phase+phase_offset[i]-phasei[L-1];if(phase_jump>90){phase_offset[i]-=360}else if(phase_jump<-90){phase_offset[i]+=360}}response[i+N].push(phase+phase_offset[i])}f*=delta_f}var result=[];for(var name in this.node_map){var index=this.node_map[name];result[name]=index==-1?0:response[index];result[name+"_phase"]=index==-1?0:response[index+N]}result["_frequencies_"]=response[2*N];return result};Circuit.prototype.add_device=function(d,name){this.devices.push(d);d.name=name;if(name){if(this.device_map[name]===undefined)this.device_map[name]=d;else{alert("Warning: two circuit elements share the same name "+name);this.device_map[name]=d}}return d};Circuit.prototype.r=function(n1,n2,v,name){if(typeof v=="string"){v=parse_number(v,undefined);if(v===undefined)return undefined}if(v!=0){var d=new Resistor(n1,n2,v);return this.add_device(d,name)}else return this.v(n1,n2,"0",name)};Circuit.prototype.d=function(n1,n2,area,type,name){if(typeof area=="string"){area=parse_number(area,undefined);if(area===undefined)return undefined}if(area!=0){var d=new Diode(n1,n2,area,type);return this.add_device(d,name)}};Circuit.prototype.c=function(n1,n2,v,name){if(typeof v=="string"){v=parse_number(v,undefined);if(v===undefined)return undefined}var d=new Capacitor(n1,n2,v);return this.add_device(d,name)};Circuit.prototype.l=function(n1,n2,v,name){if(typeof v=="string"){v=parse_number(v,undefined);if(v===undefined)return undefined}var branch=this.node(undefined,T_CURRENT);var d=new Inductor(n1,n2,branch,v);return this.add_device(d,name)};Circuit.prototype.v=function(n1,n2,v,name){var branch=this.node(undefined,T_CURRENT);var d=new VSource(n1,n2,branch,v);this.voltage_sources.push(d);return this.add_device(d,name)};Circuit.prototype.i=function(n1,n2,v,name){var d=new ISource(n1,n2,v);this.current_sources.push(d);return this.add_device(d,name)};Circuit.prototype.opamp=function(np,nn,no,ng,A,name){var ratio;if(typeof A=="string"){ratio=parse_number(A,undefined);if(A===undefined)return undefined}var branch=this.node(undefined,T_CURRENT);var d=new Opamp(np,nn,no,ng,branch,A,name);return this.add_device(d,name)};Circuit.prototype.n=function(d,g,s,ratio,name){if(typeof ratio=="string"){ratio=parse_number(ratio,undefined);if(ratio===undefined)return undefined}var d=new Fet(d,g,s,ratio,name,"n");return this.add_device(d,name)};Circuit.prototype.p=function(d,g,s,ratio,name){if(typeof ratio=="string"){ratio=parse_number(ratio,undefined);if(ratio===undefined)return undefined}var d=new Fet(d,g,s,ratio,name,"p");return this.add_device(d,name)};Circuit.prototype.add_two_terminal=function(i,j,g,M){if(i>=0){M[i][i]+=g;if(j>=0){M[i][j]-=g;M[j][i]-=g;M[j][j]+=g}}else if(j>=0)M[j][j]+=g};Circuit.prototype.get_two_terminal=function(i,j,x){var xi_minus_xj=0;if(i>=0)xi_minus_xj=x[i];if(j>=0)xi_minus_xj-=x[j];return xi_minus_xj};Circuit.prototype.add_conductance_l=function(i,j,g){this.add_two_terminal(i,j,g,this.Gl)};Circuit.prototype.add_conductance=function(i,j,g){this.add_two_terminal(i,j,g,this.G)};Circuit.prototype.add_capacitance=function(i,j,c){this.add_two_terminal(i,j,c,this.C)};Circuit.prototype.add_to_Gl=function(i,j,g){if(i>=0&&j>=0)this.Gl[i][j]+=g};Circuit.prototype.add_to_G=function(i,j,g){if(i>=0&&j>=0)this.G[i][j]+=g};Circuit.prototype.add_to_C=function(i,j,c){if(i>=0&&j>=0)this.C[i][j]+=c};Circuit.prototype.add_to_rhs=function(i,v,rhs){if(i>=0)rhs[i]+=v};function mat_make(N,M){var mat=new Array(N);for(var i=N-1;i>=0;--i){mat[i]=new Array(M);for(var j=M-1;j>=0;--j){mat[i][j]=0}}return mat}function mat_v_mult(M,x,b,scale){var n=M.length;var m=M[0].length;if(n!=b.length||m!=x.length)throw"Rows of M mismatched to b or cols mismatch to x.";for(var i=0;i<n;i++){var temp=0;for(var j=0;j<m;j++)temp+=M[i][j]*x[j];b[i]=scale*temp}}function mat_scale_add(A,B,scalea,scaleb,C){var n=A.length;var m=A[0].length;if(n>B.length||m>B[0].length)throw"Row or columns of A to large for B";if(n>C.length||m>C[0].length)throw"Row or columns of A to large for C";if(typeof scalea=="number"&&typeof scaleb=="number")for(var i=0;i<n;i++)for(var j=0;j<m;j++)C[i][j]=scalea*A[i][j]+scaleb*B[i][j];else if(typeof scaleb=="number"&&scalea instanceof Array)for(var i=0;i<n;i++)for(var j=0;j<m;j++)C[i][j]=scalea[i]*A[i][j]+scaleb*B[i][j];else if(typeof scaleb instanceof Array&&scalea instanceof Array)for(var i=0;i<n;i++)for(var j=0;j<m;j++)C[i][j]=scalea[i]*A[i][j]+scaleb[i]*B[i][j];else throw"scalea and scaleb must be scalars or Arrays"}Circuit.prototype.algebraic=function(M){var Nr=M.length;var Mc=mat_make(Nr,Nr);mat_copy(M,Mc);var R=mat_rank(Mc);var one_if_alg=new Array(Nr);for(var row=0;row<Nr;row++){for(var col=Nr-1;col>=0;--col)Mc[row][col]=0;if(mat_rank(Mc)==R)one_if_alg[row]=1;else{for(var col=Nr-1;col>=0;--col)Mc[row][col]=M[row][col];one_if_alg[row]=0}}return one_if_alg};function mat_copy(src,dest){var n=src.length;var m=src[0].length;if(n>dest.length||m>dest[0].length)throw"Rows or cols > rows or cols of dest";for(var i=0;i<n;i++)for(var j=0;j<m;j++)dest[i][j]=src[i][j]}function mat_copy_transposed(src,dest){var n=src.length;var m=src[0].length;if(n>dest[0].length||m>dest.length)throw"Rows or cols > cols or rows of dest";for(var i=0;i<n;i++)for(var j=0;j<m;j++)dest[j][i]=src[i][j]}function mat_rank(Mo){var Nr=Mo.length;var Nc=Mo[0].length;var temp,i,j;var M=mat_make(Nr,Nc);mat_copy(Mo,M);var max_abs_entry=0;for(var row=Nr-1;row>=0;--row){for(var col=Nr-1;col>=0;--col){if(Math.abs(M[row][col])>max_abs_entry)max_abs_entry=Math.abs(M[row][col])}}var the_rank=0;var start_col=0;for(var row=0;row<Nr;row++){for(var col=start_col;col<Nc;col++){var max_v=Math.abs(M[row][col]);var max_row=row;for(var i=row+1;i<Nr;i++){temp=Math.abs(M[i][col]);if(temp>max_v){max_v=temp;max_row=i}}if(Math.abs(max_v)>eps*max_abs_entry){start_col=col+1;the_rank+=1;temp=M[row];M[row]=M[max_row];M[max_row]=temp;for(var i=row+1;i<Nr;i++){temp=M[i][col]/M[row][col];if(temp!=0)for(var j=col;j<Nc;j++)M[i][j]-=M[row][j]*temp}break}}}return the_rank}function mat_solve_rq(M,rhs){var scale;var Nr=M.length;var Nc=M[0].length;if(rhs!=null){for(var row=Nr-1;row>=0;--row)M[row][Nc-1]=rhs[row]}var mat_scale=0;var max_nonzero_row=Nr-1;for(var row=0;row<Nr;row++){var max_row=row;var maxsumsq=0;for(var rowp=row;rowp<Nr;rowp++){var Mr=M[rowp];var sumsq=0;for(var col=Nc-2;col>=0;--col)sumsq+=Mr[col]*Mr[col];if(row==rowp||sumsq>maxsumsq){max_row=rowp;maxsumsq=sumsq}}if(max_row>row){var temp=M[row];M[row]=M[max_row];M[max_row]=temp}var row_norm=Math.sqrt(maxsumsq);if(row==0)mat_scale=row_norm;if(row_norm>mat_scale*eps)scale=1/row_norm;else{max_nonzero_row=row-1;break}var Mr=M[row];for(var col=Nc-1;col>=0;--col)Mr[col]*=scale;for(var rowp=row+1;rowp<Nr;rowp++){var Mrp=M[rowp];var inner=0;for(var col=Nc-2;col>=0;--col)inner+=Mr[col]*Mrp[col];for(var col=Nc-1;col>=0;--col)Mrp[col]-=inner*Mr[col]}}var x=new Array(Nc-1);for(var col=Nc-2;col>=0;--col)x[col]=0;for(var row=max_nonzero_row;row>=0;--row){Mr=M[row];for(var col=Nc-2;col>=0;--col){x[col]+=Mr[col]*Mr[Nc-1]}}return x}function mat_solve(M,rhs){var N=M.length;var temp,i,j;if(rhs!=null){for(var row=0;row<N;row++)M[row][N]=rhs[row]}for(var col=0;col<N;col++){var max_v=Math.abs(M[col][col]);var max_col=col;for(i=col+1;i<N;i++){temp=Math.abs(M[i][col]);if(temp>max_v){max_v=temp;max_col=i}}if(max_v==0)M[col][col]=eps;else{temp=M[col];M[col]=M[max_col];M[max_col]=temp}for(i=col+1;i<N;i++){temp=M[i][col]/M[col][col];if(temp!=0)for(j=col;j<=N;j++)M[i][j]-=M[col][j]*temp}}var x=new Array(N);for(i=N-1;i>=0;--i){temp=M[i][N];for(j=N-1;j>i;--j)temp-=M[i][j]*x[j];x[i]=temp/M[i][i]}return x}function Device(){}Device.prototype.finalize=function(){};Device.prototype.load_linear=function(ckt){};Device.prototype.load_dc=function(ckt,soln,rhs){};Device.prototype.load_tran=function(ckt,soln){};Device.prototype.load_ac=function(ckt,rhs){};Device.prototype.breakpoint=function(time){return undefined};function ord(ch){return ch.charCodeAt(0)}function parse_number(s,default_v){var slen=s.length;var multiplier=1;var result=0;var index=0;while(index<slen&&s.charAt(index)<=" ")index+=1;if(index==slen)return default_v;if(s.charAt(index)=="-"){multiplier=-1;index+=1}else if(s.charAt(index)=="+")index+=1;var start=index;if(index>=slen)return default_v;else if(s.charAt(index)=="0"){index+=1;if(index>=slen)return 0;if(s.charAt(index)=="x"||s.charAt(index)=="X"){while(true){index+=1;if(index>=slen)break;if(s.charAt(index)>="0"&&s.charAt(index)<="9")result=result*16+ord(s.charAt(index))-ord("0");else if(s.charAt(index)>="A"&&s.charAt(index)<="F")result=result*16+ord(s.charAt(index))-ord("A")+10;else if(s.charAt(index)>="a"&&s.charAt(index)<="f")result=result*16+ord(s.charAt(index))-ord("a")+10;else break}return result*multiplier}else if(s.charAt(index)=="b"||s.charAt(index)=="B"){while(true){index+=1;if(index>=slen)break;if(s.charAt(index)>="0"&&s.charAt(index)<="1")result=result*2+ord(s.charAt(index))-ord("0");else break}return result*multiplier}else if(s.charAt(index)!="."){while(true){if(s.charAt(index)>="0"&&s.charAt(index)<="7")result=result*8+ord(s.charAt(index))-ord("0");else break;index+=1;if(index>=slen)break}return result*multiplier}}while(true){if(s.charAt(index)>="0"&&s.charAt(index)<="9")result=result*10+ord(s.charAt(index))-ord("0");else break;index+=1;if(index>=slen)break}if(index<slen&&s.charAt(index)=="."){while(true){index+=1;if(index>=slen)break;if(s.charAt(index)>="0"&&s.charAt(index)<="9"){result=result*10+ord(s.charAt(index))-ord("0");multiplier*=.1}else break}}if(index==start)return default_v;result*=multiplier;if(index<slen){var scale=s.charAt(index);index+=1;if(scale=="e"||scale=="E"){var exponent=0;multiplier=10;if(index<slen){if(s.charAt(index)=="+")index+=1;else if(s.charAt(index)=="-"){index+=1;multiplier=.1}}while(index<slen){if(s.charAt(index)>="0"&&s.charAt(index)<="9"){exponent=exponent*10+ord(s.charAt(index))-ord("0");index+=1}else break}while(exponent>0){exponent-=1;result*=multiplier}}else if(scale=="t"||scale=="T")result*=1e12;else if(scale=="g"||scale=="G")result*=1e9;else if(scale=="M")result*=1e6;else if(scale=="k"||scale=="K")result*=1e3;else if(scale=="m")result*=.001;else if(scale=="u"||scale=="U")result*=1e-6;else if(scale=="n"||scale=="N")result*=1e-9;else if(scale=="p"||scale=="P")result*=1e-12;else if(scale=="f"||scale=="F")result*=1e-15}return result}Circuit.prototype.parse_number=parse_number;function parse_source(v){var src={};src.period=0;src.value=function(t){return 0};src.inflection_point=function(t){return undefined};var index=v.indexOf("(");var ch;if(index>=0){src.fun=v.slice(0,index);src.args=[];var end=v.indexOf(")",index);if(end==-1)end=v.length;index+=1;while(index<end){ch=v.charAt(index);if(ch<=" "){index++;continue}var arg_end=v.indexOf(",",index);if(arg_end==-1)arg_end=end;src.args.push(parse_number(v.slice(index,arg_end),undefined));index=arg_end+1}}else{src.fun="dc";src.args=[parse_number(v,0)]}if(src.fun=="dc"){var v=arg_value(src.args,0,0);src.args=[v];src.value=function(t){return v}}else if(src.fun=="impulse"){var h=arg_value(src.args,0,1);var w=Math.abs(arg_value(src.args,2,1e-9));
5src.args=[h,w];pwl_source(src,[0,0,w/2,h,w,0],false)}else if(src.fun=="step"){var v1=arg_value(src.args,0,0);var v2=arg_value(src.args,1,1);var td=Math.max(0,arg_value(src.args,2,0));var tr=Math.abs(arg_value(src.args,3,1e-9));src.args=[v1,v2,td,tr];pwl_source(src,[td,v1,td+tr,v2],false)}else if(src.fun=="square"){var v1=arg_value(src.args,0,0);var v2=arg_value(src.args,1,1);var freq=Math.abs(arg_value(src.args,2,1));var duty_cycle=Math.min(100,Math.abs(arg_value(src.args,3,50)));src.args=[v1,v2,freq,duty_cycle];var per=freq==0?Infinity:1/freq;var t_change=.01*per;var t_pw=.01*duty_cycle*.98*per;pwl_source(src,[0,v1,t_change,v2,t_change+t_pw,v2,t_change+t_pw+t_change,v1,per,v1],true)}else if(src.fun=="triangle"){var v1=arg_value(src.args,0,0);var v2=arg_value(src.args,1,1);var freq=Math.abs(arg_value(src.args,2,1));src.args=[v1,v2,freq];var per=freq==0?Infinity:1/freq;pwl_source(src,[0,v1,per/2,v2,per,v1],true)}else if(src.fun=="pwl"||src.fun=="pwl_repeating"){pwl_source(src,src.args,src.fun=="pwl_repeating")}else if(src.fun=="pulse"){var v1=arg_value(src.args,0,0);var v2=arg_value(src.args,1,1);var td=Math.max(0,arg_value(src.args,2,0));var tr=Math.abs(arg_value(src.args,3,1e-9));var tf=Math.abs(arg_value(src.args,4,1e-9));var pw=Math.abs(arg_value(src.args,5,1e9));var per=Math.abs(arg_value(src.args,6,1e9));src.args=[v1,v2,td,tr,tf,pw,per];var t1=td;var t2=t1+tr;var t3=t2+pw;var t4=t3+tf;pwl_source(src,[t1,v1,t2,v2,t3,v2,t4,v1,per,v1],true)}else if(src.fun=="sin"){var voffset=arg_value(src.args,0,0);var va=arg_value(src.args,1,1);var freq=Math.abs(arg_value(src.args,2,1));src.period=1/freq;var td=Math.max(0,arg_value(src.args,3,0));var phase=arg_value(src.args,4,0);src.args=[voffset,va,freq,td,phase];phase/=360;src.value=function(t){if(t<td)return voffset+va*Math.sin(2*Math.PI*phase);else return voffset+va*Math.sin(2*Math.PI*(freq*(t-td)+phase))};src.inflection_point=function(t){if(t<td)return td;else return undefined}}src.dc=src.value(0);return src}function pwl_source(src,tv_pairs,repeat){var nvals=tv_pairs.length;if(repeat)src.period=tv_pairs[nvals-2];if(nvals%2==1)npts-=1;if(nvals<=2){src.value=function(t){return nvals==2?tv_pairs[1]:0};src.inflection_point=function(t){return undefined}}else{src.value=function(t){if(repeat)t=Math.fmod(t,tv_pairs[nvals-2]);var last_t=tv_pairs[0];var last_v=tv_pairs[1];if(t>last_t){var next_t,next_v;for(var i=2;i<nvals;i+=2){next_t=tv_pairs[i];next_v=tv_pairs[i+1];if(next_t>last_t)if(t<next_t)return last_v+(next_v-last_v)*(t-last_t)/(next_t-last_t);last_t=next_t;last_v=next_v}}return last_v};src.inflection_point=function(t){if(repeat)t=Math.fmod(t,tv_pairs[nvals-2]);for(var i=0;i<nvals;i+=2){var next_t=tv_pairs[i];if(t<next_t)return next_t}return undefined}}}function arg_value(args,index,default_v){if(index<args.length){var result=args[index];if(result===undefined)result=default_v;return result}else return default_v}Math.fmod=function(numerator,denominator){var quotient=Math.floor(numerator/denominator);return numerator-quotient*denominator};function VSource(npos,nneg,branch,v){Device.call(this);this.src=parse_source(v);this.npos=npos;this.nneg=nneg;this.branch=branch}VSource.prototype=new Device;VSource.prototype.constructor=VSource;VSource.prototype.load_linear=function(ckt){ckt.add_to_Gl(this.branch,this.npos,1);ckt.add_to_Gl(this.branch,this.nneg,-1);ckt.add_to_Gl(this.npos,this.branch,1);ckt.add_to_Gl(this.nneg,this.branch,-1)};VSource.prototype.load_dc=function(ckt,soln,rhs){ckt.add_to_rhs(this.branch,this.src.dc,rhs)};VSource.prototype.load_tran=function(ckt,soln,rhs,time){ckt.add_to_rhs(this.branch,this.src.value(time),rhs)};VSource.prototype.breakpoint=function(time){return this.src.inflection_point(time)};VSource.prototype.load_ac=function(ckt,rhs){ckt.add_to_rhs(this.branch,1,rhs)};function ISource(npos,nneg,v){Device.call(this);this.src=parse_source(v);this.npos=npos;this.nneg=nneg}ISource.prototype=new Device;ISource.prototype.constructor=ISource;ISource.prototype.load_linear=function(ckt){};ISource.prototype.load_dc=function(ckt,soln,rhs){var is=this.src.dc;ckt.add_to_rhs(this.npos,-is,rhs);ckt.add_to_rhs(this.nneg,is,rhs)};ISource.prototype.load_tran=function(ckt,soln,rhs,time){var is=this.src.value(time);ckt.add_to_rhs(this.npos,-is,rhs);ckt.add_to_rhs(this.nneg,is,rhs)};ISource.prototype.breakpoint=function(time){return this.src.inflection_point(time)};ISource.prototype.load_ac=function(ckt,rhs){ckt.add_to_rhs(this.npos,-1,rhs);ckt.add_to_rhs(this.nneg,1,rhs)};function Resistor(n1,n2,v){Device.call(this);this.n1=n1;this.n2=n2;this.g=1/v}Resistor.prototype=new Device;Resistor.prototype.constructor=Resistor;Resistor.prototype.load_linear=function(ckt){ckt.add_conductance_l(this.n1,this.n2,this.g)};Resistor.prototype.load_dc=function(ckt){};Resistor.prototype.load_tran=function(ckt,soln){};Resistor.prototype.load_ac=function(ckt){};function Diode(n1,n2,v,type){Device.call(this);this.anode=n1;this.cathode=n2;this.area=v;this.type=type;this.is=1e-14;this.ais=this.area*this.is;this.vt=type=="normal"?.0258:1e-4;this.exp_arg_max=50;this.exp_max=Math.exp(this.exp_arg_max)}Diode.prototype=new Device;Diode.prototype.constructor=Diode;Diode.prototype.load_linear=function(ckt){};Diode.prototype.load_dc=function(ckt,soln,rhs){var vd=ckt.get_two_terminal(this.anode,this.cathode,soln);var exp_arg=vd/this.vt;var temp1,temp2;var abs_exp_arg=Math.abs(exp_arg);var d_arg=abs_exp_arg-this.exp_arg_max;if(d_arg>0){var quad=1+d_arg+.5*d_arg*d_arg;temp1=this.exp_max*quad;temp2=this.exp_max*(1+d_arg)}else{temp1=Math.exp(abs_exp_arg);temp2=temp1}if(exp_arg<0){temp1=1/temp1;temp2=temp1*temp2*temp1}var id=this.ais*(temp1-1);var gd=this.ais*(temp2/this.vt);ckt.add_to_rhs(this.anode,-id,rhs);ckt.add_to_rhs(this.cathode,id,rhs);ckt.add_conductance(this.anode,this.cathode,gd)};Diode.prototype.load_tran=function(ckt,soln,rhs,time){this.load_dc(ckt,soln,rhs)};Diode.prototype.load_ac=function(ckt){};function Capacitor(n1,n2,v){Device.call(this);this.n1=n1;this.n2=n2;this.value=v}Capacitor.prototype=new Device;Capacitor.prototype.constructor=Capacitor;Capacitor.prototype.load_linear=function(ckt){ckt.add_capacitance(this.n1,this.n2,this.value)};Capacitor.prototype.load_dc=function(ckt,soln,rhs){};Capacitor.prototype.load_ac=function(ckt){};Capacitor.prototype.load_tran=function(ckt){};function Inductor(n1,n2,branch,v){Device.call(this);this.n1=n1;this.n2=n2;this.branch=branch;this.value=v}Inductor.prototype=new Device;Inductor.prototype.constructor=Inductor;Inductor.prototype.load_linear=function(ckt){ckt.add_to_Gl(this.n1,this.branch,1);ckt.add_to_Gl(this.n2,this.branch,-1);ckt.add_to_Gl(this.branch,this.n1,-1);ckt.add_to_Gl(this.branch,this.n2,1);ckt.add_to_C(this.branch,this.branch,this.value)};Inductor.prototype.load_dc=function(ckt,soln,rhs){};Inductor.prototype.load_ac=function(ckt){};Inductor.prototype.load_tran=function(ckt){};function Opamp(np,nn,no,ng,branch,A,name){Device.call(this);this.np=np;this.nn=nn;this.no=no;this.ng=ng;this.branch=branch;this.gain=A;this.name=name}Opamp.prototype=new Device;Opamp.prototype.constructor=Opamp;Opamp.prototype.load_linear=function(ckt){var invA=1/this.gain;ckt.add_to_Gl(this.no,this.branch,1);ckt.add_to_Gl(this.ng,this.branch,-1);ckt.add_to_Gl(this.branch,this.no,invA);ckt.add_to_Gl(this.branch,this.ng,-invA);ckt.add_to_Gl(this.branch,this.np,-1);ckt.add_to_Gl(this.branch,this.nn,1)};Opamp.prototype.load_dc=function(ckt,soln,rhs){};Opamp.prototype.load_ac=function(ckt){};Opamp.prototype.load_tran=function(ckt){};function Fet(d,g,s,ratio,name,type){Device.call(this);this.d=d;this.g=g;this.s=s;this.name=name;this.ratio=ratio;if(type!="n"&&type!="p"){throw"fet type is not n or p"}this.type_sign=type=="n"?1:-1;this.vt=.5;this.kp=2e-5;this.beta=this.kp*this.ratio;this.lambda=.05}Fet.prototype=new Device;Fet.prototype.constructor=Fet;Fet.prototype.load_linear=function(ckt){};Fet.prototype.load_dc=function(ckt,soln,rhs){var vds=this.type_sign*ckt.get_two_terminal(this.d,this.s,soln);if(vds<0){var temp=this.d;this.d=this.s;this.s=temp;vds=this.type_sign*ckt.get_two_terminal(this.d,this.s,soln)}var vgs=this.type_sign*ckt.get_two_terminal(this.g,this.s,soln);var vgst=vgs-this.vt;with(this){var gmgs,ids,gds;if(vgst>0){if(vgst<vds){gmgs=beta*(1+lambda*vds)*vgst;ids=type_sign*.5*gmgs*vgst;gds=.5*beta*vgst*vgst*lambda}else{gmgs=beta*(1+lambda*vds);ids=type_sign*gmgs*vds*(vgst-.5*vds);gds=gmgs*(vgst-vds)+beta*lambda*vds*(vgst-.5*vds);gmgs*=vds}ckt.add_to_rhs(d,-ids,rhs);ckt.add_to_rhs(s,ids,rhs);ckt.add_conductance(d,s,gds);ckt.add_to_G(s,s,gmgs);ckt.add_to_G(d,s,-gmgs);ckt.add_to_G(d,g,gmgs);ckt.add_to_G(s,g,-gmgs)}}};Fet.prototype.load_tran=function(ckt,soln,rhs){this.load_dc(ckt,soln,rhs)};Fet.prototype.load_ac=function(ckt){};var module={Circuit:Circuit,parse_number:parse_number,parse_source:parse_source};return module}();function update_schematics(){var schematics=$(".schematic");for(var i=0;i<schematics.length;++i)if(schematics[i].getAttribute("loaded")!="true"){try{new schematic.Schematic(schematics[i])}catch(err){var msgdiv=document.createElement("div");msgdiv.style.border="thick solid #FF0000";msgdiv.style.margins="20px";msgdiv.style.padding="20px";var msg=document.createTextNode("Sorry, there a browser error in starting the schematic tool. The tool is known to be compatible with the latest versions of Firefox and Chrome, which we recommend you use.");msgdiv.appendChild(msg);schematics[i].parentNode.insertBefore(msgdiv,schematics[i])}schematics[i].setAttribute("loaded","true")}}window.update_schematics=update_schematics;schematic=function(){var background_style="rgb(220,220,220)";var element_style="rgb(255,255,255)";var thumb_style="rgb(128,128,128)";var normal_style="rgb(0,0,0)";var component_style="rgb(64,64,255)";var selected_style="rgb(64,255,64)";var grid_style="rgb(128,128,128)";var annotation_style="rgb(255,64,64)";var property_size=5;var annotation_size=6;var parts_map={g:[Ground,"Ground connection"],L:[Label,"Node label"],v:[VSource,"Voltage source"],i:[ISource,"Current source"],r:[Resistor,"Resistor"],c:[Capacitor,"Capacitor"],l:[Inductor,"Inductor"],o:[OpAmp,"Op Amp"],d:[Diode,"Diode"],n:[NFet,"NFet"],p:[PFet,"PFet"],s:[Probe,"Voltage Probe"],a:[Ammeter,"Current Probe"]};if(typeof sch_clipboard=="undefined")sch_clipboard=[];function Schematic(input){this.show_grid=true;this.grid=8;this.scale=2;this.origin_x=input.getAttribute("origin_x");if(this.origin_x==undefined)this.origin_x=0;this.origin_y=input.getAttribute("origin_y");if(this.origin_y==undefined)this.origin_y=0;this.cursor_x=0;this.cursor_y=0;this.window_list=[];this.edits_allowed=true;var parts=input.getAttribute("parts");if(parts==undefined||parts=="None"){parts=[];for(var p in parts_map)parts.push(p)}else if(parts==""){this.edits_allowed=false;parts=[]}else parts=parts.split(",");this.parts_bin=[];for(var i=0;i<parts.length;i++){var part=new Part(this);var pm=parts_map[parts[i]];part.set_component(new pm[0](0,0,0),pm[1]);this.parts_bin.push(part)}var analyses=input.getAttribute("analyses");if(analyses==undefined||analyses=="None")analyses=["dc","ac","tran"];else if(analyses=="")analyses=[];else analyses=analyses.split(",");if(parts.length==0&&analyses.length==0)this.diagram_only=true;else this.diagram_only=false;var submit=input.getAttribute("submit_analyses");if(submit&&submit.indexOf("{")!=-1)this.submit_analyses=JSON.parse(submit);else this.submit_analyses=undefined;this.tools=[];this.toolbar=[];if(this.edits_allowed){this.tools["grid"]=this.add_tool(grid_icon,"Grid: toggle grid display",this.toggle_grid);this.enable_tool("grid",true);this.tools["cut"]=this.add_tool(cut_icon,"Cut: move selected components from diagram to the clipboard",this.cut);this.tools["copy"]=this.add_tool(copy_icon,"Copy: copy selected components into the clipboard",this.copy);this.tools["paste"]=this.add_tool(paste_icon,"Paste: copy clipboard into the diagram",this.paste);this.toolbar.push(null)}if(typeof cktsim!="undefined"){if(analyses.indexOf("dc")!=-1){this.tools["dc"]=this.add_tool("DC","DC Analysis",this.dc_analysis);this.enable_tool("dc",true);this.dc_max_iters="1000"}if(analyses.indexOf("ac")!=-1){this.tools["ac"]=this.add_tool("AC","AC Small-Signal Analysis",this.setup_ac_analysis);this.enable_tool("ac",true);this.ac_npts="50";this.ac_fstart="10";this.ac_fstop="1G";this.ac_source_name=undefined}if(analyses.indexOf("tran")!=-1){this.tools["tran"]=this.add_tool("TRAN","Transient Analysis",this.transient_analysis);this.enable_tool("tran",true);this.tran_npts="100";this.tran_tstop="1"}}this.canvas=document.createElement("canvas");this.width=input.getAttribute("width");this.width=parseInt(this.width==undefined?"400":this.width);this.canvas.width=this.width;this.height=input.getAttribute("height");this.height=parseInt(this.height==undefined?"300":this.height);this.canvas.height=this.height;this.sctl_r=16;this.sctl_x=this.sctl_r+8;this.sctl_y=this.sctl_r+8;this.zctl_left=this.sctl_x-8;this.zctl_top=this.sctl_y+this.sctl_r+8;this.bg_image=document.createElement("canvas");this.bg_image.width=this.width;this.bg_image.height=this.height;if(!this.diagram_only){this.canvas.tabIndex=0;this.canvas.style.borderStyle="solid";this.canvas.style.borderWidth="1px";this.canvas.style.borderColor=grid_style;this.canvas.style.outline="none"}this.canvas.schematic=this;if(this.edits_allowed){this.canvas.addEventListener("mousemove",schematic_mouse_move,false);this.canvas.addEventListener("mouseover",schematic_mouse_enter,false);this.canvas.addEventListener("mouseout",schematic_mouse_leave,false);this.canvas.addEventListener("mousedown",schematic_mouse_down,false);this.canvas.addEventListener("mouseup",schematic_mouse_up,false);this.canvas.addEventListener("mousewheel",schematic_mouse_wheel,false);this.canvas.addEventListener("DOMMouseScroll",schematic_mouse_wheel,false);this.canvas.addEventListener("dblclick",schematic_double_click,false);this.canvas.addEventListener("keydown",schematic_key_down,false);this.canvas.addEventListener("keyup",schematic_key_up,false)}if(!this.diagram_only){this.status_div=document.createElement("div");this.status=document.createTextNode("");this.status_div.appendChild(this.status);this.status_div.style.height=status_height+"px"}else this.status_div=undefined;this.connection_points=[];this.components=[];this.dragging=false;this.select_rect=undefined;this.wire=undefined;this.operating_point=undefined;this.dc_results=undefined;this.ac_results=undefined;this.transient_results=undefined;this.ctrlKey=false;this.shiftKey=false;this.altKey=false;this.cmdKey=false;input.schematic=this;this.input=input;var table,tr,td;table=document.createElement("table");table.rules="none";if(!this.diagram_only){table.frame="box";table.style.borderStyle="solid";table.style.borderWidth="2px";table.style.borderColor=normal_style;table.style.backgroundColor=background_style}if(this.toolbar.length>0){tr=document.createElement("tr");table.appendChild(tr);td=document.createElement("td");td.style.verticalAlign="top";td.colSpan=2;tr.appendChild(td);for(var i=0;i<this.toolbar.length;++i){var tool=this.toolbar[i];if(tool!=null)td.appendChild(tool)}}tr=document.createElement("tr");table.appendChild(tr);td=document.createElement("td");tr.appendChild(td);var wrapper=document.createElement("div");td.appendChild(wrapper);wrapper.style.position="relative";wrapper.appendChild(this.canvas);td=document.createElement("td");td.style.verticalAlign="top";tr.appendChild(td);var parts_table=document.createElement("table");td.appendChild(parts_table);parts_table.rules="none";parts_table.frame="void";parts_table.cellPadding="0";parts_table.cellSpacing="0";var parts_per_column=Math.floor(this.height/(part_h+5));for(var i=0;i<parts_per_column;++i){tr=document.createElement("tr");parts_table.appendChild(tr);for(var j=i;j<this.parts_bin.length;j+=parts_per_column){td=document.createElement("td");tr.appendChild(td);td.appendChild(this.parts_bin[j].canvas)}}if(this.status_div!=undefined){tr=document.createElement("tr");table.appendChild(tr);td=document.createElement("td");tr.appendChild(td);td.colSpan=2;td.appendChild(this.status_div)}var toplevel=document.createElement("div");toplevel.onselectstart=function(){return false};toplevel.appendChild(table);this.input.parentNode.insertBefore(toplevel,this.input.nextSibling);this.load_schematic(this.input.getAttribute("value"),this.input.getAttribute("initial_value"));this.zoomall()}var part_w=42;var part_h=42;var status_height=18;Schematic.prototype.add_component=function(new_c){this.components.push(new_c)};Schematic.prototype.remove_component=function(c){var index=this.components.indexOf(c);if(index!=-1)this.components.splice(index,1)};Schematic.prototype.find_connections=function(cp){return this.connection_points[cp.location]};Schematic.prototype.add_connection_point=function(cp){var cplist=this.connection_points[cp.location];if(cplist)cplist.push(cp);else{cplist=[cp];this.connection_points[cp.location]=cplist}return cplist};Schematic.prototype.remove_connection_point=function(cp,old_location){var cplist=this.connection_points[old_location];if(cplist){var index=cplist.indexOf(cp);if(index!=-1){cplist.splice(index,1);if(cplist.length==0)delete this.connection_points[old_location]}}};Schematic.prototype.update_connection_point=function(cp,old_location){this.remove_connection_point(cp,old_location);return this.add_connection_point(cp)};Schematic.prototype.add_wire=function(x1,y1,x2,y2){var new_wire=new Wire(x1,y1,x2,y2);new_wire.add(this);new_wire.move_end();return new_wire};Schematic.prototype.split_wire=function(w,cp){w.remove();this.add_wire(w.x,w.y,cp.x,cp.y);this.add_wire(w.x+w.dx,w.y+w.dy,cp.x,cp.y)};Schematic.prototype.check_wires=function(c){for(var i=0;i<this.components.length;i++){var cc=this.components[i];if(cc!=c){var cp=cc.bisect(c);if(cp){this.split_wire(cc,cp);this.redraw_background()}}}};Schematic.prototype.check_connection_points=function(w){for(var locn in this.connection_points){var cplist=this.connection_points[locn];if(cplist&&w.bisect_cp(cplist[0])){this.split_wire(w,cplist[0]);this.redraw_background();return}}};Schematic.prototype.clean_up_wires=function(){for(var locn in this.connection_points){var cplist=this.connection_points[locn];if(cplist&&cplist.length==2){var c1=cplist[0].parent;var c2=cplist[1].parent;if(c1.type=="w"&&c2.type=="w"){var e1=c1.other_end(cplist[0]);var e2=c2.other_end(cplist[1]);var e3=cplist[0];if(collinear(e1,e2,e3)){c1.remove();c2.remove();this.add_wire(e1.x,e1.y,e2.x,e2.y)}}}}};Schematic.prototype.unselect_all=function(which){this.operating_point=undefined;for(var i=this.components.length-1;i>=0;--i)if(i!=which)this.components[i].set_select(false)};Schematic.prototype.drag_begin=function(){for(var i=this.components.length-1;i>=0;--i){var component=this.components[i];if(component.selected)component.move_begin()}this.drag_x=this.cursor_x;this.drag_y=this.cursor_y;this.dragging=true};Schematic.prototype.drag_end=function(){for(var i=this.components.length-1;i>=0;--i){var component=this.components[i];if(component.selected)component.move_end()}this.dragging=false;this.clean_up_wires();this.redraw_background()};Schematic.prototype.help=function(){window.open("/static/handouts/schematic_tutorial.pdf")};Schematic.prototype.rescale=function(nscale,cx,cy){if(cx==undefined){cx=this.origin_x+this.width/(2*this.scale);cy=this.origin_y+this.height/(2*this.scale)}this.origin_x+=cx*(this.scale-nscale);this.origin_y+=cy*(this.scale-nscale);this.scale=nscale;this.redraw_background()};Schematic.prototype.toggle_grid=function(){this.show_grid=!this.show_grid;this.redraw_background()};var zoom_factor=1.25;var zoom_min=.5;var zoom_max=4;var origin_min=-200;var origin_max=200;Schematic.prototype.zoomin=function(){var nscale=this.scale*zoom_factor;if(nscale<zoom_max){this.origin_x+=this.width/2*(1/this.scale-1/nscale);this.origin_y+=this.height/2*(1/this.scale-1/nscale);this.scale=nscale;this.redraw_background()}};Schematic.prototype.zoomout=function(){var nscale=this.scale/zoom_factor;if(nscale>zoom_min){this.origin_x+=this.width/2*(1/this.scale-1/nscale);this.origin_y+=this.height/2*(1/this.scale-1/nscale);this.scale=nscale;this.redraw_background()}};Schematic.prototype.zoomall=function(){var sch_w=1.5*(this.bbox[2]-this.bbox[0]);var sch_h=1.5*(this.bbox[3]-this.bbox[1]);if(sch_w==0&&sch_h==0){this.origin_x=0;this.origin_y=0;this.scale=2}else{var scale_x=this.width/sch_w;var scale_y=this.height/sch_h;this.scale=Math.pow(zoom_factor,Math.ceil(Math.log(Math.min(scale_x,scale_y))/Math.log(zoom_factor)));if(this.scale<zoom_min)this.scale=zoom_min;else if(this.scale>zoom_max)this.scale=zoom_max;this.origin_x=(this.bbox[2]+this.bbox[0])/2-this.width/(2*this.scale);this.origin_y=(this.bbox[3]+this.bbox[1])/2-this.height/(2*this.scale)}this.redraw_background()};Schematic.prototype.cut=function(){sch_clipboard=[];for(var i=this.components.length-1;i>=0;--i){var c=this.components[i];if(c.selected){c.remove();sch_clipboard.push(c)}}this.redraw()};Schematic.prototype.copy=function(){sch_clipboard=[];for(var i=this.components.length-1;i>=0;--i){var c=this.components[i];if(c.selected)sch_clipboard.push(c.clone(c.x,c.y))}};Schematic.prototype.paste=function(){var left=undefined;var top=undefined;for(var i=sch_clipboard.length-1;i>=0;--i){var c=sch_clipboard[i];left=left?Math.min(left,c.x):c.x;top=top?Math.min(top,c.y):c.y}this.message("cursor "+this.cursor_x+","+this.cursor_y);this.unselect_all(-1);this.redraw_background();for(var i=sch_clipboard.length-1;i>=0;--i){var c=sch_clipboard[i];var new_c=c.clone(this.cursor_x+(c.x-left),this.cursor_y+(c.y-top));new_c.set_select(true);new_c.add(this)}this.redraw()};Schematic.prototype.load_schematic=function(value,initial_value){if(value==undefined||value.indexOf("[")==-1)value=initial_value;if(value&&value.indexOf("[")!=-1){var json=JSON.parse(value);for(var i=json.length-1;i>=0;--i){var c=json[i];if(c[0]=="view"){this.ac_fstart=c[5];this.ac_fstop=c[6];this.ac_source_name=c[7];this.tran_npts=c[8];this.tran_tstop=c[9];this.dc_max_iters=c[10]}else if(c[0]=="w"){this.add_wire(c[1][0],c[1][1],c[1][2],c[1][3])}else if(c[0]=="dc"){this.dc_results=c[1]}else if(c[0]=="transient"){this.transient_results=c[1]}else if(c[0]=="ac"){this.ac_results=c[1]}else{var type=c[0];var coords=c[1];var properties=c[2];var part=new parts_map[type][0](coords[0],coords[1],coords[2]);for(var name in properties)part.properties[name]=properties[name];part.add(this)}}}this.redraw_background()};Schematic.prototype.label_connection_points=function(){for(var i=this.components.length-1;i>=0;--i)this.components[i].clear_labels();for(var i=this.components.length-1;i>=0;--i)this.components[i].add_default_labels();this.next_label=0;for(var i=this.components.length-1;i>=0;--i)this.components[i].label_connections()};Schematic.prototype.get_next_label=function(){this.next_label+=1;return this.next_label.toString()};Schematic.prototype.propagate_label=function(label,location){var cplist=this.connection_points[location];for(var i=cplist.length-1;i>=0;--i)cplist[i].propagate_label(label)};Schematic.prototype.update_value=function(){this.label_connection_points();this.input.value=JSON.stringify(this.json_with_analyses())};Schematic.prototype.json=function(){var json=[];var n=this.components.length;for(var i=0;i<n;i++)json.push(this.components[i].json(i));json.push(["view",this.origin_x,this.origin_y,this.scale,this.ac_npts,this.ac_fstart,this.ac_fstop,this.ac_source_name,this.tran_npts,this.tran_tstop,this.dc_max_iters]);return json};Schematic.prototype.json_with_analyses=function(){var json=this.json();if(this.dc_results!=undefined)json.push(["dc",this.dc_results]);if(this.ac_results!=undefined)json.push(["ac",this.ac_results]);if(this.transient_results!=undefined)json.push(["transient",this.transient_results]);return json};Schematic.prototype.extract_circuit=function(){this.label_connection_points();var netlist=this.json();this.input.value=JSON.stringify(netlist);var ckt=new cktsim.Circuit;if(ckt.load_netlist(netlist))return ckt;else return null};Schematic.prototype.dc_analysis=function(){this.unselect_all(-1);this.redraw_background();var ckt=this.extract_circuit();if(ckt===null)return;this.operating_point=ckt.dc();if(this.operating_point!=undefined){this.dc_results={};for(var i in this.operating_point)this.dc_results[i]=this.operating_point[i];this.redraw()}};Schematic.prototype.find_probes=function(){var result=[];var result=[];for(var i=this.components.length-1;i>=0;--i){var c=this.components[i];var info=c.probe_info();if(info!=undefined)result.push(c.probe_info())}return result};Schematic.prototype.setup_ac_analysis=function(){this.unselect_all(-1);this.redraw_background();var npts_lbl="Number of points/decade";var fstart_lbl="Starting frequency (Hz)";var fstop_lbl="Ending frequency (Hz)";var source_name_lbl="Name of V or I source for ac";if(this.find_probes().length==0){alert("AC Analysis: there are no voltage probes in the diagram!");return}var fields=[];fields[fstart_lbl]=build_input("text",10,this.ac_fstart);fields[fstop_lbl]=build_input("text",10,this.ac_fstop);fields[source_name_lbl]=build_input("text",10,this.ac_source_name);var content=build_table(fields);content.fields=fields;content.sch=this;this.dialog("AC Analysis",content,function(content){var sch=content.sch;sch.ac_fstart=content.fields[fstart_lbl].value;sch.ac_fstop=content.fields[fstop_lbl].value;sch.ac_source_name=content.fields[source_name_lbl].value;sch.ac_analysis(cktsim.parse_number(sch.ac_npts),cktsim.parse_number(sch.ac_fstart),cktsim.parse_number(sch.ac_fstop),sch.ac_source_name)})};Schematic.prototype.ac_analysis=function(npts,fstart,fstop,ac_source_name){var ckt=this.extract_circuit();if(ckt===null)return;var results=ckt.ac(npts,fstart,fstop,ac_source_name);if(typeof results=="string")this.message(results);else{var x_values=results["_frequencies_"];for(var i=x_values.length-1;i>=0;--i)x_values[i]=Math.log(x_values[i])/Math.LN10;if(this.submit_analyses!=undefined){var submit=this.submit_analyses["ac"];if(submit!=undefined){this.ac_results={};for(var j=0;j<submit.length;j++){var flist=submit[j];var node=flist[0];var values=results[node];var fvlist=[];for(var k=1;k<flist.length;k++){var f=flist[k];var v=interpolate(f,x_values,values);fvlist.push([f,v==undefined?"undefined":20*Math.log(v)/Math.LN10])}this.ac_results[node]=fvlist}}}var y_values=[];var z_values=[];var probes=this.find_probes();var probe_maxv=[];var probe_color=[];for(var i=probes.length-1;i>=0;--i){if(probes[i][3]!="voltage")continue;probe_color[i]=probes[i][0];var label=probes[i][1];var v=results[label];probe_maxv[i]=array_max(v)}var all_max=array_max(probe_maxv);if(all_max<1e-16){alert("Zero ac response, -infinity on DB scale.")}else{for(var i=probes.length-1;i>=0;--i){if(probes[i][3]!="voltage")continue;if(probe_maxv[i]/all_max<1e-10){alert("Near zero ac response, remove "+probe_color[i]+" probe");return}}}for(var i=probes.length-1;i>=0;--i){if(probes[i][3]!="voltage")continue;var color=probes[i][0];var label=probes[i][1];var offset=cktsim.parse_number(probes[i][2]);var v=results[label];var v_max=1;for(var j=v.length-1;j>=0;--j)v[j]=20*Math.log(v[j]/v_max)/Math.LN10;y_values.push([color,offset,v]);var v=results[label+"_phase"];z_values.push([color,0,v])}var graph2=this.graph(x_values,"log(Frequency in Hz)",z_values,"degrees");this.window("AC Analysis - Phase",graph2);var graph1=this.graph(x_values,"log(Frequency in Hz)",y_values,"dB");this.window("AC Analysis - Magnitude",graph1,50)}};Schematic.prototype.transient_analysis=function(){this.unselect_all(-1);this.redraw_background();var npts_lbl="Minimum number of timepoints";var tstop_lbl="Stop Time (seconds)";var probes=this.find_probes();if(probes.length==0){alert("Transient Analysis: there are no probes in the diagram!");return}var fields=[];fields[tstop_lbl]=build_input("text",10,this.tran_tstop);var content=build_table(fields);content.fields=fields;content.sch=this;this.dialog("Transient Analysis",content,function(content){var sch=content.sch;var ckt=sch.extract_circuit();if(ckt===null)return;sch.tran_tstop=content.fields[tstop_lbl].value;var probe_list=sch.find_probes();var probe_names=new Array(probe_list.length);for(var i=probe_list.length-1;i>=0;--i)probe_names[i]=probe_list[i][1];var results=ckt.tran(ckt.parse_number(sch.tran_npts),0,ckt.parse_number(sch.tran_tstop),probe_names,false);if(typeof results=="string")sch.message(results);else{if(sch.submit_analyses!=undefined){var submit=sch.submit_analyses["tran"];if(submit!=undefined){sch.transient_results={};var times=results["_time_"];for(var j=0;j<submit.length;j++){var tlist=submit[j];var node=tlist[0];var values=results[node];var tvlist=[];for(var k=1;k<tlist.length;k++){var t=tlist[k];var v=interpolate(t,times,values);tvlist.push([t,v==undefined?"undefined":v])}sch.transient_results[node]=tvlist}}}var x_values=results["_time_"];var x_legend="Time";var v_values=[];var i_values=[];var probes=sch.find_probes();for(var i=probes.length-1;i>=0;--i){var color=probes[i][0];var label=probes[i][1];var offset=cktsim.parse_number(probes[i][2]);var v=results[label];if(v==undefined){alert("The "+color+" probe is connected to node "+'"'+label+'"'+" which is not an actual circuit node")}else if(probes[i][3]=="voltage"){if(color=="x-axis"){x_values=v;x_legend="Voltage"}else v_values.push([color,offset,v])}else{if(color=="x-axis"){x_values=v;x_legend="Current"}else i_values.push([color,offset,v])}}var graph=sch.graph(x_values,x_legend,v_values,"Voltage",i_values,"Current");sch.window("Results of Transient Analysis",graph)}})};function interpolate(t,times,values){if(values==undefined)return undefined;for(var i=0;i<times.length;i++)if(t<times[i]){var t1=i==0?times[0]:times[i-1];var t2=times[i];if(t2==undefined)return undefined;var v1=i==0?values[0]:values[i-1];var v2=values[i];var v=v1;if(t!=t1)v+=(t-t1)*(v2-v1)/(t2-t1);return v}}Schematic.prototype.set_property=function(component_name,property,value){this.unselect_all(-1);for(var i=this.components.length-1;i>=0;--i){var component=this.components[i];if(component.properties["name"]==component_name){component.properties[property]=value.toString();break}}this.redraw_background()};Schematic.prototype.redraw_background=function(){var c=this.bg_image.getContext("2d");c.lineCap="round";c.fillStyle=element_style;c.fillRect(0,0,this.width,this.height);if(!this.diagram_only&&this.show_grid){c.strokeStyle=grid_style;var first_x=this.origin_x;var last_x=first_x+this.width/this.scale;var first_y=this.origin_y;var last_y=first_y+this.height/this.scale;for(var i=this.grid*Math.ceil(first_x/this.grid);i<last_x;i+=this.grid)this.draw_line(c,i,first_y,i,last_y,.1);for(var i=this.grid*Math.ceil(first_y/this.grid);i<last_y;i+=this.grid)this.draw_line(c,first_x,i,last_x,i,.1)}var min_x=Infinity;var max_x=-Infinity;var min_y=Infinity;var max_y=-Infinity;for(var i=this.components.length-1;i>=0;--i){var component=this.components[i];if(!component.selected){component.draw(c);min_x=Math.min(component.bbox[0],min_x);max_x=Math.max(component.bbox[2],max_x);min_y=Math.min(component.bbox[1],min_y);max_y=Math.max(component.bbox[3],max_y)}}this.unsel_bbox=[min_x,min_y,max_x,max_y];this.redraw()};Schematic.prototype.redraw=function(){var c=this.canvas.getContext("2d");c.drawImage(this.bg_image,0,0);var min_x=this.unsel_bbox[0];var max_x=this.unsel_bbox[2];var min_y=this.unsel_bbox[1];var max_y=this.unsel_bbox[3];var selections=false;for(var i=this.components.length-1;i>=0;--i){var component=this.components[i];if(component.selected){component.draw(c);selections=true;min_x=Math.min(component.bbox[0],min_x);max_x=Math.max(component.bbox[2],max_x);min_y=Math.min(component.bbox[1],min_y);max_y=Math.max(component.bbox[3],max_y)}}if(min_x==Infinity)this.bbox=[0,0,0,0];else this.bbox=[min_x,min_y,max_x,max_y];this.enable_tool("cut",selections);this.enable_tool("copy",selections);this.enable_tool("paste",sch_clipboard.length>0);for(var location in this.connection_points){var cplist=this.connection_points[location];cplist[0].draw(c,cplist.length);
6}if(this.wire){var r=this.wire;c.strokeStyle=selected_style;this.draw_line(c,r[0],r[1],r[2],r[3],1)}if(this.select_rect){var r=this.select_rect;c.lineWidth=1;c.strokeStyle=selected_style;c.beginPath();c.moveTo(r[0],r[1]);c.lineTo(r[0],r[3]);c.lineTo(r[2],r[3]);c.lineTo(r[2],r[1]);c.lineTo(r[0],r[1]);c.stroke()}if(this.operating_point){if(typeof this.operating_point=="string")this.message(this.operating_point);else{var temp=[];for(var i in this.operating_point)temp[i]=this.operating_point[i];for(var location in this.connection_points)this.connection_points[location][0].display_voltage(c,temp);for(var i=this.components.length-1;i>=0;--i)this.components[i].display_current(c,temp)}}if(!this.diagram_only){var r=this.sctl_r;var x=this.sctl_x;var y=this.sctl_y;c.fillStyle=element_style;c.beginPath();c.arc(x,y,r,0,2*Math.PI);c.fill();c.strokeStyle=grid_style;c.lineWidth=.5;c.beginPath();c.arc(x,y,r,0,2*Math.PI);c.stroke();c.lineWidth=3;c.beginPath();c.moveTo(x+4,y-r+8);c.lineTo(x,y-r+4);c.lineTo(x-4,y-r+8);c.moveTo(x+r-8,y+4);c.lineTo(x+r-4,y);c.lineTo(x+r-8,y-4);c.moveTo(x+4,y+r-8);c.lineTo(x,y+r-4);c.lineTo(x-4,y+r-8);c.moveTo(x-r+8,y+4);c.lineTo(x-r+4,y);c.lineTo(x-r+8,y-4);c.stroke();x=this.zctl_left;y=this.zctl_top;c.lineWidth=.5;c.fillStyle=element_style;c.fillRect(x,y,16,48);c.strokeStyle=grid_style;c.strokeRect(x,y,16,48);c.lineWidth=1;c.beginPath();c.moveTo(x+4,y+8);c.lineTo(x+12,y+8);c.moveTo(x+8,y+4);c.lineTo(x+8,y+12);c.moveTo(x+4,y+24);c.lineTo(x+12,y+24);c.strokeRect(x+4,y+36,8,8);c.stroke()}};Schematic.prototype.cross_cursor=function(c,x,y){this.draw_line(c,x-this.grid,y,x+this.grid,y,1);this.draw_line(c,x,y-this.grid,x,y+this.grid,1)};Schematic.prototype.moveTo=function(c,x,y){c.moveTo((x-this.origin_x)*this.scale,(y-this.origin_y)*this.scale)};Schematic.prototype.lineTo=function(c,x,y){c.lineTo((x-this.origin_x)*this.scale,(y-this.origin_y)*this.scale)};Schematic.prototype.draw_line=function(c,x1,y1,x2,y2,width){c.lineWidth=width*this.scale;c.beginPath();c.moveTo((x1-this.origin_x)*this.scale,(y1-this.origin_y)*this.scale);c.lineTo((x2-this.origin_x)*this.scale,(y2-this.origin_y)*this.scale);c.stroke()};Schematic.prototype.draw_arc=function(c,x,y,radius,start_radians,end_radians,anticlockwise,width,filled){c.lineWidth=width*this.scale;c.beginPath();c.arc((x-this.origin_x)*this.scale,(y-this.origin_y)*this.scale,radius*this.scale,start_radians,end_radians,anticlockwise);if(filled)c.fill();else c.stroke()};Schematic.prototype.draw_text=function(c,text,x,y,size){c.font=size*this.scale+"pt sans-serif";c.fillText(text,(x-this.origin_x)*this.scale,(y-this.origin_y)*this.scale)};try{if(HTMLCanvasElement)HTMLCanvasElement.prototype.relMouseCoords=function(event){var totalOffsetX=0;var totalOffsetY=0;var currentElement=this;do{totalOffsetX+=currentElement.offsetLeft;totalOffsetY+=currentElement.offsetTop}while(currentElement=currentElement.offsetParent);this.mouse_x=event.pageX-totalOffsetX;this.mouse_y=event.pageY-totalOffsetY;this.page_x=event.pageX;this.page_y=event.pageY}}catch(err){}function schematic_key_down(event){if(!event)event=window.event;var sch=window.event?event.srcElement.schematic:event.target.schematic;var code=event.keyCode;if(code==16)sch.shiftKey=true;else if(code==17)sch.ctrlKey=true;else if(code==18)sch.altKey=true;else if(code==91)sch.cmdKey=true;else if(code==8||code==46){for(var i=sch.components.length-1;i>=0;--i){var component=sch.components[i];if(component.selected)component.remove()}sch.clean_up_wires();sch.redraw_background();event.preventDefault();return false}else if((sch.ctrlKey||sch.cmdKey)&&code==88){sch.cut();event.preventDefault();return false}else if((sch.ctrlKey||sch.cmdKey)&&code==67){sch.copy();event.preventDefault();return false}else if((sch.ctrlKey||sch.cmdKey)&&code==86){sch.paste();event.preventDefault();return false}else if(!sch.ctrlKey&&!sch.altKey&&!sch.cmdKey&&code==82){for(var i=sch.components.length-1;i>=0;--i){var component=sch.components[i];if(component.selected){component.rotate(1);sch.check_wires(component)}}sch.clean_up_wires();sch.redraw_background();event.preventDefault();return false}else return true;sch.redraw();event.preventDefault();return false}function schematic_key_up(event){if(!event)event=window.event;var sch=window.event?event.srcElement.schematic:event.target.schematic;var code=event.keyCode;if(code==16)sch.shiftKey=false;else if(code==17)sch.ctrlKey=false;else if(code==18)sch.altKey=false;else if(code==91)sch.cmdKey=false}function schematic_mouse_enter(event){if(!event)event=window.event;var sch=window.event?event.srcElement.schematic:event.target.schematic;if(sch.new_part){var part=sch.new_part;sch.new_part=undefined;part.select(false);sch.unselect_all(-1);sch.redraw_background();part=part.component.clone(sch.cursor_x,sch.cursor_y);part.add(sch);part.set_select(true);sch.drag_begin()}sch.drawCursor=true;sch.redraw();sch.canvas.focus();return false}function schematic_mouse_leave(event){if(!event)event=window.event;var sch=window.event?event.srcElement.schematic:event.target.schematic;sch.drawCursor=false;sch.redraw();return false}function schematic_mouse_down(event){if(!event)event=window.event;else event.preventDefault();var sch=window.event?event.srcElement.schematic:event.target.schematic;sch.canvas.relMouseCoords(event);var mx=sch.canvas.mouse_x;var my=sch.canvas.mouse_y;var sx=mx-sch.sctl_x;var sy=my-sch.sctl_y;var zx=mx-sch.zctl_left;var zy=my-sch.zctl_top;if(sx*sx+sy*sy<=sch.sctl_r*sch.sctl_r){if(Math.abs(sy)>Math.abs(sx)){var delta=this.height/8;if(sy>0)delta=-delta;var temp=sch.origin_y-delta;if(temp>origin_min*sch.grid&&temp<origin_max*sch.grid)sch.origin_y=temp}else{var delta=this.width/8;if(sx<0)delta=-delta;var temp=sch.origin_x+delta;if(temp>origin_min*sch.grid&&temp<origin_max*sch.grid)sch.origin_x=temp}}else if(zx>=0&&zx<16&&zy>=0&&zy<48){if(zy<16)sch.zoomin();else if(zy<32)sch.zoomout();else sch.zoomall()}else{var x=mx/sch.scale+sch.origin_x;var y=my/sch.scale+sch.origin_y;sch.cursor_x=Math.round(x/sch.grid)*sch.grid;sch.cursor_y=Math.round(y/sch.grid)*sch.grid;var cplist=sch.connection_points[sch.cursor_x+","+sch.cursor_y];if(cplist&&!event.shiftKey){sch.unselect_all(-1);sch.wire=[sch.cursor_x,sch.cursor_y,sch.cursor_x,sch.cursor_y]}else{var which=-1;for(var i=sch.components.length-1;i>=0;--i)if(sch.components[i].select(x,y,event.shiftKey)){if(sch.components[i].selected){sch.drag_begin();which=i}break}var reselect=which!=-1&&sch.components[which].was_previously_selected;if(!event.shiftKey){if(!reselect)sch.unselect_all(which);if(!sch.dragging)sch.select_rect=[sch.canvas.mouse_x,sch.canvas.mouse_y,sch.canvas.mouse_x,sch.canvas.mouse_y]}}}sch.redraw_background();return false}function schematic_mouse_move(event){if(!event)event=window.event;var sch=window.event?event.srcElement.schematic:event.target.schematic;sch.canvas.relMouseCoords(event);var x=sch.canvas.mouse_x/sch.scale+sch.origin_x;var y=sch.canvas.mouse_y/sch.scale+sch.origin_y;sch.cursor_x=Math.round(x/sch.grid)*sch.grid;sch.cursor_y=Math.round(y/sch.grid)*sch.grid;if(sch.wire){sch.wire[2]=sch.cursor_x;sch.wire[3]=sch.cursor_y}else if(sch.dragging){var dx=sch.cursor_x-sch.drag_x;var dy=sch.cursor_y-sch.drag_y;if(dx!=0||dy!=0){sch.drag_x=sch.cursor_x;sch.drag_y=sch.cursor_y;for(var i=sch.components.length-1;i>=0;--i){var component=sch.components[i];if(component.selected)component.move(dx,dy)}}}else if(sch.select_rect){sch.select_rect[2]=sch.canvas.mouse_x;sch.select_rect[3]=sch.canvas.mouse_y}sch.redraw();return false}function schematic_mouse_up(event){if(!event)event=window.event;else event.preventDefault();var sch=window.event?event.srcElement.schematic:event.target.schematic;if(sch.wire){var r=sch.wire;sch.wire=undefined;if(r[0]!=r[2]||r[1]!=r[3]){sch.add_wire(r[0],r[1],r[2],r[3]);sch.clean_up_wires();sch.redraw_background()}else sch.redraw()}if(sch.dragging)sch.drag_end();if(sch.select_rect){var r=sch.select_rect;if(r[0]!=r[2]||r[1]!=r[3]){var s=[r[0]/sch.scale+sch.origin_x,r[1]/sch.scale+sch.origin_y,r[2]/sch.scale+sch.origin_x,r[3]/sch.scale+sch.origin_y];canonicalize(s);if(!event.shiftKey)sch.unselect_all();for(var i=sch.components.length-1;i>=0;--i)sch.components[i].select_rect(s,event.shiftKey)}sch.select_rect=undefined;sch.redraw_background()}return false}function schematic_mouse_wheel(event){if(!event)event=window.event;else event.preventDefault();var sch=window.event?event.srcElement.schematic:event.target.schematic;var delta=0;if(event.wheelDelta)delta=event.wheelDelta;else if(event.detail)delta=-event.detail;if(delta){var nscale=delta>0?sch.scale*zoom_factor:sch.scale/zoom_factor;if(nscale>zoom_min&&nscale<zoom_max){sch.canvas.relMouseCoords(event);var s=1/sch.scale-1/nscale;sch.origin_x+=sch.canvas.mouse_x*s;sch.origin_y+=sch.canvas.mouse_y*s;sch.scale=nscale;sch.redraw_background()}}}function schematic_double_click(event){if(!event)event=window.event;else event.preventDefault();var sch=window.event?event.srcElement.schematic:event.target.schematic;sch.canvas.relMouseCoords(event);var x=sch.canvas.mouse_x/sch.scale+sch.origin_x;var y=sch.canvas.mouse_y/sch.scale+sch.origin_y;sch.cursor_x=Math.round(x/sch.grid)*sch.grid;sch.cursor_y=Math.round(y/sch.grid)*sch.grid;for(var i=sch.components.length-1;i>=0;--i)if(sch.components[i].edit_properties(x,y))break;return false}Schematic.prototype.message=function(message){this.status.nodeValue=message};Schematic.prototype.append_message=function(message){this.status.nodeValue+=" / "+message};Schematic.prototype.dialog=function(title,content,callback){var dialog=document.createElement("div");dialog.sch=this;dialog.content=content;dialog.callback=callback;var plist=content.getElementsByClassName("property");for(var i=plist.length-1;i>=0;--i){var field=plist[i];field.dialog=dialog;field.addEventListener("keypress",dialog_check_for_ENTER,false)}var body=document.createElement("div");content.style.marginBotton="5px";body.appendChild(content);body.style.padding="5px";dialog.appendChild(body);var ok_button=document.createElement("span");ok_button.appendChild(document.createTextNode("OK"));ok_button.dialog=dialog;ok_button.addEventListener("click",dialog_okay,false);ok_button.style.display="inline";ok_button.style.border="1px solid";ok_button.style.padding="5px";ok_button.style.margin="10px";var cancel_button=document.createElement("span");cancel_button.appendChild(document.createTextNode("Cancel"));cancel_button.dialog=dialog;cancel_button.addEventListener("click",dialog_cancel,false);cancel_button.style.display="inline";cancel_button.style.border="1px solid";cancel_button.style.padding="5px";cancel_button.style.margin="10px";var buttons=document.createElement("div");buttons.style.textAlign="center";buttons.appendChild(ok_button);buttons.appendChild(cancel_button);buttons.style.padding="5px";buttons.style.margin="10px";dialog.appendChild(buttons);this.window(title,dialog)};function dialog_cancel(event){if(!event)event=window.event;var dialog=window.event?event.srcElement.dialog:event.target.dialog;window_close(dialog.win)}function dialog_okay(event){if(!event)event=window.event;var dialog=window.event?event.srcElement.dialog:event.target.dialog;window_close(dialog.win);if(dialog.callback)dialog.callback(dialog.content)}function dialog_check_for_ENTER(event){var key=window.event?window.event.keyCode:event.keyCode;if(key==13)dialog_okay(event)}function build_table(a){var tbl=document.createElement("table");for(var i in a){var label=document.createTextNode(i+": ");var col1=document.createElement("td");col1.appendChild(label);var col2=document.createElement("td");col2.appendChild(a[i]);var row=document.createElement("tr");row.appendChild(col1);row.appendChild(col2);row.style.verticalAlign="center";tbl.appendChild(row)}return tbl}function build_input(type,size,value){var input=document.createElement("input");input.type=type;input.size=size;input.className="property";if(value==undefined)input.value="";else input.value=value.toString();return input}function build_select(options,selected){var select=document.createElement("select");for(var i=0;i<options.length;i++){var option=document.createElement("option");option.text=options[i];select.add(option);if(options[i]==selected)select.selectedIndex=i}return select}Schematic.prototype.window=function(title,content,offset){var win=document.createElement("div");win.sch=this;win.content=content;win.drag_x=undefined;win.draw_y=undefined;var head=document.createElement("div");head.style.backgroundColor="black";head.style.color="white";head.style.textAlign="center";head.style.padding="5px";head.appendChild(document.createTextNode(title));head.win=win;win.head=head;var close_button=new Image;close_button.src=close_icon;close_button.style.cssFloat="right";close_button.addEventListener("click",window_close_button,false);close_button.win=win;head.appendChild(close_button);win.appendChild(head);head.addEventListener("mousedown",window_mouse_down,false);win.appendChild(content);content.win=win;if(offset==undefined)offset=0;win.left=this.canvas.mouse_x+offset;win.top=this.canvas.mouse_y+offset;win.style.background="white";win.style.position="absolute";win.style.left=win.left+"px";win.style.top=win.top+"px";win.style.border="2px solid";this.canvas.parentNode.insertBefore(win,this.canvas);bring_to_front(win,true)};function bring_to_front(win,insert){var wlist=win.sch.window_list;var i=wlist.indexOf(win);if(i!=-1)wlist.splice(i,1);if(insert)wlist.push(win);for(i=0;i<wlist.length;i+=1)wlist[i].style.zIndex=1e3+i}function window_close(win){win.parentNode.removeChild(win);bring_to_front(win,false)}function window_close_button(event){if(!event)event=window.event;var src=window.event?event.srcElement:event.target;window_close(src.win)}function window_mouse_down(event){if(!event)event=window.event;var src=window.event?event.srcElement:event.target;var win=src.win;bring_to_front(win,true);document.addEventListener("mousemove",window_mouse_move,false);document.addEventListener("mouseup",window_mouse_up,false);document.tracking_window=win;win.drag_x=event.pageX;win.drag_y=event.pageY;return false}function window_mouse_up(event){var win=document.tracking_window;document.removeEventListener("mousemove",window_mouse_move,false);document.removeEventListener("mouseup",window_mouse_up,false);document.tracking_window=undefined;win.drag_x=undefined;win.drag_y=undefined;return true}function window_mouse_move(event){var win=document.tracking_window;if(win.drag_x){var dx=event.pageX-win.drag_x;var dy=event.pageY-win.drag_y;win.left+=dx;win.top+=dy;win.style.left=win.left+"px";win.style.top=win.top+"px";win.drag_x+=dx;win.drag_y+=dy;return true}}Schematic.prototype.add_tool=function(icon,tip,callback){var tool,child,label,hidden;tool=document.createElement("button");child=document.createElement("img");label=document.createElement("span");hidden=document.createElement("span");tool.style.backgroundImage="none";tool.setAttribute("title",tip);label.innerHTML=tip;label.classList.add("sr");hidden.setAttribute("aria-hidden","true");if(icon.search("data:image")!=-1){child.setAttribute("src",icon);child.setAttribute("alt","");tool.appendChild(child)}else{tool.style.font="small-caps small sans-serif";hidden.innerHTML=icon;tool.appendChild(hidden);tool.appendChild(label)}tool.style.height="32px";tool.style.width="auto";tool.style.verticalAlign="top";tool.addEventListener("mouseover",tool_enter,false);tool.addEventListener("mouseout",tool_leave,false);tool.addEventListener("click",tool_click,false);tool.sch=this;tool.tip=tip;tool.callback=callback;this.toolbar.push(tool);tool.enabled=false;return tool};Schematic.prototype.enable_tool=function(tname,which){var tool=this.tools[tname];if(tool!=undefined){tool.removeAttribute("disabled");tool.enabled=which;if(!which){tool.sch.message("");tool.setAttribute("disabled","true")}}};function tool_enter(event){if(!event)event=window.event;var tool=event.target;if(event.target.tagName.toLowerCase()=="img"||event.target.tagName.toLowerCase()=="span"){tool=event.target.parentNode}if(tool.enabled){tool.sch.message(tool.tip)}event.stopPropagation()}function tool_leave(event){if(!event)event=window.event;var tool=event.target;if(event.target.tagName.toLowerCase()=="img"||event.target.tagName.toLowerCase()=="span"){tool=event.target.parentNode}if(tool.enabled){tool.sch.message("")}event.stopPropagation()}function tool_click(event){if(!event)event=window.event;var tool=event.target;if(event.target.tagName.toLowerCase()=="img"||event.target.tagName.toLowerCase()=="span"){tool=event.target.parentNode}if(tool.enabled){tool.sch.canvas.relMouseCoords(event);tool.callback.call(tool.sch)}event.stopPropagation()}var help_icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABgFBMVEUARMwAZsz///8AM5kGqP+s1/8AeuARp/8AZ803qPsAXNYAdNwAZcxZuv9auf99xv8AdNoEd9uTzP8AYsgAivQTl/cAj/V9xf8Ad90AeN5PtP8AUMoAj/oRiOgprf84qfwAb9UAifAAdtwAf+UAgOYActgAk/oAie8cqP8AbtQAXtkXof8AatBNuP8AbdMAgukXcOEAXdcAlP0AhuwJmv0prv8YceGCyP8AbtUAZd8elvMAZcsAW9Ucpv8AjfM3sP8AiO4AWdNOuP8AddsPgeIAhOoAbdT///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABH5RCxAAAASHRSTlP//////////////////////////////////////////////////////////////////////////////////////////////wCc7PJgAAAAAWJLR0R/SL9x5QAAAAlwSFlzAAAASAAAAEgARslrPgAAAAl2cEFnAAAAEAAAABAAXMatwwAAAK5JREFUGNM1zwcOwjAMBVAHQ9PFbIG27L333pve/0bEBr5kyf9JkWIIKYLDK3CNcZgUiE0QFIuuu89kBIHIDy5TUOmXSknBsFxDRAXMJ4FIZOeqA41lxQVB+w/1L9RyO+B+fLwJ7q/OOUfd9FvDkQJDmyyuoLqWGtsVBq3RnAHcUlXbNgSEWPY8n570dH2F6h94Sqe3BAdd7xKEKKVTACg4UuL3OMQoB/F3LRGF1w/Arhm2Q9w2ZQAAACV0RVh0Y3JlYXRlLWRhdGUAMjAwOC0xMC0yM1QxMTo1ODozNiswODowMKkTWd4AAAAldEVYdG1vZGlmeS1kYXRlADIwMDgtMTAtMjNUMTE6NTk6NTArMDg6MDC833hpAAAAAElFTkSuQmCC";var cut_icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1QocFh0xaEFkXgAAArRJREFUOMuFk11Ik1EYx59z3nevr9vUfaXbbPgVaHjRVRB0YZRJV0XeZCIRaGmWWKhpgZAElaV9gYgQlBjoEPRKkCS6DAK1MG0zNvJj7zZ1m+51X+92zttNzmFa5+78/w8//s/znIMg5TzrfXIOAN7zPO9tunm7dI/Xz7LspTvNrbpUHadeGIYZu9XYrI1Go8t9/a87Uz0Fq7hw5nS55sWrnk8HAggh/E+HHdfV1lcQQo7t6E97HpeZc82m7ZCIKKUnDgRgjENLS7+AT0tDsVisdCcFy7JThYWF4HF7KKXU8a8EFTabDVZdK6iutr44kUic6nnePVBSUqJAgMHhdAAAWA8E3G299xljvLy4aAc+jUeSJB3X6/TXZAqwvrFGAWCiraXj4YEAAABKaeXCjwV5bc0DjTeaVPFEHIliEObm5iQA6Npb/xegraVjGmM8ZF+00WBwC2s0GhDcgizL8ru2lo7p/wL+pJianZnGTqcD0jkeMt8ORhBCb/arRXuFMaOxl1B6Pb65qSblZTIz+REVGHNAIHQLITRQ6fG07wsYM5k6437/g6MmEyQoRd6tTdkX3h5mZVRVkJ3D8BxHJVkG5/o6KLKyrla63UPJFsbN5hrJ5+sqNhrpwsrKVDASlgJBEdfEaU2UIzqWwTQQEhOO1dUPR/R6EvP5BsfN5t2XOmowCPNFRWSEYe4DAMxYLCGrUpnY8UcYhnzJNQcBAIYxbv+Wn09GDQZhd4ixmF6SJFJFyKMJleqlgmV5hLE9OWmOm1Hz6arJjIy+y5R2gyxTIMSwC+A4Qa1UMl/z8mImna5pXhC8iszMK8mPpNU2fHe5Ng4fOtQwa7HECKUYMA4AADAAANVarc/l95/0SxIbAJA5tfrsRUFI7twqiu7q7GyPNxDI8YfDGl8k4lOoVOetouj+DaDzOgfcNME8AAAAAElFTkSuQmCC";var copy_icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAd0lEQVQ4y9WTsQ7AIAhE7wj//69dHKWLJqSlFOtUFpXA8SAIbBrHaR9yAAA6L2bvGiRvPtltQa+OqMrFPCo1jFhoRytBmXgqUCH5GUEkWCbova8TeBORfBNJVpYIrbVJdwDjY5hjJfk4vFnAzMDxiEqmo/fJAHACspMyA7UYnWgAAAAASUVORK5CYII=";var paste_icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAABZElEQVQ4y6WSMUsDMRiGn6RteoJSENS5oCdFR3+D0MHBciA4uujiVrq0o1NBcBEEFycXRzcnf4GDINTiL7BTr9LeJdfGoaX0ei21+MFHAsn7fG9eAjOqXCwoz/NKgAWs53mlcrGgZt0VE3s7fdhsfgHguttztTHA5+0ZjUaDzdM7HEeRy60C0G7/EASa78cLXNelcPkw1qYnkVprfN/n+6aEUgqlFFJKjDForclms2itYzZigH6/Tz6fp9PpAFC8fp3h/J2rw42P2ksLADkNMMbgOA6O4wzfZW2sAWovrb3janUn4cAYgzGGRWWtRQjRPKpUdmOAKIrGgCiK5gKEGGb/XK9/JhwEQUC32yUMw7nTJ0ExQK/Xw/d9BoPBeMqiigHCMEQIQSqV+pM4AbCAXEKcAGAtKSn/AYCE/UVZpIEVYA1ASkkmkxl/mqfzg5ExG1tP7t8AtoAOwDqwP4pgmd4H1n8B+QWeF/d+HLAAAAAASUVORK5CYII=";var close_icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACOUlEQVR42m2TzWtTQRTF30ysxE9E0VZKaapBa1OJxtRAW7XVGOrCKijFIEqXbgQFwf/BTReia7GUuBEUF5Y2YiMKKn6iKEqRom1DtAsjStGaGX9v3iQ+Y4Z35t6ZOfe8uXdmhFPVDqRSktYvpBzAxphaBQpKqSdalTLYO7fHxnWZL/zBfclkWAbksBBip7cmHEGvDd3raFlVUoOj2Wz+H4H9vT0RGQhMMLHGkxaienduuJV6p0ql5PjdiRlD2rurO0jwM9zWWnG1dPhyWql9ht3T1XmKwEtAaLNVMUT3AFyBsAz7g9lBbBc4+zcb54joTnQIKeRDZjrcvyNQxG9A5Bd2NwIZ+Gn8e2AxmHNFbTbXRWc8FoRcJLjObtDtbjB3DLtALZbws3l8d/0aOOzLZlYktkfX4eS9epuiehlqZ+TRi5cny8zEtuhVVo/7eabW8a2RFdivwlbPbu079uDT129yZYEd7W17oNzCXe4rdFHE2lrd0SRosbX5TXAK5EAd5NPYi9gF0AtGwSIrcN9IRTeFLxB8zp7RPAExMAUxAw7h3wRpdh+SQjzHBm0KZ4xA+8aWRgivzLU16TvuLZsB8UqyjvMYNDOu98rgfEQ8UklmS6hpQCs9ghuwdShfSKF9Ezb/n5x939upT7mKwOamRogqjchlhit9R+XbhGlfeGgn3k/Pjv33mNwWXl8f4sWdJ+Yow9W+JTetYSkDQ5P5wuear7HcNjSs5Upqd60ZLAXfwPSHwpyu5v4BhpTicEl0i9QAAAAASUVORK5CYII=";var grid_icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAMklEQVQ4y2NkYGD4z0ABYGFgYGD4/x/VDEZGRqLFmCixnYGBYRAYwMgwGoijgTgsAhEAq84fH/l+ELYAAAAASUVORK5CYII=";try{if(CanvasRenderingContext2D)CanvasRenderingContext2D.prototype.dashedLineTo=function(fromX,fromY,toX,toY,pattern){var lt=function(a,b){return a<=b};var gt=function(a,b){return a>=b};var capmin=function(a,b){return Math.min(a,b)};var capmax=function(a,b){return Math.max(a,b)};var checkX={thereYet:gt,cap:capmin};var checkY={thereYet:gt,cap:capmin};if(fromY-toY>0){checkY.thereYet=lt;checkY.cap=capmax}if(fromX-toX>0){checkX.thereYet=lt;checkX.cap=capmax}this.moveTo(fromX,fromY);var offsetX=fromX;var offsetY=fromY;var idx=0,dash=true;while(!(checkX.thereYet(offsetX,toX)&&checkY.thereYet(offsetY,toY))){var ang=Math.atan2(toY-fromY,toX-fromX);var len=pattern[idx];offsetX=checkX.cap(toX,offsetX+Math.cos(ang)*len);offsetY=checkY.cap(toY,offsetY+Math.sin(ang)*len);if(dash)this.lineTo(offsetX,offsetY);else this.moveTo(offsetX,offsetY);idx=(idx+1)%pattern.length;dash=!dash}}}catch(err){}function view_limits(vmin,vmax){if(vmin==vmax){if(vmin==0){vmin=-.5;vmax=.5}else{vmin=vmin>0?.9*vmin:1.1*vmin;vmax=vmax>0?1.1*vmax:.9*vmax}}var log_range=Math.log(vmax-vmin)/Math.LN10;var exponent=Math.floor(log_range);var scale=Math.pow(10,-exponent);vmin=Math.floor(scale*vmin)/scale;vmax=Math.ceil(scale*vmax)/scale;return[vmin,vmax,1/scale]}function engineering_notation(n,nplaces,trim){if(n==0)return"0";if(n==undefined)return"undefined";if(trim==undefined)trim=true;var sign=n<0?-1:1;var log10=Math.log(sign*n)/Math.LN10;var exp=Math.floor(log10/3);var mantissa=sign*Math.pow(10,log10-3*exp);var mstring=(mantissa+sign*.5*Math.pow(10,-nplaces)).toString();var mlen=mstring.length;var endindex=mstring.indexOf(".");if(endindex!=-1){if(nplaces>0){endindex+=nplaces+1;if(endindex>mlen)endindex=mlen;if(trim){while(mstring.charAt(endindex-1)=="0")endindex-=1;if(mstring.charAt(endindex-1)==".")endindex-=1}}if(endindex<mlen)mstring=mstring.substring(0,endindex)}switch(exp){case-5:return mstring+"f";case-4:return mstring+"p";case-3:return mstring+"n";case-2:return mstring+"u";case-1:return mstring+"m";case 0:return mstring;case 1:return mstring+"K";case 2:return mstring+"M";case 3:return mstring+"G"}return n.toString()}var grid_pattern=[1,2];var cursor_pattern=[5,5];Schematic.prototype.graph=function(x_values,x_legend,y_values,y_legend,z_values,z_legend){var pwidth=400;var pheight=300;var left_margin=y_values!=undefined&&y_values.length>0?55:25;var top_margin=25;var right_margin=z_values!=undefined&&z_values.length>0?55:25;var bottom_margin=45;var tick_length=5;var w=pwidth+left_margin+right_margin;var h=pheight+top_margin+bottom_margin;var canvas=document.createElement("canvas");canvas.width=w;canvas.height=h;var bg_image=document.createElement("canvas");bg_image.width=w;bg_image.height=h;canvas.bg_image=bg_image;var c=bg_image.getContext("2d");c.fillStyle=background_style;c.fillRect(0,0,w,h);c.fillStyle=element_style;c.fillRect(left_margin,top_margin,pwidth,pheight);var x_min=array_min(x_values);var x_max=array_max(x_values);var x_limits=view_limits(x_min,x_max);x_min=x_limits[0];x_max=x_limits[1];var x_scale=pwidth/(x_max-x_min);function plot_x(x){return(x-x_min)*x_scale+left_margin}c.strokeStyle=grid_style;c.lineWidth=1;c.fillStyle=normal_style;c.font="10pt sans-serif";c.textAlign="center";c.textBaseline="top";var end=top_margin+pheight;for(var x=x_min;x<=x_max;x+=x_limits[2]){var temp=plot_x(x)+.5;c.beginPath();if(x==x_min){c.moveTo(temp,top_margin);c.lineTo(temp,end)}else c.dashedLineTo(temp,top_margin,temp,end,grid_pattern);c.stroke();c.beginPath();c.moveTo(temp,end);c.lineTo(temp,end+tick_length);c.stroke();c.fillText(engineering_notation(x,2),temp,end+tick_length)}if(y_values!=undefined&&y_values.length>0){var y_min=Infinity;var y_max=-Infinity;var plot;for(plot=y_values.length-1;plot>=0;--plot){var values=y_values[plot][2];if(values==undefined)continue;var offset=y_values[plot][1];var temp=array_min(values)+offset;if(temp<y_min)y_min=temp;temp=array_max(values)+offset;if(temp>y_max)y_max=temp}var y_limits=view_limits(y_min,y_max);y_min=y_limits[0];y_max=y_limits[1];var y_scale=pheight/(y_max-y_min);function plot_y(y){return(y_max-y)*y_scale+top_margin}c.textAlign="right";c.textBaseline="middle";for(var y=y_min;y<=y_max;y+=y_limits[2]){if(Math.abs(y/y_max)<.001)y=0;var temp=plot_y(y)+.5;c.beginPath();if(y==y_min){c.moveTo(left_margin,temp);c.lineTo(left_margin+pwidth,temp)}else c.dashedLineTo(left_margin,temp,left_margin+pwidth,temp,grid_pattern);c.stroke();c.beginPath();c.moveTo(left_margin-tick_length,temp);c.lineTo(left_margin,temp);c.stroke();c.fillText(engineering_notation(y,2),left_margin-tick_length-2,temp)}var x,y;var nx,ny;c.lineWidth=3;c.lineCap="round";for(plot=y_values.length-1;plot>=0;--plot){var color=probe_colors_rgb[y_values[plot][0]];if(color==undefined)continue;c.strokeStyle=color;var values=y_values[plot][2];if(values==undefined)continue;var offset=y_values[plot][1];x=plot_x(x_values[0]);y=plot_y(values[0]+offset);c.beginPath();c.moveTo(x,y);for(var i=1;i<x_values.length;i++){nx=plot_x(x_values[i]);ny=plot_y(values[i]+offset);c.lineTo(nx,ny);x=nx;y=ny;if(i%100==99){c.stroke();c.beginPath();c.moveTo(x,y)}}c.stroke()}}if(z_values!=undefined&&z_values.length>0){var z_min=Infinity;var z_max=-Infinity;for(plot=z_values.length-1;plot>=0;--plot){var values=z_values[plot][2];if(values==undefined)continue;var offset=z_values[plot][1];var temp=array_min(values)+offset;if(temp<z_min)z_min=temp;temp=array_max(values)+offset;if(temp>z_max)z_max=temp}var z_limits=view_limits(z_min,z_max);z_min=z_limits[0];z_max=z_limits[1];var z_scale=pheight/(z_max-z_min);function plot_z(z){return(z_max-z)*z_scale+top_margin}c.textAlign="left";c.textBaseline="middle";c.lineWidth=1;c.strokeStyle=normal_style;var tick_length_half=Math.floor(tick_length/2);var tick_delta=tick_length-tick_length_half;for(var z=z_min;z<=z_max;z+=z_limits[2]){if(Math.abs(z/z_max)<.001)z=0;var temp=plot_z(z)+.5;c.beginPath();c.moveTo(left_margin+pwidth-tick_length_half,temp);c.lineTo(left_margin+pwidth+tick_delta,temp);c.stroke();c.fillText(engineering_notation(z,2),left_margin+pwidth+tick_length+2,temp)}var z;var nz;c.lineWidth=3;for(plot=z_values.length-1;plot>=0;--plot){var color=probe_colors_rgb[z_values[plot][0]];if(color==undefined)continue;c.strokeStyle=color;var values=z_values[plot][2];if(values==undefined)continue;var offset=z_values[plot][1];x=plot_x(x_values[0]);z=plot_z(values[0]+offset);c.beginPath();c.moveTo(x,z);for(var i=1;i<x_values.length;i++){nx=plot_x(x_values[i]);nz=plot_z(values[i]+offset);c.lineTo(nx,nz);x=nx;z=nz;if(i%100==99){c.stroke();c.beginPath();c.moveTo(x,z)}}c.stroke()}}c.font="12pt sans-serif";c.textAlign="center";c.textBaseline="bottom";c.fillText(x_legend,left_margin+pwidth/2,h-5);if(y_values!=undefined&&y_values.length>0){c.textBaseline="top";c.save();c.translate(5,top_margin+pheight/2);c.rotate(-Math.PI/2);c.fillText(y_legend,0,0);c.restore()}if(z_values!=undefined&&z_values.length>0){c.textBaseline="bottom";c.save();c.translate(w-5,top_margin+pheight/2);c.rotate(-Math.PI/2);c.fillText(z_legend,0,0);c.restore()}canvas.x_values=x_values;canvas.y_values=y_values;canvas.z_values=z_values;canvas.x_legend=x_legend;canvas.y_legend=y_legend;canvas.z_legend=y_legend;canvas.x_min=x_min;canvas.x_scale=x_scale;canvas.y_min=y_min;canvas.y_scale=y_scale;canvas.z_min=z_min;canvas.z_scale=z_scale;canvas.left_margin=left_margin;canvas.top_margin=top_margin;canvas.pwidth=pwidth;canvas.pheight=pheight;canvas.tick_length=tick_length;canvas.cursor1_x=undefined;canvas.cursor2_x=undefined;canvas.sch=this;canvas.addEventListener("mousemove",graph_mouse_move,false);redraw_plot(canvas);return canvas};function array_max(a){var max=-Infinity;for(var i=a.length-1;i>=0;--i)if(a[i]>max)max=a[i];return max}function array_min(a){var min=Infinity;for(var i=a.length-1;i>=0;--i)if(a[i]<min)min=a[i];return min}function plot_cursor(c,graph,cursor_x,left_margin){var x=graph.left_margin+cursor_x;var end_y=graph.top_margin+graph.pheight+graph.tick_length;c.strokeStyle=grid_style;c.lineWidth=1;c.beginPath();c.dashedLineTo(x,graph.top_margin,x,end_y,cursor_pattern);c.stroke();var graph_x=cursor_x/graph.x_scale+graph.x_min;c.font="10pt sans-serif";c.textAlign="center";c.textBaseline="top";c.fillStyle=background_style;c.fillText("█████",x,end_y);c.fillStyle=normal_style;c.fillText(engineering_notation(graph_x,3,false),x,end_y);var x_values=graph.x_values;var len=x_values.length;var index=0;while(index<len&&graph_x>=x_values[index])index+=1;var x1=index==0?x_values[0]:x_values[index-1];var x2=x_values[index];if(x2!=undefined){c.textAlign="left";var tx=graph.left_margin+left_margin;var ty=graph.top_margin;if(graph.y_values!=undefined){for(var plot=0;plot<graph.y_values.length;plot++){var values=graph.y_values[plot][2];var color=probe_colors_rgb[graph.y_values[plot][0]];if(values==undefined||color==undefined)continue;var y1=index==0?values[0]:values[index-1];var y2=values[index];var y=y1;if(graph_x!=x1)y+=(graph_x-x1)*(y2-y1)/(x2-x1);c.fillStyle=element_style;c.fillText("█████",tx-3,ty);c.fillStyle=color;c.fillText(engineering_notation(y,3,false),tx,ty);ty+=14}}c.textAlign="right";if(graph.z_values!=undefined){var tx=graph.left_margin+graph.pwidth-left_margin;var ty=graph.top_margin;for(var plot=0;plot<graph.z_values.length;plot++){var values=graph.z_values[plot][2];var color=probe_colors_rgb[graph.z_values[plot][0]];if(values==undefined||color==undefined)continue;var z1=index==0?values[0]:values[index-1];var z2=values[index];var z=z1;if(graph_x!=x1)z+=(graph_x-x1)*(z2-z1)/(x2-x1);c.fillStyle=element_style;c.fillText("█████",tx+3,ty);c.fillStyle=color;c.fillText(engineering_notation(z,3,false),tx,ty);ty+=14}}}}function redraw_plot(graph){var c=graph.getContext("2d");c.drawImage(graph.bg_image,0,0);if(graph.cursor1_x!=undefined)plot_cursor(c,graph,graph.cursor1_x,4);if(graph.cursor2_x!=undefined)plot_cursor(c,graph,graph.cursor2_x,30)}function graph_mouse_move(event){if(!event)event=window.event;var g=window.event?event.srcElement:event.target;g.relMouseCoords(event);var gx=g.mouse_x-g.left_margin-3;var gy=g.pheight-(g.mouse_y-g.top_margin)+3;if(gx>=0&&gx<=g.pwidth&&gy>=0&&gy<=g.pheight){g.cursor1_x=gx}else{g.cursor1_x=undefined;g.cursor2_x=undefined}redraw_plot(g)}function Part(sch){this.sch=sch;this.component=undefined;this.selected=false;this.canvas=document.createElement("canvas");this.canvas.style.borderStyle="solid";this.canvas.style.borderWidth="1px";this.canvas.style.borderColor=background_style;this.canvas.style.cursor="default";this.canvas.height=part_w;this.canvas.width=part_h;this.canvas.part=this;this.canvas.addEventListener("mouseover",part_enter,false);this.canvas.addEventListener("mouseout",part_leave,false);this.canvas.addEventListener("mousedown",part_mouse_down,false);this.canvas.addEventListener("mouseup",part_mouse_up,false);
7this.canvas.addEventListener("click",function(){},false)}Part.prototype.set_location=function(left,top){this.canvas.style.left=left+"px";this.canvas.style.top=top+"px"};Part.prototype.right=function(){return this.canvas.offsetLeft+this.canvas.offsetWidth};Part.prototype.bottom=function(){return this.canvas.offsetTop+this.canvas.offsetHeight};Part.prototype.set_component=function(component,tip){component.sch=this;this.component=component;this.tip=tip;var b=component.bounding_box;var dx=b[2]-b[0];var dy=b[3]-b[1];this.scale=.8;this.origin_x=b[0]+dx/2-part_w/(2*this.scale);this.origin_y=b[1]+dy/2-part_h/(2*this.scale);this.redraw()};Part.prototype.redraw=function(part){var c=this.canvas.getContext("2d");c.fillStyle=this.selected?selected_style:background_style;c.fillRect(0,0,part_w,part_h);if(this.component)this.component.draw(c)};Part.prototype.select=function(which){this.selected=which;this.redraw()};Part.prototype.update_connection_point=function(cp,old_location){};Part.prototype.moveTo=function(c,x,y){c.moveTo((x-this.origin_x)*this.scale,(y-this.origin_y)*this.scale)};Part.prototype.lineTo=function(c,x,y){c.lineTo((x-this.origin_x)*this.scale,(y-this.origin_y)*this.scale)};Part.prototype.draw_line=function(c,x1,y1,x2,y2,width){c.lineWidth=width*this.scale;c.beginPath();c.moveTo((x1-this.origin_x)*this.scale,(y1-this.origin_y)*this.scale);c.lineTo((x2-this.origin_x)*this.scale,(y2-this.origin_y)*this.scale);c.stroke()};Part.prototype.draw_arc=function(c,x,y,radius,start_radians,end_radians,anticlockwise,width,filled){c.lineWidth=width*this.scale;c.beginPath();c.arc((x-this.origin_x)*this.scale,(y-this.origin_y)*this.scale,radius*this.scale,start_radians,end_radians,anticlockwise);if(filled)c.fill();else c.stroke()};Part.prototype.draw_text=function(c,text,x,y,size){};function part_enter(event){if(!event)event=window.event;var canvas=window.event?event.srcElement:event.target;var part=canvas.part;canvas.style.borderColor=normal_style;part.sch.message(part.tip+": drag onto diagram to insert");return false}function part_leave(event){if(!event)event=window.event;var canvas=window.event?event.srcElement:event.target;var part=canvas.part;if(typeof part.sch.new_part=="undefined"){}canvas.style.borderColor=background_style;part.sch.message("");return false}function part_mouse_down(event){if(!event)event=window.event;var part=window.event?event.srcElement.part:event.target.part;part.select(true);part.sch.new_part=part;return false}function part_mouse_up(event){if(!event)event=window.event;var part=window.event?event.srcElement.part:event.target.part;part.select(false);part.sch.new_part=undefined;return false}function canonicalize(r){var temp;if(r[0]>r[2]){temp=r[0];r[0]=r[2];r[2]=temp}if(r[1]>r[3]){temp=r[1];r[1]=r[3];r[3]=temp}}function between(x,x1,x2){return x1<=x&&x<=x2}function inside(rect,x,y){return between(x,rect[0],rect[2])&&between(y,rect[1],rect[3])}function intersect(r1,r2){var result=!(r2[0]>r1[2]||r2[2]<r1[0]||r2[1]>r1[3]||r2[3]<r1[1]);return result}function Component(type,x,y,rotation){this.sch=undefined;this.type=type;this.x=x;this.y=y;this.rotation=rotation;this.selected=false;this.properties=[];this.bounding_box=[0,0,0,0];this.bbox=this.bounding_box;this.connections=[]}Component.prototype.json=function(index){this.properties["_json_"]=index;var props={};for(var p in this.properties)props[p]=this.properties[p];var conns=[];for(var i=0;i<this.connections.length;i++)conns.push(this.connections[i].json());var json=[this.type,[this.x,this.y,this.rotation],props,conns];return json};Component.prototype.add_connection=function(offset_x,offset_y){this.connections.push(new ConnectionPoint(this,offset_x,offset_y))};Component.prototype.update_coords=function(){var x=this.x;var y=this.y;var b=this.bounding_box;this.bbox[0]=this.transform_x(b[0],b[1])+x;this.bbox[1]=this.transform_y(b[0],b[1])+y;this.bbox[2]=this.transform_x(b[2],b[3])+x;this.bbox[3]=this.transform_y(b[2],b[3])+y;canonicalize(this.bbox);for(var i=this.connections.length-1;i>=0;--i)this.connections[i].update_location()};Component.prototype.rotate=function(amount){var old_rotation=this.rotation;this.rotation=(this.rotation+amount)%8;this.update_coords()};Component.prototype.move_begin=function(){this.move_x=this.x;this.move_y=this.y};Component.prototype.move=function(dx,dy){this.x+=dx;this.y+=dy;this.update_coords()};Component.prototype.move_end=function(){var dx=this.x-this.move_x;var dy=this.y-this.move_y;if(dx!=0||dy!=0){this.sch.check_wires(this)}};Component.prototype.add=function(sch){this.sch=sch;sch.add_component(this);this.update_coords()};Component.prototype.remove=function(){for(var i=this.connections.length-1;i>=0;--i){var cp=this.connections[i];this.sch.remove_connection_point(cp,cp.location)}this.sch.remove_component(this);this.sch=undefined};Component.prototype.transform_x=function(x,y){var rot=this.rotation;if(rot==0||rot==6)return x;else if(rot==1||rot==5)return-y;else if(rot==2||rot==4)return-x;else return y};Component.prototype.transform_y=function(x,y){var rot=this.rotation;if(rot==1||rot==7)return x;else if(rot==2||rot==6)return-y;else if(rot==3||rot==5)return-x;else return y};Component.prototype.moveTo=function(c,x,y){var nx=this.transform_x(x,y)+this.x;var ny=this.transform_y(x,y)+this.y;this.sch.moveTo(c,nx,ny)};Component.prototype.lineTo=function(c,x,y){var nx=this.transform_x(x,y)+this.x;var ny=this.transform_y(x,y)+this.y;this.sch.lineTo(c,nx,ny)};Component.prototype.draw_line=function(c,x1,y1,x2,y2){c.strokeStyle=this.selected?selected_style:this.type=="w"?normal_style:component_style;var nx1=this.transform_x(x1,y1)+this.x;var ny1=this.transform_y(x1,y1)+this.y;var nx2=this.transform_x(x2,y2)+this.x;var ny2=this.transform_y(x2,y2)+this.y;this.sch.draw_line(c,nx1,ny1,nx2,ny2,1)};Component.prototype.draw_circle=function(c,x,y,radius,filled){if(filled)c.fillStyle=this.selected?selected_style:normal_style;else c.strokeStyle=this.selected?selected_style:this.type=="w"?normal_style:component_style;var nx=this.transform_x(x,y)+this.x;var ny=this.transform_y(x,y)+this.y;this.sch.draw_arc(c,nx,ny,radius,0,2*Math.PI,false,1,filled)};var rot_angle=[0,Math.PI/2,Math.PI,3*Math.PI/2,0,Math.PI/2,Math.PI,3*Math.PI/2];Component.prototype.draw_arc=function(c,x,y,radius,start_radians,end_radians){c.strokeStyle=this.selected?selected_style:this.type=="w"?normal_style:component_style;var nx=this.transform_x(x,y)+this.x;var ny=this.transform_y(x,y)+this.y;this.sch.draw_arc(c,nx,ny,radius,start_radians+rot_angle[this.rotation],end_radians+rot_angle[this.rotation],false,1,false)};Component.prototype.draw=function(c){};var aOrient=[0,1,2,3,4,5,6,7,8,2,5,8,1,4,7,0,3,6,8,7,6,5,4,3,2,1,0,6,3,0,7,4,1,8,5,3,2,1,0,5,4,3,8,7,6,8,5,2,7,4,1,6,3,0,6,7,8,3,4,5,0,1,2,0,3,6,1,4,7,2,5,8];var textAlign=["left","center","right","left","center","right","left","center","right"];var textBaseline=["top","top","top","middle","middle","middle","bottom","bottom","bottom"];Component.prototype.draw_text=function(c,text,x,y,alignment,size,fill){var a=aOrient[this.rotation*9+alignment];c.textAlign=textAlign[a];c.textBaseline=textBaseline[a];if(fill==undefined)c.fillStyle=this.selected?selected_style:normal_style;else c.fillStyle=fill;this.sch.draw_text(c,text,this.transform_x(x,y)+this.x,this.transform_y(x,y)+this.y,size)};Component.prototype.set_select=function(which){if(which!=this.selected){this.selected=which}};Component.prototype.select=function(x,y,shiftKey){this.was_previously_selected=this.selected;if(this.near(x,y)){this.set_select(shiftKey?!this.selected:true);return true}else return false};Component.prototype.select_rect=function(s){this.was_previously_selected=this.selected;if(intersect(this.bbox,s))this.set_select(true)};Component.prototype.bisect=function(c){return null};Component.prototype.near=function(x,y){return inside(this.bbox,x,y)};Component.prototype.edit_properties=function(x,y){if(this.near(x,y)){var fields=[];for(var i in this.properties)if(i.charAt(0)!="_")fields[i]=build_input("text",10,this.properties[i]);var content=build_table(fields);content.fields=fields;content.component=this;this.sch.dialog("Edit Properties",content,function(content){for(var i in content.fields)content.component.properties[i]=content.fields[i].value;content.component.sch.redraw_background()});return true}else return false};Component.prototype.clear_labels=function(){for(var i=this.connections.length-1;i>=0;--i){this.connections[i].clear_label()}};Component.prototype.propagate_label=function(label){};Component.prototype.add_default_labels=function(){};Component.prototype.label_connections=function(){for(var i=this.connections.length-1;i>=0;--i){var cp=this.connections[i];if(!cp.label)cp.propagate_label(this.sch.get_next_label())}};Component.prototype.probe_info=function(){return undefined};Component.prototype.display_current=function(c,vmap){};var connection_point_radius=2;function ConnectionPoint(parent,x,y){this.parent=parent;this.offset_x=x;this.offset_y=y;this.location="";this.update_location();this.label=undefined}ConnectionPoint.prototype.toString=function(){return"<ConnectionPoint ("+this.offset_x+","+this.offset_y+") "+this.parent.toString()+">"};ConnectionPoint.prototype.json=function(){return this.label};ConnectionPoint.prototype.clear_label=function(){this.label=undefined};ConnectionPoint.prototype.propagate_label=function(label){if(this.label===undefined){this.label=label;this.parent.sch.propagate_label(label,this.location);this.parent.propagate_label(label)}else if(this.label!="0"&&label!="0"&&this.label!=label)alert("Node has two conflicting labels: "+this.label+", "+label)};ConnectionPoint.prototype.update_location=function(){var old_location=this.location;var parent=this.parent;var nx=parent.transform_x(this.offset_x,this.offset_y)+parent.x;var ny=parent.transform_y(this.offset_x,this.offset_y)+parent.y;this.x=nx;this.y=ny;this.location=nx+","+ny;if(parent.sch)parent.sch.update_connection_point(this,old_location)};ConnectionPoint.prototype.coincident=function(x,y){return this.x==x&&this.y==y};ConnectionPoint.prototype.draw=function(c,n){if(n!=2)this.parent.draw_circle(c,this.offset_x,this.offset_y,connection_point_radius,n>2)};ConnectionPoint.prototype.draw_x=function(c){this.parent.draw_line(c,this.offset_x-2,this.offset_y-2,this.offset_x+2,this.offset_y+2,grid_style);this.parent.draw_line(c,this.offset_x+2,this.offset_y-2,this.offset_x-2,this.offset_y+2,grid_style)};ConnectionPoint.prototype.display_voltage=function(c,vmap){var v=vmap[this.label];if(v!=undefined){var label=v.toFixed(2)+"V";c.globalAlpha=.85;this.parent.draw_text(c,"███",this.offset_x,this.offset_y,4,annotation_size,element_style);c.globalAlpha=1;this.parent.draw_text(c,label,this.offset_x,this.offset_y,4,annotation_size,annotation_style);delete vmap[this.label]}};function collinear(p1,p2,p3){var area=p1.x*(p2.y-p3.y)+p2.x*(p3.y-p1.y)+p3.x*(p1.y-p2.y);return area==0}var near_distance=2;function Wire(x1,y1,x2,y2){Component.call(this,"w",x1,y1,0);this.dx=x2-x1;this.dy=y2-y1;this.add_connection(0,0);this.add_connection(this.dx,this.dy);var r=[0,0,this.dx,this.dy];canonicalize(r);r[0]-=near_distance;r[1]-=near_distance;r[2]+=near_distance;r[3]+=near_distance;this.bounding_box=r;this.update_coords();this.len=Math.sqrt(this.dx*this.dx+this.dy*this.dy)}Wire.prototype=new Component;Wire.prototype.constructor=Wire;Wire.prototype.toString=function(){return"<Wire ("+this.x+","+this.y+") ("+(this.x+this.dx)+","+(this.y+this.dy)+")>"};Wire.prototype.other_end=function(cp){if(cp==this.connections[0])return this.connections[1];else if(cp==this.connections[1])return this.connections[0];else return undefined};Wire.prototype.json=function(index){var json=["w",[this.x,this.y,this.x+this.dx,this.y+this.dy]];return json};Wire.prototype.draw=function(c){this.draw_line(c,0,0,this.dx,this.dy)};Wire.prototype.clone=function(x,y){return new Wire(x,y,x+this.dx,y+this.dy)};Wire.prototype.near=function(x,y){if(inside(this.bbox,x,y)){var D=Math.abs((x-this.x)*this.dy-(y-this.y)*this.dx)/this.len;if(D<=near_distance)return true}return false};Wire.prototype.select_rect=function(s){this.was_previously_selected=this.selected;if(inside(s,this.x,this.y)||inside(s,this.x+this.dx,this.y+this.dy))this.set_select(true)};Wire.prototype.bisect_cp=function(cp){var x=cp.x;var y=cp.y;if(inside(this.bbox,x,y)){var D=Math.abs((x-this.x)*this.dy-(y-this.y)*this.dx)/this.len;if(D<1&&!this.connections[0].coincident(x,y)&&!this.connections[1].coincident(x,y))return true}return false};Wire.prototype.bisect=function(c){if(c==undefined)return;for(var i=c.connections.length-1;i>=0;--i){var cp=c.connections[i];if(this.bisect_cp(cp))return cp}return null};Wire.prototype.move_end=function(){this.sch.check_wires(this);this.sch.check_connection_points(this)};Wire.prototype.propagate_label=function(label){this.connections[0].propagate_label(label);this.connections[1].propagate_label(label)};Wire.prototype.edit_properties=function(x,y){return false};Wire.prototype.label_connections=function(){};function Ground(x,y,rotation){Component.call(this,"g",x,y,rotation);this.add_connection(0,0);this.bounding_box=[-6,0,6,8];this.update_coords()}Ground.prototype=new Component;Ground.prototype.constructor=Ground;Ground.prototype.toString=function(){return"<Ground ("+this.x+","+this.y+")>"};Ground.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,0,0,0,8);this.draw_line(c,-6,8,6,8)};Ground.prototype.clone=function(x,y){return new Ground(x,y,this.rotation)};Ground.prototype.edit_properties=function(x,y){return false};Ground.prototype.add_default_labels=function(){this.connections[0].propagate_label("0")};function Label(x,y,rotation,label){Component.call(this,"L",x,y,rotation);this.properties["label"]=label?label:"???";this.add_connection(0,0);this.bounding_box=[-2,0,2,8];this.update_coords()}Label.prototype=new Component;Label.prototype.constructor=Label;Label.prototype.toString=function(){return"<Label"+" ("+this.x+","+this.y+")>"};Label.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,0,0,0,8);this.draw_text(c,this.properties["label"],0,9,1,property_size)};Label.prototype.clone=function(x,y){return new Label(x,y,this.rotation,this.properties["label"])};Label.prototype.add_default_labels=function(){this.connections[0].propagate_label(this.properties["label"])};var probe_colors=["red","green","blue","cyan","magenta","yellow","black","x-axis"];var probe_colors_rgb={red:"rgb(255,64,64)",green:"rgb(64,255,64)",blue:"rgb(64,64,255)",cyan:"rgb(64,255,255)",magenta:"rgb(255,64,255)",yellow:"rgb(255,255,64)",black:"rgb(0,0,0)","x-axis":undefined};function Probe(x,y,rotation,color,offset){Component.call(this,"s",x,y,rotation);this.add_connection(0,0);this.properties["color"]=color?color:"cyan";this.properties["offset"]=offset==undefined||offset==""?"0":offset;this.bounding_box=[0,0,27,-21];this.update_coords()}Probe.prototype=new Component;Probe.prototype.constructor=Probe;Probe.prototype.toString=function(){return"<Probe ("+this.x+","+this.y+")>"};Probe.prototype.draw=function(c){this.draw_line(c,0,0,4,-4);this.draw_line(c,2,-6,6,-2);this.draw_line(c,2,-6,17,-21);this.draw_line(c,6,-2,21,-17);this.draw_line(c,17,-21,21,-17);this.draw_arc(c,19,-11,8,3*Math.PI/2,0);var color=probe_colors_rgb[this.properties["color"]];if(color!=undefined){c.fillStyle=color;c.beginPath();this.moveTo(c,2,-6);this.lineTo(c,6,-2);this.lineTo(c,21,-17);this.lineTo(c,17,-21);this.lineTo(c,2,-6);c.fill()}else{this.draw_text(c,this.properties["color"],27,-11,1,property_size)}};Probe.prototype.clone=function(x,y){return new Probe(x,y,this.rotation,this.properties["color"],this.properties["offset"])};Probe.prototype.edit_properties=function(x,y){if(inside(this.bbox,x,y)){var fields=[];fields["Plot color"]=build_select(probe_colors,this.properties["color"]);fields["Plot offset"]=build_input("text",10,this.properties["offset"]);var content=build_table(fields);content.fields=fields;content.component=this;this.sch.dialog("Edit Properties",content,function(content){var color_choice=content.fields["Plot color"];content.component.properties["color"]=probe_colors[color_choice.selectedIndex];content.component.properties["offset"]=content.fields["Plot offset"].value;content.component.sch.redraw_background()});return true}else return false};Probe.prototype.probe_info=function(){var color=this.properties["color"];var offset=this.properties["offset"];if(offset==undefined||offset=="")offset="0";return[color,this.connections[0].label,offset,"voltage"]};function Ammeter(x,y,rotation,color,offset){Component.call(this,"a",x,y,rotation);this.add_connection(0,0);this.add_connection(16,0);this.properties["color"]=color?color:"magenta";this.properties["offset"]=offset==undefined||offset==""?"0":offset;this.bounding_box=[-3,0,16,3];this.update_coords()}Ammeter.prototype=new Component;Ammeter.prototype.constructor=Ammeter;Ammeter.prototype.toString=function(){return"<Ammeter ("+this.x+","+this.y+")>"};Ammeter.prototype.move_end=function(){Component.prototype.move_end.call(this);var e1=this.connections[0].location;var e2=this.connections[1].location;var cplist=this.sch.find_connections(this.connections[0]);for(var i=cplist.length-1;i>=0;--i){var c=cplist[i].parent;if(c.type=="w"){var c_e1=c.connections[0].location;var c_e2=c.connections[1].location;if(e1==c_e1&&c2==c_e2||e1==c_e2&&e2==c_e1){c.remove();break}}}};Ammeter.prototype.draw=function(c){this.draw_line(c,0,0,16,0);c.strokeStyle=probe_colors_rgb[this.properties["color"]];if(c.strokeStyle!=undefined){c.beginPath();this.moveTo(c,6,-3);this.lineTo(c,10,0);this.lineTo(c,6,3);c.stroke()}};Ammeter.prototype.clone=function(x,y){return new Ammeter(x,y,this.rotation,this.properties["color"],this.properties["offset"])};Ammeter.prototype.edit_properties=Probe.prototype.edit_properties;Ammeter.prototype.label=function(){var name=this.properties["name"];var label="I("+(name?name:"_"+this.properties["_json_"])+")";return label};Ammeter.prototype.display_current=function(c,vmap){var label=this.label();var v=vmap[label];if(v!=undefined){var i=engineering_notation(v,2)+"A";this.draw_text(c,i,8,-5,7,annotation_size,annotation_style);delete vmap[label]}};Ammeter.prototype.probe_info=function(){var color=this.properties["color"];var offset=this.properties["offset"];if(offset==undefined||offset=="")offset="0";return[color,this.label(),offset,"current"]};function Resistor(x,y,rotation,name,r){Component.call(this,"r",x,y,rotation);this.properties["name"]=name;this.properties["r"]=r?r:"1";this.add_connection(0,0);this.add_connection(0,48);this.bounding_box=[-5,0,5,48];this.update_coords()}Resistor.prototype=new Component;Resistor.prototype.constructor=Resistor;Resistor.prototype.toString=function(){return"<Resistor "+this.properties["r"]+" ("+this.x+","+this.y+")>"};Resistor.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,0,0,0,12);this.draw_line(c,0,12,4,14);this.draw_line(c,4,14,-4,18);this.draw_line(c,-4,18,4,22);this.draw_line(c,4,22,-4,26);this.draw_line(c,-4,26,4,30);this.draw_line(c,4,30,-4,34);this.draw_line(c,-4,34,0,36);this.draw_line(c,0,36,0,48);if(this.properties["r"])this.draw_text(c,this.properties["r"]+"Ω",5,24,3,property_size);if(this.properties["name"])this.draw_text(c,this.properties["name"],-5,24,5,property_size)};Resistor.prototype.clone=function(x,y){return new Resistor(x,y,this.rotation,this.properties["name"],this.properties["r"])};function Capacitor(x,y,rotation,name,c){Component.call(this,"c",x,y,rotation);this.properties["name"]=name;this.properties["c"]=c?c:"1p";this.add_connection(0,0);this.add_connection(0,48);this.bounding_box=[-8,0,8,48];this.update_coords()}Capacitor.prototype=new Component;Capacitor.prototype.constructor=Capacitor;Capacitor.prototype.toString=function(){return"<Capacitor "+this.properties["r"]+" ("+this.x+","+this.y+")>"};Capacitor.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,0,0,0,22);this.draw_line(c,-8,22,8,22);this.draw_line(c,-8,26,8,26);this.draw_line(c,0,26,0,48);if(this.properties["c"])this.draw_text(c,this.properties["c"]+"F",9,24,3,property_size);if(this.properties["name"])this.draw_text(c,this.properties["name"],-9,24,5,property_size)};Capacitor.prototype.clone=function(x,y){return new Capacitor(x,y,this.rotation,this.properties["name"],this.properties["c"])};function Inductor(x,y,rotation,name,l){Component.call(this,"l",x,y,rotation);this.properties["name"]=name;this.properties["l"]=l?l:"1n";this.add_connection(0,0);this.add_connection(0,48);this.bounding_box=[-4,0,5,48];this.update_coords()}Inductor.prototype=new Component;Inductor.prototype.constructor=Inductor;Inductor.prototype.toString=function(){return"<Inductor "+this.properties["l"]+" ("+this.x+","+this.y+")>"};Inductor.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,0,0,0,14);this.draw_arc(c,0,18,4,6*Math.PI/4,3*Math.PI/4);this.draw_arc(c,0,24,4,5*Math.PI/4,3*Math.PI/4);this.draw_arc(c,0,30,4,5*Math.PI/4,2*Math.PI/4);this.draw_line(c,0,34,0,48);if(this.properties["l"])this.draw_text(c,this.properties["l"]+"H",6,24,3,property_size);if(this.properties["name"])this.draw_text(c,this.properties["name"],-3,24,5,property_size)};Inductor.prototype.clone=function(x,y){return new Inductor(x,y,this.rotation,this.properties["name"],this.properties["l"])};var diode_types=["normal","ideal"];function Diode(x,y,rotation,name,area,type){Component.call(this,"d",x,y,rotation);this.properties["name"]=name;this.properties["area"]=area?area:"1";this.properties["type"]=type?type:"normal";this.add_connection(0,0);this.add_connection(0,48);this.bounding_box=type=="ideal"?[-12,0,12,48]:[-8,0,8,48];this.update_coords()}Diode.prototype=new Component;Diode.prototype.constructor=Diode;Diode.prototype.toString=function(){return"<Diode "+this.properties["area"]+" ("+this.x+","+this.y+")>"};Diode.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,0,0,0,16);this.draw_line(c,-8,16,8,16);this.draw_line(c,-8,16,0,32);this.draw_line(c,8,16,0,32);this.draw_line(c,-8,32,8,32);this.draw_line(c,0,32,0,48);if(this.properties["type"]=="ideal"){this.draw_line(c,-10,12,10,12);this.draw_line(c,-10,12,-10,36);this.draw_line(c,10,12,10,36);this.draw_line(c,-10,36,10,36)}if(this.properties["area"])this.draw_text(c,this.properties["area"],10,24,3,property_size);if(this.properties["name"])this.draw_text(c,this.properties["name"],-10,24,5,property_size)};Diode.prototype.clone=function(x,y){return new Diode(x,y,this.rotation,this.properties["name"],this.properties["area"],this.properties["type"])};Diode.prototype.edit_properties=function(x,y){if(inside(this.bbox,x,y)){var fields=[];fields["name"]=build_input("text",10,this.properties["name"]);fields["area"]=build_input("text",10,this.properties["area"]);fields["type"]=build_select(diode_types,this.properties["type"]);var content=build_table(fields);content.fields=fields;content.component=this;this.sch.dialog("Edit Properties",content,function(content){content.component.properties["name"]=content.fields["name"].value;content.component.properties["area"]=content.fields["area"].value;content.component.properties["type"]=diode_types[content.fields["type"].selectedIndex];content.component.sch.redraw_background()});return true}else return false};function NFet(x,y,rotation,name,w_over_l){Component.call(this,"n",x,y,rotation);this.properties["name"]=name;this.properties["W/L"]=w_over_l?w_over_l:"2";this.add_connection(0,0);this.add_connection(-24,24);this.add_connection(0,48);this.bounding_box=[-24,0,8,48];this.update_coords()}NFet.prototype=new Component;NFet.prototype.constructor=NFet;NFet.prototype.toString=function(){return"<NFet "+this.properties["W/L"]+" ("+this.x+","+this.y+")>"};NFet.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,0,0,0,16);this.draw_line(c,-8,16,0,16);this.draw_line(c,-8,16,-8,32);this.draw_line(c,-8,32,0,32);this.draw_line(c,0,32,0,48);this.draw_line(c,-24,24,-12,24);this.draw_line(c,-12,16,-12,32);var dim=this.properties["W/L"];if(this.properties["name"]){this.draw_text(c,this.properties["name"],2,22,6,property_size);this.draw_text(c,dim,2,26,0,property_size)}else this.draw_text(c,dim,2,24,3,property_size)};NFet.prototype.clone=function(x,y){return new NFet(x,y,this.rotation,this.properties["name"],this.properties["W/L"])};function PFet(x,y,rotation,name,w_over_l){Component.call(this,"p",x,y,rotation);this.properties["name"]=name;this.properties["W/L"]=w_over_l?w_over_l:"2";this.add_connection(0,0);this.add_connection(-24,24);this.add_connection(0,48);this.bounding_box=[-24,0,8,48];this.update_coords()}PFet.prototype=new Component;PFet.prototype.constructor=PFet;PFet.prototype.toString=function(){return"<PFet "+this.properties["W/L"]+" ("+this.x+","+this.y+")>"};PFet.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,0,0,0,16);this.draw_line(c,-8,16,0,16);this.draw_line(c,-8,16,-8,32);this.draw_line(c,-8,32,0,32);this.draw_line(c,0,32,0,48);this.draw_line(c,-24,24,-16,24);this.draw_circle(c,-14,24,2,false);this.draw_line(c,-12,16,-12,32);var dim=this.properties["W/L"];if(this.properties["name"]){this.draw_text(c,this.properties["name"],2,22,6,property_size);this.draw_text(c,dim,2,26,0,property_size)}else this.draw_text(c,dim,2,24,3,property_size)};PFet.prototype.clone=function(x,y){return new PFet(x,y,this.rotation,this.properties["name"],this.properties["W/L"])};function OpAmp(x,y,rotation,name,A){Component.call(this,"o",x,y,rotation);this.properties["name"]=name;this.properties["A"]=A?A:"30000";this.add_connection(0,0);this.add_connection(0,16);this.add_connection(48,8);this.add_connection(24,32);this.bounding_box=[0,-8,48,32];this.update_coords()}OpAmp.prototype=new Component;OpAmp.prototype.constructor=OpAmp;OpAmp.prototype.toString=function(){return"<OpAmp"+this.properties["A"]+" ("+this.x+","+this.y+")>"};OpAmp.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,8,-8,8,24);this.draw_line(c,8,-8,40,8);this.draw_line(c,8,24,40,8);this.draw_line(c,0,0,8,0);this.draw_line(c,0,16,8,16);this.draw_text(c,"gnd",37,18,property_size);this.draw_line(c,40,8,48,8);this.draw_line(c,24,16,24,32);this.draw_line(c,10,0,16,0);this.draw_line(c,13,-3,13,3);this.draw_line(c,10,16,16,16);if(this.properties["name"])this.draw_text(c,this.properties["name"],32,16,0,property_size)};OpAmp.prototype.clone=function(x,y){return new OpAmp(x,y,this.rotation,this.properties["name"],this.properties["A"])};function Source(x,y,rotation,name,type,value){Component.call(this,type,x,y,rotation);this.properties["name"]=name;if(value==undefined)value="dc(1)";this.properties["value"]=value;this.add_connection(0,0);this.add_connection(0,48);this.bounding_box=[-12,0,12,48];this.update_coords();this.content=document.createElement("div")}Source.prototype=new Component;Source.prototype.constructor=Source;Source.prototype.toString=function(){return"<"+this.type+"source "+this.properties["params"]+" ("+this.x+","+this.y+")>"};Source.prototype.draw=function(c){Component.prototype.draw.call(this,c);this.draw_line(c,0,0,0,12);this.draw_circle(c,0,24,12,false);this.draw_line(c,0,36,0,48);if(this.type=="v"){this.draw_line(c,0,15,0,21);this.draw_line(c,-3,18,3,18);this.draw_line(c,-3,30,3,30)}else if(this.type=="i"){this.draw_line(c,0,15,0,32);this.draw_line(c,-3,26,0,32);this.draw_line(c,3,26,0,32)}if(this.properties["name"])this.draw_text(c,this.properties["name"],-13,24,5,property_size);if(this.properties["value"])this.draw_text(c,this.properties["value"],13,24,3,property_size)};var source_functions={dc:["DC value"],impulse:["Height","Width (secs)"],step:["Initial value","Plateau value","Delay until step (secs)","Rise time (secs)"],square:["Initial value","Plateau value","Frequency (Hz)","Duty cycle (%)"],triangle:["Initial value","Plateau value","Frequency (Hz)"],pwl:["Comma-separated list of alternating times and values"],pwl_repeating:["Comma-separated list of alternating times and values"],pulse:["Initial value","Plateau value","Delay until pulse (secs)","Time for first transition (secs)","Time for second transition (secs)","Pulse width (secs)","Period (secs)"],sin:["Offset value","Amplitude","Frequency (Hz)","Delay until sin starts (secs)","Phase offset (degrees)"]};Source.prototype.build_content=function(src){var fields=[];fields["name"]=build_input("text",10,this.properties["name"]);if(src==undefined){fields["value"]=this.properties["value"]}else{var src_types=[];for(var t in source_functions)src_types.push(t);var type_select=build_select(src_types,src.fun);type_select.component=this;type_select.addEventListener("change",source_type_changed,false);fields["type"]=type_select;if(src.fun=="pwl"||src.run=="pwl_repeating"){var v="";var first=true;for(var i=0;i<src.args.length;i++){if(first)first=false;else v+=",";v+=engineering_notation(src.args[i],3);if(i%2==0)v+="s"}fields[source_functions[src.fun][0]]=build_input("text",30,v)}else{var labels=source_functions[src.fun];for(var i=0;i<labels.length;i++){var v=engineering_notation(src.args[i],3);fields[labels[i]]=build_input("text",10,v)}}}var div=this.content;if(div.hasChildNodes())div.removeChild(div.firstChild);div.appendChild(build_table(fields));div.fields=fields;div.component=this;return div};function source_type_changed(event){if(!event)event=window.event;var select=window.event?event.srcElement:event.target;var type=select.options[select.selectedIndex].value;var src=undefined;if(this.src!=undefined&&type==this.src.fun)src=this.src;else if(typeof cktsim!="undefined")src=cktsim.parse_source(type+"()");select.component.build_content(src)}Source.prototype.edit_properties=function(x,y){if(this.near(x,y)){this.src=undefined;if(typeof cktsim!="undefined")this.src=cktsim.parse_source(this.properties["value"]);var content=this.build_content(this.src);this.sch.dialog("Edit Properties",content,function(content){var c=content.component;var fields=content.fields;var first=true;var value="";for(var label in fields){if(label=="name")c.properties["name"]=fields["name"].value;else if(label=="value"){value=fields["value"].value;c.sch.redraw_background();return}else if(label=="type"){var select=fields["type"];value=select.options[select.selectedIndex].value+"("}else{if(first)first=false;else value+=",";value+=fields[label].value}}c.properties["value"]=value+")";c.sch.redraw_background()});return true}else return false};function VSource(x,y,rotation,name,value){Source.call(this,x,y,rotation,name,"v",value);this.type="v"}VSource.prototype=new Component;VSource.prototype.constructor=VSource;VSource.prototype.toString=Source.prototype.toString;VSource.prototype.draw=Source.prototype.draw;VSource.prototype.clone=Source.prototype.clone;VSource.prototype.build_content=Source.prototype.build_content;VSource.prototype.edit_properties=Source.prototype.edit_properties;VSource.prototype.display_current=function(c,vmap){var name=this.properties["name"];var label="I("+(name?name:"_"+this.properties["_json_"])+")";var v=vmap[label];if(v!=undefined){c.globalAlpha=.5;this.draw_text(c,"███",-8,8,4,annotation_size,element_style);c.globalAlpha=1;var i=engineering_notation(v,2)+"A";this.draw_text(c,i,-3,5,5,annotation_size,annotation_style);this.draw_line(c,-3,4,0,8);this.draw_line(c,3,4,0,8);delete vmap[label]}};VSource.prototype.clone=function(x,y){return new VSource(x,y,this.rotation,this.properties["name"],this.properties["value"])};function ISource(x,y,rotation,name,value){Source.call(this,x,y,rotation,name,"i",value);this.type="i"}ISource.prototype=new Component;ISource.prototype.constructor=ISource;ISource.prototype.toString=Source.prototype.toString;ISource.prototype.draw=Source.prototype.draw;ISource.prototype.clone=Source.prototype.clone;ISource.prototype.build_content=Source.prototype.build_content;ISource.prototype.edit_properties=Source.prototype.edit_properties;ISource.prototype.clone=function(x,y){return new ISource(x,y,this.rotation,this.properties["name"],this.properties["value"]);
8};function component_slider(event,ui){var sname=$(this).slider("option","schematic");var cname=$(this).slider("option","component");var pname=$(this).slider("option","property");var suffix=$(this).slider("option","suffix");if(typeof suffix!="string")suffix="";var v=ui.value;$(this).slider("value",v);var choices=$(this).slider("option","choices");if(choices instanceof Array)v=choices[v];$("."+sname).each(function(index,element){element.schematic.set_property(cname,pname,v.toString()+suffix)});var analysis=$(this).slider("option","analysis");if(analysis=="dc")$("."+sname).each(function(index,element){element.schematic.dc_analysis()});return false}var module={Schematic:Schematic,component_slider:component_slider};return module}();(function(define){"use strict";define("video/00_i18n.js",[],function(){return{Play:gettext("Play"),Pause:gettext("Pause"),Mute:gettext("Mute"),Unmute:gettext("Unmute"),"Exit full browser":gettext("Exit full browser"),"Fill browser":gettext("Fill browser"),Speed:gettext("Speed"),Volume:gettext("Volume"),Muted:gettext("Muted"),"Very low":gettext("Very low"),Low:gettext("Low"),Average:gettext("Average"),Loud:gettext("Loud"),"Very loud":gettext("Very loud"),Maximum:gettext("Maximum")}})})(RequireJS.define);(function(define){define("video/00_sjson.js",[],function(){"use strict";var Sjson=function(data){var sjson={start:data.start.concat(),text:data.text.concat()},module={};var getter=function(propertyName){return function(){return sjson[propertyName]}};var getStartTimes=getter("start");var getCaptions=getter("text");var size=function(){return sjson.text.length};function search(time,startTime,endTime){var start=getStartTimes(),max=size()-1,min=0,results,index;if(typeof startTime!=="undefined"&&typeof endTime!=="undefined"){results=filter(startTime,endTime);start=results.start;max=results.captions.length-1}else{start=getStartTimes()}while(min<max){index=Math.ceil((max+min)/2);if(time<start[index]){max=index-1}if(time>=start[index]){min=index}}return min}function filter(start,end){var filteredTimes=[];var filteredCaptions=[];var startTimes=getStartTimes();var captions=getCaptions();if(startTimes.length!==captions.length){console.warn("video caption and start time arrays do not match in length")}if(end===null&&startTimes.length){end=startTimes[startTimes.length-1]}_.filter(startTimes,function(currentStartTime,i){if(currentStartTime>=start&¤tStartTime<=end){filteredTimes.push(currentStartTime);filteredCaptions.push(captions[i])}});return{start:filteredTimes,captions:filteredCaptions}}return{getCaptions:getCaptions,getStartTimes:getStartTimes,getSize:size,filter:filter,search:search}};return Sjson})})(RequireJS.define);(function(define){define("video/00_iterator.js",[],function(){"use strict";var Iterator=function(list){this.list=list;this.index=0;this.size=this.list.length;this.lastIndex=this.list.length-1};Iterator.prototype={_isValid:function(index){return _.isNumber(index)&&index<this.size&&index>=0},next:function(index){if(!this._isValid(index)){index=this.index}this.index=index>=this.lastIndex?0:index+1;return this.list[this.index]},prev:function(index){if(!this._isValid(index)){index=this.index}this.index=index<1?this.lastIndex:index-1;return this.list[this.index]},last:function(){return this.list[this.lastIndex]},first:function(){return this.list[0]},isEnd:function(){return this.index===this.lastIndex}};return Iterator})})(RequireJS.define);(function(requirejs,require,define){define("video/01_initialize.js",["video/03_video_player.js","video/00_i18n.js","moment","underscore"],function(VideoPlayer,i18n,moment,_){var moment=moment||window.moment;var Initialize=function(state,element){_makeFunctionsPublic(state);state.initialize(element).done(function(){if(state.isYoutubeType()){state.parseSpeed()}if(/iP(hone|od)/i.test(state.isTouch[0])){_hideWaitPlaceholder(state);state.el.trigger("initialize",arguments);return false}_initializeModules(state,i18n).done(function(){if(/iPad|Android/i.test(state.isTouch[0])){state.el.on("play",_.once(function(){state.trigger("videoControl.show",null)}))}else{state.trigger("videoControl.show",null)}_hideWaitPlaceholder(state);state.el.trigger("initialize",arguments)})})},methodsDict={bindTo:bindTo,fetchMetadata:fetchMetadata,getCurrentLanguage:getCurrentLanguage,getDuration:getDuration,getPlayerMode:getPlayerMode,getVideoMetadata:getVideoMetadata,initialize:initialize,isHtml5Mode:isHtml5Mode,isFlashMode:isFlashMode,isYoutubeType:isYoutubeType,parseSpeed:parseSpeed,parseYoutubeStreams:parseYoutubeStreams,setPlayerMode:setPlayerMode,setSpeed:setSpeed,speedToString:speedToString,trigger:trigger,youtubeId:youtubeId,loadHtmlPlayer:loadHtmlPlayer,loadYoutubePlayer:loadYoutubePlayer,loadYouTubeIFrameAPI:loadYouTubeIFrameAPI},_youtubeApiDeferred=null,_oldOnYouTubeIframeAPIReady;Initialize.prototype=methodsDict;return Initialize;function _makeFunctionsPublic(state){bindTo(methodsDict,state,state)}function _renderElements(state){var video,onYTApiReady,setupOnYouTubeIframeAPIReady;if(state.videoType==="youtube"){state.youtubeApiAvailable=false;onYTApiReady=function(){console.log("[Video info]: YouTube API is available and is loaded.");if(state.htmlPlayerLoaded){return}console.log("[Video info]: Starting YouTube player.");video=VideoPlayer(state);state.modules.push(video);state.__dfd__.resolve();state.youtubeApiAvailable=true};if(window.YT){if(_youtubeApiDeferred){_youtubeApiDeferred.resolve()}window.YT.ready(onYTApiReady)}else{setupOnYouTubeIframeAPIReady=function(){_oldOnYouTubeIframeAPIReady=window.onYouTubeIframeAPIReady||undefined;window.onYouTubeIframeAPIReady=function(){window.onYouTubeIframeAPIReady.resolve()};window.onYouTubeIframeAPIReady.resolve=_youtubeApiDeferred.resolve;window.onYouTubeIframeAPIReady.done=_youtubeApiDeferred.done;if(_oldOnYouTubeIframeAPIReady){window.onYouTubeIframeAPIReady.done(_oldOnYouTubeIframeAPIReady)}};if(!_youtubeApiDeferred){_youtubeApiDeferred=$.Deferred();setupOnYouTubeIframeAPIReady()}else if(!window.onYouTubeIframeAPIReady||!window.onYouTubeIframeAPIReady.done){setupOnYouTubeIframeAPIReady()}window.onYouTubeIframeAPIReady.done(function(){window.YT.ready(onYTApiReady)})}}else{video=VideoPlayer(state);state.modules.push(video);state.__dfd__.resolve();state.htmlPlayerLoaded=true}}function _waitForYoutubeApi(state){console.log("[Video info]: Starting to wait for YouTube API to load.");window.setTimeout(function(){if(!state.youtubeApiAvailable){console.log("[Video info]: YouTube API is not available.");if(!state.htmlPlayerLoaded){state.loadHtmlPlayer()}}state.el.trigger("youtube_availability",[state.youtubeApiAvailable])},state.config.ytTestTimeout)}function loadYouTubeIFrameAPI(scriptTag){var firstScriptTag=document.getElementsByTagName("script")[0];firstScriptTag.parentNode.insertBefore(scriptTag,firstScriptTag)}function _configureCaptions(state){if(state.config.showCaptions){state.hide_captions=$.cookie("hide_captions")==="true"}else{state.hide_captions=true;$.cookie("hide_captions",state.hide_captions,{expires:3650,path:"/"});state.el.addClass("closed")}}function _parseYouTubeIDs(state){if(state.parseYoutubeStreams(state.config.streams)){state.videoType="youtube";return true}console.log("[Video info]: Youtube Video IDs are incorrect or absent.");return false}function _prepareHTML5Video(state){state.speeds=["0.75","1.0","1.25","1.50"];if(!state.config.sources.length){_hideWaitPlaceholder(state);state.el.find(".video-player div").addClass("hidden");state.el.find(".video-player .video-error").removeClass("is-hidden");return false}state.videoType="html5";if(!_.keys(state.config.transcriptLanguages).length){state.config.showCaptions=false}state.setSpeed(state.speed);return true}function _hideWaitPlaceholder(state){state.el.addClass("is-initialized").find(".spinner").attr({"aria-hidden":"true",tabindex:-1})}function _setConfigurations(state){_configureCaptions(state);state.setPlayerMode(state.config.mode);state.controlState="visible";state.controlHideTimeout=null;state.captionState="invisible";state.captionHideTimeout=null}function _initializeModules(state,i18n){var dfd=$.Deferred(),modulesList=$.map(state.modules,function(module){var options=state.options[module.moduleName]||{};if(_.isFunction(module)){return module(state,i18n,options)}else if($.isPlainObject(module)){return module}});$.when.apply(null,modulesList).done(dfd.resolve);return dfd.promise()}function _getConfiguration(data,storage){var isBoolean=function(value){var regExp=/^true$/i;return regExp.test(value.toString())},extractKeys=[],compatKeys={start:"startTime",end:"endTime"},conversions={showCaptions:isBoolean,autoplay:isBoolean,autohideHtml5:isBoolean,savedVideoPosition:function(value){return storage.getItem("savedVideoPosition",true)||Number(value)||0},speed:function(value){return storage.getItem("speed",true)||value},generalSpeed:function(value){return storage.getItem("general_speed")||value||"1.0"},transcriptLanguage:function(value){return storage.getItem("language")||value||"en"},ytTestTimeout:function(value){value=parseInt(value,10);if(!isFinite(value)){value=1500}return value},startTime:function(value){value=parseInt(value,10);if(!isFinite(value)||value<0){return 0}return value},endTime:function(value){value=parseInt(value,10);if(!isFinite(value)||value===0){return null}return value}},config={};data=_.extend({startTime:0,endTime:null,sub:"",streams:""},data);$.each(data,function(option,value){if($.inArray(option,extractKeys)!==-1){return}if(compatKeys[option]){option=compatKeys[option]}if(conversions[option]){if(_.isFunction(conversions[option])){value=conversions[option].call(this,value)}else{throw new TypeError(option+" is not a function.")}}config[option]=value});return config}function bindTo(methodsDict,obj,context,rewrite){$.each(methodsDict,function(name,method){if(_.isFunction(method)){if(_.isUndefined(rewrite)){rewrite=true}if(_.isUndefined(obj[name])||rewrite){obj[name]=_.bind(method,context)}}})}function loadYoutubePlayer(){if(this.htmlPlayerLoaded){return}console.log("[Video info]: Fetch metadata for YouTube video.");this.fetchMetadata();this.parseSpeed()}function loadHtmlPlayer(){if(!_prepareHTML5Video(this)){console.log("[Video info]: Continue loading "+"YouTube video.");this.el.find(".video-player div").removeClass("hidden");this.el.find(".video-player .video-error").addClass("is-hidden");this.loadYoutubePlayer()}else{console.log("[Video info]: Start HTML5 player.");this.el.find(".quality_control").hide();_renderElements(this)}}function initialize(element){var self=this,el=this.el,id=this.id,container=el.find(".video-wrapper"),__dfd__=$.Deferred(),isTouch=onTouchBasedDevice()||"";if(isTouch){el.addClass("is-touch")}$.extend(this,{__dfd__:__dfd__,container:container,isFullScreen:false,isTouch:isTouch});console.log('[Video info]: Initializing video with id "%s".',id);this.config=$.extend({},_getConfiguration(this.metadata,this.storage),{element:element,fadeOutTimeout:1400,captionsFreezeTime:1e4,mode:$.cookie("edX_video_player_mode"),availableHDQualities:[]});if(this.config.endTime<this.config.startTime){this.config.endTime=null}this.lang=this.config.transcriptLanguage;this.speed=this.speedToString(this.config.speed||this.config.generalSpeed);this.htmlPlayerLoaded=false;_setConfigurations(this);if(!_parseYouTubeIDs(this)){if(!_prepareHTML5Video(this)){__dfd__.reject();return __dfd__.promise()}console.log("[Video info]: Start player in HTML5 mode.");_renderElements(this)}else{_renderElements(this);_waitForYoutubeApi(this);var scriptTag=document.createElement("script");scriptTag.src=this.config.ytApiUrl;scriptTag.async=true;$(scriptTag).on("load",function(){self.loadYoutubePlayer()});$(scriptTag).on("error",function(){console.log("[Video info]: YouTube returned an error for "+'video with id "'+self.id+'".');if(!self.htmlPlayerLoaded){self.loadHtmlPlayer()}});window.Video.loadYouTubeIFrameAPI(scriptTag)}return __dfd__.promise()}function parseYoutubeStreams(youtubeStreams){if(_.isUndefined(youtubeStreams)||!youtubeStreams.length){return false}this.videos={};_.each(youtubeStreams.split(/,/),function(video){var speed;video=video.split(/:/);speed=this.speedToString(video[0]);this.videos[speed]=video[1]},this);return _.isString(this.videos["1.0"])}function fetchMetadata(){var self=this,metadataXHRs=[];this.metadata={};metadataXHRs=_.map(this.videos,function(url,speed){return self.getVideoMetadata(url,function(data){if(data.items.length>0){var metaDataItem=data.items[0];self.metadata[metaDataItem.id]=metaDataItem.contentDetails}})});$.when.apply(this,metadataXHRs).done(function(){self.el.trigger("metadata_received");self.youtubeMetadataReceived=true})}function parseSpeed(){this.speeds=_.keys(this.videos).sort()}function setSpeed(newSpeed){var map={.25:"0.75","0.50":"0.75",.75:"0.50",1.25:"1.50","2.0":"1.50"};if(_.contains(this.speeds,newSpeed)){this.speed=newSpeed}else{newSpeed=map[newSpeed];this.speed=_.contains(this.speeds,newSpeed)?newSpeed:"1.0"}}function getVideoMetadata(url,callback){if(!_.isString(url)){url=this.videos["1.0"]||""}if(this.config.ytKey){return $.ajax({url:[this.config.ytMetadataUrl,"?id=",url,"&part=contentDetails&key=",this.config.ytKey].join(""),timeout:this.config.ytTestTimeout,success:_.isFunction(callback)?callback:null,error:function(){console.warn("YouTube API request failed - usually this means the YouTube API key is invalid. "+"Some video metadata may be unavailable.")},notifyOnError:false})}else{return $.Deferred().reject().promise()}}function youtubeId(speed){var currentSpeed=this.isFlashMode()?this.speed:"1.0";return this.videos[speed]||this.videos[currentSpeed]||this.videos["1.0"]}function getDuration(){try{return moment.duration(this.metadata[this.youtubeId()].duration,moment.ISO_8601).asSeconds()}catch(err){return _.result(this.metadata[this.youtubeId("1.0")],"duration")||0}}function setPlayerMode(mode){var supportedModes=["html5","flash"];mode=_.contains(supportedModes,mode)?mode:"html5";this.currentPlayerMode=mode}function getPlayerMode(){return this.currentPlayerMode}function isFlashMode(){return this.getPlayerMode()==="flash"}function isHtml5Mode(){return this.getPlayerMode()==="html5"}function isYoutubeType(){return this.videoType==="youtube"}function speedToString(speed){return parseFloat(speed).toFixed(2).replace(/\.00$/,".0")}function getCurrentLanguage(){var keys=_.keys(this.config.transcriptLanguages);if(keys.length){if(!_.contains(keys,this.lang)){if(_.contains(keys,"en")){this.lang="en"}else{this.lang=keys.pop()}}}else{return null}return this.lang}function trigger(objChain){var extraParameters=Array.prototype.slice.call(arguments,1),i,tmpObj,chain;tmpObj=this;chain=objChain.split(".");while(chain.length){i=chain.shift();if(tmpObj.hasOwnProperty(i)){tmpObj=tmpObj[i]}else{return false}}tmpObj.apply(this,extraParameters);return true}})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(requirejs,require,define){define("video/025_focus_grabber.js",[],function(){return function(state){var dfd=$.Deferred();state.focusGrabber={};_makeFunctionsPublic(state);_renderElements(state);_bindHandlers(state);dfd.resolve();return dfd.promise()};function _makeFunctionsPublic(state){var methodsDict={disableFocusGrabber:disableFocusGrabber,enableFocusGrabber:enableFocusGrabber,onFocus:onFocus};state.bindTo(methodsDict,state.focusGrabber,state)}function _renderElements(state){state.focusGrabber.elFirst=state.el.find(".focus_grabber.first");state.focusGrabber.elLast=state.el.find(".focus_grabber.last");state.focusGrabber.disableFocusGrabber()}function _bindHandlers(state){state.focusGrabber.elFirst.on("focus",state.focusGrabber.onFocus);state.focusGrabber.elLast.on("focus",state.focusGrabber.onFocus);state.el.on("blur",function(){state.el.trigger("mousemove")})}function enableFocusGrabber(){var tabIndex;if($(document.activeElement).parents().hasClass("video")){tabIndex=-1}else{tabIndex=0}this.focusGrabber.elFirst.attr("tabindex",tabIndex);this.focusGrabber.elLast.attr("tabindex",tabIndex);if(tabIndex===-1){this.el.focus();this.focusGrabber.elFirst.attr("tabindex",0);this.focusGrabber.elLast.attr("tabindex",0)}}function disableFocusGrabber(){this.focusGrabber.elFirst.attr("tabindex",-1);this.focusGrabber.elLast.attr("tabindex",-1)}function onFocus(event,params){this.el.trigger("mousemove");this.focusGrabber.disableFocusGrabber()}})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(requirejs,require,define){define("video/02_html5_video.js",["video/019_html5_video.js"],function(HTML5Video){HTML5Video_mod={};HTML5Video_mod.PlayerState=HTML5Video.PlayerState;HTML5Video_mod.Player=function(){Player.prototype=Object.create(HTML5Video.Player.prototype);Player.prototype.getAvailableQualityLevels=function(){return this.videoEl.find("source")["length"]};Player.prototype.setPlaybackQuality=function(value){if(value=="large"){return}if(this.getAvailableQualityLevels()==1){return}var btn=this.el.find(".quality-control");var is_active=btn.hasClass("high-def");if(is_active){btn.removeClass("high-def");btn.find(".icon").html("SD")}else{btn.addClass("high-def");btn.find(".icon").html("HD")}var state_before_switch=this.playerState;var time=this.getCurrentTime();var sources_obj=this.videoEl.find("source");this.video.innerHTML=sources_obj.eq(1).prop("outerHTML")+" "+sources_obj.eq(0).prop("outerHTML");var self=this;var g=self.pauseVideo.bind(self);var handler=function(){self.seekTo(time);if(state_before_switch=="2"){setTimeout(g,200)}self.video.removeEventListener("loadedmetadata",handler,false)};this.video.addEventListener("loadedmetadata",handler,false);this.video.load();this.playVideo()};return Player;function Player(el,config){HTML5Video.Player.call(this,el,config)}}();return HTML5Video_mod})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(requirejs,require,define){define("video/03_video_player.js",["video/02_html5_video.js","video/00_resizer.js"],function(HTML5Video,Resizer){var dfd=$.Deferred(),VideoPlayer=function(state){state.videoPlayer={};_makeFunctionsPublic(state);_initialize(state);return dfd.promise()},methodsDict={destroy:destroy,duration:duration,handlePlaybackQualityChange:handlePlaybackQualityChange,isBuffering:isBuffering,isCued:isCued,isEnded:isEnded,isPlaying:isPlaying,isUnstarted:isUnstarted,onCaptionSeek:onSeek,onEnded:onEnded,onError:onError,onPause:onPause,onPlay:onPlay,runTimer:runTimer,stopTimer:stopTimer,onLoadMetadataHtml5:onLoadMetadataHtml5,onPlaybackQualityChange:onPlaybackQualityChange,onReady:onReady,onSlideSeek:onSeek,onSpeedChange:onSpeedChange,onStateChange:onStateChange,onUnstarted:onUnstarted,onVolumeChange:onVolumeChange,pause:pause,play:play,seekTo:seekTo,setPlaybackRate:setPlaybackRate,update:update,figureOutStartEndTime:figureOutStartEndTime,figureOutStartingTime:figureOutStartingTime,updatePlayTime:updatePlayTime};VideoPlayer.prototype=methodsDict;return VideoPlayer;function _makeFunctionsPublic(state){var debouncedF=_.debounce(function(params){if(state.videoPlayer){return onSeek.call(this,params)}}.bind(state),300);state.bindTo(methodsDict,state.videoPlayer,state);state.videoPlayer.onSlideSeek=debouncedF;state.videoPlayer.onCaptionSeek=debouncedF}function onLoadMetadataHtml5(){var player=this.videoPlayer.player.videoEl,videoWidth=player[0].videoWidth||player.width(),videoHeight=player[0].videoHeight||player.height();_resize(this,videoWidth,videoHeight);_updateVcrAndRegion(this)}function _initialize(state){var youTubeId,player,userAgent;state.videoPlayer.ready=_.once(function(){if(!state.isFlashMode()&&state.speed!="1.0"){state.videoPlayer.setPlaybackRate(state.speed)}});if(state.isYoutubeType()){state.videoPlayer.PlayerState=YT.PlayerState;state.videoPlayer.PlayerState.UNSTARTED=-1}else{state.videoPlayer.PlayerState=HTML5Video.PlayerState}state.videoPlayer.currentTime=0;state.videoPlayer.goToStartTime=true;state.videoPlayer.stopAtEndTime=true;state.videoPlayer.playerVars={controls:0,wmode:"transparent",rel:0,showinfo:0,enablejsapi:1,modestbranding:1,cc_load_policy:0};if(!state.isFlashMode()){state.videoPlayer.playerVars.html5=1}userAgent=navigator.userAgent.toLowerCase();state.browserIsFirefox=userAgent.indexOf("firefox")>-1;state.browserIsChrome=userAgent.indexOf("chrome")>-1;state.browserIsSafari=userAgent.indexOf("safari")>-1&&!state.browserIsChrome;if(state.videoType==="html5"){state.videoPlayer.player=new HTML5Video.Player(state.el,{playerVars:state.videoPlayer.playerVars,videoSources:state.config.sources,events:{onReady:state.videoPlayer.onReady,onStateChange:state.videoPlayer.onStateChange,onError:state.videoPlayer.onError}});player=state.videoEl=state.videoPlayer.player.videoEl;player[0].addEventListener("loadedmetadata",state.videoPlayer.onLoadMetadataHtml5,false)}else{youTubeId=state.youtubeId();state.videoPlayer.player=new YT.Player(state.id,{playerVars:state.videoPlayer.playerVars,videoId:youTubeId,events:{onReady:state.videoPlayer.onReady,onStateChange:state.videoPlayer.onStateChange,onPlaybackQualityChange:state.videoPlayer.onPlaybackQualityChange,onError:state.videoPlayer.onError}});state.el.on("initialize",function(){var player=state.videoEl=state.el.find("iframe"),videoWidth=player.attr("width")||player.width(),videoHeight=player.attr("height")||player.height();_resize(state,videoWidth,videoHeight);_updateVcrAndRegion(state,true)})}if(state.isTouch){dfd.resolve()}}function _updateVcrAndRegion(state,isYoutube){var update=function(state){var duration=state.videoPlayer.duration(),time;time=state.videoPlayer.figureOutStartingTime(duration);state.trigger("videoControl.updateVcrVidTime",{time:time,duration:duration});state.trigger("videoProgressSlider.updateStartEndTimeRegion",{duration:duration});state.trigger("videoProgressSlider.updatePlayTime",{time:time,duration:duration})};if(state.youtubeMetadataReceived||!isYoutube){update(state)}else{state.el.on("metadata_received",function(){update(state)})}}function _resize(state,videoWidth,videoHeight){state.resizer=new Resizer({element:state.videoEl,elementRatio:videoWidth/videoHeight,container:state.container}).callbacks.once(function(){state.el.trigger("caption:resize")}).setMode("width");if(/iPad|Android/i.test(state.isTouch[0])){state.el.on("controls:show",function(){state.el.trigger("caption:resize")})}$(window).on("resize.video",_.debounce(function(){state.trigger("videoFullScreen.updateControlsHeight",null);state.el.trigger("caption:resize");state.resizer.align()},100))}function _restartUsingFlash(state){state.videoPlayer.player.destroy();state.setPlayerMode("flash");console.log('[Video info]: Changing YouTube player mode to "flash".');delete state.videoPlayer.playerVars.html5;state.videoPlayer.player=new YT.Player(state.id,{playerVars:state.videoPlayer.playerVars,videoId:state.youtubeId(),events:{onReady:state.videoPlayer.onReady,onStateChange:state.videoPlayer.onStateChange,onPlaybackQualityChange:state.videoPlayer.onPlaybackQualityChange,onError:state.videoPlayer.onError}});_updateVcrAndRegion(state,true);state.el.trigger("caption:fetch");state.resizer.setElement(state.el.find("iframe")).align()}function destroy(){var player=this.videoPlayer.player;this.el.removeClass(["is-unstarted","is-playing","is-paused","is-buffered","is-ended","is-cued"].join(" "));$(window).off(".video");this.el.trigger("destroy");this.el.off();this.videoPlayer.stopTimer();if(this.resizer&&this.resizer.destroy){this.resizer.destroy()}if(player&&player.video){player.video.removeEventListener("loadedmetadata",this.videoPlayer.onLoadMetadataHtml5,false)}if(player&&_.isFunction(player.destroy)){player.destroy()}delete this.videoPlayer}function pause(){if(this.videoPlayer.player.pauseVideo){this.videoPlayer.player.pauseVideo()}}function play(){if(this.videoPlayer.player.playVideo){if(this.videoPlayer.isEnded()){this.videoPlayer.goToStartTime=true}this.videoPlayer.player.playVideo()}}function update(time){this.videoPlayer.currentTime=time||this.videoPlayer.player.getCurrentTime();if(isFinite(this.videoPlayer.currentTime)){this.videoPlayer.updatePlayTime(this.videoPlayer.currentTime);if(this.videoPlayer.endTime!==null&&this.videoPlayer.endTime<=this.videoPlayer.currentTime){this.videoPlayer.pause();this.trigger("videoProgressSlider.notifyThroughHandleEnd",{end:true});this.el.trigger("stop")}this.el.trigger("timeupdate",[this.videoPlayer.currentTime])}}function setPlaybackRate(newSpeed){this.videoPlayer.player.setPlaybackRate(newSpeed)}function onSpeedChange(newSpeed){var time=this.videoPlayer.currentTime;if(this.isFlashMode()){this.videoPlayer.currentTime=Time.convert(time,parseFloat(this.speed),newSpeed)}newSpeed=parseFloat(newSpeed).toFixed(2).replace(/\.00$/,".0");this.setSpeed(newSpeed);this.videoPlayer.setPlaybackRate(newSpeed)}function onSeek(params){var time=params.time,type=params.type,oldTime=this.videoPlayer.currentTime;this.videoPlayer.goToStartTime=false;this.videoPlayer.seekTo(time);this.trigger("videoProgressSlider.focusSlider");this.el.trigger("seek",[time,oldTime,type])}function seekTo(time){var duration=this.videoPlayer.duration();if(typeof time!=="number"||time>duration||time<0){return false}this.el.off("play.seek");if(this.videoPlayer.isPlaying()){this.videoPlayer.stopTimer()}var isUnplayed=this.videoPlayer.isUnstarted()||this.videoPlayer.isCued();if(isUnplayed&&this.isYoutubeType()){this.videoPlayer.player.cueVideoById(this.youtubeId(),time)}else{if(this.isYoutubeType()&&this.videoPlayer.isBuffering()){this.el.on("play.seek",function(){this.videoPlayer.player.seekTo(time,true)}.bind(this))}else{this.videoPlayer.player.seekTo(time,true)}}this.videoPlayer.updatePlayTime(time,true);if(this.videoPlayer.isPlaying()){this.videoPlayer.runTimer()}this.videoPlayer.currentTime=time}function runTimer(){if(!this.videoPlayer.updateInterval){this.videoPlayer.updateInterval=window.setInterval(this.videoPlayer.update,200);this.videoPlayer.update()}}function stopTimer(){window.clearInterval(this.videoPlayer.updateInterval);delete this.videoPlayer.updateInterval}function onEnded(){var time=this.videoPlayer.duration();this.trigger("videoProgressSlider.notifyThroughHandleEnd",{end:true});if(this.videoPlayer.skipOnEndedStartEndReset){this.videoPlayer.skipOnEndedStartEndReset=undefined}this.videoPlayer.updatePlayTime(time);if(this.isYoutubeType()){this.el.trigger("pause",arguments)}this.el.trigger("ended",arguments)}function onPause(){this.videoPlayer.stopTimer();this.el.trigger("pause",arguments)}function onPlay(){this.videoPlayer.runTimer();this.trigger("videoProgressSlider.notifyThroughHandleEnd",{end:false});this.videoPlayer.ready();this.el.trigger("play",arguments)}function onUnstarted(){}function handlePlaybackQualityChange(value){this.videoPlayer.player.setPlaybackQuality(value)}function onPlaybackQualityChange(){var quality;quality=this.videoPlayer.player.getPlaybackQuality();this.trigger("videoQualityControl.onQualityChange",quality);this.el.trigger("qualitychange",arguments)}function onReady(){var _this=this,availablePlaybackRates,baseSpeedSubs,player,videoWidth,videoHeight;dfd.resolve();this.el.on("speedchange",function(event,speed){_this.videoPlayer.onSpeedChange(speed)});this.el.on("volumechange volumechange:silent",function(event,volume){_this.videoPlayer.onVolumeChange(volume)});availablePlaybackRates=this.videoPlayer.player.getAvailablePlaybackRates();availablePlaybackRates=_.filter(availablePlaybackRates,function(item){var speed=Number(item);return speed>.25&&speed<=5});if((this.isHtml5Mode()||availablePlaybackRates.length>1)&&this.isYoutubeType()){if(availablePlaybackRates.length===1&&!this.isTouch){_restartUsingFlash(this);return false}else if(availablePlaybackRates.length>1){this.setPlayerMode("html5");baseSpeedSubs=this.videos["1.0"];$.each(this.videos,function(index,value){delete _this.videos[index]});this.speeds=[];$.each(availablePlaybackRates,function(index,value){var key=value.toFixed(2).replace(/\.00$/,".0");_this.videos[key]=baseSpeedSubs;_this.speeds.push(key)});this.setSpeed(this.speed);this.el.trigger("speed:render",[this.speeds,this.speed])}}if(this.isFlashMode()){this.setSpeed(this.speed);this.el.trigger("speed:set",[this.speed])}if(this.isHtml5Mode()){this.videoPlayer.player.setPlaybackRate(this.speed)}var duration=this.videoPlayer.duration(),time=this.videoPlayer.figureOutStartingTime(duration);if(time>0&&this.videoPlayer.goToStartTime){this.videoPlayer.seekTo(time)}this.el.trigger("ready",arguments);if(this.config.autoplay){this.videoPlayer.play()}}function onStateChange(event){this.el.removeClass(["is-unstarted","is-playing","is-paused","is-buffered","is-ended","is-cued"].join(" "));switch(event.data){case this.videoPlayer.PlayerState.UNSTARTED:this.el.addClass("is-unstarted");this.videoPlayer.onUnstarted();break;case this.videoPlayer.PlayerState.PLAYING:this.el.addClass("is-playing");this.videoPlayer.onPlay();break;case this.videoPlayer.PlayerState.PAUSED:this.el.addClass("is-paused");this.videoPlayer.onPause();break;case this.videoPlayer.PlayerState.BUFFERING:this.el.addClass("is-buffered");this.el.trigger("buffering");break;case this.videoPlayer.PlayerState.ENDED:this.el.addClass("is-ended");this.videoPlayer.onEnded();break;case this.videoPlayer.PlayerState.CUED:this.el.addClass("is-cued");if(this.isFlashMode()){this.videoPlayer.play()}break}}function onError(code){this.el.trigger("error",[code])}function figureOutStartEndTime(duration){var videoPlayer=this.videoPlayer;videoPlayer.startTime=this.config.startTime;if(videoPlayer.startTime>=duration){videoPlayer.startTime=0}else if(this.isFlashMode()){videoPlayer.startTime/=Number(this.speed)}videoPlayer.endTime=this.config.endTime;if(videoPlayer.endTime<=videoPlayer.startTime||videoPlayer.endTime>=duration){videoPlayer.endTime=null}else if(this.isFlashMode()){videoPlayer.endTime/=Number(this.speed)}}function figureOutStartingTime(duration){var savedVideoPosition=this.config.savedVideoPosition,time=0,startTime,endTime;this.videoPlayer.figureOutStartEndTime(duration);startTime=this.videoPlayer.startTime;endTime=this.videoPlayer.endTime;if(startTime>0){if(startTime<savedVideoPosition&&(endTime>savedVideoPosition||endTime===null)&&savedVideoPosition<duration-1){time=savedVideoPosition}else{time=startTime}}else if(savedVideoPosition>0&&(endTime>savedVideoPosition||endTime===null)&&savedVideoPosition<duration-1){time=savedVideoPosition}return time}function updatePlayTime(time,skip_seek){var videoPlayer=this.videoPlayer,endTime=this.videoPlayer.duration(),youTubeId;if(this.config.endTime){endTime=Math.min(this.config.endTime,endTime)}this.trigger("videoProgressSlider.updatePlayTime",{time:time,duration:endTime});this.trigger("videoControl.updateVcrVidTime",{time:time,duration:endTime});this.el.trigger("caption:update",[time])}function isEnded(){var playerState=this.videoPlayer.player.getPlayerState(),ENDED=this.videoPlayer.PlayerState.ENDED;return playerState===ENDED}function isPlaying(){var playerState=this.videoPlayer.player.getPlayerState();return playerState===this.videoPlayer.PlayerState.PLAYING}function isBuffering(){var playerState=this.videoPlayer.player.getPlayerState();return playerState===this.videoPlayer.PlayerState.BUFFERING}function isCued(){var playerState=this.videoPlayer.player.getPlayerState();return playerState===this.videoPlayer.PlayerState.CUED}function isUnstarted(){var playerState=this.videoPlayer.player.getPlayerState();return playerState===this.videoPlayer.PlayerState.UNSTARTED}function duration(){var dur;if(this.videoPlayer.player.getDuration){dur=this.videoPlayer.player.getDuration()}if(!isFinite(dur)||dur<=0){if(this.isYoutubeType()){dur=this.getDuration()}}if(!isFinite(dur)||dur<=0){dur=0}return Math.floor(dur)}function onVolumeChange(volume){this.videoPlayer.player.setVolume(volume)}})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(define){"use strict";define("video/035_video_accessible_menu.js",["underscore"],function(_){var VideoTranscriptDownloadHandler=function(element,options){if(!(this instanceof VideoTranscriptDownloadHandler)){return new VideoTranscriptDownloadHandler(element,options);
9}_.bindAll(this,"clickHandler");this.container=element;this.options=options||{};if(this.container.find(".wrapper-downloads .wrapper-download-transcripts")){this.initialize()}return false};VideoTranscriptDownloadHandler.prototype={initialize:function(){this.value=this.options.storage.getItem("transcript_download_format");this.el=this.container.find(".list-download-transcripts");this.el.on("click",".btn-link",this.clickHandler)},clickHandler:function(event){var that=this,fileType,data,downloadUrl;event.preventDefault();fileType=$(event.target).data("value");data={transcript_download_format:fileType};downloadUrl=$(event.target).attr("href");$.ajax({url:this.options.saveStateUrl,type:"POST",dataType:"json",data:data,success:function(){that.options.storage.setItem("transcript_download_format",fileType)},complete:function(){document.location.href=downloadUrl}})}};return VideoTranscriptDownloadHandler})})(RequireJS.define);(function(requirejs,require,define){define("video/04_video_control.js",[],function(){return function(state){var dfd=$.Deferred();state.videoControl={};_makeFunctionsPublic(state);_renderElements(state);_bindHandlers(state);dfd.resolve();return dfd.promise()};function _makeFunctionsPublic(state){var methodsDict={destroy:destroy,hideControls:hideControls,show:show,showControls:showControls,focusFirst:focusFirst,updateVcrVidTime:updateVcrVidTime};state.bindTo(methodsDict,state.videoControl,state)}function destroy(){this.el.off({mousemove:this.videoControl.showControls,keydown:this.videoControl.showControls,destroy:this.videoControl.destroy,initialize:this.videoControl.focusFirst});this.el.off("controls:show");if(this.controlHideTimeout){clearTimeout(this.controlHideTimeout)}delete this.videoControl}function _renderElements(state){state.videoControl.el=state.el.find(".video-controls");state.videoControl.vidTimeEl=state.videoControl.el.find(".vidtime");if(state.videoType==="html5"&&state.config.autohideHtml5){state.videoControl.fadeOutTimeout=state.config.fadeOutTimeout;state.videoControl.el.addClass("html5");state.controlHideTimeout=setTimeout(state.videoControl.hideControls,state.videoControl.fadeOutTimeout)}}function _bindHandlers(state){if(state.videoType==="html5"&&state.config.autohideHtml5){state.el.on({mousemove:state.videoControl.showControls,keydown:state.videoControl.showControls})}if(state.config.focusFirstControl){state.el.on("initialize",state.videoControl.focusFirst)}state.el.on("destroy",state.videoControl.destroy)}function focusFirst(){this.videoControl.el.find(".vcr a, .vcr button").first().focus()}function show(){this.videoControl.el.removeClass("is-hidden");this.el.trigger("controls:show",arguments)}function showControls(event){if(!this.controlShowLock){if(!this.captionsHidden){return}this.controlShowLock=true;if(this.controlState==="invisible"){this.videoControl.el.show();this.controlState="visible"}else if(this.controlState==="hiding"){this.videoControl.el.stop(true,false).css("opacity",1).show();this.controlState="visible"}else if(this.controlState==="visible"){clearTimeout(this.controlHideTimeout)}this.controlHideTimeout=setTimeout(this.videoControl.hideControls,this.videoControl.fadeOutTimeout);this.controlShowLock=false}}function hideControls(){var _this=this;this.controlHideTimeout=null;if(!this.captionsHidden){return}this.controlState="hiding";this.videoControl.el.fadeOut(this.videoControl.fadeOutTimeout,function(){_this.controlState="invisible";_this.videoVolumeControl.el.removeClass("open");_this.videoSpeedControl.el.removeClass("open");_this.focusGrabber.enableFocusGrabber()})}function updateVcrVidTime(params){var endTime=this.config.endTime!==null?this.config.endTime:params.duration;endTime=Math.min(endTime,params.duration);this.videoControl.vidTimeEl.html(Time.format(params.time)+" / "+Time.format(endTime))}})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(define){"use strict";define("video/04_video_full_screen.js",["edx-ui-toolkit/js/utils/html-utils"],function(HtmlUtils){var template=['<button class="control add-fullscreen" aria-disabled="false" title="',gettext("Fill browser"),'">','<span class="icon fa fa-arrows-alt" aria-hidden="true"></span>',"</button>"].join("");return function(state){var dfd=$.Deferred();state.videoFullScreen={};_makeFunctionsPublic(state);_renderElements(state);_bindHandlers(state);dfd.resolve();return dfd.promise()};function _makeFunctionsPublic(state){var methodsDict={destroy:destroy,enter:enter,exitHandler:exitHandler,exit:exit,onFullscreenChange:onFullscreenChange,toggle:toggle,toggleHandler:toggleHandler,updateControlsHeight:updateControlsHeight};state.bindTo(methodsDict,state.videoFullScreen,state)}function destroy(){$(document).off("keyup",this.videoFullScreen.exitHandler);this.videoFullScreen.fullScreenEl.remove();this.el.off({fullscreen:this.videoFullScreen.onFullscreenChange,destroy:this.videoFullScreen.destroy});if(this.isFullScreen){this.videoFullScreen.exit()}delete this.videoFullScreen}function _renderElements(state){state.videoFullScreen.fullScreenEl=$(template);state.videoFullScreen.sliderEl=state.el.find(".slider");state.videoFullScreen.fullScreenState=false;HtmlUtils.append(state.el.find(".secondary-controls"),HtmlUtils.HTML(state.videoFullScreen.fullScreenEl));state.videoFullScreen.updateControlsHeight()}function _bindHandlers(state){state.videoFullScreen.fullScreenEl.on("click",state.videoFullScreen.toggleHandler);state.el.on({fullscreen:state.videoFullScreen.onFullscreenChange,destroy:state.videoFullScreen.destroy});$(document).on("keyup",state.videoFullScreen.exitHandler)}function _getControlsHeight(controls,slider){return controls.height()+.5*slider.height()}function onFullscreenChange(event,isFullScreen){var height=this.videoFullScreen.updateControlsHeight();if(isFullScreen){this.resizer.delta.substract(height,"height").setMode("both")}else{this.resizer.delta.reset().setMode("width")}}function updateControlsHeight(){var controls=this.el.find(".video-controls"),slider=this.videoFullScreen.sliderEl;this.videoFullScreen.height=_getControlsHeight(controls,slider);return this.videoFullScreen.height}function toggleHandler(event){event.preventDefault();this.videoCommands.execute("toggleFullScreen")}function exit(){var fullScreenClassNameEl=this.el.add(document.documentElement),closedCaptionsEl=this.el.find(".closed-captions");this.videoFullScreen.fullScreenState=this.isFullScreen=false;fullScreenClassNameEl.removeClass("video-fullscreen");$(window).scrollTop(this.scrollPos);this.videoFullScreen.fullScreenEl.attr("title",gettext("Fill browser")).find(".icon").removeClass("fa-compress").addClass("fa-arrows-alt");this.el.trigger("fullscreen",[this.isFullScreen]);$(closedCaptionsEl).css({top:"70%",left:"5%"})}function enter(){var fullScreenClassNameEl=this.el.add(document.documentElement),closedCaptionsEl=this.el.find(".closed-captions");this.scrollPos=$(window).scrollTop();$(window).scrollTop(0);this.videoFullScreen.fullScreenState=this.isFullScreen=true;fullScreenClassNameEl.addClass("video-fullscreen");this.videoFullScreen.fullScreenEl.attr("title",gettext("Exit full browser")).find(".icon").removeClass("fa-arrows-alt").addClass("fa-compress");this.el.trigger("fullscreen",[this.isFullScreen]);$(closedCaptionsEl).css({top:"70%",left:"5%"})}function toggle(){if(this.videoFullScreen.fullScreenState){this.videoFullScreen.exit()}else{this.videoFullScreen.enter()}}function exitHandler(event){if(this.isFullScreen&&event.keyCode===27){event.preventDefault();this.videoCommands.execute("toggleFullScreen")}}})})(RequireJS.define);(function(requirejs,require,define){"use strict";define("video/05_video_quality_control.js",["video/049_video_quality_control.js"],function(VideoQualityControl){return function(state){var old_videoType=state.videoType;var dfd=null;if(old_videoType=="html5"){state.videoType="youtube";dfd=VideoQualityControl.call(this,state)}else{dfd=VideoQualityControl.call(this,state);return dfd}state.videoQualityControl.el.find(".icon").html("SD");state.videoType=old_videoType;state.videoQualityControl.quality="large";state.videoQualityControl.showQualityControl();return dfd}})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(requirejs,require,define){define("video/06_video_progress_slider.js",[],function(){var template=['<div class="slider" role="application" title="',gettext("Video position. Press space to toggle playback"),'"></div>'].join("");return function(state){var dfd=$.Deferred();state.videoProgressSlider={};_makeFunctionsPublic(state);_renderElements(state);dfd.resolve();return dfd.promise()};function _makeFunctionsPublic(state){var methodsDict={destroy:destroy,buildSlider:buildSlider,getRangeParams:getRangeParams,onSlide:onSlide,onStop:onStop,updatePlayTime:updatePlayTime,updateStartEndTimeRegion:updateStartEndTimeRegion,notifyThroughHandleEnd:notifyThroughHandleEnd,getTimeDescription:getTimeDescription,focusSlider:focusSlider};state.bindTo(methodsDict,state.videoProgressSlider,state)}function destroy(){this.videoProgressSlider.el.removeAttr("tabindex").slider("destroy");this.el.off("destroy",this.videoProgressSlider.destroy);delete this.videoProgressSlider}function bindHandlers(state){state.videoProgressSlider.el.on("keypress",sliderToggle.bind(state));state.el.on("destroy",state.videoProgressSlider.destroy)}function _renderElements(state){state.videoProgressSlider.el=$(template);state.el.find(".video-controls").prepend(state.videoProgressSlider.el);state.videoProgressSlider.buildSlider();_buildHandle(state);bindHandlers(state)}function _buildHandle(state){state.videoProgressSlider.handle=state.videoProgressSlider.el.find(".ui-slider-handle");state.videoProgressSlider.el.attr({tabindex:-1});state.videoProgressSlider.handle.attr({role:"slider","aria-disabled":false,"aria-valuetext":getTimeDescription(state.videoProgressSlider.slider.slider("option","value")),"aria-valuemax":state.videoPlayer.duration(),"aria-valuemin":"0","aria-valuenow":state.videoPlayer.currentTime,tabindex:"0","aria-label":gettext("Video position. Press space to toggle playback")})}function buildSlider(){var sliderContents=edx.HtmlUtils.joinHtml(edx.HtmlUtils.HTML('<div class="ui-slider-handle progress-handle"></div>'));this.videoProgressSlider.el.append(sliderContents.text);this.videoProgressSlider.slider=this.videoProgressSlider.el.slider({range:"min",min:this.config.startTime,max:this.config.endTime,slide:this.videoProgressSlider.onSlide,stop:this.videoProgressSlider.onStop});this.videoProgressSlider.sliderProgress=this.videoProgressSlider.slider.find(".ui-slider-range.ui-widget-header.ui-slider-range-min")}function updateStartEndTimeRegion(params){var start,end,duration,rangeParams;if(!params.duration){return}else{duration=params.duration}start=this.config.startTime;end=this.config.endTime;if(start>duration){start=0}else if(this.isFlashMode()){start/=Number(this.speed)}if(end===null||end>duration){end=duration}else if(this.isFlashMode()){end/=Number(this.speed)}if(start===0&&end===duration){return}rangeParams=getRangeParams(start,end,duration)}function getRangeParams(startTime,endTime,duration){var step=100/duration,left=startTime*step,width=endTime*step-left;return{left:left+"%",width:width+"%"}}function onSlide(event,ui){var time=ui.value,endTime=this.videoPlayer.duration();if(this.config.endTime){endTime=Math.min(this.config.endTime,endTime)}this.videoProgressSlider.frozen=true;this.videoProgressSlider.lastSeekValue=time;this.trigger("videoControl.updateVcrVidTime",{time:time,duration:endTime});this.trigger("videoPlayer.onSlideSeek",{type:"onSlideSeek",time:time});this.videoProgressSlider.handle.attr("aria-valuetext",getTimeDescription(this.videoPlayer.currentTime))}function onStop(event,ui){var _this=this;this.videoProgressSlider.frozen=true;if(this.videoProgressSlider.lastSeekValue!==ui.value){this.trigger("videoPlayer.onSlideSeek",{type:"onSlideSeek",time:ui.value})}this.videoProgressSlider.handle.attr("aria-valuetext",getTimeDescription(this.videoPlayer.currentTime));setTimeout(function(){_this.videoProgressSlider.frozen=false},200)}function updatePlayTime(params){var time=Math.floor(params.time);var endTime=Math.floor(params.duration);if(this.config.endTime!==null){endTime=Math.min(this.config.endTime,endTime)}if(this.videoProgressSlider.slider&&!this.videoProgressSlider.frozen){this.videoProgressSlider.slider.slider("option","max",endTime).slider("option","value",time)}this.videoProgressSlider.handle.attr({"aria-valuemax":endTime,"aria-valuenow":time})}function notifyThroughHandleEnd(params){if(params.end){this.videoProgressSlider.handle.attr("title",gettext("Video ended")).focus()}else{this.videoProgressSlider.handle.attr("title",gettext("Video position"))}}function getTimeDescription(time){var seconds=Math.floor(time),minutes=Math.floor(seconds/60),hours=Math.floor(minutes/60),i18n=function(value,word){var msg;switch(word){case"hour":msg=ngettext("%(value)s hour","%(value)s hours",value);break;case"minute":msg=ngettext("%(value)s minute","%(value)s minutes",value);break;case"second":msg=ngettext("%(value)s second","%(value)s seconds",value);break}return interpolate(msg,{value:value},true)};seconds=seconds%60;minutes=minutes%60;if(hours){return i18n(hours,"hour")+" "+i18n(minutes,"minute")+" "+i18n(seconds,"second")}else if(minutes){return i18n(minutes,"minute")+" "+i18n(seconds,"second")}return i18n(seconds,"second")}function focusSlider(){this.videoProgressSlider.handle.attr("aria-valuetext",getTimeDescription(this.videoPlayer.currentTime));this.videoProgressSlider.el.trigger("focus")}function sliderToggle(e){if(e.which===32){e.preventDefault();this.videoCommands.execute("togglePlayback")}}})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(define){"use strict";define("video/07_video_volume_control.js",["edx-ui-toolkit/js/utils/html-utils"],function(HtmlUtils){var VolumeControl=function(state,i18n){if(!(this instanceof VolumeControl)){return new VolumeControl(state,i18n)}_.bindAll(this,"keyDownHandler","updateVolumeSilently","onVolumeChangeHandler","openMenu","closeMenu","toggleMuteHandler","keyDownButtonHandler","destroy");this.state=state;this.state.videoVolumeControl=this;this.i18n=i18n;this.initialize();return $.Deferred().resolve().promise()};VolumeControl.prototype={min:0,max:100,step:20,videoVolumeControlHtml:HtmlUtils.interpolateHtml(HtmlUtils.HTML(['<div class="volume" role="application">','<p class="sr instructions">',"{volumeInstructions}","</p>",'<button class="control" aria-disabled="false"','" aria-expanded="false" title="',"{adjustVideoVolume}",'">','<span class="icon fa fa-volume-up" aria-hidden="true"></span>',"</button>",'<div class="volume-slider-container" aria-hidden="true" title="',"{adjustVideoVolume}",'">','<div class="volume-slider" ','role="slider"','aria-orientation="vertical" ','aria-valuemin="0" ','aria-valuemax="100" ','aria-valuenow="" ','aria-label="',"{volumeText}",'"></div>',"</div>","</div>"].join("")),{volumeInstructions:gettext("Click on this button to mute or unmute this video or press UP or DOWN buttons to increase or decrease volume level."),adjustVideoVolume:gettext("Adjust video volume"),volumeText:gettext("Volume")}),destroy:function(){this.volumeSlider.slider("destroy");this.state.el.find("iframe").removeAttr("tabindex");this.a11y.destroy();this.cookie=this.a11y=null;this.closeMenu();this.state.el.off("play.volume").off({keydown:this.keyDownHandler,volumechange:this.onVolumeChangeHandler});this.el.off({mouseenter:this.openMenu,mouseleave:this.closeMenu});this.button.off({mousedown:this.toggleMuteHandler,keydown:this.keyDownButtonHandler,focus:this.openMenu,blur:this.closeMenu});this.el.remove();delete this.state.videoVolumeControl},initialize:function(){var volume;if(this.state.isTouch){return false}this.el=$(this.videoVolumeControlHtml.toString());this.state.el.find("iframe").attr("tabindex",-1);this.button=this.el.children(".control");this.cookie=new CookieManager(this.min,this.max);this.a11y=new Accessibility(this.button,this.min,this.max,this.i18n);volume=this.cookie.getVolume();this.storedVolume=this.max;this.render();this.bindHandlers();this.setVolume(volume,true,false);this.checkMuteButtonStatus(volume)},render:function(){var container=this.el.find(".volume-slider"),instructionsId="volume-instructions-"+this.state.id;HtmlUtils.append(container,HtmlUtils.HTML('<div class="ui-slider-handle volume-handle"></div>'));this.volumeSlider=container.slider({orientation:"vertical",range:"min",min:this.min,max:this.max,slide:this.onSlideHandler.bind(this)});container.find(".volume-handle").attr("tabindex",-1);this.state.el.find(".secondary-controls").append(this.el);this.el.find(".instructions").attr("id",instructionsId);this.button.attr("aria-describedby",instructionsId)},bindHandlers:function(){this.state.el.on({"play.volume":_.once(this.updateVolumeSilently),volumechange:this.onVolumeChangeHandler});this.state.el.find(".volume").on({mouseenter:this.openMenu,mouseleave:this.closeMenu});this.button.on({keydown:this.keyDownHandler,click:false,mousedown:this.toggleMuteHandler,focus:this.openMenu,blur:this.closeMenu});this.state.el.on("destroy",this.destroy)},updateVolumeSilently:function(){this.state.el.trigger("volumechange:silent",[this.getVolume()])},getVolume:function(){return this.volume},setVolume:function(volume,silent,withoutSlider){if(volume===this.getVolume()){return false}this.volume=volume;this.a11y.update(this.getVolume());if(!withoutSlider){this.updateSliderView(this.getVolume())}if(!silent){this.cookie.setVolume(this.getVolume());this.state.el.trigger("volumechange",[this.getVolume()])}},increaseVolume:function(){var volume=Math.min(this.getVolume()+this.step,this.max);this.setVolume(volume,false,false);this.el.find(".volume-slider").attr("aria-valuenow",volume)},decreaseVolume:function(){var volume=Math.max(this.getVolume()-this.step,this.min);this.setVolume(volume,false,false);this.el.find(".volume-slider").attr("aria-valuenow",volume)},updateSliderView:function(volume){this.volumeSlider.slider("value",volume);this.el.find(".volume-slider").attr("aria-valuenow",volume)},mute:function(muteStatus){var volume;this.updateMuteButtonView(muteStatus);if(muteStatus){this.storedVolume=this.getVolume()||this.max}volume=muteStatus?0:this.storedVolume;this.setVolume(volume,false,false);this.el.find(".volume-slider").attr("aria-valuenow",volume)},getMuteStatus:function(){return this.getVolume()===0},updateMuteButtonView:function(isMuted){var action=isMuted?"addClass":"removeClass";this.el[action]("is-muted");if(isMuted){this.el.find(".control .icon").removeClass("fa-volume-up").addClass("fa-volume-off")}else{this.el.find(".control .icon").removeClass("fa-volume-off").addClass("fa-volume-up")}},toggleMute:function(){this.mute(!this.getMuteStatus())},checkMuteButtonStatus:function(volume){if(volume<=this.min){this.updateMuteButtonView(true);this.state.el.off("volumechange.is-muted");this.state.el.on("volumechange.is-muted",_.once(function(){this.updateMuteButtonView(false)}.bind(this)))}},openMenu:function(){this.el.addClass("is-opened");this.button.attr("aria-expanded","true")},closeMenu:function(){this.el.removeClass("is-opened");this.button.attr("aria-expanded","false")},keyDownHandler:function(event){if(event.altKey){return true}if($(event.target).hasClass("ui-slider-handle")){return true}var KEY=$.ui.keyCode,keyCode=event.keyCode;switch(keyCode){case KEY.UP:if(event.shiftKey){return true}this.increaseVolume();return false;case KEY.DOWN:if(event.shiftKey){return true}this.decreaseVolume();return false;case KEY.SPACE:case KEY.ENTER:if(event.shiftKey){return true}this.toggleMute();return false}return true},keyDownButtonHandler:function(event){if(event.altKey){return true}var KEY=$.ui.keyCode,keyCode=event.keyCode;switch(keyCode){case KEY.ENTER:case KEY.SPACE:this.toggleMute();return false}return true},onSlideHandler:function(event,ui){this.setVolume(ui.value,false,true);this.el.find(".volume-slider").attr("aria-valuenow",ui.volume)},toggleMuteHandler:function(event){this.toggleMute();event.preventDefault()},onVolumeChangeHandler:function(event,volume){this.checkMuteButtonStatus(volume)}};var Accessibility=function(button,min,max,i18n){this.min=min;this.max=max;this.button=button;this.i18n=i18n;this.initialize()};Accessibility.prototype={destroy:function(){this.liveRegion.remove()},initialize:function(){this.liveRegion=$("<div />",{class:"sr video-live-region","aria-hidden":"false","aria-live":"polite"});this.button.after(HtmlUtils.HTML(this.liveRegion).toString())},update:function(volume){this.liveRegion.text([this.getVolumeDescription(volume),this.i18n["Volume"]+"."].join(" "));$(this.button).parent().find(".volume-slider").attr("aria-valuenow",volume)},getVolumeDescription:function(volume){if(volume===0){return this.i18n["Muted"]}else if(volume<=20){return this.i18n["Very low"]}else if(volume<=40){return this.i18n["Low"]}else if(volume<=60){return this.i18n["Average"]}else if(volume<=80){return this.i18n["Loud"]}else if(volume<=99){return this.i18n["Very loud"]}return this.i18n["Maximum"]}};var CookieManager=function(min,max){this.min=min;this.max=max;this.cookieName="video_player_volume_level"};CookieManager.prototype={getVolume:function(){var volume=parseInt($.cookie(this.cookieName),10);if(_.isFinite(volume)){volume=Math.max(volume,this.min);volume=Math.min(volume,this.max)}else{volume=this.max}return volume},setVolume:function(value){$.cookie(this.cookieName,value,{expires:3650,path:"/"})}};return VolumeControl})})(RequireJS.define);(function(requirejs,require,define){"use strict";define("video/08_video_speed_control.js",["video/00_iterator.js","edx-ui-toolkit/js/utils/html-utils"],function(Iterator,HtmlUtils){var SpeedControl=function(state){if(!(this instanceof SpeedControl)){return new SpeedControl(state)}_.bindAll(this,"onSetSpeed","onRenderSpeed","clickLinkHandler","keyDownLinkHandler","mouseEnterHandler","mouseLeaveHandler","clickMenuHandler","keyDownMenuHandler","destroy");this.state=state;this.state.videoSpeedControl=this;this.initialize();return $.Deferred().resolve().promise()};SpeedControl.prototype={template:['<div class="speeds menu-container" role="application">','<p class="sr instructions">',gettext("Press UP to enter the speed menu then use the UP and DOWN arrow keys to navigate the different speeds, then press ENTER to change to the selected speed."),"</p>",'<button class="control speed-button" aria-disabled="false" aria-expanded="false"','title="',gettext("Adjust video speed"),'">',"<span>",'<span class="icon fa fa-caret-right" aria-hidden="true"></span>',"</span>",'<span class="label" aria-hidden="true">',gettext("Speed"),"</span>",'<span class="value"></span>',"</button>",'<ol class="video-speeds menu"></ol>',"</div>"].join(""),destroy:function(){this.el.off({mouseenter:this.mouseEnterHandler,mouseleave:this.mouseLeaveHandler,click:this.clickMenuHandler,keydown:this.keyDownMenuHandler});this.state.el.off({"speed:set":this.onSetSpeed,"speed:render":this.onRenderSpeed});this.closeMenu(true);this.speedsContainer.remove();this.el.remove();delete this.state.videoSpeedControl},initialize:function(){var state=this.state;if(!this.isPlaybackRatesSupported(state)){console.log("[Video info]: playbackRate is not supported.");return false}this.el=$(this.template);this.speedsContainer=this.el.find(".video-speeds");this.speedButton=this.el.find(".speed-button");this.render(state.speeds,state.speed);this.setSpeed(state.speed,true,true);this.bindHandlers();return true},render:function(speeds,currentSpeed){var speedsContainer=this.speedsContainer,reversedSpeeds=speeds.concat().reverse(),instructionsId="speed-instructions-"+this.state.id,speedsList=$.map(reversedSpeeds,function(speed){return HtmlUtils.interpolateHtml(HtmlUtils.HTML(['<li data-speed="{speed}">','<button class="control speed-option" tabindex="-1" aria-pressed="false">',"{speed}x","</button>","</li>"].join("")),{speed:speed}).toString()});HtmlUtils.setHtml(speedsContainer,HtmlUtils.HTML(speedsList));this.speedLinks=new Iterator(speedsContainer.find(".speed-option"));HtmlUtils.prepend(this.state.el.find(".secondary-controls"),HtmlUtils.HTML(this.el));this.setActiveSpeed(currentSpeed);this.el.find(".instructions").attr("id",instructionsId);this.speedButton.attr("aria-describedby",instructionsId)},bindHandlers:function(){this.el.on({mouseenter:this.mouseEnterHandler,mouseleave:this.mouseLeaveHandler,click:this.openMenu,keydown:this.keyDownMenuHandler});this.speedsContainer.on({click:this.clickLinkHandler,keydown:this.keyDownLinkHandler},".speed-option");this.state.el.on({"speed:set":this.onSetSpeed,"speed:render":this.onRenderSpeed});this.state.el.on("destroy",this.destroy)},onSetSpeed:function(event,speed){this.setSpeed(speed,true)},onRenderSpeed:function(event,speeds,currentSpeed){this.render(speeds,currentSpeed)},isPlaybackRatesSupported:function(state){var isHtml5=state.videoType==="html5",isTouch=state.isTouch,video=document.createElement("video");return!isTouch||isHtml5&&!Boolean(video.playbackRate)},openMenu:function(bindEvent){if(bindEvent){$(window).on("click.speedMenu",this.clickMenuHandler)}this.el.addClass("is-opened");this.speedButton.attr("tabindex",-1).attr("aria-expanded","true")},closeMenu:function(unBindEvent){if(unBindEvent){$(window).off("click.speedMenu")}this.el.removeClass("is-opened");this.speedButton.attr("tabindex",0).attr("aria-expanded","false")},setSpeed:function(speed,silent,forceUpdate){if(speed!==this.currentSpeed||forceUpdate){this.speedsContainer.find("li").siblings("li[data-speed='"+speed+"']");this.speedButton.find(".value").text(speed+"x");this.currentSpeed=speed;if(!silent){this.el.trigger("speedchange",[speed,this.state.speed])}}this.resetActiveSpeed();this.setActiveSpeed(speed)},resetActiveSpeed:function(){var speedOptions=this.speedsContainer.find("li");$(speedOptions).each(function(index,el){$(el).removeClass("is-active").find(".speed-option").attr("aria-pressed","false")})},setActiveSpeed:function(speed){var speedOption=this.speedsContainer.find('li[data-speed="'+speed+'"]');speedOption.addClass("is-active").find(".speed-option").attr("aria-pressed","true");this.speedButton.attr("title",gettext("Video speed: ")+speed+"x")},clickMenuHandler:function(){this.closeMenu();return false},clickLinkHandler:function(event){var el=$(event.currentTarget).parent(),speed=$(el).data("speed");this.resetActiveSpeed();this.setActiveSpeed(speed);this.state.videoCommands.execute("speed",speed);this.closeMenu(true);return false},mouseEnterHandler:function(){this.openMenu();return false},mouseLeaveHandler:function(){if(!this.speedLinks.list.is(":focus")){this.closeMenu()}return false},keyDownMenuHandler:function(event){var KEY=$.ui.keyCode,keyCode=event.keyCode;switch(keyCode){case KEY.ENTER:case KEY.SPACE:case KEY.UP:this.openMenu(true);this.speedLinks.last().focus();break;case KEY.ESCAPE:this.closeMenu(true);break}return event.keyCode===KEY.TAB},keyDownLinkHandler:function(event){if(event.altKey){return true}var KEY=$.ui.keyCode,self=this,parent=$(event.currentTarget).parent(),index=parent.index(),speed=parent.data("speed");switch(event.keyCode){case KEY.TAB:setTimeout(function(){self.closeMenu(true)},25);return true;case KEY.ESCAPE:this.closeMenu(true);this.speedButton.focus();return false;case KEY.UP:if(event.shiftKey){return true}this.speedLinks.prev(index).focus();return false;case KEY.DOWN:if(event.shiftKey){return true}this.speedLinks.next(index).focus();return false;case KEY.ENTER:case KEY.SPACE:this.closeMenu(true);this.speedButton.focus();this.setSpeed(this.state.speedToString(speed));return false}return true}};return SpeedControl})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(define){"use strict";define("video/09_video_caption.js",["video/00_sjson.js","video/00_async_process.js","edx-ui-toolkit/js/utils/html-utils","draggabilly"],function(Sjson,AsyncProcess,HtmlUtils,Draggabilly){var VideoCaption=function(state){if(!(this instanceof VideoCaption)){return new VideoCaption(state)}_.bindAll(this,"toggle","onMouseEnter","onMouseLeave","onMovement","onContainerMouseEnter","onContainerMouseLeave","fetchCaption","onResize","pause","play","onCaptionUpdate","onCaptionHandler","destroy","handleKeypress","handleKeypressLink","openLanguageMenu","closeLanguageMenu","previousLanguageMenuItem","nextLanguageMenuItem","handleCaptionToggle","showClosedCaptions","hideClosedCaptions","toggleClosedCaptions","updateCaptioningCookie","handleCaptioningCookie","handleTranscriptToggle","listenForDragDrop");this.state=state;this.state.videoCaption=this;this.renderElements();this.handleCaptioningCookie();this.listenForDragDrop();return $.Deferred().resolve().promise()};VideoCaption.prototype={destroy:function(){this.state.el.off({"caption:fetch":this.fetchCaption,"caption:resize":this.onResize,"caption:update":this.onCaptionUpdate,ended:this.pause,fullscreen:this.onResize,pause:this.pause,play:this.play,destroy:this.destroy}).removeClass("is-captions-rendered");if(this.fetchXHR&&this.fetchXHR.abort){this.fetchXHR.abort()}if(this.availableTranslationsXHR&&this.availableTranslationsXHR.abort){this.availableTranslationsXHR.abort()}this.subtitlesEl.remove();this.container.remove();delete this.state.videoCaption},renderElements:function(){var languages=this.state.config.transcriptLanguages;var langHtml=HtmlUtils.interpolateHtml(HtmlUtils.HTML(['<div class="grouped-controls">','<button class="control toggle-captions" aria-disabled="false">','<span class="icon fa fa-cc" aria-hidden="true"></span>',"</button>",'<button class="control toggle-transcript" aria-disabled="false">','<span class="icon fa fa-quote-left" aria-hidden="true"></span>',"</button>",'<div class="lang menu-container" role="application">','<p class="sr instructions" id="lang-instructions-{courseId}"></p>','<button class="control language-menu" aria-disabled="false"','aria-describedby="lang-instructions-{courseId}" ','title="{langTitle}">','<span class="icon fa fa-caret-left" aria-hidden="true"></span>',"</button>","</div>","</div>"].join("")),{langTitle:gettext("Open language menu"),courseId:this.state.id});var subtitlesHtml=HtmlUtils.interpolateHtml(HtmlUtils.HTML(['<div class="subtitles" role="region" id="transcript-{courseId}">','<h3 id="transcript-label-{courseId}" class="transcript-title sr"></h3>','<ol id="transcript-captions-{courseId}" class="subtitles-menu" lang="{courseLang}"></ol>',"</div>"].join("")),{courseId:this.state.id,courseLang:this.state.lang});this.loaded=false;this.subtitlesEl=$(HtmlUtils.ensureHtml(subtitlesHtml).toString());this.subtitlesMenuEl=this.subtitlesEl.find(".subtitles-menu");this.container=$(HtmlUtils.ensureHtml(langHtml).toString());this.captionControlEl=this.container.find(".toggle-captions");this.captionDisplayEl=this.state.el.find(".closed-captions");this.transcriptControlEl=this.container.find(".toggle-transcript");this.languageChooserEl=this.container.find(".lang");this.menuChooserEl=this.languageChooserEl.parent();if(_.keys(languages).length){this.renderLanguageMenu(languages);this.fetchCaption()}},bindHandlers:function(){var state=this.state,events=["mouseover","mouseout","mousedown","click","focus","blur","keydown"].join(" ");this.captionControlEl.on({click:this.toggleClosedCaptions,keydown:this.handleCaptionToggle});this.transcriptControlEl.on({click:this.toggle,keydown:this.handleTranscriptToggle});this.subtitlesMenuEl.on({mouseenter:this.onMouseEnter,mouseleave:this.onMouseLeave,mousemove:this.onMovement,mousewheel:this.onMovement,DOMMouseScroll:this.onMovement}).on(events,"span[data-index]",this.onCaptionHandler);this.container.on({mouseenter:this.onContainerMouseEnter,mouseleave:this.onContainerMouseLeave});if(this.showLanguageMenu){this.languageChooserEl.on({keydown:this.handleKeypress},".language-menu");this.languageChooserEl.on({keydown:this.handleKeypressLink},".control-lang")}state.el.on({"caption:fetch":this.fetchCaption,"caption:resize":this.onResize,"caption:update":this.onCaptionUpdate,ended:this.pause,
10fullscreen:this.onResize,pause:this.pause,play:this.play,destroy:this.destroy});if(state.videoType==="html5"&&state.config.autohideHtml5){this.subtitlesMenuEl.on("scroll",state.videoControl.showControls)}},onCaptionUpdate:function(event,time){this.updatePlayTime(time)},handleCaptionToggle:function(event){var KEY=$.ui.keyCode,keyCode=event.keyCode;switch(keyCode){case KEY.SPACE:case KEY.ENTER:event.preventDefault();this.toggleClosedCaptions(event)}},handleTranscriptToggle:function(event){var KEY=$.ui.keyCode,keyCode=event.keyCode;switch(keyCode){case KEY.SPACE:case KEY.ENTER:event.preventDefault();this.toggle(event)}},handleKeypressLink:function(event){var KEY=$.ui.keyCode,keyCode=event.keyCode,focused,index,total;switch(keyCode){case KEY.UP:event.preventDefault();focused=$(":focus").parent();index=this.languageChooserEl.find("li").index(focused);total=this.languageChooserEl.find("li").size()-1;this.previousLanguageMenuItem(event,index);break;case KEY.DOWN:event.preventDefault();focused=$(":focus").parent();index=this.languageChooserEl.find("li").index(focused);total=this.languageChooserEl.find("li").size()-1;this.nextLanguageMenuItem(event,index,total);break;case KEY.ESCAPE:this.closeLanguageMenu(event);break;case KEY.ENTER:case KEY.SPACE:return true}},handleKeypress:function(event){var KEY=$.ui.keyCode,keyCode=event.keyCode;switch(keyCode){case KEY.ENTER:case KEY.SPACE:case KEY.UP:event.preventDefault();this.openLanguageMenu(event);break;case KEY.ESCAPE:this.closeLanguageMenu(event);break}return event.keyCode===KEY.TAB},nextLanguageMenuItem:function(event,index,total){event.preventDefault();if(event.altKey||event.shiftKey){return true}if(index===total){this.languageChooserEl.find(".control-lang").first().focus()}else{this.languageChooserEl.find("li:eq("+index+")").next().find(".control-lang").focus()}return false},previousLanguageMenuItem:function(event,index){event.preventDefault();if(event.altKey||event.shiftKey){return true}if(index===0){this.languageChooserEl.find(".control-lang").last().focus()}else{this.languageChooserEl.find("li:eq("+index+")").prev().find(".control-lang").focus()}return false},openLanguageMenu:function(event){event.preventDefault();var button=this.languageChooserEl,menu=button.parent().find(".menu");button.addClass("is-opened");menu.find(".control-lang").last().focus()},closeLanguageMenu:function(event){event.preventDefault();var button=this.languageChooserEl;button.removeClass("is-opened").find(".language-menu").focus()},onCaptionHandler:function(event){switch(event.type){case"mouseover":case"mouseout":this.captionMouseOverOut(event);break;case"mousedown":this.captionMouseDown(event);break;case"click":this.captionClick(event);break;case"focusin":this.captionFocus(event);break;case"focusout":this.captionBlur(event);break;case"keydown":this.captionKeyDown(event);break}},onContainerMouseEnter:function(event){event.preventDefault();$(event.currentTarget).find(".lang").addClass("is-opened");if($(event.currentTarget).find(".lang").length){this.state.el.trigger("language_menu:show")}},onContainerMouseLeave:function(event){event.preventDefault();$(event.currentTarget).find(".lang").removeClass("is-opened");if($(event.currentTarget).find(".lang").length){this.state.el.trigger("language_menu:hide")}},onMouseEnter:function(){if(this.frozen){clearTimeout(this.frozen)}this.frozen=setTimeout(this.onMouseLeave,this.state.config.captionsFreezeTime)},onMouseLeave:function(){if(this.frozen){clearTimeout(this.frozen)}this.frozen=null;if(this.playing){this.scrollCaption()}},onMovement:function(){this.onMouseEnter()},getStartEndTimes:function(){var config=this.state.config;var startTime=config.startTime*1e3;var endTime=config.endTime!==null?config.endTime*1e3:null;return[startTime,endTime]},getBoundedCaptions:function(){var times=this.getStartEndTimes();var results=this.sjson.filter.apply(this.sjson,times);var start=results.start;var captions=results.captions;return{start:start,captions:captions}},fetchCaption:function(fetchWithYoutubeId){var self=this,state=this.state,language=state.getCurrentLanguage(),url=state.config.transcriptTranslationUrl.replace("__lang__",language),data,youtubeId;if(this.loaded){this.hideCaptions(false)}if(this.fetchXHR&&this.fetchXHR.abort){this.fetchXHR.abort()}if(state.videoType==="youtube"||fetchWithYoutubeId){try{youtubeId=state.youtubeId("1.0")}catch(err){youtubeId=null}if(!youtubeId){return false}data={videoId:youtubeId}}state.el.removeClass("is-captions-rendered");this.fetchXHR=$.ajaxWithPrefix({url:url,notifyOnError:false,data:data,success:function(sjson){self.sjson=new Sjson(sjson);var results=self.getBoundedCaptions();var start=results.start;var captions=results.captions;if(self.loaded){if(self.rendered){self.renderCaption(start,captions);self.updatePlayTime(state.videoPlayer.currentTime)}}else{if(state.isTouch){HtmlUtils.setHtml(self.subtitlesEl.find(".subtitles-menu"),HtmlUtils.joinHtml(HtmlUtils.HTML("<li>"),gettext("Transcript will be displayed when you start playing the video."),HtmlUtils.HTML("</li>")))}else{self.renderCaption(start,captions)}self.hideCaptions(state.hide_captions,false);HtmlUtils.append(self.state.el.find(".video-wrapper").parent(),HtmlUtils.HTML(self.subtitlesEl));HtmlUtils.append(self.state.el.find(".secondary-controls"),HtmlUtils.HTML(self.container));self.bindHandlers()}self.loaded=true},error:function(jqXHR,textStatus,errorThrown){console.log("[Video info]: ERROR while fetching captions.");console.log("[Video info]: STATUS:",textStatus+", MESSAGE:",""+errorThrown);if(_.keys(state.config.transcriptLanguages).length>1){self.fetchAvailableTranslations()}else if(!fetchWithYoutubeId&&state.videoType==="html5"){console.log("[Video info]: Html5 mode fetching caption with youtubeId.");self.fetchCaption(true)}else{self.hideCaptions(true,false);self.state.el.find(".lang").hide();self.state.el.find(".transcript-control").hide();self.subtitlesEl.hide()}}});return true},fetchAvailableTranslations:function(){var self=this,state=this.state;this.availableTranslationsXHR=$.ajaxWithPrefix({url:state.config.transcriptAvailableTranslationsUrl,notifyOnError:false,success:function(response){var currentLanguages=state.config.transcriptLanguages,newLanguages=_.pick(currentLanguages,response);state.config.transcriptLanguages=newLanguages;self.container.find(".langs-list").remove();if(_.keys(newLanguages).length){self.fetchCaption();self.renderLanguageMenu(newLanguages)}},error:function(){self.hideCaptions(true,false);self.state.el.find(".lang").hide();self.state.el.find(".transcript-control").hide();self.subtitlesEl.hide()}});return this.availableTranslationsXHR},onResize:function(){this.subtitlesEl.find(".spacing").first().height(this.topSpacingHeight());this.subtitlesEl.find(".spacing").last().height(this.bottomSpacingHeight());this.scrollCaption();this.setSubtitlesHeight()},renderLanguageMenu:function(languages){var self=this,state=this.state,$menu=$('<ol class="langs-list menu">'),currentLang=state.getCurrentLanguage(),$li,$link,linkHtml;if(_.keys(languages).length<2){self.container.find(".lang").remove();return false}this.showLanguageMenu=true;$.each(languages,function(code,label){$li=$("<li />",{"data-lang-code":code});linkHtml=HtmlUtils.joinHtml(HtmlUtils.HTML('<button class="control control-lang">'),label,HtmlUtils.HTML("</button>"));$link=$(linkHtml.toString());if(currentLang===code){$li.addClass("is-active");$link.attr("aria-pressed","true")}$li.append($link);$menu.append($li)});HtmlUtils.append(this.languageChooserEl,HtmlUtils.HTML($menu));$menu.on("click",".control-lang",function(e){var el=$(e.currentTarget).parent(),state=self.state,langCode=el.data("lang-code");if(state.lang!==langCode){state.lang=langCode;el.addClass("is-active").siblings("li").removeClass("is-active").find(".control-lang").attr("aria-pressed","false");$(e.currentTarget).attr("aria-pressed","true");state.el.trigger("language_menu:change",[langCode]);self.fetchCaption();self.captionDisplayEl.attr("lang",langCode);self.subtitlesMenuEl.attr("lang",langCode);self.closeLanguageMenu(e)}})},buildCaptions:function(container,start,captions){var process=function(text,index){var $spanEl=$("<span>",{role:"link","data-index":index,"data-start":start[index],tabindex:0});HtmlUtils.setHtml($($spanEl),HtmlUtils.HTML(text.toString()));return $spanEl.wrap("<li>").parent()[0]};return AsyncProcess.array(captions,process).done(function(list){HtmlUtils.append(container,HtmlUtils.HTML(list))})},renderCaption:function(start,captions){var self=this;var onRender=function(){self.addPaddings();self.autoScrolling=true;self.currentCaptionIndex=-1;self.isMouseFocus=false;self.rendered=true;self.state.el.addClass("is-captions-rendered");self.subtitlesEl.attr("aria-label",gettext("Activating a link in this group will skip to the corresponding point in the video."));self.subtitlesEl.find(".transcript-title").text(gettext("Video transcript"));self.subtitlesEl.find(".transcript-start").text(gettext("Start of transcript. Skip to the end.")).attr("lang",$("html").attr("lang"));self.subtitlesEl.find(".transcript-end").text(gettext("End of transcript. Skip to the start.")).attr("lang",$("html").attr("lang"));self.container.find(".menu-container .instructions").text(gettext("Press the UP arrow key to enter the language menu then use UP and DOWN arrow keys to navigate language options. Press ENTER to change to the selected language."))};this.rendered=false;this.subtitlesMenuEl.empty();this.setSubtitlesHeight();this.buildCaptions(this.subtitlesMenuEl,start,captions).done(onRender)},addPaddings:function(){var topSpacer=HtmlUtils.interpolateHtml(HtmlUtils.HTML(['<li class="spacing" style="height: {height}px">','<a href="#transcript-end-{id}" id="transcript-start-{id}" class="transcript-start"></a>',"</li>"].join("")),{id:this.state.id,height:this.topSpacingHeight()});var bottomSpacer=HtmlUtils.interpolateHtml(HtmlUtils.HTML(['<li class="spacing" style="height: {height}px">','<a href="#transcript-start-{id}" id="transcript-end-{id}" class="transcript-end"></a>',"</li>"].join("")),{id:this.state.id,height:this.bottomSpacingHeight()});HtmlUtils.prepend(this.subtitlesMenuEl,topSpacer);HtmlUtils.append(this.subtitlesMenuEl,bottomSpacer)},captionMouseOverOut:function(event){var caption=$(event.target),captionIndex=parseInt(caption.attr("data-index"),10);if(captionIndex===this.currentCaptionIndex){if(event.type==="mouseover"){caption.removeClass("focused")}else{caption.addClass("focused")}}},captionMouseDown:function(event){var caption=$(event.target);this.isMouseFocus=true;this.autoScrolling=true;caption.removeClass("focused");this.currentCaptionIndex=-1},captionClick:function(event){this.seekPlayer(event)},captionFocus:function(event){var caption=$(event.target),container=caption.parent(),captionIndex=parseInt(caption.attr("data-index"),10);if(this.isMouseFocus){this.autoScrolling=true;container.removeClass("focused");this.currentCaptionIndex=-1}else{this.currentCaptionIndex=captionIndex;container.addClass("focused");if(captionIndex<=1||captionIndex>=this.sjson.getSize()-2){this.autoScrolling=false}}},captionBlur:function(event){var caption=$(event.target),container=caption.parent(),captionIndex=parseInt(caption.attr("data-index"),10);container.removeClass("focused");if(captionIndex===0||captionIndex===this.sjson.getSize()-1){this.autoScrolling=true}},captionKeyDown:function(event){this.isMouseFocus=false;if(event.which===13){this.seekPlayer(event)}},scrollCaption:function(){var el=this.subtitlesEl.find(".current:first");if(!this.frozen&&el.length&&this.autoScrolling){this.subtitlesEl.scrollTo(el,{offset:-1*this.calculateOffset(el)})}},play:function(){var captions,startAndCaptions,start;if(this.loaded){if(!this.rendered){startAndCaptions=this.getBoundedCaptions();start=startAndCaptions.start;captions=startAndCaptions.captions;this.renderCaption(start,captions)}this.playing=true}},pause:function(){if(this.loaded){this.playing=false}},updatePlayTime:function(time){var state=this.state,params,newIndex;if(this.loaded){if(state.isFlashMode()){time=Time.convert(time,state.speed,"1.0")}time=Math.round(time*1e3+100);var times=this.getStartEndTimes();params=[time].concat(times);newIndex=this.sjson.search.apply(this.sjson,params);if(typeof newIndex!=="undefined"&&newIndex!==-1&&this.currentIndex!==newIndex){if(typeof this.currentIndex!=="undefined"){this.subtitlesEl.find("li.current").removeClass("current")}this.subtitlesEl.find("span[data-index='"+newIndex+"']").parent().addClass("current");this.currentIndex=newIndex;this.captionDisplayEl.text(this.subtitlesEl.find("span[data-index='"+newIndex+"']").text());this.scrollCaption()}}},seekPlayer:function(event){var state=this.state,time=parseInt($(event.target).data("start"),10);if(state.isFlashMode()){time=Math.round(Time.convert(time,"1.0",state.speed))}state.trigger("videoPlayer.onCaptionSeek",{type:"onCaptionSeek",time:time/1e3});event.preventDefault()},calculateOffset:function(element){return this.captionHeight()/2-element.height()/2},topSpacingHeight:function(){return this.calculateOffset(this.subtitlesEl.find("li:not(.spacing)").first())},bottomSpacingHeight:function(){return this.calculateOffset(this.subtitlesEl.find("li:not(.spacing)").last())},toggle:function(event){event.preventDefault();if(this.state.el.hasClass("closed")){this.hideCaptions(false,true,true)}else{this.hideCaptions(true,true,true)}},handleCaptioningCookie:function(){if($.cookie("show_closed_captions")==="true"){this.state.showClosedCaptions=true;this.showClosedCaptions();$.cookie("show_closed_captions","true",{expires:3650,path:"/"})}else{this.hideClosedCaptions()}},toggleClosedCaptions:function(event){event.preventDefault();if(this.state.el.hasClass("has-captions")){this.state.showClosedCaptions=false;this.updateCaptioningCookie(false);this.hideClosedCaptions()}else{this.state.showClosedCaptions=true;this.updateCaptioningCookie(true);this.showClosedCaptions()}},showClosedCaptions:function(){this.state.el.addClass("has-captions");this.captionDisplayEl.show().addClass("is-visible").attr("lang",this.state.lang);this.captionControlEl.addClass("is-active").attr("title",gettext("Hide closed captions"));if(this.subtitlesEl.find(".current").text()){this.captionDisplayEl.text(this.subtitlesEl.find(".current").text())}else{this.captionDisplayEl.text(gettext("(Caption will be displayed when you start playing the video.)"))}this.state.el.trigger("captions:show")},hideClosedCaptions:function(){this.state.el.removeClass("has-captions");this.captionDisplayEl.hide().removeClass("is-visible");this.captionControlEl.removeClass("is-active").attr("title",gettext("Turn on closed captioning"));this.state.el.trigger("captions:hide")},updateCaptioningCookie:function(method){if(method){$.cookie("show_closed_captions","true",{expires:3650,path:"/"})}else{$.cookie("show_closed_captions",null,{path:"/"})}},listenForDragDrop:function(){var captions=document.querySelector(".closed-captions"),draggable;if(typeof Draggabilly==="function"){draggable=new Draggabilly(captions,{containment:true})}else{console.log("Closed captioning available but not draggable")}},hideCaptions:function(hide_captions,update_cookie,trigger_event){var transcriptControlEl=this.transcriptControlEl,state=this.state,text;if(typeof update_cookie==="undefined"){update_cookie=true}if(hide_captions){state.captionsHidden=true;state.el.addClass("closed");text=gettext("Turn on transcripts");if(trigger_event){this.state.el.trigger("transcript:hide")}transcriptControlEl.removeClass("is-active").attr("title",gettext(text))}else{state.captionsHidden=false;state.el.removeClass("closed");this.scrollCaption();text=gettext("Turn off transcripts");if(trigger_event){this.state.el.trigger("transcript:show")}transcriptControlEl.addClass("is-active").attr("title",gettext(text))}if(state.resizer){if(state.isFullScreen){state.resizer.setMode("both")}else{state.resizer.alignByWidthOnly()}}this.setSubtitlesHeight();if(update_cookie){$.cookie("hide_captions",hide_captions,{expires:3650,path:"/"})}},captionHeight:function(){var state=this.state;if(state.isFullScreen){return state.container.height()-state.videoFullScreen.height}else{return state.container.height()}},setSubtitlesHeight:function(){var height=0,state=this.state;if(state.captionsHidden===undefined&&state.hide_captions||state.captionsHidden===true){height=state.el.find(".video-controls").height()+.5*state.el.find(".slider").height()}this.subtitlesEl.css({maxHeight:this.captionHeight()-height})}};return VideoCaption})})(RequireJS.define);(function(define){"use strict";define("video/09_play_placeholder.js",[],function(){var PlayPlaceholder=function(state,i18n){if(!(this instanceof PlayPlaceholder)){return new PlayPlaceholder(state,i18n)}_.bindAll(this,"onClick","hide","show","destroy");this.state=state;this.state.videoPlayPlaceholder=this;this.i18n=i18n;this.initialize();return $.Deferred().resolve().promise()};PlayPlaceholder.prototype={destroy:function(){this.el.off("click",this.onClick);this.state.el.on({destroy:this.destroy,play:this.hide,"ended pause":this.show});this.hide();delete this.state.videoPlayPlaceholder},shouldBeShown:function(){return/iPad|Android/i.test(this.state.isTouch[0])&&!this.state.isYoutubeType()},initialize:function(){if(!this.shouldBeShown()){return false}this.el=this.state.el.find(".btn-play");this.bindHandlers();this.show()},bindHandlers:function(){this.el.on("click",this.onClick);this.state.el.on({destroy:this.destroy,play:this.hide,"ended pause":this.show})},onClick:function(){this.state.videoCommands.execute("play")},hide:function(){this.el.addClass("is-hidden").attr({"aria-hidden":"true",tabindex:-1})},show:function(){this.el.removeClass("is-hidden").attr({"aria-hidden":"false",tabindex:0})}};return PlayPlaceholder})})(RequireJS.define);(function(define){"use strict";define("video/09_play_pause_control.js",[],function(){var PlayPauseControl=function(state,i18n){if(!(this instanceof PlayPauseControl)){return new PlayPauseControl(state,i18n)}_.bindAll(this,"play","pause","onClick","destroy");this.state=state;this.state.videoPlayPauseControl=this;this.i18n=i18n;this.initialize();return $.Deferred().resolve().promise()};PlayPauseControl.prototype={template:['<button class="control video_control play" aria-disabled="false" title="',gettext("Play"),'">','<span class="icon fa fa-play" aria-hidden="true"></span>',"</button>"].join(""),destroy:function(){this.el.remove();this.state.el.off("destroy",this.destroy);delete this.state.videoPlayPauseControl},initialize:function(){this.el=$(this.template);this.render();this.bindHandlers()},render:function(){this.state.el.find(".vcr").prepend(this.el)},bindHandlers:function(){this.el.on({click:this.onClick});this.state.el.on({play:this.play,"pause ended":this.pause,destroy:this.destroy})},onClick:function(event){event.preventDefault();this.state.videoCommands.execute("togglePlayback")},play:function(){this.el.addClass("pause").removeClass("play").attr("title",gettext("Pause")).find(".icon").removeClass("fa-play").addClass("fa-pause")},pause:function(){this.el.removeClass("pause").addClass("play").attr("title",gettext("Play")).find(".icon").removeClass("fa-pause").addClass("fa-play")}};return PlayPauseControl})})(RequireJS.define);(function(define){"use strict";define("video/09_play_skip_control.js",[],function(){var PlaySkipControl=function(state,i18n){if(!(this instanceof PlaySkipControl)){return new PlaySkipControl(state,i18n)}_.bindAll(this,"play","onClick","destroy");this.state=state;this.state.videoPlaySkipControl=this;this.i18n=i18n;this.initialize();return $.Deferred().resolve().promise()};PlaySkipControl.prototype={template:['<button class="control video_control play play-skip-control" title="',gettext("Play"),'">','<span class="icon fa fa-play" aria-hidden="true"></span>',"</button>"].join(""),destroy:function(){this.el.remove();this.state.el.off("destroy",this.destroy);delete this.state.videoPlaySkipControl},initialize:function(){this.el=$(this.template);this.render();this.bindHandlers()},render:function(){this.state.el.find(".vcr").prepend(this.el)},bindHandlers:function(){this.el.on("click",this.onClick);this.state.el.on({play:this.play,destroy:this.destroy})},onClick:function(event){event.preventDefault();if(this.state.videoPlayer.isPlaying()){this.state.videoCommands.execute("skip")}else{this.state.videoCommands.execute("play")}},play:function(){this.el.removeClass("play").addClass("skip").attr("title",gettext("Skip")).find(".icon").removeClass("fa-play").addClass("fa-step-forward");this.state.el.find("video").off("click")}};return PlaySkipControl})})(RequireJS.define);(function(define){"use strict";define("video/09_skip_control.js",[],function(){var SkipControl=function(state,i18n){if(!(this instanceof SkipControl)){return new SkipControl(state,i18n)}_.bindAll(this,"onClick","render","destroy");this.state=state;this.state.videoSkipControl=this;this.i18n=i18n;this.initialize();return $.Deferred().resolve().promise()};SkipControl.prototype={template:['<button class="control video_control skip skip-control" aria-disabled="false" title="',gettext("Do not show again"),'">','<span class="icon fa fa-step-forward" aria-hidden="true"></span>',"</button>"].join(""),destroy:function(){this.el.remove();this.state.el.off(".skip");delete this.state.videoSkipControl},initialize:function(){this.el=$(this.template);this.bindHandlers()},render:function(){this.state.el.find(".vcr .control").after(this.el)},bindHandlers:function(){this.el.on("click",this.onClick);this.state.el.on({"play.skip":_.once(this.render),"destroy.skip":this.destroy})},onClick:function(event){event.preventDefault();this.state.videoCommands.execute("skip",true)}};return SkipControl})})(RequireJS.define);(function(define){"use strict";define("video/09_bumper.js",[],function(){var VideoBumper=function(player,state){if(!(this instanceof VideoBumper)){return new VideoBumper(player,state)}_.bindAll(this,"showMainVideoHandler","destroy","skipByDuration","destroyAndResolve");this.dfd=$.Deferred();this.element=state.el;this.element.addClass("is-bumper");this.player=player;this.state=state;this.doNotShowAgain=false;this.state.videoBumper=this;this.bindHandlers();this.initialize();this.maxBumperDuration=35};VideoBumper.prototype={initialize:function(){this.player()},getPromise:function(){return this.dfd.promise()},showMainVideoHandler:function(){this.state.storage.setItem("isBumperShown",true);setTimeout(function(){this.saveState();this.showMainVideo()}.bind(this),20)},destroyAndResolve:function(){this.destroy();this.dfd.resolve()},showMainVideo:function(){if(this.state.videoPlayer){this.destroyAndResolve()}else{this.state.el.on("initialize",this.destroyAndResolve)}},skip:function(){this.element.trigger("skip",[this.doNotShowAgain]);this.showMainVideoHandler()},skipAndDoNotShowAgain:function(){this.doNotShowAgain=true;this.skip()},skipByDuration:function(event,time){if(time>this.maxBumperDuration){this.element.trigger("ended")}},bindHandlers:function(){var events=["ended","error"].join(" ");this.element.on(events,this.showMainVideoHandler);this.element.on("timeupdate",this.skipByDuration)},saveState:function(){var info={bumper_last_view_date:true};if(this.doNotShowAgain){_.extend(info,{bumper_do_not_show_again:true})}if(this.state.videoSaveStatePlugin){this.state.videoSaveStatePlugin.saveState(true,info)}},destroy:function(){var events=["ended","error"].join(" ");this.element.off(events,this.showMainVideoHandler);this.element.off({timeupdate:this.skipByDuration,initialize:this.destroyAndResolve});this.element.removeClass("is-bumper");if(_.isFunction(this.state.videoPlayer.destroy)){this.state.videoPlayer.destroy()}delete this.state.videoBumper}};return VideoBumper})})(RequireJS.define);(function(define){"use strict";define("video/09_save_state_plugin.js",[],function(){var SaveStatePlugin=function(state,i18n,options){if(!(this instanceof SaveStatePlugin)){return new SaveStatePlugin(state,i18n,options)}_.bindAll(this,"onSpeedChange","saveStateHandler","bindUnloadHandler","onUnload","onYoutubeAvailability","onLanguageChange","destroy");this.state=state;this.options=_.extend({events:[]},options);this.state.videoSaveStatePlugin=this;this.i18n=i18n;this.initialize();return $.Deferred().resolve().promise()};SaveStatePlugin.moduleName="SaveStatePlugin";SaveStatePlugin.prototype={destroy:function(){this.state.el.off(this.events).off("destroy",this.destroy);$(window).off("unload",this.onUnload);delete this.state.videoSaveStatePlugin},initialize:function(){this.events={speedchange:this.onSpeedChange,play:this.bindUnloadHandler,"pause destroy":this.saveStateHandler,"language_menu:change":this.onLanguageChange,youtube_availability:this.onYoutubeAvailability};this.bindHandlers()},bindHandlers:function(){if(this.options.events.length){_.each(this.options.events,function(eventName){var callback;if(_.has(this.events,eventName)){callback=this.events[eventName];this.state.el.on(eventName,callback)}},this)}else{this.state.el.on(this.events)}this.state.el.on("destroy",this.destroy)},bindUnloadHandler:_.once(function(){$(window).on("unload.video",this.onUnload)}),onSpeedChange:function(event,newSpeed){this.saveState(true,{speed:newSpeed});this.state.storage.setItem("speed",newSpeed,true);this.state.storage.setItem("general_speed",newSpeed)},saveStateHandler:function(){this.saveState(true)},onUnload:function(){this.saveState()},onLanguageChange:function(event,langCode){this.state.storage.setItem("language",langCode)},onYoutubeAvailability:function(event,youtubeIsAvailable){if(youtubeIsAvailable!==this.state.config.recordedYoutubeIsAvailable){this.saveState(true,{youtube_is_available:youtubeIsAvailable})}},saveState:function(async,data){if(!$.isPlainObject(data)){data={saved_video_position:this.state.videoPlayer.currentTime}}if(data.speed){this.state.storage.setItem("speed",data.speed,true)}if(_.has(data,"saved_video_position")){this.state.storage.setItem("savedVideoPosition",data.saved_video_position,true);data.saved_video_position=Time.formatFull(data.saved_video_position)}$.ajax({url:this.state.config.saveStateUrl,type:"POST",async:async?true:false,dataType:"json",data:data})}};return SaveStatePlugin})})(RequireJS.define);(function(define){"use strict";define("video/09_events_plugin.js",[],function(){var EventsPlugin=function(state,i18n,options){if(!(this instanceof EventsPlugin)){return new EventsPlugin(state,i18n,options)}_.bindAll(this,"onReady","onPlay","onPause","onEnded","onSeek","onSpeedChange","onShowLanguageMenu","onHideLanguageMenu","onSkip","onShowTranscript","onHideTranscript","onShowCaptions","onHideCaptions","destroy");this.state=state;this.options=_.extend({},options);this.state.videoEventsPlugin=this;this.i18n=i18n;this.initialize();return $.Deferred().resolve().promise()};EventsPlugin.moduleName="EventsPlugin";EventsPlugin.prototype={destroy:function(){this.state.el.off(this.events);delete this.state.videoEventsPlugin},initialize:function(){this.events={ready:this.onReady,play:this.onPlay,pause:this.onPause,"ended stop":this.onEnded,seek:this.onSeek,skip:this.onSkip,speedchange:this.onSpeedChange,"language_menu:show":this.onShowLanguageMenu,"language_menu:hide":this.onHideLanguageMenu,"transcript:show":this.onShowTranscript,"transcript:hide":this.onHideTranscript,"captions:show":this.onShowCaptions,"captions:hide":this.onHideCaptions,destroy:this.destroy};this.bindHandlers();this.emitPlayVideoEvent=true},bindHandlers:function(){this.state.el.on(this.events)},onReady:function(){this.log("load_video")},onPlay:function(){if(this.emitPlayVideoEvent){this.log("play_video",{currentTime:this.getCurrentTime()});this.emitPlayVideoEvent=false}},onPause:function(){this.log("pause_video",{currentTime:this.getCurrentTime()});this.emitPlayVideoEvent=true},onEnded:function(){this.log("stop_video",{currentTime:this.getCurrentTime()});this.emitPlayVideoEvent=true},onSkip:function(event,doNotShowAgain){var info={currentTime:this.getCurrentTime()},eventName=doNotShowAgain?"do_not_show_again_video":"skip_video";this.log(eventName,info)},onSeek:function(event,time,oldTime,type){this.log("seek_video",{old_time:oldTime,new_time:time,type:type});this.emitPlayVideoEvent=true},onSpeedChange:function(event,newSpeed,oldSpeed){this.log("speed_change_video",{current_time:this.getCurrentTime(),old_speed:oldSpeed,new_speed:newSpeed})},onShowLanguageMenu:function(){this.log("edx.video.language_menu.shown")},onHideLanguageMenu:function(){this.log("edx.video.language_menu.hidden",{language:this.getCurrentLanguage()})},onShowTranscript:function(){this.log("show_transcript",{current_time:this.getCurrentTime()})},onHideTranscript:function(){this.log("hide_transcript",{current_time:this.getCurrentTime()})},onShowCaptions:function(){this.log("edx.video.closed_captions.shown",{current_time:this.getCurrentTime()})},onHideCaptions:function(){this.log("edx.video.closed_captions.hidden",{current_time:this.getCurrentTime()})},getCurrentTime:function(){var player=this.state.videoPlayer;return player?player.currentTime:0},getCurrentLanguage:function(){var language=this.state.lang;return language},log:function(eventName,data){var logInfo=_.extend({id:this.state.id,code:this.state.isYoutubeType()?this.state.youtubeId():"html5"},data,this.options.data);Logger.log(eventName,logInfo)}};return EventsPlugin})})(RequireJS.define);(function(define){"use strict";define("video/09_events_bumper_plugin.js",[],function(){var EventsBumperPlugin=function(state,i18n,options){if(!(this instanceof EventsBumperPlugin)){return new EventsBumperPlugin(state,i18n,options)}_.bindAll(this,"onReady","onPlay","onEnded","onShowLanguageMenu","onHideLanguageMenu","onSkip","onShowCaptions","onHideCaptions","destroy");this.state=state;this.options=_.extend({},options);this.state.videoEventsBumperPlugin=this;this.i18n=i18n;this.initialize();return $.Deferred().resolve().promise()};EventsBumperPlugin.moduleName="EventsBumperPlugin";EventsBumperPlugin.prototype={destroy:function(){this.state.el.off(this.events);delete this.state.videoEventsBumperPlugin},initialize:function(){this.events={ready:this.onReady,play:this.onPlay,"ended stop":this.onEnded,skip:this.onSkip,"language_menu:show":this.onShowLanguageMenu,"language_menu:hide":this.onHideLanguageMenu,"captions:show":this.onShowCaptions,"captions:hide":this.onHideCaptions,destroy:this.destroy};this.bindHandlers()},bindHandlers:function(){this.state.el.on(this.events)},onReady:function(){this.log("edx.video.bumper.loaded")},onPlay:function(){this.log("edx.video.bumper.played",{currentTime:this.getCurrentTime()})},onEnded:function(){this.log("edx.video.bumper.stopped",{currentTime:this.getCurrentTime()})},onSkip:function(event,doNotShowAgain){var info={currentTime:this.getCurrentTime()},eventName="edx.video.bumper."+(doNotShowAgain?"dismissed":"skipped");this.log(eventName,info)},onShowLanguageMenu:function(){this.log("edx.video.bumper.transcript.menu.shown")},onHideLanguageMenu:function(){this.log("edx.video.bumper.transcript.menu.hidden")},onShowCaptions:function(){this.log("edx.video.bumper.transcript.shown",{currentTime:this.getCurrentTime()})},onHideCaptions:function(){this.log("edx.video.bumper.transcript.hidden",{currentTime:this.getCurrentTime()})},getCurrentTime:function(){var player=this.state.videoPlayer;return player?player.currentTime:0},getDuration:function(){var player=this.state.videoPlayer;return player?player.duration():0},log:function(eventName,data){var logInfo=_.extend({host_component_id:this.state.id,bumper_id:this.state.config.sources[0]||"",duration:this.getDuration(),code:"html5"},data,this.options.data);Logger.log(eventName,logInfo)}};return EventsBumperPlugin})})(RequireJS.define);(function(define){"use strict";define("video/09_poster.js",[],function(){var VideoPoster=function(element,options){if(!(this instanceof VideoPoster)){return new VideoPoster(element,options)}_.bindAll(this,"onClick","destroy");this.element=element;this.container=element.find(".video-player");this.options=options||{};this.initialize();
11};VideoPoster.moduleName="Poster";VideoPoster.prototype={template:_.template(['<div class="video-pre-roll is-<%= type %> poster" ','style="background-image: url(<%= url %>)">','<button class="btn-play btn-pre-roll">','<img src="/static/images/play.png" alt="">','<span class="sr">',gettext("Play video"),"</span>","</button>","</div>"].join("")),initialize:function(){this.el=$(this.template({url:this.options.poster.url,type:this.options.poster.type}));this.element.addClass("is-pre-roll");this.render();this.bindHandlers()},bindHandlers:function(){this.el.on("click",this.onClick);this.element.on("destroy",this.destroy)},render:function(){this.container.append(this.el)},onClick:function(){if(_.isFunction(this.options.onClick)){this.options.onClick()}this.destroy()},destroy:function(){this.element.off("destroy",this.destroy).removeClass("is-pre-roll");this.el.remove()}};return VideoPoster})})(RequireJS.define);(function(define){"use strict";define("video/095_video_context_menu.js",["video/00_component.js"],function(Component){var AbstractItem,AbstractMenu,Menu,Overlay,Submenu,MenuItem;AbstractItem=Component.extend({initialize:function(options){this.options=$.extend(true,{label:"",prefix:"edx-",dataAttrs:{menu:this},attrs:{},items:[],callback:$.noop,initialize:$.noop},options);this.id=_.uniqueId();this.element=this.createElement();this.element.attr(this.options.attrs).data(this.options.dataAttrs);this.children=[];this.delegateEvents();this.options.initialize.call(this,this)},destroy:function(){_.invoke(this.getChildren(),"destroy");this.undelegateEvents();this.getElement().remove()},open:function(){this.getElement().addClass("is-opened");return this},close:function(){},closeSiblings:function(){_.invoke(this.getSiblings(),"close");return this},getElement:function(){return this.element},addChild:function(child){var firstChild=null,lastChild=null;if(this.hasChildren()){lastChild=this.getLastChild();lastChild.next=child;firstChild=this.getFirstChild();firstChild.prev=child}child.parent=this;child.next=firstChild;child.prev=lastChild;this.children.push(child);return this},getChildren:function(){return this.children.concat()},hasChildren:function(){return this.getChildren().length>0},getFirstChild:function(){return _.first(this.children)},getLastChild:function(){return _.last(this.children)},bindEvent:function(element,events,handler){$(element).on(this.addNamespace(events),handler);return this},getNext:function(){var item=this.next;while(item.isHidden()&&this.id!==item.id){item=item.next}return item},getPrev:function(){var item=this.prev;while(item.isHidden()&&this.id!==item.id){item=item.prev}return item},createElement:function(){return null},getRoot:function(){var item=this;while(item.parent){item=item.parent}return item},populateElement:function(){},focus:function(){this.getElement().focus();this.closeSiblings();return this},isHidden:function(){return this.getElement().is(":hidden")},getSiblings:function(){var items=[],item=this;while(item.next&&item.next.id!==this.id){item=item.next;items.push(item)}return items},select:function(){},unselect:function(){},setLabel:function(){},itemHandler:function(){},keyDownHandler:function(){},delegateEvents:function(){},undelegateEvents:function(){this.getElement().off("."+this.id)},addNamespace:function(events){return _.map(events.split(/\s+/),function(event){return event+"."+this.id},this).join(" ")}});AbstractMenu=AbstractItem.extend({delegateEvents:function(){this.bindEvent(this.getElement(),"keydown mouseleave mouseover",this.itemHandler.bind(this)).bindEvent(this.getElement(),"contextmenu",function(event){event.preventDefault()});return this},populateElement:function(){var fragment=document.createDocumentFragment();_.each(this.getChildren(),function(child){fragment.appendChild(child.populateElement()[0])},this);this.appendContent([fragment]);this.isRendered=true;return this.getElement()},close:function(){this.closeChildren();this.getElement().removeClass("is-opened");return this},closeChildren:function(){_.invoke(this.getChildren(),"close");return this},itemHandler:function(event){event.preventDefault();var item=$(event.target).data("menu");switch(event.type){case"keydown":this.keyDownHandler.call(this,event,item);break;case"mouseover":this.mouseOverHandler.call(this,event,item);break;case"mouseleave":this.mouseLeaveHandler.call(this,event,item);break}},keyDownHandler:function(){},mouseOverHandler:function(){},mouseLeaveHandler:function(){}});Menu=AbstractMenu.extend({initialize:function(options,contextmenuElement,container){this.contextmenuElement=$(contextmenuElement);this.container=$(container);this.overlay=this.getOverlay();AbstractMenu.prototype.initialize.apply(this,arguments);this.build(this,this.options.items)},createElement:function(){return $("<ol />",{class:["contextmenu",this.options.prefix+"contextmenu"].join(" "),role:"menu",tabindex:-1})},delegateEvents:function(){AbstractMenu.prototype.delegateEvents.call(this);this.bindEvent(this.contextmenuElement,"contextmenu",this.contextmenuHandler.bind(this)).bindEvent(window,"resize",_.debounce(this.close.bind(this),100));return this},destroy:function(){AbstractMenu.prototype.destroy.call(this);this.overlay.destroy();this.contextmenuElement.removeData("contextmenu");return this},undelegateEvents:function(){AbstractMenu.prototype.undelegateEvents.call(this);this.contextmenuElement.off(this.addNamespace("contextmenu"));this.overlay.undelegateEvents();return this},appendContent:function(content){this.getElement().append(content);return this},addChild:function(){AbstractMenu.prototype.addChild.apply(this,arguments);this.next=this.getFirstChild();this.prev=this.getLastChild();return this},build:function(container,items){_.each(items,function(item){var child;if(_.has(item,"items")){child=this.build(new Submenu(item,this.contextmenuElement),item.items)}else{child=new MenuItem(item)}container.addChild(child)},this);return container},focus:function(){this.getElement().focus();return this},open:function(){var menu=this.isRendered?this.getElement():this.populateElement();this.container.append(menu);AbstractItem.prototype.open.call(this);this.overlay.show(this.container);return this},close:function(){AbstractMenu.prototype.close.call(this);this.getElement().detach();this.overlay.hide();return this},position:function(event){this.getElement().position({my:"left top",of:event,collision:"flipfit flipfit",within:this.contextmenuElement});return this},pointInContainerBox:function(x,y){var containerOffset=this.contextmenuElement.offset(),containerBox={x0:containerOffset.left,y0:containerOffset.top,x1:containerOffset.left+this.contextmenuElement.outerWidth(),y1:containerOffset.top+this.contextmenuElement.outerHeight()};return containerBox.x0<=x&&x<=containerBox.x1&&containerBox.y0<=y&&y<=containerBox.y1},getOverlay:function(){return new Overlay(this.close.bind(this),function(event){event.preventDefault();if(this.pointInContainerBox(event.pageX,event.pageY)){this.position(event).focus();this.closeChildren()}else{this.close()}}.bind(this))},contextmenuHandler:function(event){event.preventDefault();event.stopPropagation();this.open().position(event).focus()},keyDownHandler:function(event,item){var KEY=$.ui.keyCode,keyCode=event.keyCode;switch(keyCode){case KEY.UP:item.getPrev().focus();event.stopPropagation();break;case KEY.DOWN:item.getNext().focus();event.stopPropagation();break;case KEY.TAB:event.stopPropagation();break;case KEY.ESCAPE:this.close();break}return false}});Overlay=Component.extend({ns:".overlay",initialize:function(clickHandler,contextmenuHandler){this.element=$("<div />",{class:"overlay"});this.clickHandler=clickHandler;this.contextmenuHandler=contextmenuHandler},destroy:function(){this.getElement().remove();this.undelegateEvents()},getElement:function(){return this.element},hide:function(){this.getElement().detach();this.undelegateEvents();return this},show:function(container){$(container).append(this.getElement());this.delegateEvents();return this},delegateEvents:function(){var self=this;$(document).on("click"+this.ns,function(){if(_.isFunction(self.clickHandler)){self.clickHandler.apply(this,arguments)}self.hide()}).on("contextmenu"+this.ns,function(){if(_.isFunction(self.contextmenuHandler)){self.contextmenuHandler.apply(this,arguments)}});return this},undelegateEvents:function(){$(document).off(this.ns);return this}});Submenu=AbstractMenu.extend({initialize:function(options,contextmenuElement){this.contextmenuElement=contextmenuElement;AbstractMenu.prototype.initialize.apply(this,arguments)},createElement:function(){var element=$("<li />",{class:["submenu-item","menu-item",this.options.prefix+"submenu-item"].join(" "),"aria-expanded":"false","aria-haspopup":"true","aria-labelledby":"submenu-item-label-"+this.id,role:"menuitem",tabindex:-1});this.label=$("<span />",{id:"submenu-item-label-"+this.id,text:this.options.label}).appendTo(element);this.list=$("<ol />",{class:["submenu",this.options.prefix+"submenu"].join(" "),role:"menu"}).appendTo(element);return element},appendContent:function(content){this.list.append(content);return this},setLabel:function(label){this.label.text(label);return this},openKeyboard:function(){if(this.hasChildren()){this.open();this.getFirstChild().focus()}return this},keyDownHandler:function(event){var KEY=$.ui.keyCode,keyCode=event.keyCode;switch(keyCode){case KEY.LEFT:this.close().focus();event.stopPropagation();break;case KEY.RIGHT:case KEY.ENTER:case KEY.SPACE:this.openKeyboard();event.stopPropagation();break}return false},open:function(){AbstractMenu.prototype.open.call(this);this.getElement().attr({"aria-expanded":"true"});this.position();return this},close:function(){AbstractMenu.prototype.close.call(this);this.getElement().attr({"aria-expanded":"false"});return this},position:function(){this.list.position({my:"left top",at:"right top",of:this.getElement(),collision:"flipfit flipfit",within:this.contextmenuElement});return this},mouseOverHandler:function(){clearTimeout(this.timer);this.timer=setTimeout(this.open.bind(this),200);this.focus()},mouseLeaveHandler:function(){clearTimeout(this.timer);this.timer=setTimeout(this.close.bind(this),200);this.focus()}});MenuItem=AbstractItem.extend({createElement:function(){var classNames=["menu-item",this.options.prefix+"menu-item",this.options.isSelected?"is-selected":""].join(" ");return $("<li />",{class:classNames,"aria-selected":this.options.isSelected?"true":"false",role:"menuitem",tabindex:-1,text:this.options.label})},populateElement:function(){return this.getElement()},delegateEvents:function(){this.bindEvent(this.getElement(),"click keydown contextmenu mouseover",this.itemHandler.bind(this));return this},setLabel:function(label){this.getElement().text(label);return this},select:function(event){this.options.callback.call(this,event,this,this.options);this.getElement().addClass("is-selected").attr({"aria-selected":"true"});_.invoke(this.getSiblings(),"unselect");this.getRoot().close();return this},unselect:function(){this.getElement().removeClass("is-selected").attr({"aria-selected":"false"});return this},itemHandler:function(event){event.preventDefault();switch(event.type){case"contextmenu":case"click":this.select();break;case"mouseover":this.focus();event.stopPropagation();break;case"keydown":this.keyDownHandler.call(this,event,this);break}},keyDownHandler:function(event){var KEY=$.ui.keyCode,keyCode=event.keyCode;switch(keyCode){case KEY.RIGHT:event.stopPropagation();break;case KEY.ENTER:case KEY.SPACE:this.select();event.stopPropagation();break}return false}});return function(state,i18n){var speedCallback=function(event,menuitem,options){var speed=parseFloat(options.label);state.videoCommands.execute("speed",speed)},options={items:[{label:i18n.Play,callback:function(){state.videoCommands.execute("togglePlayback")},initialize:function(menuitem){state.el.on({play:function(){menuitem.setLabel(i18n.Pause)},pause:function(){menuitem.setLabel(i18n.Play)}})}},{label:state.videoVolumeControl.getMuteStatus()?i18n.Unmute:i18n.Mute,callback:function(){state.videoCommands.execute("toggleMute")},initialize:function(menuitem){state.el.on({volumechange:function(){if(state.videoVolumeControl.getMuteStatus()){menuitem.setLabel(i18n.Unmute)}else{menuitem.setLabel(i18n.Mute)}}})}},{label:i18n["Fill browser"],callback:function(){state.videoCommands.execute("toggleFullScreen")},initialize:function(menuitem){state.el.on({fullscreen:function(event,isFullscreen){if(isFullscreen){menuitem.setLabel(i18n["Exit full browser"])}else{menuitem.setLabel(i18n["Fill browser"])}}})}},{label:i18n.Speed,items:_.map(state.speeds,function(speed){var isSelected=speed===state.speed;return{label:speed+"x",callback:speedCallback,speed:speed,isSelected:isSelected}}),initialize:function(menuitem){state.el.on({speedchange:function(event,speed){var item=menuitem.getChildren().filter(function(item){return item.options.speed===speed})[0];if(item){item.select()}}})}}]};$.fn.contextmenu=function(container,options){return this.each(function(){$(this).data("contextmenu",new Menu(options,this,container))})};if(!state.isYoutubeType()){state.el.find("video").contextmenu(state.el,options);state.el.on("destroy",function(){var contextmenu=$(this).find("video").data("contextmenu");if(contextmenu){contextmenu.destroy()}})}return $.Deferred().resolve().promise()}})})(RequireJS.define);(function(define){"use strict";define("video/10_commands.js",[],function(){var VideoCommands,Command,playCommand,pauseCommand,togglePlaybackCommand,toggleMuteCommand,toggleFullScreenCommand,setSpeedCommand,skipCommand;VideoCommands=function(state,i18n){if(!(this instanceof VideoCommands)){return new VideoCommands(state,i18n)}_.bindAll(this,"destroy");this.state=state;this.state.videoCommands=this;this.i18n=i18n;this.commands=[];this.initialize();return $.Deferred().resolve().promise()};VideoCommands.prototype={destroy:function(){this.state.el.off("destroy",this.destroy);delete this.state.videoCommands},initialize:function(){this.commands=this.getCommands();this.state.el.on("destroy",this.destroy)},execute:function(command){var args=[].slice.call(arguments,1)||[];if(_.has(this.commands,command)){this.commands[command].execute.apply(this,[this.state].concat(args))}else{console.log('Command "'+command+'" is not available.')}},getCommands:function(){var commands={},commandsList=[playCommand,pauseCommand,togglePlaybackCommand,toggleMuteCommand,toggleFullScreenCommand,setSpeedCommand,skipCommand];_.each(commandsList,function(command){commands[command.name]=command},this);return commands}};Command=function(name,execute){this.name=name;this.execute=execute};playCommand=new Command("play",function(state){state.videoPlayer.play()});pauseCommand=new Command("pause",function(state){state.videoPlayer.pause()});togglePlaybackCommand=new Command("togglePlayback",function(state){if(state.videoPlayer.isPlaying()){pauseCommand.execute(state)}else{playCommand.execute(state)}});toggleMuteCommand=new Command("toggleMute",function(state){state.videoVolumeControl.toggleMute()});toggleFullScreenCommand=new Command("toggleFullScreen",function(state){state.videoFullScreen.toggle()});setSpeedCommand=new Command("speed",function(state,speed){state.videoSpeedControl.setSpeed(state.speedToString(speed))});skipCommand=new Command("skip",function(state,doNotShowAgain){if(doNotShowAgain){state.videoBumper.skipAndDoNotShowAgain()}else{state.videoBumper.skip()}});return VideoCommands})})(RequireJS.define);(function(require,$){"use strict";window.Video=function(){var tempCallStack=[];return function(element,processTempCallStack){if(processTempCallStack){$.each(tempCallStack,function(index,element){window.Video(element)});return}tempCallStack.push(element);return{}}}();require(["video/00_video_storage.js","video/01_initialize.js","video/025_focus_grabber.js","video/035_video_accessible_menu.js","video/04_video_control.js","video/04_video_full_screen.js","video/05_video_quality_control.js","video/06_video_progress_slider.js","video/07_video_volume_control.js","video/08_video_speed_control.js","video/09_video_caption.js","video/09_play_placeholder.js","video/09_play_pause_control.js","video/09_play_skip_control.js","video/09_skip_control.js","video/09_bumper.js","video/09_save_state_plugin.js","video/09_events_plugin.js","video/09_events_bumper_plugin.js","video/09_poster.js","video/10_commands.js","video/095_video_context_menu.js"],function(VideoStorage,initialize,FocusGrabber,VideoAccessibleMenu,VideoControl,VideoFullScreen,VideoQualityControl,VideoProgressSlider,VideoVolumeControl,VideoSpeedControl,VideoCaption,VideoPlayPlaceholder,VideoPlayPauseControl,VideoPlaySkipControl,VideoSkipControl,VideoBumper,VideoSaveStatePlugin,VideoEventsPlugin,VideoEventsBumperPlugin,VideoPoster,VideoCommands,VideoContextMenu){var youtubeXhr=null,oldVideo=window.Video;window.Video=function(element){var el=$(element).find(".video"),id=el.attr("id").replace(/video_/,""),storage=VideoStorage("VideoState",id),bumperMetadata=el.data("bumper-metadata"),mainVideoModules=[FocusGrabber,VideoControl,VideoPlayPlaceholder,VideoPlayPauseControl,VideoProgressSlider,VideoSpeedControl,VideoVolumeControl,VideoQualityControl,VideoFullScreen,VideoCaption,VideoCommands,VideoContextMenu,VideoSaveStatePlugin,VideoEventsPlugin],bumperVideoModules=[VideoControl,VideoPlaySkipControl,VideoSkipControl,VideoVolumeControl,VideoCaption,VideoCommands,VideoSaveStatePlugin,VideoEventsBumperPlugin],state={el:el,id:id,metadata:el.data("metadata"),storage:storage,options:{},youtubeXhr:youtubeXhr,modules:mainVideoModules};var getBumperState=function(metadata){var bumperState=$.extend(true,{el:el,id:id,storage:storage,options:{},youtubeXhr:youtubeXhr},{metadata:metadata});bumperState.modules=bumperVideoModules;bumperState.options={SaveStatePlugin:{events:["language_menu:change"]}};return bumperState};var player=function(state){return function(){_.extend(state.metadata,{autoplay:true,focusFirstControl:true});initialize(state,element)}};new VideoAccessibleMenu(el,{storage:storage,saveStateUrl:state.metadata.saveStateUrl});if(bumperMetadata){new VideoPoster(el,{poster:el.data("poster"),onClick:_.once(function(){var mainVideoPlayer=player(state),bumper,bumperState;if(storage.getItem("isBumperShown")){mainVideoPlayer()}else{bumperState=getBumperState(bumperMetadata);bumper=new VideoBumper(player(bumperState),bumperState);state.bumperState=bumperState;bumper.getPromise().done(function(){delete state.bumperState;mainVideoPlayer()})}})})}else{initialize(state,element)}if(!youtubeXhr){youtubeXhr=state.youtubeXhr}el.data("video-player-state",state);var onSequenceChange=function onSequenceChange(){if(state&&state.videoPlayer){state.videoPlayer.destroy()}$(".sequence").off("sequence:change",onSequenceChange)};$(".sequence").on("sequence:change",onSequenceChange);return state};window.Video.clearYoutubeXhr=function(){youtubeXhr=null};window.Video.loadYouTubeIFrameAPI=initialize.prototype.loadYouTubeIFrameAPI;oldVideo(null,true)})})(window.RequireJS.require,window.jQuery);(function(requirejs,require,define){define("video/019_html5_video.js",[],function(){var HTML5Video={};HTML5Video.Player=function(){Player.prototype.callStateChangeCallback=function(){if($.isFunction(this.config.events.onStateChange)){this.config.events.onStateChange({data:this.playerState})}};Player.prototype.pauseVideo=function(){this.video.pause()};Player.prototype.seekTo=function(value){if(typeof value==="number"&&value<=this.video.duration&&value>=0){this.video.currentTime=value}};Player.prototype.setVolume=function(value){if(typeof value==="number"&&value<=100&&value>=0){this.video.volume=value*.01}};Player.prototype.getCurrentTime=function(){return this.video.currentTime};Player.prototype.playVideo=function(){this.video.play()};Player.prototype.getPlayerState=function(){return this.playerState};Player.prototype.getVolume=function(){return this.video.volume};Player.prototype.getDuration=function(){if(isNaN(this.video.duration)){return 0}return this.video.duration};Player.prototype.setPlaybackRate=function(value){var newSpeed;newSpeed=parseFloat(value);if(isFinite(newSpeed)){if(this.video.playbackRate!==value){this.video.playbackRate=value}}};Player.prototype.getAvailablePlaybackRates=function(){return[.75,1,1.25,1.5]};Player.prototype._getLogs=function(){return this.logs};Player.prototype.showErrorMessage=function(){this.el.find(".video-player div").addClass("hidden").end().find(".video-player .video-error").removeClass("is-hidden").end().addClass("is-initialized").find(".spinner").attr({"aria-hidden":"true",tabindex:-1})};Player.prototype.onError=function(event){if($.isFunction(this.config.events.onError)){this.config.events.onError()}};Player.prototype.destroy=function(){this.video.removeEventListener("loadedmetadata",this.onLoadedMetadata,false);this.video.removeEventListener("play",this.onPlay,false);this.video.removeEventListener("playing",this.onPlaying,false);this.video.removeEventListener("pause",this.onPause,false);this.video.removeEventListener("ended",this.onEnded,false);this.el.find(".video-player div").removeClass("is-hidden").end().find(".video-player .video-error").addClass("is-hidden").end().removeClass("is-initialized").find(".spinner").attr({"aria-hidden":"false"});this.videoEl.remove()};Player.prototype.onLoadedMetadata=function(){this.playerState=HTML5Video.PlayerState.PAUSED;if($.isFunction(this.config.events.onReady)){this.config.events.onReady(null)}};Player.prototype.onPlay=function(){this.playerState=HTML5Video.PlayerState.BUFFERING;this.callStateChangeCallback()};Player.prototype.onPlaying=function(){this.playerState=HTML5Video.PlayerState.PLAYING;this.callStateChangeCallback()};Player.prototype.onPause=function(){this.playerState=HTML5Video.PlayerState.PAUSED;this.callStateChangeCallback()};Player.prototype.onEnded=function(){this.playerState=HTML5Video.PlayerState.ENDED;this.callStateChangeCallback()};return Player;function Player(el,config){var isTouch=onTouchBasedDevice()||"",sourceList,_this,errorMessage,lastSource;_.bindAll(this,"onLoadedMetadata","onPlay","onPlaying","onPause","onEnded");this.logs=[];this.el=$(el);if(this.el.length===0){this.el=$("#"+el);if(this.el.length===0){errorMessage=gettext("VideoPlayer: Element corresponding to the given selector was not found.");if(window.console&&console.log){console.log(errorMessage)}else{throw new Error(errorMessage)}return}}if($.isPlainObject(config)){this.config=config}else{return}if(!config.videoSources&&!config.videoSources.length){return}_this=this;sourceList=$.map(config.videoSources,function(source){return["<source ",'src="',source,source.indexOf("?")===-1?"?":"&",(new Date).getTime(),'" />'].join("")});this.video=document.createElement("video");errorMessage=[gettext("This browser cannot play .mp4, .ogg, or .webm files."),gettext("Try using a different browser, such as Google Chrome.")].join("");this.video.innerHTML=sourceList.join("")+errorMessage;this.videoEl=$(this.video);lastSource=this.videoEl.find("source").last();lastSource.on("error",this.showErrorMessage.bind(this));lastSource.on("error",this.onError.bind(this));this.videoEl.on("error",this.onError.bind(this));if(/iP(hone|od)/i.test(isTouch[0])){this.videoEl.prop("controls",true)}this.playerState=HTML5Video.PlayerState.UNSTARTED;this.videoEl.on("click",function(event){var PlayerState=HTML5Video.PlayerState;if(_this.playerState===PlayerState.PLAYING){_this.playerState=PlayerState.PAUSED;_this.pauseVideo()}else{_this.playerState=PlayerState.PLAYING;_this.playVideo()}});var events=["loadstart","progress","suspend","abort","error","emptied","stalled","play","pause","loadedmetadata","loadeddata","waiting","playing","canplay","canplaythrough","seeking","seeked","timeupdate","ended","ratechange","durationchange","volumechange"];this.debug=false;$.each(events,function(index,eventName){_this.video.addEventListener(eventName,function(){_this.logs.push({"event name":eventName,state:_this.playerState});if(_this.debug){console.log("event name:",eventName,"state:",_this.playerState,"readyState:",_this.video.readyState,"networkState:",_this.video.networkState)}el.trigger("html5:"+eventName,arguments)})});this.video.addEventListener("loadedmetadata",this.onLoadedMetadata,false);this.video.addEventListener("play",this.onPlay,false);this.video.addEventListener("playing",this.onPlaying,false);this.video.addEventListener("pause",this.onPause,false);this.video.addEventListener("ended",this.onEnded,false);this.videoEl.appendTo(this.el.find(".video-player div"))}}();HTML5Video.PlayerState={UNSTARTED:-1,ENDED:0,PLAYING:1,PAUSED:2,BUFFERING:3,CUED:5};return HTML5Video})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(requirejs,require,define){"use strict";define("video/049_video_quality_control.js",["edx-ui-toolkit/js/utils/html-utils"],function(HtmlUtils){var template=HtmlUtils.interpolateHtml(HtmlUtils.HTML(['<button class="control quality-control is-hidden" aria-disabled="false" title="',"{highDefinition}",'">','<span class="icon icon-hd" aria-hidden="true">HD</span>','<span class="sr text-translation">',"{highDefinition}","</span> ",'<span class="sr control-text">',"{off}","</span>","</button>"].join("")),{highDefinition:gettext("High Definition"),off:gettext("off")});return function(state){var dfd=$.Deferred();if(state.videoType!=="youtube"){return}state.videoQualityControl={};_makeFunctionsPublic(state);_renderElements(state);_bindHandlers(state);dfd.resolve();return dfd.promise()};function _makeFunctionsPublic(state){var methodsDict={destroy:destroy,fetchAvailableQualities:fetchAvailableQualities,onQualityChange:onQualityChange,showQualityControl:showQualityControl,toggleQuality:toggleQuality};state.bindTo(methodsDict,state.videoQualityControl,state)}function destroy(){this.videoQualityControl.el.off({click:this.videoQualityControl.toggleQuality,destroy:this.videoQualityControl.destroy});this.el.off(".quality");this.videoQualityControl.el.remove();delete this.videoQualityControl}function _renderElements(state){var element=state.videoQualityControl.el=$(template.toString());state.videoQualityControl.quality="large";HtmlUtils.append(state.el.find(".secondary-controls"),HtmlUtils.HTML(element))}function _bindHandlers(state){state.videoQualityControl.el.on("click",state.videoQualityControl.toggleQuality);state.el.on("play.quality",_.once(state.videoQualityControl.fetchAvailableQualities));state.el.on("destroy.quality",state.videoQualityControl.destroy)}function showQualityControl(){this.videoQualityControl.el.removeClass("is-hidden")}function fetchAvailableQualities(){var qualities=this.videoPlayer.player.getAvailableQualityLevels();this.config.availableHDQualities=_.intersection(qualities,["highres","hd1080","hd720"]);if(this.config.availableHDQualities.length>0){this.trigger("videoQualityControl.showQualityControl");this.trigger("videoQualityControl.onQualityChange",this.videoQualityControl.quality)}this.trigger("videoPlayer.handlePlaybackQualityChange",this.videoQualityControl.quality)}function onQualityChange(value){var controlStateStr;this.videoQualityControl.quality=value;if(_.contains(this.config.availableHDQualities,value)){controlStateStr=gettext("on");this.videoQualityControl.el.addClass("active").find(".control-text").text(controlStateStr)}else{controlStateStr=gettext("off");this.videoQualityControl.el.removeClass("active").find(".control-text").text(controlStateStr)}}function toggleQuality(event){var newQuality,value=this.videoQualityControl.quality,isHD=_.contains(this.config.availableHDQualities,value);event.preventDefault();newQuality=isHD?"large":"highres";this.trigger("videoPlayer.handlePlaybackQualityChange",newQuality)}})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(requirejs,require,define){define("video/019_html5_video.js",[],function(){var HTML5Video={};HTML5Video.Player=function(){Player.prototype.callStateChangeCallback=function(){if($.isFunction(this.config.events.onStateChange)){this.config.events.onStateChange({data:this.playerState})}};Player.prototype.pauseVideo=function(){this.video.pause()};Player.prototype.seekTo=function(value){if(typeof value==="number"&&value<=this.video.duration&&value>=0){this.video.currentTime=value}};Player.prototype.setVolume=function(value){if(typeof value==="number"&&value<=100&&value>=0){this.video.volume=value*.01}};Player.prototype.getCurrentTime=function(){return this.video.currentTime};Player.prototype.playVideo=function(){this.video.play()};Player.prototype.getPlayerState=function(){return this.playerState};Player.prototype.getVolume=function(){return this.video.volume};Player.prototype.getDuration=function(){if(isNaN(this.video.duration)){return 0}return this.video.duration};Player.prototype.setPlaybackRate=function(value){var newSpeed;newSpeed=parseFloat(value);if(isFinite(newSpeed)){if(this.video.playbackRate!==value){this.video.playbackRate=value}}};Player.prototype.getAvailablePlaybackRates=function(){return[.75,1,1.25,1.5]};Player.prototype._getLogs=function(){return this.logs};Player.prototype.showErrorMessage=function(){this.el.find(".video-player div").addClass("hidden").end().find(".video-player .video-error").removeClass("is-hidden").end().addClass("is-initialized").find(".spinner").attr({"aria-hidden":"true",tabindex:-1})};Player.prototype.onError=function(event){if($.isFunction(this.config.events.onError)){this.config.events.onError()}};Player.prototype.destroy=function(){this.video.removeEventListener("loadedmetadata",this.onLoadedMetadata,false);this.video.removeEventListener("play",this.onPlay,false);this.video.removeEventListener("playing",this.onPlaying,false);this.video.removeEventListener("pause",this.onPause,false);this.video.removeEventListener("ended",this.onEnded,false);this.el.find(".video-player div").removeClass("is-hidden").end().find(".video-player .video-error").addClass("is-hidden").end().removeClass("is-initialized").find(".spinner").attr({"aria-hidden":"false"});this.videoEl.remove()};Player.prototype.onLoadedMetadata=function(){this.playerState=HTML5Video.PlayerState.PAUSED;if($.isFunction(this.config.events.onReady)){this.config.events.onReady(null)}};Player.prototype.onPlay=function(){this.playerState=HTML5Video.PlayerState.BUFFERING;this.callStateChangeCallback()};Player.prototype.onPlaying=function(){this.playerState=HTML5Video.PlayerState.PLAYING;this.callStateChangeCallback()};Player.prototype.onPause=function(){this.playerState=HTML5Video.PlayerState.PAUSED;this.callStateChangeCallback()};Player.prototype.onEnded=function(){this.playerState=HTML5Video.PlayerState.ENDED;this.callStateChangeCallback()};return Player;function Player(el,config){var isTouch=onTouchBasedDevice()||"",sourceList,_this,errorMessage,lastSource;_.bindAll(this,"onLoadedMetadata","onPlay","onPlaying","onPause","onEnded");this.logs=[];this.el=$(el);if(this.el.length===0){this.el=$("#"+el);if(this.el.length===0){errorMessage=gettext("VideoPlayer: Element corresponding to the given selector was not found.");if(window.console&&console.log){console.log(errorMessage)}else{throw new Error(errorMessage)}return}}if($.isPlainObject(config)){this.config=config}else{return}if(!config.videoSources&&!config.videoSources.length){return}_this=this;sourceList=$.map(config.videoSources,function(source){return["<source ",'src="',source,source.indexOf("?")===-1?"?":"&",(new Date).getTime(),'" />'].join("")});this.video=document.createElement("video");errorMessage=[gettext("This browser cannot play .mp4, .ogg, or .webm files."),gettext("Try using a different browser, such as Google Chrome.")].join("");this.video.innerHTML=sourceList.join("")+errorMessage;this.videoEl=$(this.video);lastSource=this.videoEl.find("source").last();lastSource.on("error",this.showErrorMessage.bind(this));lastSource.on("error",this.onError.bind(this));this.videoEl.on("error",this.onError.bind(this));if(/iP(hone|od)/i.test(isTouch[0])){this.videoEl.prop("controls",true)}this.playerState=HTML5Video.PlayerState.UNSTARTED;this.videoEl.on("click",function(event){
12var PlayerState=HTML5Video.PlayerState;if(_this.playerState===PlayerState.PLAYING){_this.playerState=PlayerState.PAUSED;_this.pauseVideo()}else{_this.playerState=PlayerState.PLAYING;_this.playVideo()}});var events=["loadstart","progress","suspend","abort","error","emptied","stalled","play","pause","loadedmetadata","loadeddata","waiting","playing","canplay","canplaythrough","seeking","seeked","timeupdate","ended","ratechange","durationchange","volumechange"];this.debug=false;$.each(events,function(index,eventName){_this.video.addEventListener(eventName,function(){_this.logs.push({"event name":eventName,state:_this.playerState});if(_this.debug){console.log("event name:",eventName,"state:",_this.playerState,"readyState:",_this.video.readyState,"networkState:",_this.video.networkState)}el.trigger("html5:"+eventName,arguments)})});this.video.addEventListener("loadedmetadata",this.onLoadedMetadata,false);this.video.addEventListener("play",this.onPlay,false);this.video.addEventListener("playing",this.onPlaying,false);this.video.addEventListener("pause",this.onPause,false);this.video.addEventListener("ended",this.onEnded,false);this.videoEl.appendTo(this.el.find(".video-player div"))}}();HTML5Video.PlayerState={UNSTARTED:-1,ENDED:0,PLAYING:1,PAUSED:2,BUFFERING:3,CUED:5};return HTML5Video})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);(function(requirejs,require,define){"use strict";define("video/049_video_quality_control.js",["edx-ui-toolkit/js/utils/html-utils"],function(HtmlUtils){var template=HtmlUtils.interpolateHtml(HtmlUtils.HTML(['<button class="control quality-control is-hidden" aria-disabled="false" title="',"{highDefinition}",'">','<span class="icon icon-hd" aria-hidden="true">HD</span>','<span class="sr text-translation">',"{highDefinition}","</span> ",'<span class="sr control-text">',"{off}","</span>","</button>"].join("")),{highDefinition:gettext("High Definition"),off:gettext("off")});return function(state){var dfd=$.Deferred();if(state.videoType!=="youtube"){return}state.videoQualityControl={};_makeFunctionsPublic(state);_renderElements(state);_bindHandlers(state);dfd.resolve();return dfd.promise()};function _makeFunctionsPublic(state){var methodsDict={destroy:destroy,fetchAvailableQualities:fetchAvailableQualities,onQualityChange:onQualityChange,showQualityControl:showQualityControl,toggleQuality:toggleQuality};state.bindTo(methodsDict,state.videoQualityControl,state)}function destroy(){this.videoQualityControl.el.off({click:this.videoQualityControl.toggleQuality,destroy:this.videoQualityControl.destroy});this.el.off(".quality");this.videoQualityControl.el.remove();delete this.videoQualityControl}function _renderElements(state){var element=state.videoQualityControl.el=$(template.toString());state.videoQualityControl.quality="large";HtmlUtils.append(state.el.find(".secondary-controls"),HtmlUtils.HTML(element))}function _bindHandlers(state){state.videoQualityControl.el.on("click",state.videoQualityControl.toggleQuality);state.el.on("play.quality",_.once(state.videoQualityControl.fetchAvailableQualities));state.el.on("destroy.quality",state.videoQualityControl.destroy)}function showQualityControl(){this.videoQualityControl.el.removeClass("is-hidden")}function fetchAvailableQualities(){var qualities=this.videoPlayer.player.getAvailableQualityLevels();this.config.availableHDQualities=_.intersection(qualities,["highres","hd1080","hd720"]);if(this.config.availableHDQualities.length>0){this.trigger("videoQualityControl.showQualityControl");this.trigger("videoQualityControl.onQualityChange",this.videoQualityControl.quality)}this.trigger("videoPlayer.handlePlaybackQualityChange",this.videoQualityControl.quality)}function onQualityChange(value){var controlStateStr;this.videoQualityControl.quality=value;if(_.contains(this.config.availableHDQualities,value)){controlStateStr=gettext("on");this.videoQualityControl.el.addClass("active").find(".control-text").text(controlStateStr)}else{controlStateStr=gettext("off");this.videoQualityControl.el.removeClass("active").find(".control-text").text(controlStateStr)}}function toggleQuality(event){var newQuality,value=this.videoQualityControl.quality,isHD=_.contains(this.config.availableHDQualities,value);event.preventDefault();newQuality=isHD?"large":"highres";this.trigger("videoPlayer.handlePlaybackQualityChange",newQuality)}})})(RequireJS.requirejs,RequireJS.require,RequireJS.define);