// (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',
	'jqueryUI',
	'lib/jquery-ui-timepicker-addon',
	'hpsum/view/node/jquery.hpsumSchedule'
	],
function(presenter,router, urlFragment, notifications, FormStateView, localizer) { "use strict";

    var NodeDirectStagedDeployView = (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',
			CMP_VERBOSE_LOGGING_ITEM ='#hpsum-staged-deploy-cmpVerbose',
			INSTALLATION_OPTION_PANEL ='#hpsum-node-deploy-installation-Options',
			FAILED_DEP_CHECKBOX = '#hpsum-staged_failedDepCheckbox',
			CMP_VERBOSE_CHKBOX='#hpsum-comp-verbose-checkbox',
			IGNORE_WARNINGS_CHKBOX= '#hpsum-deploy-ignoreWarnings-checkbox',
			SPLASH_DIALOG ='#hpsum-splash-dialog',
			SPLASH_DIALOG_MESSAGE ='#hpsum-splash-message',
			SPLASH_SPINNER = '#hpsum-splash-spinner',
            SCHEUDLED_STAGED = '#hpsum-stage-scheduled',
            DIRECT_DEPLOY_DESCRIPTION = '#hpsum-node-stage-directdeploy-general-description',
            DIRECT_DEPLOY_SELECT_BASELINE = '#hpsum-node-stage-directdeploy-select-baseline',
            ABORT_DIRECT_DEPLOY = '#hpsum-node-abort-stage',
            INSTALLATION_OPTION_ENABLE_REWRITE = '#hpsum-dd-enable-rw-checkbox',
            INSTALLATION_OPTION_ENABLE_DOWNGRADE = '#hpsum-dd-enable-dg-checkbox',
			REBOOT_SLIDER = '#hpsum-node-dd-reboot-slider',
            REBOOT_SLIDER_VAL = '#hpsum-node-dd-reboot-slider-value',
			REBOOT_SLIDER_SUFFIX = '#hpsum-node-dd-reboot-slider-reboot-sufix';
			


        var ROUTE_PREFIX = '/node/inventoryd';
        var STAGE_FLAG = '#hpsum-node-stage';
        var nodeItemStage;
        var bIsResetingAttributes = false;
        var bIsDirectDeployButtonCliked = false;

        
        /**
         * Constructor
         */
        function NodeDirectStagedDeployView() {
          
            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 gotoNodeShow()
			{
				router.go(urlFragment.replaceView(router.location(), 'show'));			
			}
            function onItemChange(item) {
                item = item.hapi;
				if (item.scheduled == "false" && (!item.schedule_date_time))
				{
					$(ABORT_DIRECT_DEPLOY).attr('disabled', true);
				}
				else
				{
					$(ABORT_DIRECT_DEPLOY).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"))
                {
                    if(item.schedule_date_time)
                    {
                        $("#schedule").hpsumSchedule('selectScheduled');
                    }
                    else
                    {
                        $("#schedule").hpsumSchedule('selectImmediately');
                    }
                }
                else
                {
                    $("#schedule").hpsumSchedule('stageImmediatly');
                }
                
				if(item.node_state.match(/inventory/i)) {
					gotoNodeShow();
				}
				if(item.type.match(/windows/i))
					$(CMP_VERBOSE_LOGGING_ITEM).show();
				else	
					$(CMP_VERBOSE_LOGGING_ITEM).hide();
                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.common.directDeploy'));
                            $(DIRECT_DEPLOY_DESCRIPTION).text(localizer.getString('hpsum.common.directDeploy') + localizer.getString('hpsum.server.stagedirectdeployDescription') + localizer.getString('hpsum.server.andInitiateDeploy') + " " + localizer.getString('hpsum.server.directdeploySchedInfo'));							
                            $(DIRECT_DEPLOY_SELECT_BASELINE).text(localizer.getString('hpsum.node.selectBaselineStageDirectdeploy') + localizer.getString('hpsum.common.directDeploy').toLowerCase() + ".");
                            $(OK).prop('value',localizer.getString('hpsum.common.directDeploy'));
                            $(ABORT_DIRECT_DEPLOY).prop('value', localizer.getString('hpsum.common.abortdeploy'));
                            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();
				loadAttributes();
            }
			function loadAttributes()
				{
					presenter.otheroption(nodeItem, {
						success : function(data) {
							if(data.hapi.hcode == 0)
								populateInstallationOptions(data);
						},
						error : function(data) {
						}
					});
				}
            
				function populateInstallationOptions(data)
				{
					if(data && data.hasOwnProperty("hapi"))
					{
						if(data.hapi.hasOwnProperty("ignore_warnings") && data.hapi.ignore_warnings){
							$(IGNORE_WARNINGS_CHKBOX).attr('checked', true);
						}
						else
						{
							$(IGNORE_WARNINGS_CHKBOX).removeAttr("checked");
						}
						
						if(data.hapi.hasOwnProperty("verbose") && data.hapi.verbose){
							$(CMP_VERBOSE_CHKBOX).attr('checked', true);
						}
						else
						{
							$(CMP_VERBOSE_CHKBOX).removeAttr("checked");
						}

			                        if(data.hapi.hasOwnProperty("failed_dependency_handling") && data.hapi.failed_dependency_handling == 'OMITCOMPONENTS')
			                        {
			                            $(FAILED_DEP_CHECKBOX).attr('checked', true);
			                        }
			                        else
			                        {
			                            $(FAILED_DEP_CHECKBOX).removeAttr("checked");
			                        }
						if(data.hapi.hasOwnProperty("installation_option") && data.hapi.installation_option)
						{
							var rewriteOption = data.hapi.installation_option.rewrite;
							var downgradeOption = data.hapi.installation_option.downgrade;
							var firmwareOption = data.hapi.installation_option.firmware;
							var softwareOption = data.hapi.installation_option.software;
							var foreSoftwareOption = data.hapi.installation_option.forcesoftware;
							var forceFfirmwareOption = data.hapi.installation_option.forcefirmware;
							if((forceFfirmwareOption || firmwareOption) && (softwareOption || foreSoftwareOption))
							{
								if(rewriteOption)
								{
									/* Check ENABLEREWRITE */
									$(INSTALLATION_OPTION_ENABLE_REWRITE).attr('checked', true);
								}
								else
								{
									$(INSTALLATION_OPTION_ENABLE_REWRITE).removeAttr("checked");			
								}
								
								if(downgradeOption)
								{
									/* Check DOWNGRADE */
									$(INSTALLATION_OPTION_ENABLE_DOWNGRADE).attr('checked', true);
								}
								else
								{
									$(INSTALLATION_OPTION_ENABLE_DOWNGRADE).removeAttr("checked");			
								}
							}
							else
							{
								/* Un-check REWRITE  and DOWNGRADE*/
								$(INSTALLATION_OPTION_ENABLE_DOWNGRADE).removeAttr("checked");
								$(INSTALLATION_OPTION_ENABLE_REWRITE).removeAttr("checked");
							}
						}	
					}					
				}			
			
            function onInventoryError(errorMessage) {
                $(FAILEDPANEL).show();
                $(FAILEDMSG).text(errorMessage);
                $(OK).attr("disabled", "disabled");
                inventoryInProgress = false;
            }

            function onInventorySuccess(item) {
                inventoryInProgress = false;
				formStateView.reset();
            }

            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();
					}

                    var isScheduleChecked = $("#schedule").hpsumSchedule('isScheduleSelected');
                    if(isScheduleChecked == true)
                    {
                        /* validate the date and time only incase schedule is selected by user */
                        var scheduledDateTime = "";
                        scheduledDateTime = $("#schedule").hpsumSchedule('getScheduledDateTime');
                        if(!$("#schedule").hpsumSchedule('validateUserEnteredTime',nodeItemStage.local_date_time) )
                        {
                            return; /* in case its not valid time. return, it will show the error message */
                        }
                    }
                    
					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 = 2;
                        nodeItem.set_schedule_date_time = scheduledDateTime;
                        inventoryInProgress = true;
                        presenter.startInventory(nodeItem, {
                            success : onInventorySuccess,
                            error : onInventoryError
                        });
                   }
                }
            }
            
            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)
            {
            	
            }
			
			function showAnalysisSplash(flag)
			{
				$(SPLASH_DIALOG).dialog({
			        modal : true,
			        position : "center",
			        draggable : false,
			        resizable : false,
			        show : 'fade',
					closeOnEscape: false,
			        dialogClass : 'hp-splash-dialog',
			        width : 400
			    });
				if(flag)
					$('#hpsum-splash-message').html(localizer.getString("hpsum.group.applyingInstallationOptions"));
				else
					$('#hpsum-splash-message').html("Resetting All User Selections");
			    $(SPLASH_SPINNER).show();	
			}
			
			function closeAnalysisSplash(){
				$(SPLASH_SPINNER).hide();
				try {
					$(SPLASH_DIALOG).dialog('destroy');
				} catch(e) {}
			}

			function getInstallationOptions() {
				var     installationOptions = {hapi:{}};
                var     isRewriteChecked = false;
                var     isDowngradeChecked = false;
                installationOptions.hapi.installation_option ={};
                if($(INSTALLATION_OPTION_ENABLE_REWRITE).is(':checked'))
                {
                    isRewriteChecked= true;
                }
                if($(INSTALLATION_OPTION_ENABLE_DOWNGRADE).is(':checked'))
                {
                    isDowngradeChecked = true;
                }

                /* Set the attributes of rewrite/downgrade as opted. Other options i.e.software, firmware, force(software/firmware) will be true if any one is checked, as in DD its easy mode */
                if(isRewriteChecked || isDowngradeChecked)
                {
                    installationOptions.hapi.installation_option.rewrite = isRewriteChecked;
                    installationOptions.hapi.installation_option.downgrade = isDowngradeChecked;

                    installationOptions.hapi.installation_option.firmware = true;
                    installationOptions.hapi.installation_option.software = true;
                    installationOptions.hapi.installation_option.forcefirmware = true;
                    installationOptions.hapi.installation_option.forcesoftware = true;
                }
                else
                {
                    /* Default attribute which is upgrade both i.e. software & firmware options will true, and others should be false */
                    installationOptions.hapi.installation_option.firmware = true;
                    installationOptions.hapi.installation_option.software = true;
                    installationOptions.hapi.installation_option.rewrite = false;
                    installationOptions.hapi.installation_option.downgrade = false;
                    installationOptions.hapi.installation_option.forcefirmware = false;
                    installationOptions.hapi.installation_option.forcesoftware = false;
                }
				return installationOptions;
			}

            /* this will send all the installation options to backend as one setattribute command */
            function sendInstallationOptions()
            {
                var     installationOptions = {hapi:{}};
                var     isRewriteChecked = false;
                var     isDowngradeChecked = false;
                
                installationOptions.hapi.installation_option ={};
                if($(REBOOT_SLIDER_VAL).text() != 'Never' )
                {
                    installationOptions.hapi.reboot_options ={};
                    installationOptions.hapi.reboot_options.action = 'If Needed';
                    installationOptions.hapi.reboot_options.delay = $(REBOOT_SLIDER_VAL).text()*60; 
                    installationOptions.hapi.reboot_options.message = '';
                }

                if($(INSTALLATION_OPTION_ENABLE_REWRITE).is(':checked'))
                {
                    isRewriteChecked= true;
                }
                if($(INSTALLATION_OPTION_ENABLE_DOWNGRADE).is(':checked'))
                {
                    isDowngradeChecked = true;
                }
                /* Set the attributes of rewrite/downgrade as opted. Other options i.e.software, firmware, force(software/firmware) will be true if any one is checked, as in DD its easy mode */
                if(isRewriteChecked || isDowngradeChecked)
                {
                    installationOptions.hapi.installation_option.rewrite = isRewriteChecked;
                    installationOptions.hapi.installation_option.downgrade = isDowngradeChecked;

                    installationOptions.hapi.installation_option.firmware = true;
                    installationOptions.hapi.installation_option.software = true;
                    installationOptions.hapi.installation_option.forcefirmware = true;
                    installationOptions.hapi.installation_option.forcesoftware = true;
                }
                else
                {
                    /* Default attribute which is upgrade both i.e. software & firmware options will true, and others should be false */
                    installationOptions.hapi.installation_option.firmware = true;
                    installationOptions.hapi.installation_option.software = true;
                    installationOptions.hapi.installation_option.rewrite = false;
                    installationOptions.hapi.installation_option.downgrade = false;
                    installationOptions.hapi.installation_option.forcefirmware = false;
                    installationOptions.hapi.installation_option.forcesoftware = false;
                }

                if($(FAILED_DEP_CHECKBOX).is(':checked'))
                {
                    installationOptions.hapi.failed_dependency_handling = 'OMITCOMPONENT';
                }
                else
                {
                    installationOptions.hapi.failed_dependency_handling = 'OMITHOST';
                }
                if($(IGNORE_WARNINGS_CHKBOX).is(':checked'))
                {
                    installationOptions.hapi.ignore_warnings = true;
                }
                else
                {
                    installationOptions.hapi.ignore_warnings = false;
                }

                if($(CMP_VERBOSE_CHKBOX).is(':checked'))
                {
                    installationOptions.hapi.verbose = true;
                }
                else
                {
                    installationOptions.hapi.verbose = false;
                }

                showAnalysisSplash(true);
                applyInstallationOptions(installationOptions);

            }

            function loadSlier()
            {
				$(REBOOT_SLIDER_VAL).text('Never');
                $(REBOOT_SLIDER).slider({
                    value: 0,
                    min: 0,
                    max: 60,
                    orientation: "horizontal",
                    slide: function (event, ui) {
                        if(ui.value == 0)
                        {
                            $(REBOOT_SLIDER_VAL).text('Never');
                            $(REBOOT_SLIDER_SUFFIX).hide();
                        }
                        else
                        {
                            $(REBOOT_SLIDER_VAL).text(ui.value);
                            $(REBOOT_SLIDER_SUFFIX).show();
                        }
                    }   
                });
            }



            /* onclick of Cancel, the user selections has to be reset to default settings */
            function resetOptionsToDefault()
            {
                var resetAttributes = {hapi:{}};
                /* reset the installation option. If any of the installation option was checked before clicking cancel button, then we need to reset*/
                if($(INSTALLATION_OPTION_ENABLE_REWRITE ).is(':checked') || ($(INSTALLATION_OPTION_ENABLE_DOWNGRADE).is(':checked')))
                {
					$(INSTALLATION_OPTION_ENABLE_REWRITE ).removeAttr("checked");
					$(INSTALLATION_OPTION_ENABLE_DOWNGRADE).removeAttr("checked");
                    resetAttributes.hapi.installation_option ={};
                    resetAttributes.hapi.installation_option.firmware = true;
                    resetAttributes.hapi.installation_option.software = true;
					resetAttributes.hapi.installation_option.rewrite = false;
                    resetAttributes.hapi.installation_option.downgrade = false;
                    resetAttributes.hapi.installation_option.forcefirmware = false;
                    resetAttributes.hapi.installation_option.forcesoftware = false;
					
                    bIsResetingAttributes = true;
                }
                /* If skip failed dependancy is checked means user has changed the degfault option hence need to be reset */
                if($(FAILED_DEP_CHECKBOX).is(':checked'))
                {
                    resetAttributes.hapi.failed_dependency_handling = 'OMITHOST';
                    bIsResetingAttributes = true;
                }
                /* if ignore warnigns is checked means user has changed the degfault option hence need to be reset */
                if($(IGNORE_WARNINGS_CHKBOX).is(':checked'))
                {
                    resetAttributes.hapi.ignore_warnings = false;
                    bIsResetingAttributes = true;
                }
                /* Send the reset attribute options to backend, ONLY IF ANY OF THE DEFAULT OPTIONS HAS CHANGED BY THE USER*/
                if(bIsResetingAttributes == true)
                {
                    showAnalysisSplash(false);
                    applyInstallationOptions(resetAttributes);
                }
            }
            /* when on click of cancel reset happens, then it will route to showview page else just close splash */
            function handleResetAction()
            {
                closeAnalysisSplash();
                if(bIsResetingAttributes == true)
                {
                    bIsResetingAttributes = false;
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                }
            }

            /* send the attributes to backend*/
			function applyInstallationOptions(forceOptions)
			{
				if(!nodeItem)
				{
					closeAnalysisSplash();
					return;
				}
				presenter.setattribute(nodeItem, forceOptions, {
                    success : function() { 
						setTimeout(handleResetAction, 1000);
					},
                    error : function() {
                        handleResetAction();
                    }
                });
			}
			
            this.resume = function () {

                presenter.on('itemChange', onItemChange);
				bIsResetingAttributes = false;
				bIsDirectDeployButtonCliked = false;
				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_OPTION_PANEL).show();
                if($(STAGE_FLAG).length != 0 )
                {
                    stage_mode = 1;
                    ROUTE_PREFIX = '/node/stage';
					
                }
				
				$(ABORT_DIRECT_DEPLOY).hide();
            };
            
            this.pause = function () {
				bIsDirectDeployButtonCliked = false;
				bIsResetingAttributes = false;
                presenter.off('itemChange', onItemChange);
                $(BASELINES).hpSearchCombo('set', {id:'', name: ''});
                $(HOTFIX).hpSearchCombo('set', {id:'', name: ''});
                $(INSTALLATION_OPTION_ENABLE_REWRITE).removeAttr("checked");
                $(INSTALLATION_OPTION_ENABLE_DOWNGRADE).removeAttr("checked");
				$(FAILED_DEP_CHECKBOX).removeAttr("checked");
				$(CMP_VERBOSE_CHKBOX).removeAttr("checked");
				$(IGNORE_WARNINGS_CHKBOX).removeAttr("checked");
                $(PANELS).hpStackedPanels('pause');
				
            };
            /**
             * @public
             */
            this.init = function () {
                loadSlier();

             
			 $("#schedule").hpsumSchedule({
                    enableButton: function(){
                        $(OK).removeAttr("disabled");
                        
                    },
                    disableButton: function(){
                        $(OK).attr("disabled", "disabled");
                    }
                });
				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);

               		$(CANCEL).click(function () {
                        /* before routing to the showview page we need to reset all the installation and other options to default */
                        if(bIsDirectDeployButtonCliked == false)
                        {
                            resetOptionsToDefault();
                        }
                        /* this condition will prevent to route to showview page before the splash completes. The variable will be set to TRUE or FALSE,
                        in showAnalysisSplash() and closeAnalysisSplash, respectively*/
                        if(bIsResetingAttributes == false)
                        {
                            gotoNodeShow();
                        }
                    });
                $(FAILEDPANEL).hide();
                   $(PANELS).hpStackedPanels({
                    	panelSelector : PANEL_SELECTOR
                	});
                
                formStateView.init({form: FORM,
                    routePattern: ROUTE_PREFIX + '.*',
                    autoTrack: false});
               
				$(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();
				});
				
				$(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;
                    bIsDirectDeployButtonCliked = true;
		    sendInstallationOptions();
                    onInventory();
                    ev.preventDefault();
                });                

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

        return new NodeDirectStagedDeployView();
    }());
    
    return NodeDirectStagedDeployView;
});
