// (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',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'hp/lib/jquery.hpSearchCombo',
    'hp/lib/jquery.hpToggle',
    'lib/jquery.selectBox'],
function(presenter,router, urlFragment, notifications, FormStateView, localizer) { "use strict";

    var NodeInventoryDView = (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',
			REMOVE_GRP_CHECKBOX = '#hpsum-remove-group-checkbox',
            REMOVE_GRP_CHECKBOX_LABEL = '#hpsum-remove-group-checkbox-descr',
            REMOVE_NODE_FROM_GROUP = "#hpsum-remove-group-descr",
            REMOVE_GRP_CONTAINER = '#hpsum-remove-grp-div',
            INSTALL_PREREQS_CHECKBOX = '#hpsum-node-add-install-prereqs-checkbox',
            INSTALL_PREREQS_WARNING_LABEL = '#hpsum-node-add-install-prereqs-warning',
            INSTALL_PREREQS_CHECKBOX_PANEL = '#hpsum-node-add-install-prereqs-panel';

        var ROUTE_PREFIX = '/node/inventoryd';
        var STAGE_FLAG = '#hpsum-node-stage';
        var initialBaselines = [];
		var cannotInventory=false;
		var baselineRevalProgress = false;
		var hotfixRevalProgress = false;
		var MENU = '.hp-search-combo-menu';
		var HEADER = '.hp-header';
		var FOOTER = MENU + ' .hp-footer';
		

        /**
         * Constructor
         */
        function NodeInventoryDView() {
          
            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;
			var allInstallSets = [], currentGroup = '';
			
            function onItemChange(item) {
            	item = item.hapi;
				if(item.node_state.match(/inventory/i)) {
					$(CANCEL).trigger('click');
				}
				formStateView.reset();
                if( $(STAGE_FLAG).length != 0 ){
                    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'));
                            $(OK).prop('value',localizer.getString('hpsum.server.stage'));
                            var list= $(START_DEPLOY_PANEL);
                            $(START_DEPLOY_PANEL).show();
                            $(BASELINE_PANEL).show();
                        }
                        else if(item.node_state.match(/remote_staging_uan/i)){
                            //The user has already stage. Just deploy
                            stage_mode = 3;
                            $(STAGE_HEADING).text(localizer.getString('hpsum.server.stageDeploy'));
                            $(OK).prop('value', localizer.getString('hpsum.node.deploy'));
                            $(START_DEPLOY_PANEL).hide();
                            $(BASELINE_PANEL).hide();
                        }
                    }
                }
                if (item) {
                    $(TITLE).text(item.name);
                    $(NAME).text(item.name);
                    if (item.type.match(/windows|linux|ilo/i)) {
                        $(INSTALL_PREREQS_CHECKBOX_PANEL).show();
                        if (item.skip_prereqs == false) {
                            $(INSTALL_PREREQS_CHECKBOX).attr('checked', true);
                        } else {
                            $(INSTALL_PREREQS_CHECKBOX).attr('checked', false);;
                        }
                    }
                    $(ASSOCBASELINE).text('');
                    $(REMOVEBASELINE).hide();
                    $(ASSOCHOTFIX).text('');
                    $(REMOVEHOTFIX).hide();
                    nodeItem= item;
                    newBaseline = null;
    				newHotFix  = null;
                    assocHotFix = null;
                    assocBaseline = null;
					 //show the remove node from group option
					
		            if (item.group)
		            {
						currentGroup = item.group;
		                $(REMOVE_NODE_FROM_GROUP).show();
		                var group_uri = '#/group/show/overview/r/session/' + item.node_session + '/node/group/' + item.group + '/getdata';
		                var uri = '<a href="' + group_uri + '" class="company-a">' + item.group_name + '</a>';		                
		                $(REMOVE_NODE_FROM_GROUP).html(localizer.getString('hpsum.node.removeNodeFromGrp', [uri]));
		                $(REMOVE_GRP_CONTAINER).show();
		                var checkboxLabel = localizer.getString('hpsum.node.removeGrpDesc', [uri]);
		                $(REMOVE_GRP_CHECKBOX_LABEL).html(checkboxLabel);

		                //disable the baseline editable items.
		                initialBaselines = item.baselines;
		                updateEditableFields(true);
		                
		            }
		            else
		            {
		                $(REMOVE_NODE_FROM_GROUP).hide();
		                $(REMOVE_GRP_CONTAINER).hide();
		            }
					
                    //read all install sets and add it to the baseline sear box.
		            if (item.server_generation >= 10 || item.type.match(/ilo5|ilo6|ilo7/i)) {
		                presenter.getInstallSets(item, {
		                    success: function (data) {
		                        if (data.hapi.installsets.installset.length > 0) {
		                            allInstallSets = [];
		                            for (var iset = 0; iset < data.hapi.installsets.installset.length ; iset++) {
		                                //Dont show unreferenced components as baseline
		                                if (!data.hapi.installsets.installset[iset].id.match(/Unreferenced_Components/i)) {
		                                var obj = {
		                                    id: data.hapi.installsets.installset[iset].id,
		                                    name: data.hapi.installsets.installset[iset].name + ' ' + localizer.getString('hpsum.common.atiLORepository') + ' ' + data.hapi.installsets.installset[iset].date,
		                                    isRecoverySet: data.hapi.installsets.installset[iset].isRecoverySet
		                                };
		                                allInstallSets.push(obj);
		                            }
		                        }
		                    }
		                    }
		                });
		            }
		            if (item.baselines) {
		                initialBaselines = item.baselines;
		                populateBaselineDetails(item.baselines);
                    	
 					 }
                } else {
                    $(TITLE).text('');
                }
            }
			
            function populateBaselineDetails(baselineList)
            {
                for (var i = 0; i < baselineList.length; i++) {
                    var baseline = presenter.getBaselineDetailsforId(baselineList[i]);
                    if (baseline) {
                        if (baseline.name.match(/^Additional Package/i)) {
                            $(ASSOCHOTFIX).text(baseline.name);
                            if (!nodeItem.group) {
                                $(REMOVEHOTFIX).show();
                            }
                            assocHotFix = baseline;
                            $(HOTFIX).hpSearchCombo('set', { id: baseline.id, name: baseline.name });
							if(baseline.baseline_status == "Revalidation in progress.")
							{
								formStateView.setMessage({
									summary: localizer.getString('hpsum.node.invDisableRevalBaseline'),
									status: 'warning',
									changing: false,
								});
								$(OK).attr("disabled", "disabled");
								hotfixRevalProgress = true;
							}
						}
							
                         else {
                            $(ASSOCBASELINE).text(baseline.name);
                            if (!nodeItem.group) {
                                $(REMOVEBASELINE).show();
                            }
                            assocBaseline = baseline;
                            $(BASELINES).hpSearchCombo('set', { id: baseline.id, name: baseline.name });
							if(baseline.baseline_status == "Revalidation in progress.")
							{
								formStateView.setMessage({
									summary: localizer.getString('hpsum.node.invDisableRevalBaseline'),
									status: 'warning',
									changing: false,
								});
								$(OK).attr("disabled", "disabled");
								baselineRevalProgress = true;
							}
                        }
                    }
                    else {
                        if (nodeItem.server_generation >= 10 || nodeItem.type.match(/ilo5|ilo6|ilo7/i)) {
                            var installItem = {
                                node_id: nodeItem.node_id,
                                installset_id: baselineList[0]
                            };
                            presenter.getInstallSetDetails(installItem, {
                                success: function (data) {
                                    //check if its an installset. 
                                    if (nodeItem.baselines == data.hapi.installset.id) {

                                        assocBaseline = data.hapi.installset.id;
                                        $(ASSOCBASELINE).text(data.hapi.installset.name + ' '+localizer.getString('hpsum.common.atiLORepository') + ' '+ data.hapi.installset.date);
                                        if (!nodeItem.group) {
                                            $(REMOVEBASELINE).show();
                                        }
                                        $(BASELINES).hpSearchCombo('set', { id: data.hapi.installset.id, name: data.hapi.installset.name + ' ' + localizer.getString('hpsum.common.atiLORepository') + ' ' + data.hapi.installset.date });                                       
                                    }
                                },
                                error: function () {

                                }
                            });
                        }
                    }
                }
                if (baselineRevalProgress == false && hotfixRevalProgress == false && !nodeItem.group)
				{
					$(OK).attr("disabled", false);
				}
            }
			function getInstallSetForId(itemId)
			{
			    for (var idx = 0; idx < allInstallSets.length ; idx++) {
			        if (itemId == allInstallSets[idx].id) {
			            return allInstallSets[idx];			            
			        }
			    }
			    return null;
			}
			function updateEditableFields(checked)
			{
			    //clear the baseline selection. 
			    
			    $(REMOVEBASELINE).hide();			    
			    $(REMOVEHOTFIX).hide();
			    assocHotFix = null;
			    assocBaseline = null;
			    if(checked) //disable
			    {
			        $(BASELINES).hpSearchCombo('disable');
			        $(HOTFIX).hpSearchCombo('disable');
			        if (initialBaselines) {
			            populateBaselineDetails(initialBaselines);
			        }
			        $(REMOVEBASELINE).hide();
			        $(REMOVEHOTFIX).hide();
			        $(OK).attr("disabled", true);
			    }
			    else //enable
			    {
			        $(BASELINES).hpSearchCombo('enable');
			        $(HOTFIX).hpSearchCombo('enable');
			        $(OK).attr("disabled", false);
			        if($(BASELINES).val() != "")
			        {
			            $(REMOVEBASELINE).show();
			        }
			        if($(HOTFIX).val() != "")
			        {
			            $(REMOVEHOTFIX).show();
			        }
			    }
			}
            
            function onInventoryError(errorMessage) {
                $(FAILEDPANEL).show();
                $(FAILEDMSG).text(errorMessage);
                $(OK).attr("disabled", "disabled");
                inventoryInProgress = false;
            }

            function onInventorySuccess(item) {
				if($(STAGE_FLAG).length != 0)
						stage_mode = 3;
                inventoryInProgress = false;
                $(CANCEL).trigger('click');
            }

            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) {

                    if(nodeItem.node_state.match(/remote_staging_uan/i))
                    {
                        //This is deploy after staging is complete
                        presenter.deploy(nodeItem, {
                                success : onDeploySuccess,
                                error : onDeployError});
                        return;
                    }
					var errorFound = false;
					if($(BASELINES).val() != ''){
						var baselinedetails = presenter.getBaselineDetailsforId($(BASELINES).val());
						if(!baselinedetails){
							//check if its an installset.
						    baselinedetails = getInstallSetForId($(BASELINES).val());
						    if (!baselinedetails) {
								errorFound = true;
								$(BASELINE_INPUT_ERR).text(localizer.getString('hpsum.node.invalidBaseline'));	
								$(BASELINE_INPUT).addClass("hp-error");
								$(BASELINE_INPUT_ERR).show();
						    }
						    else
						    {
						        newBaseline = baselinedetails;
						    }
						}
						else
						{
						    newBaseline = baselinedetails;
						}
					}
				
					if($(HOTFIX).val() != ''){
						var baselinedetails = presenter.getBaselineDetailsforId($(HOTFIX).val());
						if(!baselinedetails){
							errorFound = true;
							$(HOTFIX_INPUT_ERR).text(localizer.getString('hpsum.node.invalidAdtPackage'));	
							$(HOTFIX_INPUT).addClass("hp-error");
							$(HOTFIX_INPUT_ERR).show();
						}
						else
						{
						    newHotFix = baselinedetails;
						}
					}	
					
					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))
                		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 == true){
                		$(FAILEDPANEL).show();
                		$(FAILEDMSG).text(localizer.getString('hpsum.node.errorPleaseSelectBaseline'));
                	}
                	else {
                		nodeItem.baselines = baselineJson;
                		nodeItem.operation_mode = stage_mode;
                		inventoryInProgress = true;
                	    /* Code for CHIF installation option */
                		var bIsInstallPreReqsChecked = false;
                		if (nodeItem.type.match(/windows|linux|ilo/i)) {
                		    bIsInstallPreReqsChecked = ($(INSTALL_PREREQS_CHECKBOX).is(':checked'));
                		}
                		nodeItem.skip_prereqs = (!bIsInstallPreReqsChecked);
                    presenter.startInventory(nodeItem, {
                        success : onInventorySuccess,
                        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;
          	    //include installsets and update task queue. 
          	    if (allInstallSets.length > 0) {
          	        results = results.concat(allInstallSets);
          	    }
          	    handlers.success({ count: results.length, members: results, start: 0, total: results.length });
				if(results.length >= 1)
					{
						$(HEADER).hide();
						$(FOOTER).hide();
					}
					else
					{
						$(BASELINE_INPUT).attr("disabled", true);
						$('#hpsum-node-baselines-search-item').find('.hp-search-combo-menu').hide();
						$(HEADER).hide();
					}
          	}
            function getHotfixes(string, handlers, count, start){
          		  	var results=hotfixes;
            		handlers.success({count: results.length, members: results, start: 0, total: results.length});
					if(results.length >= 1)
					{
						
						$(HEADER).hide();
						$(FOOTER).hide();
					}
					else
					{
						$(HOTFIX_INPUT).attr("disabled", true);
						$('#hpsum-node-addpackage-search-item').find('.hp-search-combo-menu').hide();
						$(HEADER).hide();
					}
					
          	}
          
           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')));
           			});
					populateBaselineDetails(initialBaselines);
            }
            
            function getBaselinesError(msg)
            {
            	
            }

            function onStartDeployclicked(event)
            {
                if($(START_DEPLOY).is(':checked')){
                    stage_mode = 2;
                    $(OK).prop('value',localizer.getString('hpsum.server.stageandDeploy'));
                }
                else{
                    stage_mode = 1;
                    $(OK).prop('value',localizer.getString('hpsum.server.stage'));
                }
            }

            this.resume = function () {
                presenter.on('itemChange', onItemChange);
                //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();
				$(REMOVE_GRP_CHECKBOX).prop("checked", false);
				$(BASELINES).hpSearchCombo('enable');
				$(HOTFIX).hpSearchCombo('enable');
                $(BASELINES).hpSearchCombo('set', {id:'', name: ''});
                $(BASELINE_INPUT).removeClass("hp-error");
                $(HOTFIX_INPUT).removeClass("hp-error");
                $(BASELINE_INPUT_ERR).hide();
                $(HOTFIX_INPUT_ERR).hide();
				baselineRevalProgress = false;
				hotfixRevalProgress =false;
				$(REMOVEBASELINE).css("display", "none");
				$(INSTALL_PREREQS_CHECKBOX_PANEL).hide();
                /*
                    We will use the same view for staging and regular inventory.
                    The page is going to be stage.html
                */
                if($(STAGE_FLAG).length != 0 )
                {
                    stage_mode = 1;
                    ROUTE_PREFIX = '/node/stage';
                }
                else
                {
                    stage_mode = 0;
                }

                allInstallSets = [];
                
                
            };
            
            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];
			$('#hpsum-node-inventory-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'));
               		});
               		$(INSTALL_PREREQS_CHECKBOX).click(function () {
               		    $(INSTALL_PREREQS_WARNING_LABEL).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();
				});
				
				$(REMOVE_GRP_CHECKBOX).prop("checked", false);
               		$(REMOVE_GRP_CHECKBOX).change(function () {
               		    if($(REMOVE_GRP_CHECKBOX).is(':checked'))
               		    {
               		        updateEditableFields(false);
               		    }
               		    else
               		    {
               		        updateEditableFields(true);
               		    }
               		});
					
				$(window).on('resize', OnResize);
				//set width for baseline and additional package search box.
				OnResize();
				
				$(BASELINES).change(function (ev, value) {
				    assocBaseline = null;
				    $(ASSOCBASELINE).text('');
				    $(REMOVEBASELINE).hide();
                	var item = presenter.getBaselineDetailsforId(value);
					formStateView.reset();
                	if (item) {
                	    assocBaseline = item;
                	    $(ASSOCBASELINE).text(item.name);
                	    $(REMOVEBASELINE).show();
                	    newBaseline = item;
						if(item.baseline_status == "Revalidation in progress.")
						{
							$(OK).attr("disabled", "disabled");
							formStateView.setMessage({
								summary: localizer.getString('hpsum.node.invDisableRevalBaseline'),
								status: 'warning',
								changing: false,
							});
							baselineRevalProgress = true;
						}
						else
						{
							baselineRevalProgress = false;
							if(hotfixRevalProgress == false)
							{
								$(OK).attr("disabled", false);
								formStateView.reset();
							}
						}
                	}
                	else {
                	    //check if its installset.
                	    item = getInstallSetForId(value);
                	    if (item)
                	    {
                	        assocHotFix = null;
                	        assocBaseline = item;
							newBaseline = item;
                	        $(ASSOCBASELINE).text(item.name);
                	        $(REMOVEBASELINE).show();
                	        //disable additional package
                	        $(HOTFIX).hpSearchCombo('set', { id: '', name: '' });
                	        $(HOTFIX).hpSearchCombo('disable');
                	        //check if selected installset is a recovery set, if yes, disable deploy button.
                	        if (item.isRecoverySet) {
                	            //localizer.getString('hpsum.advanceMode.deployDisabledDueRecoverySet')
                	            $(OK).attr("disabled", "disabled");
                	            formStateView.setMessage({
                	                summary: localizer.getString('hpsum.node.invDisabledDueRecoverySet'),
                	                status: 'warning',
                	                changing: false,
                	            });
                	        }
                	        else {
                	            $(OK).attr("disabled", false);
                	            formStateView.reset();
                	        }

                	    }
                	    else
                	    {
                	        if (assocBaseline != null) {
                	            $(ASSOCBASELINE).text(assocBaseline.name);
                	            $(REMOVEBASELINE).show();
                	        }
                	        newBaseline = null;
                	        $(HOTFIX).hpSearchCombo('enable');
                	    }
                	}
        			
					if(!setOk){		
						$(BASELINE_INPUT_ERR).hide();
						$(BASELINE_INPUT).removeClass('hp-error');
					}
					setOk = false;	
        			$(FAILEDPANEL).hide();
    			});
				$(HOTFIX).change(function (ev, value) {
				    assocHotFix = null;
				    $(ASSOCHOTFIX).text('');
				    $(REMOVEHOTFIX).hide();
					formStateView.reset();
                	var item = presenter.getBaselineDetailsforId(value);
                	if (item) {
                	    assocHotFix = item;
        				$(ASSOCHOTFIX).text(item.name);
        				$(REMOVEHOTFIX).show();
        				newHotFix = item;
						if(item.baseline_status == "Revalidation in progress.")
						{
							$(OK).attr("disabled", "disabled");
							formStateView.setMessage({
								summary: localizer.getString('hpsum.node.invDisableRevalBaseline'),
								status: 'warning',
								changing: false,
							});
							hotfixRevalProgress = true;
						}
						else	
						{
							hotfixRevalProgress =false;
							if(baselineRevalProgress == false)
							{
								$(OK).attr("disabled", false);
								formStateView.reset();
							}
						}
        			}
        			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;
        			$(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();
                });

                if($(STAGE_FLAG).length != 0)
                {
                    $(START_DEPLOY).hpToggle({ checked: localizer.getString('hpsum.common.button.yes'),
                        unchecked: localizer.getString('hpsum.common.button.no')});

                    $(START_DEPLOY).on('change',function(){ onStartDeployclicked()});
                }
                

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

        return new NodeInventoryDView();
    }());
    
    return NodeInventoryDView;
});
