// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['hpsum/presenter/node/NodePresenter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/Notifications',
    'hp/view/FormStateView',
    'hp/core/Localizer',
	'text!hpsumpages/node/abort_confirm.html',
	'hp/view/DialogView',
	'hp/model/Session',
	'hp/services/REST',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'hp/lib/jquery.hpSearchCombo',
    'hp/lib/jquery.hpToggle',
    'lib/jquery.selectBox',
	'jqueryUI',
	'lib/jquery-ui-timepicker-addon',
	'hpsum/view/node/jquery.hpsumSchedule'
	],
function(presenter,router, urlFragment, notifications, FormStateView, localizer,abortConfirmHtml,DialogView,session,rest) { "use strict";

    var NodeStageInventoryDView = (function() {
      
        var OK = '#hpsum-node-inventory-ok';
        var CANCEL ='#hpsum-node-inventory-close';
        var PANEL_SELECTOR = '#hpsum-node-inventory-panel-selector';
        var PANELS = '#hpsum-node-inventory-panels';
        var FORM = '#hpsum-node-inventory-form';
        var TITLE = '#hpsum-node-details-title';
        var TYPE ='#hpsum-node-type';
        var NAME = '#hpsum-node-name',
        	FAILEDMSG ='#hpsum-node-inventory-failed-details',
        	FAILEDPANEL ='#hpsum-node-inventory-failed',
        	BASELINES = '#hpsum-node-baselines-search',
        	ASSOCBASELINE = '#hpsum-node-baseline',
        	REMOVEBASELINE='#hpsum-node-baseline-remove',
        	REMOVEHOTFIX='#hpsum-node-addpackage-remove',
        	HOTFIX ='#hpsum-node-addpackage-search',
        	ASSOCHOTFIX ='#hpsum-node-addpackage',
			BASELINE_INPUT = '#hpsum-node-baselines-search-input',
			HOTFIX_INPUT = '#hpsum-node-addpackage-search-input',
			BASELINE_INPUT_ERR = '#hpsum-node-baselines-search-input-err',
			HOTFIX_INPUT_ERR = '#hpsum-node-addpackage-search-input-err',
            STAGE_HEADING = '#hpsum-stage-heading',
            START_DEPLOY = '#hpsum-stage-deploy',
            START_DEPLOY_PANEL = '#hpsum-node-start-deploy',
            BASELINE_PANEL ='#hpsum-node-inventory-baseline',
            SCHEDULED_STAGED_DATETIMEPICKER = '#stage-scheudle-datetimepicker',
			INSTALLATION_OPTIONS ='#hpsum-node-deploy-installation-Options',
            SCHEUDLED_STAGED = '#hpsum-stage-scheduled',
			ABORT_STAGE = '#hpsum-node-abort-stage',
			ABORT_TITLE = '#hpsum-nodes-abort-title',
			ABORT_ERROR = '#hpsum-abort-err',
			SPLASH_SPINNER = '#hpsum-temporary-dialog',
			SPLASH_MESSAGE = '#hpsum-temporary-txt',
            DIRECT_DEPLOY_DESCRIPTION = '#hpsum-node-stage-directdeploy-general-description',
            DIRECT_DEPLOY_SELECT_BASELINE = '#hpsum-node-stage-directdeploy-select-baseline';
			//SPLASH_SPINNER = '#hpsum-temporary-spinner';


        var ROUTE_PREFIX = '/node/inventoryd';
        var STAGE_FLAG = '#hpsum-node-stage';
        var isStageScheduled = false;
        var nodeItemStage;
		var abortInProgress = false;
		var tempAbortInProgress = false;
		var scheduleDetails = {
				isScheduled : false,
				tempAbort : false,
				stageMode : "",
				schduledDateTime : "",
				baselines : ""
				};
				

        
        /**
         * Constructor
         */
        function NodeStageInventoryDView() {
          
            var formStateView = new FormStateView();
            var inventoryInProgress = false;
            var nodeItem=null;
            var baselines='',
    			hotfixes='',
    			assocBaseline=null,
    			newBaseline = null,
    			newHotFix  = null,
    			assocHotFix = null;
            var searchResults = [];
            var setOk = false;
            var stage_mode = 0;
			
            function onItemChange(item) {
            	item = item.hapi;
				if (item.scheduled == "false" && (!item.schedule_date_time))
				{
					$(ABORT_STAGE).attr('disabled', true);
				}
				else
				{
					$(ABORT_STAGE).attr('disabled', false);
				}
				if (item.baselines.length == 0)
				{
					$(OK).attr('disabled', true);
				}
				else
				{
					$(OK).attr('disabled', false);
				}
				
                $("#schedule").hpsumSchedule('setTimeinSchedulePlugin',item.local_date_time,item.schedule_date_time);
                $("#schedule").hpsumSchedule('setMasterNodeTimer',item.local_date_time);
				if(item.node_state.match("REMOTE_STAGING_SCHEDULED") || item.node_state.match("IDLE") 
							|| scheduleDetails.isScheduled)
				{
					//if(item.schedule_date_time || scheduleDetails.isScheduled)
					if(item.schedule_date_time)
					{
						$("#schedule").hpsumSchedule('selectScheduled');
						/*for temporary abort of scheduled stage nodes*/
						if(item.scheduled == "true")
						{
							tempAbortForScheduledNodes(item);
						}
					}
                    else
                    {
                        $("#schedule").hpsumSchedule('selectImmediately');
                    }
				}
				else
				{
					$("#schedule").hpsumSchedule('stageImmediatly');
				}
                
				if(item.node_state.match(/inventory/i)) {
					$(CANCEL).trigger('click');
				}

                if( $(STAGE_FLAG).length != 0 ){
                    nodeItemStage = item;
                    if( ( item.type.match(/windows/i) || item.type.match(/linux/i) ) && 
                         (item.node_phase.match(/UserActionNeeded/i) || item.node_state.match(/installdone/i) ||
                            item.node_state.match(/error/i)))
                    {
                         //Then this page was rerouted from the deploy view.
                         //The user want to do a direct stage and deploy 
                        //In this state we send both stage and deploy, If stage mode is 1. This is done internally in the state
                        //machine. 
                        if( item.node_state.match(/idle/i) ||  item.node_state.match(/installdone/i) ||
                            item.node_state.match(/error/i)){
                            stage_mode = 1;
                            $(STAGE_HEADING).text(localizer.getString('hpsum.server.stage'));
                            $(DIRECT_DEPLOY_DESCRIPTION).text(localizer.getString('hpsum.server.stage') + localizer.getString('hpsum.server.stagedirectdeployDescription') + ".");
                            $(DIRECT_DEPLOY_SELECT_BASELINE).text(localizer.getString('hpsum.node.selectBaselineStageDirectdeploy') + localizer.getString('hpsum.server.stage').toLowerCase() + ".");
                            $(OK).prop('value',localizer.getString('hpsum.server.stage'));
                            var list= $(START_DEPLOY_PANEL);
                            $(START_DEPLOY_PANEL).show();
                            $(BASELINE_PANEL).show();
                        }
                    }
                }
                if (item) {
                    $(TITLE).text(item.name);
                    $(NAME).text(item.name);
                    $(ASSOCBASELINE).text('');
                    $(REMOVEBASELINE).hide();
                    $(ASSOCHOTFIX).text('');
                    $(REMOVEHOTFIX).hide();
                    nodeItem= item;
                    newBaseline = null;
    				newHotFix  = null;
                    assocHotFix = null;
                    assocBaseline = null;
                    if(item.baselines){
                    	for (var i=0; i<item.baselines.length; i++ ){
                    		var baseline = presenter.getBaselineDetailsforId(item.baselines[i]);
                    		if(baseline){
                    			if(baseline.name.match(/^Additional Package/i)){
                    				$(ASSOCHOTFIX).text(baseline.name);
                    				$(REMOVEHOTFIX).show();
                    				assocHotFix = baseline; 
									$(HOTFIX).hpSearchCombo('set', {id: baseline.id, name: baseline.name});
                    			}else{
                    				$(ASSOCBASELINE).text(baseline.name );
                    				$(REMOVEBASELINE).show();
                    				assocBaseline = baseline;
									$(BASELINES).hpSearchCombo('set', {id: baseline.id, name: baseline.name});
                    			}
                    		}
                    	}
 					 }
                } else {
                    $(TITLE).text('');
                }
                formStateView.reset();
            }
			
			
			
			
			
			/*
				Param flag: True: -  Pausing schedule.
							False: - Abort in progress.
			*/
			function showAbortSplash(flag)
			{
				//show splash screen	
				$(SPLASH_SPINNER).dialog({
					modal : true,
					position : "center",
					draggable : false,
					resizable : false,
					show : 'fade',
					dialogClass : 'hp-splash-dialog',
					width : 400
				});
				
				if(flag)
				{
					$(SPLASH_MESSAGE).html(localizer.getString('hpsum.node.temporaryAbort'));
				}
				else
				{
					$(SPLASH_MESSAGE).html(localizer.getString('hpsum.node.abortInProgress'));
				}		
				$(SPLASH_SPINNER).show();
				$(SPLASH_SPINNER).focus();
			}
			
			/* Used to close and destroy the splash spinner dialog
				Param: routeToShowViewFlag :- True: route , False: Don't route*/
			function closeAnalysisSplash(routeToShowViewFlag)
			{
				$(SPLASH_SPINNER).hide();
				try
				{
					$(SPLASH_SPINNER).dialog('destroy');
					if(routeToShowViewFlag)
					{
						router.go(urlFragment.replaceView(router.location(), 'show'));
					}
				} catch(e) {}
			}
			
			/* send the attributes to backend*/
			function sendSetAttributes(optionsToSet)
			{
				showAbortSplash(false);
				if(!nodeItem)
				{
					closeAnalysisSplash(false);
					return;
				}
				presenter.setattribute(nodeItem, optionsToSet, {
					success : function() { 
						setTimeout(closeAnalysisSplash(true), 3000);
					},
					error : function() {
					}
				});
			}
			
			
			/* this is essential where we came to Stage page to reschedule the */
			function clearScheduleData()
			{
				var     abortOptions = {hapi:{}};
				abortOptions.hapi.clear_schedule_data = true;
				sendSetAttributes(abortOptions);
				scheduleDetails.isScheduled = false;						
				scheduleDetails.tempAbort = false;
			}
			
			
			function tempAbortForScheduledNodes(item){
				
				showAbortSplash(true);
				
				scheduleDetails.isScheduled = true;						
				scheduleDetails.tempAbort = true;
				//scheduleDetails.schduledDateTime =  $("#schedule").hpsumSchedule('getScheduledDateTime');
				scheduleDetails.schduledDateTime = item.schedule_date_time
				scheduleDetails.baselines = item.baselines;
				scheduleDetails.stageMode = item.operation_mode;

				if (!tempAbortInProgress) {
					   tempAbortInProgress = true;
					   var object = { hapi : { clearScheduleDateTime : false} };
						presenter.abortAction(object,{
											success : function(){
												tempAbortInProgress = true;
												inventoryInProgress = false;
												var progressTimer = setInterval(function () {
														var node_uri = "/Session/" + session.getToken() + "/node/" + item.node_id;
														rest.getURI(node_uri + "/getstatus", {
														success : function(data) {
															if(data.hapi.node_status.node_state === "IDLE")
															{
																tempAbortInProgress = false;
																item.node_state = data.hapi.node_status.node_state;
																rest.getURI(node_uri + "/getdata", {
																success : function(data) {
																	clearInterval(progressTimer);
																	$(SPLASH_SPINNER).dialog('destroy');
																	//item.scheduled  = data.hapi.scheduled;
																	nodeItem.scheduled = data.hapi.scheduled;
																},
																error : function()
																{
																	clearInterval(progressTimer);
																	$(SPLASH_SPINNER).dialog('destroy');
																}																
																});
																//clearInterval(progressTimer);
																//$(SPLASH_SPINNER).dialog('destroy');
															}
														},
														error : function(errorInfo) {
															tempAbortInProgress = false;
															clearInterval(progressTimer);
															$(SPLASH_SPINNER).dialog('destroy');
														}
													});
													}, 5000);												 
											},
											error : function(msg){
												tempAbortInProgress = false;	
												$(SPLASH_SPINNER).dialog('destroy');
											}
										});
					}
			
			}
            
            function onInventoryError(errorMessage) {
                $(FAILEDPANEL).show();
                $(FAILEDMSG).text(errorMessage);
                $(OK).attr("disabled", "disabled");
                inventoryInProgress = false;
            }

            function onInventorySuccess(data,item) 
            {
                if(item.hasOwnProperty("set_schedule_date_time") && item.set_schedule_date_time != "")
                {   
                    var notif = {
                        summary : localizer.getString('hpsum.node.nodeStageScheduled') + item.set_schedule_date_time,
                        uri : item.uri,
                        status : 'ok',
                        sourceName : item.ip,
                        sourceUri : item.uri
                    };
                    notifications.add(notif, true);
                }

                inventoryInProgress = false;
                router.go(urlFragment.replaceView(router.location(), 'show'));
            }

            function OnResize(){
				var BaseLineSearchWidth = ($(window).width() / 3);
				$(BASELINES).hpSearchCombo({getResults:getBaseline, width:BaseLineSearchWidth});
				$(HOTFIX).hpSearchCombo({getResults: getHotfixes, width:BaseLineSearchWidth});
			}
			
            function onInventory() {
            	var fail=false;
            	var finalBaseline;
            	var finalHotFix;
            	var baselineJson=[];
                if (! inventoryInProgress) {

					var errorFound = false;
					var baselinedetails = false;
					if($(BASELINES).val() != ''){
						baselinedetails = presenter.getBaselineDetailsforId($(BASELINES).val());
					}
					else
					{
						if($(HOTFIX).val() != ''){
							baselinedetails = presenter.getBaselineDetailsforId($(HOTFIX).val());
						}						
					}
					if(!baselinedetails){
						errorFound = true;
						$(BASELINE_INPUT_ERR).text(localizer.getString('hpsum.node.invalidBaseline'));	
						$(BASELINE_INPUT).addClass("hp-error");
						$(BASELINE_INPUT_ERR).show();
					}
					
					if( $(STAGE_FLAG).length != 0 ){
                        var schduledDateTime = $("#schedule").hpsumSchedule('getScheduledDateTime');
                        if(schduledDateTime != ""){
                            isStageScheduled = true;                           
                            if(!$("#schedule").hpsumSchedule('validateUserEnteredTime',nodeItemStage.local_date_time) )
                            {
                                errorFound = true;
                            }
                        }

                    }
					
					if (errorFound == true){
						inventoryInProgress = false;
						return;
					}
					
                	if((newBaseline == null) && (assocBaseline == null))
                		finalBaseline = null;
                	else if (newBaseline == null)
                		finalBaseline = assocBaseline;
                	else
                		finalBaseline = newBaseline;
                	if((newHotFix == null) && (assocHotFix == null))
                		finalHotFix = null;
                	else if (newHotFix == null)
                		finalHotFix = assocHotFix;
                	else
                		finalHotFix = newHotFix;
                		
                	if((finalHotFix == null) &&  (finalBaseline == null))
					{
						$(BASELINE_INPUT_ERR).text(localizer.getString('hpsum.node.invalidBaseline'));	
						$(BASELINE_INPUT).addClass("hp-error");
						$(BASELINE_INPUT_ERR).show();
						fail = true;
					}
                	else if(finalHotFix == null)
                		baselineJson.push(finalBaseline.id);
                	else if (finalBaseline == null)
                		baselineJson.push(finalHotFix.id);
                	else{
                		if(finalBaseline)
                			baselineJson.push(finalBaseline.id);
                		if(finalHotFix)
                			baselineJson.push(finalHotFix.id);
                	}
                	if(fail == false)
					{
						$(BASELINE_INPUT_ERR).hide();
						$(BASELINE_INPUT).removeClass('hp-error');
						$(HOTFIX_INPUT_ERR).hide();
						$(HOTFIX_INPUT).removeClass('hp-error');
						
                		nodeItem.baselines = baselineJson;
                        nodeItem.operation_mode = stage_mode;
                        nodeItem.set_schedule_date_time = schduledDateTime;
                    inventoryInProgress = true;
                    presenter.startInventory(nodeItem, {
                        success : function(data){ 
                                var item = nodeItem;
                                onInventorySuccess(data,item);
                            },
                        error : onInventoryError
                    });
                   }
                }
            }

            function onDeploySuccess(item)
            {
                 $(CANCEL).trigger('click');
            }

            function onDeployError(errorMessage)
            {
                $(FAILEDPANEL).show();
                $(FAILEDMSG).text(errorMessage);
                $(OK).attr("disabled", "disabled");
                inventoryInProgress = false;
            }
            
            
            function changeLocation(location) {
                if (location.length > ROUTE_PREFIX.length) {
                    $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
                } else {
                    $(PANELS).hpStackedPanels('setFirstPanel');
                }
            }
            
          	function baselinesAvailable(data){
    			//data = {count: data.count, members: data};
            	//$(BASELINES).hpSearchCombo({getResults: presenter.getResults});
            }
            
            function getBaseline(string, handlers, count, start){
            	var results=baselines;
            		if (string && string.length > 0) {
              			 results =
                		    $.grep(baselines, function(option, index) {
                    		    return (option.name.match(
                  	         			 new RegExp(string.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i')));
                  		  });	
           			 }
            		handlers.success({count: results.length, members: results, start: 0, total: results.length});
        	}
            function getHotfixes(string, handlers, count, start){
          		  	var results=hotfixes;
            		if (string && string.length > 0) {
              			 results =
                		    $.grep(hotfixes, function(option, index) {
                    		    return (option.name.match(
                  	         			 new RegExp(string.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i')));
                  		  });	
           			 }
            		handlers.success({count: results.length, members: results, start: 0, total: results.length});
          	}
          
           function getBaselinesSuccess(searchResults)
            {
					baselines = $.grep(searchResults, function (option, index ) {
        				return !(option.name.match(new RegExp('^Additional', 'i')));
        			});
        			hotfixes = $.grep(searchResults, function (option, index) {
        				return (option.name.match(new RegExp('^Additional', 'i')));
           			});
            	
            }
            
            function getBaselinesError(msg)
            {
            	
            }
			
            this.resume = function () {
			
				scheduleDetails.isScheduled = false;						
				scheduleDetails.tempAbort = false;
				scheduleDetails.schduledDateTime = "";
				
                presenter.on('itemChange', onItemChange);
				
				if( $(STAGE_FLAG).length == 0 )
				{				
					$(OK).attr('tooltip', localizer.getString('hpsum.common.inventoryhelp')).hpTooltip();
				}
                //presenter.on('searchSuggestionChange', baselinesAvailable);
                $(HOTFIX).hpSearchCombo('set', {id:'', name: ''});
                baselines = hotfixes = localizer.getString('hpsum.common.loading');
                    presenter.getAllBaselines({
                            success:getBaselinesSuccess,
                            error: getBaselinesError
                    });
                $(PANELS).hpStackedPanels('resume');
                $(OK).removeAttr("disabled");
                $(FAILEDPANEL).hide();
                $(BASELINES).hpSearchCombo('set', {id:'', name: ''});
                $(BASELINE_INPUT).removeClass("hp-error");
                $(HOTFIX_INPUT).removeClass("hp-error");
                $(BASELINE_INPUT_ERR).hide();
                $(HOTFIX_INPUT_ERR).hide();
                $(INSTALLATION_OPTIONS).hide();
                if($(STAGE_FLAG).length != 0 )
                {
                    stage_mode = 1;
                    ROUTE_PREFIX = '/node/stage';
					
                }
            };
            
            this.pause = function () {
                presenter.off('itemChange', onItemChange);
                $(BASELINES).hpSearchCombo('set', {id:'', name: ''});
                $(HOTFIX).hpSearchCombo('set', {id:'', name: ''});
                //presenter.off('searchSuggestionChange', baselinesAvailable);
                $(PANELS).hpStackedPanels('pause');
            };
            /**
             * @public
             */
            this.init = function () {
				var resource = router.location().split('/');
                	resource = resource[1];
				if( $(STAGE_FLAG).length == 0 )
				{				
					$(OK).attr('tooltip', localizer.getString('hpsum.common.inventoryhelp')).hpTooltip();
				}
                	if(resource === 'node')
                		$(TYPE).val("Unknown");
                	else
                		$(TYPE).val(resource);
               		$('#hpsum-node-inventory-close').click(function () {
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                });
                $(FAILEDPANEL).hide();
                   $(PANELS).hpStackedPanels({
                    	panelSelector : PANEL_SELECTOR
                	});
                
                formStateView.init({form: FORM,
                    routePattern: ROUTE_PREFIX + '.*',
                    autoTrack: true});
               
				$(REMOVEBASELINE).on('click',function(ev){
					assocBaseline=null;
					$(BASELINES).hpSearchCombo('set', {id:'', name: ''});
					$(ASSOCBASELINE).text('');
					$(REMOVEBASELINE).hide();
				});
				$(REMOVEHOTFIX).on('click',function(ev){
					assocHotFix=null;
					$(HOTFIX).hpSearchCombo('set', {id:'', name: ''});
					$(ASSOCHOTFIX).text('');
					$(REMOVEHOTFIX).hide();
				});
				$(CANCEL).on('click',function(ev){
					//if(nodeItem.scheduled == "false" && nodeItem.schedule_date_time)
					if(nodeItem.schedule_date_time && nodeItem.scheduled == "false")
					{
						nodeItem.baselines = scheduleDetails.baselines;
						nodeItem.operation_mode = scheduleDetails.operation_mode;
						nodeItem.operation_mode = 1;					
						nodeItem.set_schedule_date_time = nodeItem.schedule_date_time;
						inventoryInProgress = true;
						presenter.startInventory(nodeItem, {
							success : function(data){ 
									var item = nodeItem;
									onInventorySuccess(data,item);
									scheduleDetails.isScheduled = false;
									scheduleDetails.tempAbort == false;
								},
							error : onInventoryError
						});
					}
				});
				
				$(window).on('resize', OnResize);
				//set width for baseline and additional package search box.
				OnResize();
				
                $(BASELINES).change(function (ev, value) {
					$(BASELINE_INPUT_ERR).hide();
					$(BASELINE_INPUT).removeClass('hp-error');
					$(HOTFIX_INPUT_ERR).hide();
					$(HOTFIX_INPUT).removeClass('hp-error');
					
					var item = presenter.getBaselineDetailsforId(value);
                	if(item){
        				$(ASSOCBASELINE).text(item.name);
        				$(REMOVEBASELINE).show();
        				newBaseline = item;
        				}
        			else {
        				if(assocBaseline != null){
        					$(ASSOCBASELINE).text(assocBaseline.name);
        					$(REMOVEBASELINE).show();
        				}
        				newBaseline = null;
        			}//nodeItem.baselines = value;
					if(!setOk){		
						$(BASELINE_INPUT_ERR).hide();
						$(BASELINE_INPUT).removeClass('hp-error');
					}
					setOk = false;
					$(OK).removeAttr("disabled");
        			$(FAILEDPANEL).hide();
    			});
                $(HOTFIX).change(function (ev, value) {
					$(BASELINE_INPUT_ERR).hide();
					$(BASELINE_INPUT).removeClass('hp-error');
					$(HOTFIX_INPUT_ERR).hide();
					$(HOTFIX_INPUT).removeClass('hp-error');
					
					var item = presenter.getBaselineDetailsforId(value);
                	if(item){
        				$(ASSOCHOTFIX).text(item.name);
        				$(REMOVEHOTFIX).show();
        				newHotFix = item;
        				}
        			else {
        				if(assocHotFix != null){
        				$(ASSOCHOTFIX).text(assocHotFix.name);
        				$(REMOVEHOTFIX).show();
        				}
        				newHotFix = null;
        			}
        			//nodeItem.baselines = value;
					if(!setOk){
						$(HOTFIX_INPUT_ERR).hide();
						$(HOTFIX_INPUT).removeClass('hp-error');
					}
					setOk = false;
					$(OK).removeAttr("disabled");
        			$(FAILEDPANEL).hide();
    			});
				
				$(BASELINE_INPUT).unbind('keyup').bind('keyup',function(){
					$(BASELINE_INPUT_ERR).hide();
					$(BASELINE_INPUT).removeClass('hp-error');
				});
				
                $(HOTFIX_INPUT).unbind('keyup').bind('keyup',function(){
					$(HOTFIX_INPUT_ERR).hide();
					$(HOTFIX_INPUT).removeClass('hp-error');
				});
                
				$(OK).on('click', function(ev) {
					setOk = true;
                    onInventory();
                    ev.preventDefault();
                });
				
				$(ABORT_STAGE).click(function(ev){
					if($(ABORT_STAGE).hasClass("hp-disabled")) {
						ev.preventDefault();
						return;
					}
                
					if (! abortInProgress) {
					   abortInProgress = true;
						
					   var contents = $(abortConfirmHtml);
					   localizer.localizeDom(contents);
						$(ABORT_TITLE, contents).text(localizer.getString('hpsum.node.abortFor', [presenter.selectionLabel()]));
							
						$(ABORT_ERROR, contents).hide();
						var dialogView = new DialogView();
						 var object = { hapi : { clearScheduleDateTime : true} };
						dialogView.init({contents: contents,
								ok: function () {
												abortInProgress = false;
												clearScheduleData();			
								},
								cancel: function () {
									abortInProgress = false;
								}
						});
					}
					ev.preventDefault();
					
				});

                $("#schedule").hpsumSchedule({
                    enableButton: function(){
                        $(OK).removeAttr("disabled");
                        
                    },
                    disableButton: function(){
                        $(OK).attr("disabled", "disabled");
                    }
                });

                router.watch('node inventory section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
                
                this.resume();
            };
        }

        return new NodeStageInventoryDView();
    }());
    
    return NodeStageInventoryDView;
});
