doodle3d-client/www/js/doodle3d-client.min.js

2 lines
56 KiB
JavaScript

function SettingsWindow(){this.wifiboxURL,this.wifiboxCGIBinURL,this.window,this.form,this.timeoutTime=3e3,this.retryDelay=2e3,this.retryRetrieveNetworkStatusDelayTime=1e3,this.retryLoadSettingsDelay,this.retrySaveSettingsDelay,this.retryRetrieveNetworkStatusDelay,this.apFieldSet,this.clientFieldSet,this.networks,this.currentNetwork,this.selectedNetwork,this.currentLocalIP="",this.clientModeState=SettingsWindow.NOT_CONNECTED,this.currentAP,this.apModeState=SettingsWindow.NO_AP,this.retrieveNetworkStatusDelay,this.retrieveNetworkStatusDelayTime=1e3,SettingsWindow.SETTINGS_LOADED="settingsLoaded",SettingsWindow.NOT_CONNECTED="not connected",SettingsWindow.CONNECTED="connected",SettingsWindow.CONNECTING="connecting",SettingsWindow.CONNECTING_FAILED="connecting failed",SettingsWindow.NO_AP="no ap",SettingsWindow.AP="ap",SettingsWindow.CREATING_AP="creating ap",SettingsWindow.API_CONNECTING_FAILED=-1,SettingsWindow.API_NOT_CONNECTED=0,SettingsWindow.API_CONNECTING=1,SettingsWindow.API_CONNECTED=2,SettingsWindow.API_CREATING=3,SettingsWindow.API_CREATED=4,SettingsWindow.NETWORK_MODE_NEITHER="neither",SettingsWindow.NETWORK_MODE_CLIENT="clientMode",SettingsWindow.NETWORK_MODE_ACCESS_POINT="accessPointMode",this.networkMode=SettingsWindow.NETWORK_MODE_NEITHER,this.updatePanel=new UpdatePanel;var a=this;this.init=function(b,c){this.wifiboxURL=b,this.wifiboxCGIBinURL=c,this.window=$("#settings"),this.window.find(".btnOK").click(this.submitwindow),this.window.find(".settingsContainer").load("settings.html",function(){console.log("Settings:finished loading settings.html, now loading settings..."),a.form=a.window.find("form"),a.form.submit(function(b){a.submitwindow(b)}),a.loadSettings();var c=a.form.find("label[for='ap']"),d=a.form.find("label[for='client']"),e=a.form.find("#refreshNetworks"),f=a.form.find("#connectToNetwork"),g=a.form.find("#createAP"),h=a.form.find("#network");a.apFieldSet=a.form.find("#apSettings"),a.clientFieldSet=a.form.find("#clientSettings"),c.on("touchstart mousedown",a.showAPSettings),d.on("touchstart mousedown",a.showClientSettings),e.on("touchstart mousedown",a.refreshNetworks),f.on("touchstart mousedown",a.connectToNetwork),g.on("touchstart mousedown",a.createAP),h.change(a.networkSelectorChanged);var i=a.form.find("#updatePanel");a.updatePanel.init(b,i)})},this.submitwindow=function(b){b.preventDefault(),b.stopPropagation(),a.saveSettings(a.readForm(),function(){a.hideSettings()}),clearTimeout(a.retryRetrieveNetworkStatusDelay)},this.showSettings=function(){console.log("f:showSettings()"),this.loadSettings(),$("#contentOverlay").fadeIn(375,function(){document.body.removeEventListener("touchmove",prevent,!1)})},this.hideSettings=function(){$("#contentOverlay").fadeOut(375,function(){document.body.addEventListener("touchmove",prevent,!1)})},this.loadSettings=function(){return communicateWithWifibox?(console.log("Settings:loadSettings() >> getting new data..."),$.ajax({url:this.wifiboxURL+"/config/all",dataType:"json",timeout:this.timeoutTime,success:function(b){console.log("Settings:loadSettings response: ",b),settings=b.data,console.log(" settings: ",settings),a.fillForm(),$(document).trigger(SettingsWindow.SETTINGS_LOADED)}}).fail(function(){console.log("Settings:loadSettings: failed"),clearTimeout(a.retryLoadSettingsDelay),a.retryLoadSettingsDelay=setTimeout(function(){a.loadSettings()},a.retryDelay)}),this.refreshNetworks(),this.retrieveNetworkStatus(!1),void 0):(console.log(" communicateWithWifibox is false: settings aren't being loaded from wifibox..."),void 0)},this.fillForm=function(){console.log("SettingsWindow:fillForm");var a=this.form.find("select");a.each(function(a,b){var b=$(b);b.val(settings[b.attr("name")])});var b=this.form.find("input");b.each(function(a,b){var b=$(b);switch(b.attr("type")){case"text":case"number":b.val(settings[b.attr("name")]);break;case"checkbox":b.prop("checked",settings[b.attr("name")])}});var c=this.form.find("textarea");c.each(function(a,b){var b=$(b),c=settings[b.attr("name")];b.val(c)})},this.saveSettings=function(b,c){settings=b,communicateWithWifibox&&$.ajax({url:this.wifiboxURL+"/config",type:"POST",data:b,dataType:"json",timeout:this.timeoutTime,success:function(b){if(console.log("Settings:saveSettings response: ",b),"error"==b.status)clearTimeout(a.retrySaveSettingsDelay),a.retrySaveSettingsDelay=setTimeout(function(){a.saveSettings(settings)},a.retryDelay);else{var d=b.data,e=d.validation;a.clearValidationErrors();var f=!0;$.each(e,function(b,c){"ok"!=c&&(console.log("ERROR: setting '"+b+"' not successfully set. Message: "+c),a.displayValidationError(b,c),f=!1)}),settings.substituted_ssid=d.substituted_ssid,c&&f&&c()}}}).fail(function(){console.log("Settings:saveSettings: failed"),clearTimeout(a.retrySaveSettingsDelay),a.retrySaveSettingsDelay=setTimeout(function(){a.saveSettings(settings)},a.retryDelay)})},this.displayValidationError=function(b,c){var d=a.form.find("[name|='"+b+"']");console.log("formElement: ",d),d.addClass("error");var e="<p class='errorMsg'>"+c+"</p>";d.after(e)},this.clearValidationErrors=function(){var b=a.form.find(".error");b.each(function(a,b){$(b).removeClass("error")})},this.readForm=function(){var b={},c=a.form.find("select");c.each(function(a,c){var c=$(c);"network.client.network"!=c.attr("name")&&(b[c.attr("name")]=c.val())});var d=a.form.find("input");d.each(function(a,c){var c=$(c);switch(c.attr("type")){case"text":case"number":b[c.attr("name")]=c.val();break;case"checkbox":b[c.attr("name")]=c.prop("checked")}});var e=a.form.find("textarea");return e.each(function(a,c){var c=$(c);b[c.attr("name")]=c.val()}),b},this.showAPSettings=function(){a.apFieldSet.show(),a.clientFieldSet.hide()},this.showClientSettings=function(){a.clientFieldSet.show(),a.apFieldSet.hide()},this.refreshNetworks=function(){console.log("Settings:refreshNetworks"),communicateWithWifibox&&$.ajax({url:a.wifiboxURL+"/network/scan",type:"GET",dataType:"json",timeout:a.timeoutTime,success:function(b){if(console.log("Settings:refreshNetworks response: ",b),"error"==b.status);else{var c=b.data.networks;a.networks={};var d=!1,e=a.form.find("#network");e.empty(),e.append($("<option></option>").val(SettingsWindow.NOT_CONNECTED).html("not connected")),$.each(c,function(b,c){c.ssid==a.currentNetwork&&(d=!0),e.append($("<option></option>").val(c.ssid).html(c.ssid)),a.networks[c.ssid]=c}),d&&(e.val(a.currentNetwork),a.selectNetwork(a.currentNetwork))}}}).fail(function(){})},this.retrieveNetworkStatus=function(b){communicateWithWifibox&&$.ajax({url:a.wifiboxURL+"/network/status",type:"GET",dataType:"json",timeout:a.timeoutTime,success:function(c){if(console.log("Settings:retrieveNetworkStatus response: ",c),"error"==c.status);else{var d=c.data;switch("string"==typeof d.status&&(d.status=parseInt(d.status)),d.status){case SettingsWindow.API_NOT_CONNECTED:a.apFieldSet.show(),a.clientFieldSet.show(),a.networkMode=SettingsWindow.NETWORK_MODE_NEITHER;break;case SettingsWindow.API_CONNECTING_FAILED:case SettingsWindow.API_CONNECTING:case SettingsWindow.API_CONNECTED:if(a.form.find("#client").prop("checked",!0),a.apFieldSet.hide(),a.clientFieldSet.show(),d.status==SettingsWindow.API_CONNECTED){var e=a.form.find("#network");e.val(d.ssid),a.currentNetwork=d.ssid,a.currentLocalIP=d.localip,a.selectNetwork(d.ssid)}else a.currentLocalIP="";a.networkMode=SettingsWindow.NETWORK_MODE_CLIENT;break;case SettingsWindow.API_CREATING:case SettingsWindow.API_CREATED:a.form.find("#ap").prop("checked",!0),a.apFieldSet.show(),a.clientFieldSet.hide(),a.currentNetwork=void 0,a.selectNetwork(SettingsWindow.NOT_CONNECTED);var e=a.form.find("#network");e.val(SettingsWindow.NOT_CONNECTED),d.ssid&&d.status==SettingsWindow.API_CREATED&&(a.currentAP=d.ssid),a.networkMode=SettingsWindow.NETWORK_MODE_ACCESS_POINT}switch(a.updatePanel.setNetworkMode(a.networkMode),d.status){case SettingsWindow.API_CONNECTING_FAILED:a.setClientModeState(SettingsWindow.CONNECTING_FAILED,d.statusMessage),a.setAPModeState(SettingsWindow.NO_AP,"");break;case SettingsWindow.API_NOT_CONNECTED:a.setClientModeState(SettingsWindow.NOT_CONNECTED,""),a.setAPModeState(SettingsWindow.NO_AP,"");break;case SettingsWindow.API_CONNECTING:a.setClientModeState(SettingsWindow.CONNECTING,""),a.setAPModeState(SettingsWindow.NO_AP,"");break;case SettingsWindow.API_CONNECTED:a.setClientModeState(SettingsWindow.CONNECTED,""),a.setAPModeState(SettingsWindow.NO_AP,"");break;case SettingsWindow.API_CREATING:a.setClientModeState(SettingsWindow.NOT_CONNECTED,""),a.setAPModeState(SettingsWindow.CREATING_AP,"");break;case SettingsWindow.API_CREATED:a.setClientModeState(SettingsWindow.NOT_CONNECTED,""),a.setAPModeState(SettingsWindow.AP,"")}if(b)switch(d.status){case SettingsWindow.API_CONNECTING:case SettingsWindow.API_CREATING:clearTimeout(a.retryRetrieveNetworkStatusDelay),a.retryRetrieveNetworkStatusDelay=setTimeout(function(){a.retrieveNetworkStatus(b)},a.retryRetrieveNetworkStatusDelayTime)}}}}).fail(function(){console.log("Settings:retrieveNetworkStatus: failed"),clearTimeout(a.retryRetrieveNetworkStatusDelay),a.retryRetrieveNetworkStatusDelay=setTimeout(function(){a.retrieveNetworkStatus(b)},a.retryDelay)})},this.networkSelectorChanged=function(){var b=$(this).find("option:selected");a.selectNetwork(b.val())},this.selectNetwork=function(a){if(console.log("select network: ",a),""!=a)if(console.log(" checked"),this.selectedNetwork=a,void 0==this.networks||a==SettingsWindow.NOT_CONNECTED)this.hideWiFiPassword();else{var b=this.networks[a];"none"==b.encryption?this.hideWiFiPassword():this.showWiFiPassword(),this.form.find("#password").val("")}},this.showWiFiPassword=function(){this.form.find("#passwordLabel").show(),this.form.find("#password").show()},this.hideWiFiPassword=function(){this.form.find("#passwordLabel").hide(),this.form.find("#password").hide()},this.setClientModeState=function(b,c){var d=this.form.find("#clientModeState"),e=a.form.find("#connectToNetwork");switch(b){case SettingsWindow.NOT_CONNECTED:e.removeAttr("disabled"),d.html("Not connected");break;case SettingsWindow.CONNECTED:e.removeAttr("disabled");var f="Connected to: <b>"+this.currentNetwork+"</b>.";if(void 0!=this.currentLocalIP&&""!=this.currentLocalIP){var g="<a href='http://"+this.currentLocalIP+"' target='_black'>"+this.currentLocalIP+"</a>";f+=" (IP: "+g+")"}d.html(f);break;case SettingsWindow.CONNECTING:e.attr("disabled",!0),d.html("Connecting... Reconnect by connecting your device to <b>"+this.selectedNetwork+"</b> and going to <a href='http://connect.doodle3d.com'>connect.doodle3d.com</a>");break;case SettingsWindow.CONNECTING_FAILED:e.removeAttr("disabled"),d.html(c)}this.clientModeState=b},this.setAPModeState=function(a){var b=this.form.find("#apModeState"),c=this.form.find("#createAP");switch(a){case SettingsWindow.NO_AP:c.removeAttr("disabled"),b.html("Not currently a access point");break;case SettingsWindow.AP:c.removeAttr("disabled"),b.html("Is access point: <b>"+this.currentAP+"</b>");break;case SettingsWindow.CREATING_AP:c.attr("disabled",!0),b.html("Creating access point... Reconnect by connecting your device to <b>"+settings.substituted_ssid+"</b> and going to <a href='http://draw.doodle3d.com'>draw.doodle3d.com</a>")}this.apModeState=a},this.connectToNetwork=function(){if(console.log("connectToNetwork"),void 0!=a.selectedNetwork){var b={ssid:a.selectedNetwork,phrase:a.form.find("#password").val(),recreate:!0};console.log(" postData: ",b),communicateWithWifibox&&a.saveSettings(a.readForm(),function(){$.ajax({url:a.wifiboxCGIBinURL+"/network/associate",type:"POST",data:b,dataType:"json",timeout:a.timeoutTime,success:function(a){console.log("Settings:connectToNetwork response: ",a)}}).fail(function(){console.log("Settings:connectToNetwork: timeout (normal behavior)")})}),a.setClientModeState(SettingsWindow.CONNECTING,""),clearTimeout(a.retrieveNetworkStatusDelay),a.retrieveNetworkStatusDelay=setTimeout(function(){a.retrieveNetworkStatus(!0)},a.retrieveNetworkStatusDelayTime)}},this.createAP=function(){console.log("createAP"),communicateWithWifibox&&a.saveSettings(a.readForm(),function(){a.setAPModeState(SettingsWindow.CREATING_AP),$.ajax({url:a.wifiboxCGIBinURL+"/network/openap",type:"POST",dataType:"json",timeout:a.timeoutTime,success:function(a){console.log("Settings:createAP response: ",a)}}).fail(function(){console.log("Settings:createAP: timeout (normal behavior)")}),a.setAPModeState(SettingsWindow.CREATING_AP,""),clearTimeout(a.retrieveNetworkStatusDelay),a.retrieveNetworkStatusDelay=setTimeout(function(){a.retrieveNetworkStatus(!0)},a.retrieveNetworkStatusDelayTime)})}}function UpdatePanel(){this.wifiboxURL,this.element,this.statusCheckInterval=1e3,this.statusCheckDelayer,this.installedDelay=6e4,this.installedDelayer,this.retryDelay=1e3,this.retryDelayer,this.canUpdate=!1,this.currentVersion="",this.newestVersion,this.progress,this.imageSize,UpdatePanel.NONE=1,UpdatePanel.DOWNLOADING=2,UpdatePanel.DOWNLOAD_FAILED=3,UpdatePanel.IMAGE_READY=4,UpdatePanel.INSTALLING=5,UpdatePanel.INSTALLED=6,UpdatePanel.INSTALL_FAILED=7,this.state,this.stateText="",this.networkMode;var a=this;this.init=function(a,b){this.wifiboxURL=a,this.element=b,this.btnUpdate=this.element.find("#update"),this.statusDisplay=this.element.find("#updateState"),this.infoDisplay=this.element.find("#updateInfo"),this.btnUpdate.click(this.update),this.checkStatus(!1)},this.update=function(){console.log("UpdatePanel:update"),a.downloadUpdate()},this.downloadUpdate=function(){console.log("UpdatePanel:downloadUpdate"),$.ajax({url:a.wifiboxURL+"/update/download",type:"POST",dataType:"json",success:function(a){console.log("UpdatePanel:downloadUpdate response: ",a)}}).fail(function(){console.log("UpdatePanel:downloadUpdate: failed")}),a.setState(UpdatePanel.DOWNLOADING),a.startCheckingStatus()},this.installUpdate=function(){console.log("UpdatePanel:installUpdate"),a.stopCheckingStatus(),$.ajax({url:a.wifiboxURL+"/update/install",type:"POST",dataType:"json",success:function(a){console.log("UpdatePanel:installUpdate response: ",a)}}).fail(function(){console.log("UpdatePanel:installUpdate: no respons (there shouldn't be)")}),a.setState(UpdatePanel.INSTALLING),clearTimeout(a.installedDelayer),a.installedDelayer=setTimeout(function(){a.setState(UpdatePanel.INSTALLED)},a.installedDelay)},this.startCheckingStatus=function(){clearTimeout(a.statusCheckDelayer),clearTimeout(a.retryDelayer),a.statusCheckDelayer=setTimeout(function(){a.checkStatus(!0)},a.statusCheckInterval)},this.stopCheckingStatus=function(){clearTimeout(a.statusCheckDelayer),clearTimeout(a.retryDelayer)},this.checkStatus=function(b){communicateWithWifibox&&$.ajax({url:a.wifiboxURL+"/update/status",type:"GET",dataType:"json",success:function(c){if(console.log("UpdatePanel:checkStatus response: ",c),b)switch(a.state){case UpdatePanel.DOWNLOADING:case UpdatePanel.INSTALLING:clearTimeout(a.statusCheckDelayer),a.statusCheckDelayer=setTimeout(function(){a.checkStatus(b)},a.statusCheckInterval)}if("error"!=c.status){var d=c.data;a.handleStatusData(d)}}}).fail(function(){b&&(clearTimeout(a.retryDelayer),a.retryDelayer=setTimeout(function(){a.checkStatus(b)},a.retryDelay))})},this.handleStatusData=function(b){switch(a.canUpdate=b.can_update,(a.currentVersion!=b.current_version||a.newestVersion!=b.newest_version)&&(a.currentVersion=b.current_version,a.newestVersion=b.newest_version,a.updateInfoDisplay()),a.stateText=b.state_text,a.progress=b.progress,a.imageSize=b.image_size,a.setState(b.state_code),this.state){case UpdatePanel.IMAGE_READY:a.installUpdate()}},this.setState=function(b){if(this.state!=b){if(console.log("UpdatePanel:setState: ",this.state," > ",b,"(",this.stateText,") (networkMode: ",a.networkMode,") (newestVersion: ",a.newestVersion,")"),this.state=b,void 0!=a.newestVersion)switch(this.state){case UpdatePanel.NONE:case UpdatePanel.DOWNLOAD_FAILED:case UpdatePanel.INSTALL_FAILED:a.canUpdate?a.btnUpdate.removeAttr("disabled"):a.btnUpdate.attr("disabled",!0);break;default:a.btnUpdate.attr("disabled",!0)}else a.btnUpdate.attr("disabled",!0);this.updateStatusDisplay()}},this.updateStatusDisplay=function(){var b="";if(void 0!=a.newestVersion)switch(this.state){case UpdatePanel.NONE:b=a.canUpdate?"Update(s) available.":"You're up to date.";break;case UpdatePanel.DOWNLOADING:b="Downloading update...";break;case UpdatePanel.DOWNLOAD_FAILED:b="Downloading update failed.";break;case UpdatePanel.IMAGE_READY:b="Update downloaded.";break;case UpdatePanel.INSTALLING:b="Installing update... (will take a minute)";break;case UpdatePanel.INSTALLED:b="Update complete, please <a href='javascript:location.reload(true);'>refresh Page</a>.";break;case UpdatePanel.INSTALL_FAILED:b="Installing update failed."}else b=a.networkMode==SettingsWindow.NETWORK_MODE_ACCESS_POINT?"Can't access internet in access point mode.":"Can't access internet.";this.statusDisplay.html(b)},this.updateInfoDisplay=function(){var b="Current version: "+a.currentVersion+". ";a.canUpdate&&(b+="Latest version: "+a.newestVersion+"."),a.infoDisplay.text(b)},this.setNetworkMode=function(b){a.networkMode=b}}function setTemperature(a){void 0!=a&&a()}function setTemperature(a){void 0!=a&&a()}function initVerticalShapes(){VERTICALSHAPE=verticalShapes.NONE,$(".verticalShapes, .straight").on("mouseup touchend",function(a){a.preventDefault(),console.log("diverging"),VERTICALSHAPE=verticalShapes.NONE,redrawRenderedPreview()}),$(".verticalShapes, .diverging").on("mouseup touchend",function(a){a.preventDefault(),console.log("diverging"),VERTICALSHAPE=verticalShapes.DIVERGING,redrawRenderedPreview()}),$(".verticalShapes, .converging").on("mouseup touchend",function(a){a.preventDefault(),console.log("converging"),VERTICALSHAPE=verticalShapes.CONVERGING,redrawRenderedPreview()}),$(".verticalShapes, .sinus").on("mouseup touchend",function(a){a.preventDefault(),console.log("sinus"),VERTICALSHAPE=verticalShapes.SINUS,redrawRenderedPreview()})}function resetVerticalShapes(){VERTICALSHAPE=verticalShapes.NONE}function initButtonBehavior(){function a(a){a.preventDefault(),btnOopsInterval=setInterval(function(){oopsUndo()},20)}function b(a){a.preventDefault(),clearInterval(btnOopsInterval)}function c(a){a.preventDefault(),previewUp(!0),clearInterval(btnMoveUpInterval),btnMoveUpInterval=setInterval(function(){previewUp(!0)},1e3/30)}function d(a){a.preventDefault(),console.log("btnMoveUp mouse up"),clearInterval(btnMoveUpInterval),previewUp()}function e(a){a.preventDefault(),previewDown(!0),clearInterval(btnMoveDownInterval),btnMoveDownInterval=setInterval(function(){previewDown(!0)},1e3/30)}function f(a){a.preventDefault(),console.log("btnMoveDown mouse up"),clearInterval(btnMoveDownInterval),previewDown()}function g(a){a.preventDefault(),previewTwistLeft(!0),clearInterval(btnTwistLeftInterval),btnTwistLeftInterval=setInterval(function(){previewTwistLeft(!0)},1e3/30)}function h(a){a.preventDefault(),clearInterval(btnTwistLeftInterval),previewTwistLeft()}function i(a){a.preventDefault(),previewTwistRight(!0),clearInterval(btnTwistRightInterval),btnTwistRightInterval=setInterval(function(){previewTwistRight(!0)},1e3/30)}function j(a){a.preventDefault(),clearInterval(btnTwistRightInterval),previewTwistRight()}console.log("f:initButtonBehavior"),btnOops=$(".btnOops"),btnMoveUp=$("#btnMoveUp"),btnMoveDown=$("#btnMoveDown"),btnTwistLeft=$("#btnTwistLeft"),btnTwistRight=$("#btnTwistRight"),btnInfo=$(".btnInfo"),btnSettings=$(".btnSettings"),btnNew=$(".btnNew"),btnPrint=$(".btnPrint"),btnStop=$(".btnStop"),btnPrevious=$(".btnPrevious"),btnNext=$(".btnNext"),btnNew.on("touchstart mousedown",clearDoodle),btnPrint.on("touchstart mousedown",print),$("#btnPrevious").css("opacity","0.3"),btnNext.css("opacity","0.3"),$("#btnSave").css("opacity","0.3"),btnInfo.css("opacity","0.3"),btnOops.on("touchstart",function(b){a(b)}),btnOops.on("touchend",function(a){b(a)}),btnOops.mousedown(function(b){a(b)}),btnOops.mouseup(function(a){b(a)}),btnMoveUp.mousedown(function(a){c(a)}),btnMoveUp.mouseup(function(a){d(a)}),btnMoveUp.on("touchstart",function(a){c(a)}),btnMoveUp.on("touchend",function(a){d(a)}),btnMoveDown.mousedown(function(a){e(a)}),btnMoveDown.mouseup(function(a){f(a)}),btnMoveDown.on("touchstart",function(a){e(a)}),btnMoveDown.on("touchend",function(a){f(a)}),btnTwistLeft.mousedown(function(a){g(a)}),btnTwistLeft.mouseup(function(a){h(a)}),btnTwistLeft.on("touchstart",function(a){g(a)}),btnTwistLeft.on("touchend",function(a){h(a)}),btnTwistRight.mousedown(function(a){i(a)}),btnTwistRight.mouseup(function(a){j(a)}),btnTwistRight.on("touchstart",function(a){i(a)}),btnTwistRight.on("touchend",function(a){j(a)}),btnSettings.bind("touchstart mousedown",function(){settingsWindow.showSettings()}),btnInfo.mouseup(function(a){a.preventDefault(),console.log("btnInfo mouse up")})}function stopPrint(){console.log("f:stopPrint() >> sendPrintCommands = "+sendPrintCommands),sendPrintCommands&&printer.stop(),printer.overruleState(Printer.STOPPING_STATE)}function prevDoodle(){console.log("f:prevDoodle()"),console.log("f:prevDoodle()")}function nextDoodle(){console.log("f:nextDoodle()")}function print(){console.log("f:print() >> sendPrintCommands = "+sendPrintCommands),_points.length>2?(printer.overruleState(Printer.BUFFERING_STATE),btnStop.css("display","none"),clearTimeout(gcodeGenerateDelayer),gcodeGenerateDelayer=setTimeout(function(){var a=generate_gcode();sendPrintCommands?a.length>0?printer.print(a):(printer.overruleState(Printer.IDLE_STATE),printer.startStatusCheckInterval()):console.log("sendPrintCommands is false: not sending print command to 3dprinter"),debugMode&&($("#textdump").text(""),$("#textdump").text(a.join("\n")))},gcodeGenerateDelay)):console.log("f:print >> not enough points!")}function clearMainView(){ctx.save(),ctx.clearRect(0,0,canvas.width,canvas.height),ctx.restore()}function resetPreview(){previewCtx.save(),previewCtx.clearRect(0,0,canvas.width,canvas.height),previewCtx.restore(),numLayers=previewDefaults.numLayers,rStep=previewDefaults.rotation}function oopsUndo(){_points.pop(),redrawDoodle(),redrawPreview()}function previewUp(a){maxNumLayers>numLayers&&numLayers++,redrawRenderedPreview(a)}function previewDown(a){numLayers>minNumLayers&&numLayers--,redrawRenderedPreview(a)}function previewTwistLeft(a){void 0==a&&(a=!1),rStep>-previewRotationLimit&&(rStep-=twistIncrement),redrawRenderedPreview(a)}function previewTwistRight(a){previewRotationLimit>rStep&&(rStep+=twistIncrement),redrawRenderedPreview(a)}function update(){setState(printer.state,printer.hasControl),thermometer.update(printer.temperature,printer.targetTemperature),progressbar.update(printer.currentLine,printer.totalLines)}function setState(a,b){if(a!=state||b!=hasControl){prevState=state,console.log("setState: ",prevState," > ",a," ( ",b,")"),setDebugText("State: "+a);var c=a==Printer.IDLE_STATE&&b;c?(btnPrint.removeClass("disabled"),btnPrint.unbind("touchstart mousedown"),btnPrint.bind("touchstart mousedown",print)):(btnPrint.addClass("disabled"),btnPrint.unbind("touchstart mousedown"));var d=(a==Printer.PRINTING_STATE||a==Printer.BUFFERING_STATE)&&b;switch(d?(btnStop.removeClass("disabled"),btnStop.unbind("touchstart mousedown"),btnStop.bind("touchstart mousedown",stopPrint)):(btnStop.addClass("disabled"),btnStop.unbind("touchstart mousedown")),a){case Printer.IDLE_STATE:case Printer.BUFFERING_STATE:case Printer.PRINTING_STATE:case Printer.STOPPING_STATE:thermometer.show();break;default:thermometer.hide()}switch(a){case Printer.PRINTING_STATE:progressbar.show();break;default:progressbar.hide()}a==Printer.WIFIBOX_DISCONNECTED_STATE?message.set("Lost connection to WiFi box",Message.ERROR):prevState==Printer.WIFIBOX_DISCONNECTED_STATE?message.set("Connected to WiFi box",Message.INFO,!0):a==Printer.DISCONNECTED_STATE?message.set("Printer disconnected",Message.WARNING,!0):(prevState==Printer.DISCONNECTED_STATE&&a==Printer.IDLE_STATE||prevState==Printer.UNKNOWN_STATE&&a==Printer.IDLE_STATE)&&message.set("Printer connected",Message.INFO,!0),state=a,hasControl=b}}function initDoodleDrawing(){console.log("f:initDoodleDrawing()"),$canvas=$("#mycanvas"),canvas=$canvas[0],ctx=canvas.getContext("2d"),canvasWidth=canvas.width,canvasHeight=canvas.height,canvas.addEventListener?(canvas.addEventListener("mousedown",onCanvasMouseDown,!1),canvas.addEventListener("mousemove",onCanvasMouseMove,!1),canvas.addEventListener("mouseup",onCanvasMouseUp,!1),canvas.addEventListener("touchstart",onCanvasTouchDown,!1),canvas.addEventListener("touchmove",onCanvasTouchMove,!1),canvas.addEventListener("touchend",onCanvasTouchEnd,!1),debugMode||document.body.addEventListener("touchmove",prevent,!1)):(canvas.attachEvent("onmousedown",onCanvasMouseDown),canvas.attachEvent("onmousemove",onCanvasMouseMove),canvas.attachEvent("onmouseup",onCanvasMouseUp),canvas.attachEvent("ontouchstart",onCanvasTouchDown),canvas.attachEvent("ontouchmove",onCanvasTouchMove),canvas.attachEvent("ontouchend",onCanvasTouchEnd),document.body.attachEvent("ontouchmove",prevent)),drawCanvas=$("#mycanvasContainer"),console.log("drawCanvasTopLeftCoords: "+drawCanvasTopLeftCoords),drawCanvasTopLeftCoords[0]=drawCanvas.offset().left,drawCanvasTopLeftCoords[1]=drawCanvas.offset().top,console.log("f:initDoodleDrawing() >> canvasWidth: "+canvasWidth),console.log("f:initDoodleDrawing() >> canvasHeight: "+canvasHeight)}function draw(a,b,c){if(0==prevX&&0==prevY&&(prevX=a,prevY=b),ctx.beginPath(),ctx.moveTo(prevX,prevY),ctx.lineTo(a,b),void 0!=c)ctx.lineWidth=c;else{if(drawVariableLineWeight){var d=Math.sqrt(Math.pow(prevX-a,2)+Math.pow(prevY-b,2));lineweight+=10>d?.25:20>d?.5:30>d?.75:50>d?1:80>d?1.5:120>d?2.25:170>d?3.5:2,lineweight=Math.min(lineweight,30),lineweight*=.9,lineweight=Math.max(lineweight,1)}else lineweight=2;ctx.lineWidth=lineweight}ctx.lineCap="round",ctx.stroke(),prevX=a,prevY=b}function clearDoodle(){console.log("f:clearDoodle"),_points=[],prevX=0,prevY=0,updatePrevX=-1,updatePrevY=-1,doodleBounds=[-1,-1,-1,-1],doodleTransform=[0,0,1,1],dragging=!1,clearMainView(),resetPreview(),resetVerticalShapes()}function redrawDoodle(){console.log("f:redrawDoodle()"),clearMainView(),prevX=0,prevY=0;for(var a=0;a<_points.length;a++)1==_points[a][2]?draw(_points[a][0],_points[a][1],.5):draw(_points[a][0],_points[a][1])}function adjustBounds(a,b){var c=!1;return console.log("f:adjustBounds("+a+","+b+")"),-1==doodleBounds[0]?(doodleBounds[0]=a,doodleBounds[1]=b,doodleBounds[2]=a,doodleBounds[3]=b,void 0):(a<doodleBounds[0]&&(doodleBounds[0]=a,c=!0),a>doodleBounds[2]&&(doodleBounds[2]=a,c=!0),b<doodleBounds[1]&&(doodleBounds[1]=b,c=!0),b>doodleBounds[3]&&(doodleBounds[3]=b,c=!0),c)}function adjustPreviewTransformation(){doodleTransform[0]=doodleBounds[0],doodleTransform[1]=doodleBounds[1];var a,b,c;_points.length<2?(a=1,b=1,c=Math.min(a,b)):(a=canvasWidth/(doodleBounds[2]-doodleBounds[0]),b=canvasHeight/(doodleBounds[3]-doodleBounds[1]),c=Math.min(a,b)),doodleTransform[2]=c,doodleTransform[3]=c}function onCanvasMouseDown(a){dragging=!0,prevCountingTime=(new Date).getTime(),movementCounter=0;var b,c;void 0!=a.offsetX?(b=a.offsetX,c=a.offsetY):(b=a.layerX,c=a.layerY),_points.push([b,c,!0]),adjustBounds(b,c),adjustPreviewTransformation(),draw(b,c,.5)}function onCanvasMouseMove(a){if(dragging){var b,c;if(void 0!=a.offsetX?(b=a.offsetX,c=a.offsetY):(b=a.layerX,c=a.layerY),-1!=prevPoint.x||-1!=prevPoint.y){var d=Math.sqrt(Math.pow(prevPoint.x-b,2)+Math.pow(prevPoint.y-c,2));d>5&&(_points.push([b,c,!1]),adjustBounds(b,c),adjustPreviewTransformation(),draw(b,c),prevPoint.x=b,prevPoint.y=c)}else _points.push([b,c,!1]),adjustBounds(b,c),adjustPreviewTransformation(),draw(b,c),prevPoint.x=b,prevPoint.y=c;(new Date).getTime()-prevRedrawTime>redrawInterval&&(prevRedrawTime=(new Date).getTime(),_points.length<50?redrawPreview():updatePreview(b,c,!0))}}function onCanvasMouseUp(){dragging=!1,console.log("doodleBounds: "+doodleBounds),console.log("doodleTransform: "+doodleTransform),console.log("_points.length :"+_points.length),renderToImageDataPreview()}function onCanvasTouchDown(a){a.preventDefault(),console.log("f:onCanvasTouchDown >> e: ",a);var b=a.touches[0].pageX-drawCanvasTopLeftCoords[0],c=a.touches[0].pageY-drawCanvasTopLeftCoords[1];_points.push([b,c,!0]),adjustBounds(b,c),adjustPreviewTransformation(),draw(b,c,.5),movementCounter=0,prevRedrawTime=(new Date).getTime()}function onCanvasTouchMove(a){a.preventDefault();var b=a.touches[0].pageX-drawCanvasTopLeftCoords[0],c=a.touches[0].pageY-drawCanvasTopLeftCoords[1];if(console.log("f:onCanvasTouchMove >> x,y = "+b+","+c+" , e: ",a),-1!=prevPoint.x||-1!=prevPoint.y){var d=Math.sqrt(Math.pow(prevPoint.x-b,2)+Math.pow(prevPoint.y-c,2));d>5&&(_points.push([b,c,!1]),adjustBounds(b,c),adjustPreviewTransformation(),draw(b,c),prevPoint.x=b,prevPoint.y=c)}else _points.push([b,c,!1]),adjustBounds(b,c),adjustPreviewTransformation(),draw(b,c),prevPoint.x=b,prevPoint.y=c;(new Date).getTime()-prevRedrawTime>redrawInterval&&(_points.length<50?redrawPreview():updatePreview(b,c,!0),prevRedrawTime=(new Date).getTime())}function onCanvasTouchEnd(){console.log("f:onCanvasTouchEnd()"),console.log("doodleBounds: "+doodleBounds),console.log("doodleTransform: "+doodleTransform),console.log("_points.length :"+_points.length),renderToImageDataPreview()}function prevent(a){a.preventDefault()}function initPreviewRendering(){console.log("f:initPreviewRendering()"),$preview=$("#preview"),preview=$preview[0],previewCtx=preview.getContext("2d");var a=preview.width/canvas.width;preview_tmp=document.getElementById("preview_tmp"),preview_tmp.width=preview.width,preview_tmp.height=canvas.height*a,$("#preview_tmp").css("top",-preview_tmp.height),previewCtx_tmp=preview_tmp.getContext("2d"),calcPreviewCanvasProperties(),redrawPreview()}function calcPreviewCanvasProperties(){console.log("f:calcPreviewCanvasProperties()"),globalScale=preview.width/canvasWidth,layerCX=canvasWidth/2*globalScale,layerCY=canvasHeight/2*globalScale,layerOffsetY=preview.height*(1-previewVerticalPadding.bottom),yStep=(preview.height-preview.height*(previewVerticalPadding.top+previewVerticalPadding.bottom))/maxNumLayers}function redrawPreview(a){if(void 0==a&&(a=!1),!(_points.length<2)){a||(debug_redrawSimplification=_points.length<100?6:_points.length<250?7:_points.length<400?8:_points.length<550?9:_points.length<700?10:11);var b=0,c=0;previewCtx.clearRect(0,0,preview.width,preview.height),previewCtx.lineWidth=strokeWidth,previewCtx.strokeStyle="#f00";for(var d=0;numLayers>d;d++){var e=scaleFunction(d/maxNumLayers);if(previewCtx.globalAlpha=0==d||d==Math.floor(numLayers/2)||d==numLayers-1?1:globalAlpha,a&&0!=d%debug_redrawSimplification&&0!=d&&d!=Math.floor(numLayers/2)&&d!=numLayers-1)b-=yStep,c+=rStep;else{previewCtx.save(),previewCtx.translate(layerCX,layerOffsetY+b),previewCtx.scale(viewerScale*e,scaleY*viewerScale*e),previewCtx.rotate(c),previewCtx.translate(-doodleTransform[0]*globalScale*doodleTransform[2],-doodleTransform[1]*globalScale*doodleTransform[3]);var f=centeredAndScaledDoodlePoint(_points[0]);previewCtx.beginPath(),previewCtx.moveTo(f.x,f.y);for(var g=1;g<_points.length;g++)f=centeredAndScaledDoodlePoint(_points[g]),a&&0!=g%debug_redrawSimplification||previewCtx.lineTo(f.x,f.y);previewCtx.stroke(),b-=yStep,c+=rStep,previewCtx.restore()}}previewCtx.globalAlpha=globalAlpha}}function renderToImageDataPreview(){if(console.log("f:renderToImageDataPreview()"),!(_points.length<2)){previewCtx_tmp.clearRect(0,0,preview.width,preview.height),previewCtx_tmp.lineWidth=strokeWidth,previewCtx_tmp.strokeStyle="#f00",previewCtx_tmp.save(),previewCtx_tmp.translate(layerCX,layerCY),previewCtx_tmp.scale(viewerScale,viewerScale),previewCtx_tmp.translate(-doodleTransform[0]*globalScale*doodleTransform[2],-doodleTransform[1]*globalScale*doodleTransform[3]);var a=centeredAndScaledDoodlePoint(_points[0]);previewCtx_tmp.beginPath(),previewCtx_tmp.moveTo(a.x,a.y);for(var b=1;b<_points.length;b++)a=centeredAndScaledDoodlePoint(_points[b]),previewCtx_tmp.lineTo(a.x,a.y);previewCtx_tmp.stroke(),previewCtx_tmp.closePath(),previewCtx_tmp.restore();
var c=preview_tmp.toDataURL();doodleImageCapture=new Image,doodleImageCapture.onload=function(){previewCtx.clearRect(0,0,preview.width,preview.height),previewCtx.lineWidth=strokeWidth,previewCtx.strokeStyle="#f00";for(var a=0,b=0,c=0;numLayers>c;c++){var d=scaleFunction(c/maxNumLayers);previewCtx.globalAlpha=0==c||c==Math.floor(numLayers/2)||c==numLayers-1?1:globalAlpha,previewCtx.save(),previewCtx.translate(layerCX,layerOffsetY+a),previewCtx.scale(d,scaleY*d),previewCtx.rotate(b),previewCtx.translate(-layerCX,-layerCY),previewCtx.drawImage(doodleImageCapture,0,0),a-=yStep,b+=rStep,previewCtx.restore()}},doodleImageCapture.src=c,previewCtx.globalAlpha=globalAlpha}}function redrawRenderedPreview(a){void 0==a&&(a=!1),console.log("f:redrawRenderedPreview()"),previewCtx.clearRect(0,0,preview.width,preview.height),previewCtx.lineWidth=strokeWidth,previewCtx.strokeStyle="#f00";for(var b=0,c=0,d=0;numLayers>d;d++){var e=scaleFunction(d/maxNumLayers);previewCtx.globalAlpha=0==d||d==Math.floor(numLayers/2)||d==numLayers-1?1:globalAlpha,a&&0!=d%2&&0!=d&&d!=Math.floor(numLayers/2)&&d!=numLayers-1?(b-=yStep,c+=rStep):(previewCtx.save(),previewCtx.translate(layerCX,layerOffsetY+b),previewCtx.scale(e,scaleY*e),previewCtx.rotate(c),previewCtx.translate(-layerCX,-layerCY),previewCtx.drawImage(doodleImageCapture,0,0),b-=yStep,c+=rStep,previewCtx.restore())}}function centeredAndScaledDoodlePoint(a){var b={x:0,y:0};return b.x=(a[0]-(doodleBounds[2]-doodleBounds[0])/2)*globalScale*doodleTransform[2],b.y=(a[1]-(doodleBounds[3]-doodleBounds[1])/2)*globalScale*doodleTransform[3],b}function updatePreview(a,b,c){if(void 0==c&&(c=!1),c=!1,!(_points.length<2)){if(-1==updatePrevX||-1==updatePrevY)return updatePrevX=a,updatePrevY=b,void 0;var d=0,e=0;previewCtx.lineWidth=strokeWidth,previewCtx.strokeStyle="#f00";for(var f=0;numLayers>f;f++)if(previewCtx.globalAlpha=0==f||f==Math.floor(numLayers/2)||f==numLayers-1?1:globalAlpha,c&&0!=f%debug_redrawSimplification&&0!=f&&f!=Math.floor(numLayers/2)&&f!=numLayers-1)d-=yStep,e+=rStep;else{previewCtx.save(),previewCtx.translate(layerCX,layerOffsetY+d),previewCtx.scale(viewerScale,scaleY*viewerScale),previewCtx.rotate(e),previewCtx.translate(-doodleTransform[0]*globalScale*doodleTransform[2],-doodleTransform[1]*globalScale*doodleTransform[3]),previewCtx.beginPath();var g=centeredAndScaledDoodlePoint([updatePrevX,updatePrevY]);previewCtx.moveTo(g.x,g.y);var h=centeredAndScaledDoodlePoint([a,b]);previewCtx.lineTo(h.x,h.y),previewCtx.stroke(),d-=yStep,e+=rStep,previewCtx.restore()}previewCtx.globalAlpha=globalAlpha,updatePrevX=a,updatePrevY=b}}function generate_gcode(){console.log("f:generategcode()");var a=110,b=110;gcode=[],console.log("settings: ",settings);var c=settings["printer.speed"],d=c,e=.5*c,f=settings["printer.travelSpeed"],g=settings["printer.filamentThickness"],h=settings["printer.wallThickness"],i=settings["printer.screenToMillimeterScale"],j=settings["printer.layerHeight"],k=settings["printer.maxObjectHeight"],l=settings["printer.temperature"],m=settings["printer.useSubLayers"],n=settings["printer.enableTraveling"],o=settings["printer.retraction.enabled"],p=settings["printer.retraction.speed"],q=settings["printer.retraction.minDistance"],r=settings["printer.retraction.amount"],s=settings["printer.heatup.temperature"],t=settings["printer.startgcode"];t=t.replace("{printingTemp}",l),t=t.replace("{preheatTemp}",s),t=t.split("\n");var u=settings["printer.endgcode"];u=u.replace("{printingTemp}",l),u=u.replace("{preheatTemp}",s),u=u.split("\n");var v=k/j;objectHeight=Math.round(numLayers/maxNumLayers*k);var w=rStep*maxNumLayers/v;w=-w;var x=JSON.parse(JSON.stringify(_points));gcode=gcode.concat(t);var v=k/j,y=0,z=new Point;z.set(0,0);var A={x:doodleBounds[0]+(doodleBounds[2]-doodleBounds[0])/2,y:doodleBounds[1]+(doodleBounds[3]-doodleBounds[1])/2};if(console.log("f:generategcode() >> layers: "+v),1/0!=v){var B=x.length*v*(objectHeight/k);if(B>MAX_POINTS_TO_PRINT)return alert("Sorry, your doodle to to complex and / or to high"),console.log("WARNING: to many points to convert to gcode"),[];for(var C=0;v>C;C++){var D=JSON.parse(JSON.stringify(x));if(D.length<2)return;var E=C/v,F=scaleFunction(E),G=lineLength(x[0][0],x[0][1],x[x.length-1][0],x[x.length-1][1])<3;pointsTranslate(D,-A.x,-A.y),pointsScale(D,i,-i),pointsScale(D,F,F),pointsRotate(D,w*C),0==C?firstLayerSlow&&(c=e):2==C&&(gcode.push("M106"),c=d);for(var H=0,I=D.length,J=0,K=[],L=-1,M=0;M<D.length;M++)1==D[M][2]?(L++,K.push([]),K[L].push([D[M][0],D[M][1]])):K[L].push([D[M][0],D[M][1]]);for(var N=0;N<K.length;N++)for(var O=K[N],M=0;M<O.length;M++){O.length-1;var P=new Point;P.set(O[M][0],O[M][1]),P.x+=a,P.y+=b;var Q=0==C?0:C+(m?H/I:0),R=(Q+1)*j,S=!G&&0==M,T=o&&z.distance(P)>q;n&&S?(T&&gcode.push("G0 E"+(y-r).toFixed(3)+" F"+(60*p).toFixed(3)),gcode.push("G0 X"+P.x.toFixed(3)+" Y"+P.y.toFixed(3)+" Z"+R.toFixed(3)+" F"+(60*f).toFixed(3)),T&&gcode.push("G0 E"+y.toFixed(3)+" F"+(60*p).toFixed(3))):(y+=z.distance(P)*h*j/(Math.pow(g/2,2)*Math.PI),gcode.push("G1 X"+P.x.toFixed(3)+" Y"+P.y.toFixed(3)+" Z"+R.toFixed(3)+" F"+(60*c).toFixed(3)+" E"+y.toFixed(3))),H++,J=H/I,z=P}if(C/v>objectHeight/k){console.log("f:generategcode() >> (layer/layers) > (objectHeight/maxObjectHeight) is true -> breaking at layer "+(C+1));break}}return gcode=gcode.concat(u)}}function scaleFunction(a){var b=1;switch(VERTICALSHAPE){case verticalShapes.NONE:b=1;break;case verticalShapes.DIVERGING:b=.5+.5*a;break;case verticalShapes.CONVERGING:b=1-.8*a;break;case verticalShapes.SINUS:b=.25*Math.cos(4*a*Math.PI)+.75}return b}function doOnResize(){canvas.width=$canvas.width(),canvas.height=$canvas.height(),preview.width=$preview.width(),preview.height=$drawAreaContainer.height(),canvasWidth=canvas.width,canvasHeight=canvas.height,console.log(" preview.width: "+preview.width+", $preview.width(): "+$preview.width()),calcPreviewCanvasProperties(),drawCanvasTopLeftCoords[0]=drawCanvas.offset().left,drawCanvasTopLeftCoords[1]=drawCanvas.offset().top,redrawDoodle(),redrawPreview()}function initLayouting(){console.log("f:initLayouting()"),$drawAreaContainer=$(".drawareacontainer"),canvas.width=$canvas.width(),canvas.height=$canvas.height(),preview.width=$preview.width(),preview.height=$drawAreaContainer.height(),canvasWidth=canvas.width,canvasHeight=canvas.height,$drawAreaContainer.show(),console.log("window.innerHeight: "+window.innerHeight),console.log("window.innerWidth: "+window.innerWidth),console.log("$drawAreaContainer.innerHeight(): "+$drawAreaContainer.innerHeight()),console.log("$drawAreaContainer.offset().top: "+$drawAreaContainer.offset().top),setTimeout(_startOrientationAndChangeEventListening,1e3)}function _startOrientationAndChangeEventListening(){$(window).on("resize",doOnResize),doOnResize()}function Printer(){Printer.WIFIBOX_DISCONNECTED_STATE="wifibox disconnected",Printer.UNKNOWN_STATE="unknown",Printer.DISCONNECTED_STATE="disconnected",Printer.IDLE_STATE="idle",Printer.BUFFERING_STATE="buffering",Printer.PRINTING_STATE="printing",Printer.STOPPING_STATE="stopping",Printer.ON_BEFORE_UNLOAD_MESSAGE="You're doodle is still being send to the printer, leaving will result in a incomplete 3D print",this.temperature=0,this.targetTemperature=0,this.currentLine=0,this.totalLines=0,this.bufferedLines=0,this.state=Printer.UNKNOWN_STATE,this.hasControl=!0,this.wifiboxURL,this.checkStatusInterval=3e3,this.checkStatusDelay,this.timeoutTime=3e3,this.sendPrintPartTimeoutTime=5e3,this.gcode,this.sendLength=1500,this.retryDelay=2e3,this.retrySendPrintPartDelay,this.retryCheckStatusDelay,this.retryStopDelay,this.retryPreheatDelay,this.maxGCodeSize=10,this.stateOverruled=!1,Printer.UPDATE="update";var a=this;this.init=function(){console.log("Printer:init"),this.wifiboxURL=wifiboxURL,console.log(" wifiboxURL: ",this.wifiboxURL),autoUpdate&&this.startStatusCheckInterval()},this.preheat=function(){console.log("Printer:preheat");var a=this;communicateWithWifibox?$.ajax({url:this.wifiboxURL+"/printer/heatup",type:"POST",dataType:"json",timeout:this.timeoutTime,success:function(b){console.log("Printer:preheat response: ",b),"error"==b.status&&(clearTimeout(a.retryPreheatDelay),a.retryPreheatDelay=setTimeout(function(){a.preheat()},a.retryDelay))}}).fail(function(){console.log("Printer:preheat: failed"),clearTimeout(a.retryPreheatDelay),a.retryPreheatDelay=setTimeout(function(){a.preheat()},a.retryDelay)}):console.log("Printer >> f:preheat() >> communicateWithWifibox is false, so not executing this function")},this.print=function(b){console.log("Printer:print"),console.log(" gcode total # of lines: "+b.length),message.set("Sending doodle to printer...",Message.NOTICE),a.addLeaveWarning(),this.sendIndex=0,this.gcode=b;var c=this.byteSize(b[20]),d=c*b.length/1024/1024;return console.log(" gcodeSize: ",d),d>this.maxGCodeSize?(console.log("Error: Printer:print: gcode file is probably to big ("+d+"MB) (max: "+this.maxGCodeSize+"MB)"),void 0):(this.sendPrintPart(this.sendIndex,this.sendLength),void 0)},this.byteSize=function(a){return~-encodeURI(a).split(/%..|./).length},this.sendPrintPart=function(a,b){console.log("Printer:sendPrintPart sendIndex: "+a+"/"+this.gcode.length+", sendLength: "+b);var c=0==a?!0:!1,d=c,e=!1;this.gcode.length<a+b&&(console.log(" sending less than max sendLength (and last)"),b=this.gcode.length-a,e=!0);var f=this.gcode.slice(a,a+b),g={gcode:f.join("\n"),first:c,start:d},h=this;communicateWithWifibox?$.ajax({url:this.wifiboxURL+"/printer/print",type:"POST",data:g,dataType:"json",timeout:this.sendPrintPartTimeoutTime,success:function(c){console.log("Printer:sendPrintPart response: ",c),"success"==c.status&&(e?(console.log("Printer:sendPrintPart:gcode sending completed"),this.gcode=[],btnStop.css("display","block"),h.removeLeaveWarning(),message.set("Doodle is send to printer...",Message.INFO,!0)):(console.log("Printer:sendPrintPart:gcode part received (state: ",h.state,")"),(h.state==Printer.PRINTING_STATE||h.state==Printer.BUFFERING_STATE)&&(console.log("Printer:sendPrintPart:sending next part"),h.sendPrintPart(a+b,b)))),0==a&&h.startStatusCheckInterval()}}).fail(function(){console.log("Printer:sendPrintPart: failed"),clearTimeout(h.retrySendPrintPartDelay),h.retrySendPrintPartDelay=setTimeout(function(){console.log("request printer:sendPrintPart failed retry"),h.sendPrintPart(a,b)},h.retryDelay),h.startStatusCheckInterval()}):console.log("Printer >> f:sendPrintPart() >> communicateWithWifibox is false, so not executing this function")},this.stop=function(){console.log("Printer:stop");var a=this;communicateWithWifibox?$.ajax({url:this.wifiboxURL+"/printer/stop",type:"POST",dataType:"json",timeout:this.timeoutTime,success:function(b){console.log("Printer:stop response: ",b),a.startStatusCheckInterval()}}).fail(function(){console.log("Printer:stop: failed"),clearTimeout(a.retryStopDelay),a.retryStopDelay=setTimeout(function(){a.stop()},a.retryDelay),a.startStatusCheckInterval()}):console.log("Printer >> f:communicateWithWifibox() >> communicateWithWifibox is false, so not executing this function")},this.startStatusCheckInterval=function(){console.log("Printer:startStatusCheckInterval"),a.checkStatus(),clearTimeout(a.checkStatusDelay),clearTimeout(a.retryCheckStatusDelay),a.checkStatusDelay=setTimeout(function(){a.checkStatus()},a.checkStatusInterval)},this.stopStatusCheckInterval=function(){console.log("Printer:stopStatusCheckInterval"),clearTimeout(a.checkStatusDelay),clearTimeout(a.retryCheckStatusDelay)},this.checkStatus=function(){console.log("Printer:checkStatus"),this.stateOverruled=!1;var a=this;communicateWithWifibox?$.ajax({url:this.wifiboxURL+"/info/status",dataType:"json",timeout:this.timeoutTime,success:function(b){a.handleStatusUpdate(b),clearTimeout(a.checkStatusDelay),clearTimeout(a.retryCheckStatusDelay),a.checkStatusDelay=setTimeout(function(){a.checkStatus()},a.checkStatusInterval)}}).fail(function(){console.log("Printer:checkStatus: failed"),a.state=Printer.WIFIBOX_DISCONNECTED_STATE,clearTimeout(a.checkStatusDelay),clearTimeout(a.retryCheckStatusDelay),a.retryCheckStatusDelay=setTimeout(function(){a.checkStatus()},a.retryDelay),$(document).trigger(Printer.UPDATE)}):console.log("Printer >> f:checkStatus() >> communicateWithWifibox is false, so not executing this function")},this.handleStatusUpdate=function(b){console.log("Printer:handleStatusUpdate response: ",b);var c=b.data;"success"!=b.status?a.state=Printer.UNKNOWN_STATE:(this.stateOverruled||(a.state=c.state),a.temperature=c.hotend,a.targetTemperature=c.hotend_target,a.currentLine=c.current_line,a.totalLines=c.total_lines,a.bufferedLines=c.buffered_lines,a.hasControl=c.has_control,(a.state==Printer.PRINTING_STATE||a.state==Printer.STOPPING_STATE)&&console.log("progress: ",a.currentLine+"/"+a.totalLines+" ("+a.bufferedLines+") ("+a.state+")")),$(document).trigger(Printer.UPDATE)},this.overruleState=function(b){this.stateOverruled=!0,console.log(" stateOverruled: ",this.stateOverruled),a.state=b,$(document).trigger(Printer.UPDATE),this.stopStatusCheckInterval()},this.removeLeaveWarning=function(){window.onbeforeunload=null},this.addLeaveWarning=function(){window.onbeforeunload=function(){return Printer.ON_BEFORE_UNLOAD_MESSAGE}}}function Progressbar(){this.currProgress=0,this.progressbarFGImg=new Image,this.progressbarFGImgSrc="img/progress_fg.png",this.progressbarBGImg=new Image,this.progressbarBGImgSrc="img/progress_bg.png",this.progressWidth=93,this.progressHeight=82,this.quartPI=.5*Math.PI,this.twoPI=2*Math.PI,this.$canvas,this.canvas,this.context,this.$container,this.isInitted=!1,this.enabled=!0,this.init=function(a,b){console.log("Thermometer.init()"),this.$container=b,this.$canvas=a,this.canvas=this.$canvas[0],this.context=this.canvas.getContext("2d");var c=this;this.progressbarBGImg.onload=function(){console.log("progressbarBGImg img loaded"),c.progressbarFGImg.onload=function(){console.log("progressbarFGImg img loaded"),c.isInitted=!0,c.update(0,100)},c.progressbarFGImg.src=c.progressbarFGImgSrc},this.progressbarBGImg.src=this.progressbarBGImgSrc},this.update=function(a,b){if(this.isInitted){void 0==a&&(a=0),void 0==b&&(b=100);var c=a/b;c=Math.min(c,1),c=Math.max(c,0),this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(this.progressbarBGImg,0,0),this.context.font="7pt sans-serif",this.context.save(),this.context.beginPath(),this.context.moveTo(45,45),this.context.lineTo(45,0),this.context.arc(45,45,45,-this.quartPI,-this.quartPI+c*this.twoPI,!1),this.context.lineTo(45,45),this.context.clip(),this.context.drawImage(this.progressbarFGImg,0,0),this.context.restore(),debugMode&&(this.context.fillStyle="#222",this.context.strokeStyle="#fff",this.context.lineWidth=3,this.context.textAlign="center",this.context.strokeText(a+" / "+b,45,45,90),this.context.fillText(a+" / "+b,45,45,90))}else console.log("Progressbar.setTemperature() -> thermometer not initialized!")},this.show=function(){this.$container.addClass("progressbarAppear"),this.enabled=!0},this.hide=function(){this.$container.removeClass("progressbarAppear"),this.enabled=!1}}function Thermometer(){this.currentTemperature=0,this.targetTemperature=0,this.thermoOverlayImg=new Image,this.thermoOverlayImgSrc="img/thermometer_fg_overlay.png",this.thermoWidth=40,this.thermoHeight=100,this.$canvas,this.canvas,this.context,this.$container,this.isInitted=!1,this.enabled=!0,this.thermoColors=[[50,200,244],[244,190,10],[244,50,50]],this.init=function(a,b){console.log("Thermometer.init()"),this.$container=b,this.$canvas=a,this.canvas=this.$canvas[0],this.context=this.canvas.getContext("2d");var c=this;this.thermoOverlayImg.onload=function(){console.log("canvasThermoOverlay img loaded"),c.isInitted=!0,c.update(c.currentTemperature,c.targetTemperature)},this.thermoOverlayImg.src=this.thermoOverlayImgSrc},this.update=function(a,b){if(this.isInitted){if(!this.enabled)return;void 0==a&&(a=0),void 0==b&&(b=180);var c=a/b;c=Math.min(c,1),c=Math.max(c,0);var d=this.thermoHeight,e=15,f=25,g=Math.floor((d-e-f)*c),h=this.thermoColors[0];c>.98?h=this.thermoColors[2]:c>.25&&(h=this.thermoColors[1]),this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.font="10pt sans-serif",this.context.save(),this.context.beginPath(),this.context.arc(40,80,16,0,2*Math.PI,!1),this.context.arc(40,10,4,0,2*Math.PI,!1),this.context.rect(36,11,8,70),this.context.fillStyle="#fff",this.context.fill(),this.context.clip(),this.context.beginPath(),this.context.rect(20,d-e-g,60,g+e),this.context.fillStyle="rgb("+h[0]+","+h[1]+","+h[2]+")",this.context.fill(),this.context.restore(),this.context.save(),this.context.beginPath(),this.context.moveTo(32,f),this.context.lineTo(52,f),this.context.lineWidth=2,this.context.strokeStyle="#000",this.context.stroke(),this.context.fillStyle="#000",this.context.textAlign="left",this.context.textBaseline="middle",this.context.fillText(b+"°",55,f),this.context.restore(),this.context.drawImage(this.thermoOverlayImg,20,0),this.context.fillStyle="#000",this.context.textAlign="center",this.context.fillText(a+"°",40,d+e)}else console.log("Thermometer.setTemperature() -> thermometer not initialized!")},this.show=function(){this.$container.addClass("thermometerAppear"),this.enabled=!0},this.hide=function(){this.$container.removeClass("thermometerAppear"),this.enabled=!1}}function getURLParameter(a){return decodeURI((new RegExp("[&?]"+a+"="+"(.+?)(&|$)").exec(location.search)||[,null])[1])}function initSidebars(){console.log("f:initSidebars()"),sidebarLeft=new SideBar,sidebarLeft.init(".leftpanel","hideleft",function(){$(".leftpanel").show()}),sidebarRight=new SideBar,sidebarRight.init(".rightpanel","hideright",function(){$(".rightpanel").show()})}function SideBar(){this.initted=!1,this.$contentTarg=void 0,this.$sideBtn=void 0,this.contentHidden=!1,this.hideClass="",this.init=function(a,b,c){console.log("SideBar >> f:init >> targ: ",$(a),", hideClass: "+b),this.$contentTarg=$(a),this.hideClass=b,this.$contentTarg.addClass(this.hideClass),this.contentHidden=!0,this.$contentTarg.append("<div class='sidebutton'></div>"),this.$sideBtn=$(a+" .sidebutton");var d=this;this.$sideBtn.on("click",function(){console.log("sidebutton"),d.toggleShowHide()}),this.initted=!0,c()},this.toggleShowHide=function(){this.contentHidden?(this.contentHidden=!1,this.$contentTarg.removeClass(this.hideClass),this.$sideBtn.addClass("sidebuttonin")):(this.contentHidden=!0,this.$contentTarg.addClass(this.hideClass),this.$sideBtn.removeClass("sidebuttonin"))}}function Message(){Message.ERROR="error",Message.WARNING="warning",Message.NOTICE="notice",Message.INFO="info",this.mode="",this.$element;var a,b=this,c=2e3;this.init=function(a){console.log("Message:init"),this.$element=a,console.log("$element: ",a)},this.set=function(d,e,f){console.log("Message:set: ",d,e,f),b.hide(function(){b.show(),b.clear(),b.$element.text(d),b.$element.addClass(e),b.show(),b.mode=e,clearTimeout(a),f&&(a=setTimeout(function(){b.hide()},c))})},this.clear=function(){this.$element.text(""),this.$element.removeClass(this.mode)},this.show=function(){this.$element.fadeIn(200)},this.hide=function(a){this.$element.fadeOut(200,a)}}function showOrHideThermo(){console.log("f:showOrHideThermo()"),showOrHide?(thermometer.hide(),progressbar.hide()):(thermometer.show(),progressbar.show()),showOrHide=!showOrHide}function settingsLoaded(){console.log("settingsLoaded"),console.log("autoHeatup: ",settings["printer.heatup.enabled"]),settings["printer.heatup.enabled"]&&firstTimeSettingsLoaded&&(printer.preheat(),firstTimeSettingsLoaded=!1)}function setDebugText(a){$("#debug_display").text(a)}var settings={"network.ap.ssid":"d3d-ap-%%MAC_ADDR_TAIL%%","network.ap.address":"192.168.10.1","network.ap.netmask":"255.255.255.0","printer.temperature":220,"printer.maxObjectHeight":150,"printer.layerHeight":.2,"printer.wallThickness":.7,"printer.screenToMillimeterScale":.3,"printer.speed":50,"printer.travelSpeed":200,"printer.filamentThickness":2.85,"printer.enableTraveling":!0,"printer.useSubLayers":!0,"printer.firstLayerSlow":!0,"printer.autoWarmUp":!0,"printer.simplify.iterations":10,"printer.simplify.minNumPoints":15,"printer.simplify.minDistance":3,"printer.retraction.enabled":!0,"printer.retraction.speed":50,"printer.retraction.minDistance":1,"printer.retraction.amount":5,"printer.autoWarmUpCommand":"M104 S220 (hardcoded temperature)"},objectHeight=20,layerHeight=.2,enableTraveling=!0,minScale=.3,maxScale=1,shape="%",twists=0,loglevel=2,serverport=8888,autoLoadImage="hand.txt",loadOffset=[0,0],showWarmUp=!0,loopAlways=!1,firstLayerSlow=!0,useSubpathColors=!1,autoWarmUp=!0,maxScaleDifference=.1,frameRate=60,quitOnEscape=!0,screenToMillimeterScale=.3,sideis3D=!0,sidevisible=!0,sidebounds=[900,210,131,390],sideborder=[880,169,2,471],windowbounds=[0,0,800,500],windowcenter=!0,windowfullscreen=!1,autoWarmUpCommand="M104 S230",autoWarmUpDelay=3,VERTICALSHAPE,verticalShapes={NONE:"none",DIVERGING:"diverging",CONVERGING:"converging",SINUS:"sinus"},btnMoveUpInterval,btnMoveDownInterval,btnTwistLeftInterval,btnTwistRightInterval,twistIncrement=Math.PI/1800,btnOopsInterval,btnNew,btnPrevious,btnNext,btnOops,btnStop,btnClear,btnMoveUp,btnMoveDown,btnTwistLeft,btnTwistRight,btnInfo,btnSettings,state,prevState,hasControl,gcodeGenerateDelayer,gcodeGenerateDelay=50,preview,previewCtx,svgPathRegExp=/[LM]\d* \d*/gi,svgPathParamsRegExp=/([LM])(\d*) (\d*)/,dragging=!1,$canvas,canvas,ctx,canvasWidth,canvasHeight,drawCanvas,drawCanvasTopLeftCoords=[0,0],doodleBounds=[-1,-1,-1,-1],doodleTransform=[0,0,1,1],_points=[],prevCountingTime=0,movementCounter=0,drawVariableLineWeight=!1,lineweight=2,prevPoint={x:-1,y:-1};prevUpdateFullPreview=0,prevUpdateFullPreviewInterval=25;var $preview,preview,previewCtx,preview_tmp,previewCtx_tmp,previewDefaults={rotation:Math.PI/90,numLayers:10},svgPathRegExp=/[LM]\d* \d*/gi,svgPathParamsRegExp=/([LM])(\d*) (\d*)/,prevRedrawTime=(new Date).getTime(),redrawInterval=1e3/30,previewRotationLimit=Math.PI/30,numLayers=previewDefaults.numLayers,maxNumLayers=100,minNumLayers=2,globalScale=.3,globalAlpha=.2,scaleY=.4,viewerScale=.65,previewVerticalPadding={top:.15,bottom:.12},strokeWidth=2,rStep=previewDefaults.rotation,yStep,layerCX,layerCY,layerOffsetY,prevX=0,prevY=0,highlight=!0,linesRaw="",debug_redrawSimplification=6,updatePrevX=-1,updatePrevY=-1,MAX_POINTS_TO_PRINT=4e5,gcode=[];pointsTranslate=function(a,b,c){for(var d=0;d<a.length;d++)a[d][0]+=b,a[d][1]+=c},pointsScale=function(a,b,c){for(var d=0;d<a.length;d++)a[d][0]*=b,a[d][1]*=c},pointsRotate=function(a,b){for(var c,d,e=0;e<a.length;e++)d=Math.sqrt(a[e][0]*a[e][0]+a[e][1]*a[e][1]),c=Math.atan2(a[e][1],a[e][0]),a[e][0]=Math.cos(c+b)*d,a[e][1]=Math.sin(c+b)*d},lineLength=function(a,b,c,d){return Math.sqrt((a-=c)*a+(b-=d)*b)};var Point=function(){};Point.prototype={x:0,y:0,set:function(a,b){this.x=a,this.y=b},distance:function(a){var b=-1;return a instanceof Point&&(b=Math.sqrt((a.x-this.x)*(a.x-this.x)+(a.y-this.y)*(a.y-this.y))),b},toString:function(){console.log("x:"+this.x+", y:"+this.y)}};var drawAreaContainerMinHeight=300,drawAreaContainerMaxHeight=450,$displayThermometer=$("#thermometerContainer"),sidebarLeft,sidebarRight,debugMode=!1,sendPrintCommands=!0,communicateWithWifibox=!0,wifiboxIsRemote=!1,autoUpdate=!0,printer=new Printer,progressbar=new Progressbar,thermometer=new Thermometer,settingsWindow=new SettingsWindow,message=new Message,firstTimeSettingsLoaded=!0,wifiboxURL,wifiboxCGIBinURL,$drawAreaContainer,$doodleCanvas,doodleCanvas,doodleCanvasContext,$previewContainer,showhideInterval,showOrHide=!1;$(function(){console.log("ready"),"null"!=getURLParameter("d")&&(debugMode="1"==getURLParameter("d")),"null"!=getURLParameter("p")&&(sendPrintCommands="1"==getURLParameter("p")),"null"!=getURLParameter("c")&&(communicateWithWifibox="1"==getURLParameter("c")),"null"!=getURLParameter("r")&&(wifiboxIsRemote="1"==getURLParameter("r")),"null"!=getURLParameter("u")&&(autoUpdate="1"==getURLParameter("u")),wifiboxIsRemote?(wifiboxURL="http://192.168.5.1/d3dapi",wifiboxCGIBinURL="http://192.168.5.1/cgi-bin/d3dapi"):(wifiboxURL="http://"+window.location.host+"/d3dapi",wifiboxCGIBinURL="http://"+window.location.host+"/cgi-bin/d3dapi"),communicateWithWifibox||(sendPrintCommands=!1),console.log("debugMode: "+debugMode),console.log("sendPrintCommands: "+sendPrintCommands),console.log("communicateWithWifibox: "+communicateWithWifibox),console.log("wifiboxIsRemote: "+wifiboxIsRemote),console.log("wifibox URL: "+wifiboxURL),initDoodleDrawing(),initPreviewRendering(),initLayouting(),initSidebars(),initButtonBehavior(),initVerticalShapes(),thermometer.init($("#thermometerCanvas"),$("#thermometerContainer")),progressbar.init($("#progressbarCanvas"),$("#progressbarCanvasContainer")),message.init($("#message")),printer.init(),$(document).on(Printer.UPDATE,update),settingsWindow.init(wifiboxURL,wifiboxCGIBinURL),$(document).on(SettingsWindow.SETTINGS_LOADED,settingsLoaded),debugMode&&(console.log("debug mode is true"),$("body").css("overflow","auto"),$("#debug_textArea").css("display","block"),$("#preview_tmp").css("display","block"),$("#debug_display").css("display","block"),showhideInterval=setInterval(showOrHideThermo,2500))});