define(["view/base","model/monitor","codemirror","codemirror-ruby","jquery-validate","parsley"],function(e,t,i){var s=e.extend({scheduleViewInitialized:!1,metricsViewInitialized:!1,scheduleView:!0,el:".add-monitor-wrap",subscriptions:{"view:dashboard:category":"updateDashboardId","view:settings:save":"render"},events:{"click .setMetrics":"advanceToMetrics","click .testGraph":"testMetrics","click .nameSchedule":"backToSchedule","click .saveFinish":"saveFinish","click .back":"exitFullScreen","hide #addMonitor":"modalClose","show #addMonitor":"modalShow","shown #addMonitor":"focusFirst"},initialize:function(e){_.bindAll(this),this.user=e.user,this.dashboardId=e.dashboardId,this.templar=e.templar;var t=_.debounce(this.adjustModalLayout,500);$(window).resize(t),this.render()},render:function(){this.setElement($(".add-monitor-wrap")),this.templar.render({path:"addmonitor",el:this.$el,data:{}}),this.templar.render({path:"schedulemonitor",el:this.$el.find(".content-wrap"),data:{user:this.user.toJSON()}}),this.scheduleViewInitialized=!0,this.setScheduleValidation(),this.$modal=this.$el.find(".add-monitor"),this.resizeModal($("#addMonitor"),"large")},updateDashboardId:function(e){this.dashboardId=e,this.model.set({dashboardId:this.dashboardId})},adjustModalLayout:function(){var e=$("#addMonitor"),t=this.resizeModal(e,"large"),i=325,s=80,r=150,o=80;if(!this.scheduleView){var a=t.body.height-s>i?t.body.height-s:i;e.find(".hero-unit").css({height:a});var n=Math.floor((a-r)/2);this.expressionsMirror.setSize(null,n),this.metricsMirror.setSize(null,n);var d=Math.floor((a-o)/2);e.find(".graph").css({height:d}),this.chart.setSize(null,d),e.find("#outputView").css({height:d})}},advanceToMetrics:function(){this.scheduleForm.parsley("validate")},backToSchedule:function(){this._setupScheduleView()},exitFullScreen:function(){var e=this.$el.find("button.close"),t=this.$el.find("button.back"),i=$(".add-monitor .metrics .CodeMirror"),s=$(".add-monitor .expressions .CodeMirror");e.show(),t.hide(),i.removeClass("fullscreen"),i.data("beforeFullscreen")&&(i.height(i.data("beforeFullscreen").height),i.width(i.data("beforeFullscreen").width)),this.metricsMirror.refresh(),s.removeClass("fullscreen"),s.data("beforeFullscreen")&&(s.height(s.data("beforeFullscreen").height),s.width(s.data("beforeFullscreen").width)),this.expressionsMirror.refresh()},setScheduleValidation:function(){this.scheduleForm=$("#namePagerForm"),this.scheduleForm.parsley({listeners:{onFormSubmit:function(e){e&&(this._setSchedule(),this._setupMetricsView())}.bind(this)}})},setMetricsValidation:function(){$.validator.addMethod("code",function(e,t){var i=$(t).data("CodeMirror");return $(i.getWrapperElement()),this._validateMirror(i)}.bind(this),"This field is required."),$.validator.addMethod("metric-ruby",function(){var e=!1;return $.ajax({url:"/monitor.json",type:"post",data:this.model.toJSON(),async:!1,success:function(t){"success"==t.status&&(e=!0)}}),e},"Your metrics code does not validate."),$.validator.addMethod("expression-ruby",function(e){var t=!1;return $.ajax({url:"/monitor.json",type:"post",data:this.model.toJSON(),async:!1,success:function(i){("success"==i.status||""==e)&&(t=!0)}}),t}.bind(this),"Your expression code does not validate."),this.metricsForm=$("#metricsExpressionsForm"),this.metricsForm.validate({rules:{inputMetrics:{code:!0,"expression-ruby":!0},inputExpressions:{"expression-ruby":!0}},errorPlacement:function(e,t){var i=$(t).data("CodeMirror");if(i){var s=$(i.getWrapperElement());this._validateMirror(i),e.insertAfter(s)}else e.insertAfter(t)}.bind(this),highlight:function(e){$(e).closest(".control-group").addClass("error"),$(e).closest("fieldset").addClass("error")},success:function(e){$(e).closest(".control-group").removeClass("error"),$(e).closest("fieldset").removeClass("error"),$(e).remove()},submitHandler:function(){this._saveMonitor(function(){this._closeModal()}.bind(this))}.bind(this)})},testMetrics:function(){this._setMetrics(),$.post("/monitor.json",this.model.toJSON(),function(e){if(e.graph_data){var t=this.formatGraphData(e.graph_data);this.renderGraphData(this.chart,t),$("#outputView").val(e.output)}"error"===e.status&&Backbone.Mediator.pub("view:addmonitor:test",{model:this.model,errors:e.errors,raw:e.output,attention:"Monitor Test Error!",status:"error"})}.bind(this)).error(function(e){Backbone.Mediator.pub("view:addmonitor:test",{model:this.model,errors:e.errors,raw:e.output,attention:"Monitor Test Error!",status:"error"})}.bind(this))},modalClose:function(e){$(e.target).hasClass("add-monitor")&&(e.stopPropagation(),this.metricsViewInitialized&&(this.backToSchedule(),this.metricsViewInitialized=!1),Backbone.Mediator.pub("view:addmonitor:close"))},modalShow:function(){Backbone.Mediator.pub("view:addmonitor:show")},resize:function(){return _.debounce(this.adjustModalLayout,500)},saveFinish:function(){this._setMetrics(),$("#inputMetrics").css({"margin-left":"-10000px",left:"-10000px",display:"block",position:"absolute"}),$("#inputExpressions").css({"margin-left":"-10000px",left:"-10000px",display:"block",position:"absolute"}),this.metricsForm.submit()},setHelp:function(){var e="";$.ajax({url:rearview.path+"/help/quick.html",async:!1,success:function(t){e=t}});var t=this.$el.find(".help");t.tooltip({container:".expressions-metrics",trigger:"manual",html:!0,placement:"right",delay:{show:100,hide:200},title:e}).click(function(e){e.stopPropagation(),$(this).tooltip("toggle")})},destructor:function(){this.metricsViewInitialized=!1,this.scheduleViewInitialized=!1,this.metricsMonitorFooter=null,this.scheduleMonitorBody=null,this.scheduleMonitorFooter=null;var e=this.$el.prev();this.$template&&this.$template.off(),this.remove(),this.off(),$("
").insertAfter(e)},_closeModal:function(){this.$modal.modal("hide")},_getTemplateMetaData:function(e){$.ajax({url:rearview.path+"/monitors/index.json",success:function(t){"function"==typeof e&&e(t)}})},_initCodeMirror:function(){var e=this.$el.find("#inputExpressions")[0],t=".add-monitor .expressions .CodeMirror",s=this.$el.find("#inputMetrics")[0],r=".add-monitor .metrics .CodeMirror",o=this.$el.find("button.close"),a=this.$el.find("button.back");this.expressionsMirror=i.fromTextArea(e,{value:"",lineNumbers:!0,lineWrapping:!0,height:"100",mode:"ruby",theme:"ambiance",onKeyEvent:function(e,i){return 70==i.keyCode&&i.ctrlKey&&"keydown"==i.type?(i.stop(),this._toggleFullscreen(t,this.expressionsMirror,o,a)):void 0}.bind(this)}),$(e).data("CodeMirror",this.expressionsMirror),this.metricsMirror=i.fromTextArea(s,{value:"",lineNumbers:!0,lineWrapping:!0,mode:"ruby",theme:"ambiance",onKeyEvent:function(e,t){return 70==t.keyCode&&t.ctrlKey&&"keydown"==t.type?(t.stop(),this._toggleFullscreen(r,this.metricsMirror,o,a)):void 0}.bind(this)}),$(s).data("CodeMirror",this.metricsMirror)},_initDatePicker:function(){this.fromDatePicker=$("#fromDatePicker").datetimepicker()},_setTemplateSelect:function(e){this.$template=this.$el.find("#selectTemplate"),this.$template.data("template",e),this.$template.on("change",function(){var e=this.$template.data("template");if(this.selectedIndex>0){var t=this.selectedIndex-1,i=e[t];i.path&&$.ajax({url:i.path,success:function(e){i.metrics&&i.metrics.length>0&&this.metricsMirror.setValue(i.metrics.join("\n")),this.expressionsMirror.setValue(e)}.bind(this)})}}.bind(this))},_setSchedule:function(){this.model.set({userId:this.user.get("id"),name:this.$el.find("#monitorName").val(),description:this.$el.find("#description").val(),alertKeys:this.parseAlertKeys(this.$el.find("#pagerDuty").val()),cronExpr:this._createCronExpr()})},_setMetrics:function(){this.model.set({userId:this.user.get("id"),monitorExpr:this.expressionsMirror.getValue(),metrics:this.metricsMirror.getValue().split("\n"),minutes:parseInt(this.$el.find("#minutesBack").val()),toDate:this.$el.find("#fromDatePicker").val()})},_setupScheduleView:function(){this.metricsMonitorBody=$(".add-monitor .modal-body").detach(),this.metricsMonitorFooter=$(".add-monitor .modal-footer").detach(),$(".add-monitor").append(this.scheduleMonitorBody),$(".add-monitor").append(this.scheduleMonitorFooter),this.scheduleView=!0,this.adjustModalLayout()},_setupMetricsView:function(){var e=$(".add-monitor");this.metricsViewInitialized?(this.scheduleMonitorBody=$(".add-monitor .modal-body").detach(),this.scheduleMonitorFooter=$(".add-monitor .modal-footer").detach(),$(".add-monitor").append(this.metricsMonitorBody),$(".add-monitor").append(this.metricsMonitorFooter)):(this.scheduleMonitorBody=$(".add-monitor .modal-body").detach(),this.scheduleMonitorFooter=$(".add-monitor .modal-footer").detach(),this._getTemplateMetaData(function(t){this.templar.render({path:"setmetrics",el:e,append:!0,data:{monitor:{templates:t}}}),this._setTemplateSelect(t),this._initCodeMirror(),this._initDatePicker(),this.initGraph(e.find(".graph")[0]),this.setHelp(),this.setMetricsValidation(),this.metricsViewInitialized=!0,this.scheduleView=!1,this.adjustModalLayout()}.bind(this)))},_saveMonitor:function(e){this._setMetrics(),this.model.save({id:null,userId:this.user.get("id")},{success:function(i){"function"==typeof e&&e(),Backbone.Mediator.pub("view:addmonitor:save",{model:i,message:"The monitor '"+i.get("name")+"' was added.",attention:"Monitor Saved!",status:"success"}),this.model=new t}.bind(this),error:function(e,t){Backbone.Mediator.pub("view:addmonitor:save",{model:e,tryJSON:t.responseText,attention:"Monitor Save Error!",status:"error"})}})}});return s});