// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (NodeDeployView)
 * This is a view class for Custom Baseline Add menu option.
 */
define(['hpsum/presenter/ilofederation/iloFederationPresenter',
		'hp/core/Router',
		'hp/core/UrlFragment',
		'hp/core/Notifications',
		'hp/core/HelpMenu',
		'hp/view/DialogView',
		'hp/services/REST',
		'hp/core/Localizer',
		'hp/model/Session',
		'hp/view/FormStateView',
		'text!hpPages/core/header_help.html',
		'jquery',
		'hpsum/view/node/jquery.hpsumInstallables',
		'hp/lib/jquery.hpStackedPanels',
		'lib/jquery.selectBox',
		'lib/jquery.dataTables',
		'lib/jquery.dataTables.rowReordering',
		'hp/lib/jquery.hpCollapsible',
		'hp/lib/jquery.hpToggle',
		'lib/jquery-ui-timepicker-addon',
		'hp/lib/jquery.hpSearchCombo'
	],

	function(presenter, router, urlFragment, notifications, helpMenu, DialogView, rest, localizer, session, FormStateView, headerHelpHtml) {
		"use strict";

		var iloOnlineDeployView = (function() {

			var DEPLOY = '#hpsum-node-deploy-ok',
				ASSOC_ANALYSIS = '#hpsum-assoc-node-deploy-analysis',
				ASSOC_CLOSE = '#hpsum-assoc-node-deploy-close',
				CANCEL = '#hpsum-nodes-deploy-close',
				PANEL_SELECTOR = '#hpsum-deploy-panel-selector',
				FIRST_ANCHOR = PANEL_SELECTOR + ' a[href]:first',
				PANELS = '#hpsum-node-deploy-panels',
				WARNING_PANEL = '#hpsum-warning-messages',
				REBOOTOPTION = '#hpsum-reboot-option',
				DELAYSEC = '#hpsum-node-delay-seconds',
				DELAYMSG = '#hpsum-node-reboot-message',
				NAME = '#hpsum-node-name',
				INTERFACEILO = '#hpsum-node-interface',
				FILTERCOLLAPSE = '#hpsum-ilofed-offlinedeploy-collapsible',
				//GROUP = '#hpsum-node-deploy-group',			
				NONECHECKBOX = '.nonecheckbox',
				USESNMPCHECKBOX = '.useSNMPcheckbox',
				USEAGENTLESSCHECKBOX = '.useAgentlesscheckbox',
				USEWEBEMCHECKBOX = '.useWEBEMcheckbox',
				DOWNGRADECHKBOXCOMP = '.downgradechkbox',
				REWRITECHKBOXCOMP = '.rewritechkbox',
				INSTALLATIONOPTION = '#hpsum-installation-option',
				FIRMWARECHKBOXCOMP = '.firmwarechkbox',
				SOFTWARECHKBOXCOMP = '.softwarechkbox',
				DEPLOYENCCHKBOXCOMP = '.enclosurechkbox',
				COMPONENT_CONFIG_DIALOG = '#hpsum-component-config-dialog',
				FORM = '#hpsum-node-deploy-add-form',
				ASSOC_NODES = '#all-assocnodes',
				SPLASH_DIALOG = '#hpsum-splash-dialog',
				iLOFED_TECH_PREVIEW_WARNING = '#ilo-federation-tech-preview-warning',
				SPLASH_SPINNER = '#hpsum-splash-spinner',
				SCHEDULETOGGLE = '#hpsum-node-schedule-enable',
				SCHEDULE_DATE = '#hpsum-node-schedule-date',
				SCHEDULE_TIME = '#hpsum-node-schedule-time',
				SCHEDULE_TIME_LABEL = '#hpsum-node-schedule-time-label',
				SCHEDULE_ERROR = '#hpsum-node-schedule-error',
				CURRENT_DATETIME = '#hpsum-node-current-datetime',
				TIME_ZONE = '#hpsum-node-timezone',
				INSTALLED_SYSTEM_TYPE_TABLE = '#ilofed-installed-system-type-table',
				INSTALL_ERROR = '#force-options-tbody-err',
				DATETIMESECTION = '#hpsum-node-schedule-datetimepick',
				SELECTALL = '#ilofed-online-deploy-selectall',
                        	DESELECTALL = '#ilofed-online-deploy-deselectall',
				FILTER_NOT_SELECTED = '#hpsum-filter-error',
				APPLY_FILTERS = '#hpsum-node-deploy-applyfilters',
				REBOOT_DELAY_SEC = '60';

			/**
			 * Constructor
			 */
			function iloOnlineDeployView() {
				var nodeItem = null;
				var formStateView = new FormStateView();
				var scheduled_getdata_date_time;
				var scheduled_getdata;
				var schedaction;
				var schedule_time;
				var failedDependencyCount = 0;
				var deploy_flag = false;
				var applyOptions = false;
				var selectedComponentsCount = 0;
				var timezone;
				var componentConfigDialogContents;
				var ignore_warnings_flag = false; 

				var optiondetails = {
					hapi: {
						reboot_options: {
							action: 'Never',
							delay: REBOOT_DELAY_SEC,
							message: 'Reboot at user request after deploy '
						},
						activate_sfw: false,
						installation_option: {
							firmware: false,
							software: false,
							downgrade: false,
							rewrite: false,
							force: false
						},
						deploy_enclosure: false,
						associated_nodes: {
							associated_node: []
						}
					}
				};

				var displayBaselineError = false;
				var initialGetattr = null;
				var assocNodeDialogContents = null,
					assocNodeDialog = null;
				var skipInstallOptions = false;

				function onItemChange(item) {
					nodeItem = item.hapi;

					if (nodeItem) {
						presenter.off("itemChange", onItemChange);
						skipInstallOptions = false;
						//for some reason, the getattributes is called multiple times sometimes as undefined node                	
						loadAttributes();
						//Load the Schedule Information from getdata
						//loadScheduleoptions(nodeItem);
						//If the user has deleted the baseline then we cannot proceed to deploy
						//so we display a message that there is no available baseline and exit
						if (nodeItem.baselines.length == 0 && !displayBaselineError) {
							router.go(urlFragment.replaceView(router.location(), 'specifybaselineonline'));							
							
						}
						if(nodeItem.warnings && nodeItem.warnings.length > 0)
						{
							$(WARNING_PANEL).text(nodeItem.warnings[0]);
							$(WARNING_PANEL).hpsumWarnings(nodeItem, true);	
							$(DEPLOY).attr("disabled", true);
							ignore_warnings_flag = false;
						}
						else
						{
							$(WARNING_PANEL).text("");
							ignore_warnings_flag = true;  // set it true as warnings are not available.
						}
						
						$('.ignorewarnings').on('change', function(){
							//send setattribute call to engine to set the TPMOverrideFlag.							
							//create object for ignore warnings and send it to engine.
							
							var ignoreWarningDetails = {
								hapi: {									
									ignore_warnings: false									
								}
							};
							if ($(this).is(':checked')) {
								ignore_warnings_flag = true;
								ignoreWarningDetails.hapi.ignore_warnings = true;
								if(failedDependencyCount <= 0 && selectedComponentsCount > 0)
								{
									$(DEPLOY).attr("disabled", false);

								}
								else
								{
									$(DEPLOY).attr("disabled", true);
								}
							}
							else
							{
								ignore_warnings_flag = false;
								$(DEPLOY).attr("disabled", true);
							}
							presenter.setattribute(nodeItem,ignoreWarningDetails, {
								success : function(data) {
								},
								error : onsetattributeerror
							});
							
							
						});
						
						$(NAME).text(nodeItem.federation_group);
						$(INTERFACEILO).text(nodeItem.name);

						var options = {
							command: 'init',
							nodeItem: nodeItem,
							onSelectionChanged: onSelectionChanged,
							onPopulateInstallSet: onPopulateInstallSet
						};

						//initInstallReview();
						$('#all-baselines').hpsumInstallables(options);


						if (nodeItem.sug_state === 'UAN') {
							//The problem is that getdata is called multiple time and there is a chance of changing Deploy button attributes in the following
							//code. So adding conditions to check if the deploy button is enabled or not, based on this change the attribute
							if ($(DEPLOY).attr("disabled") == "disabled")
								$(DEPLOY).attr("disabled", true);
							else
								$(DEPLOY).attr("disabled", false);
						} else if (nodeItem.sug_state === 'INSTALLDONE') {
							$(DEPLOY).attr("disabled", true);
						} 
						showInstallationOptions(nodeItem);
						showAssociatedNodes(nodeItem);

						//if node is an iLO Federation, then disabling Deploy and Analysis buttons. 
						//This is for HPSUM 6.3.0 release as Deploy functionality is not included.
						/*if(nodeItem.type.match(/ILO_FEDERATION/i)) {
						$(iLOFED_TECH_PREVIEW_WARNING).fadeIn();
						$(DEPLOY).attr("disabled", true);
					} else {
						$(iLOFED_TECH_PREVIEW_WARNING).hide();
					}*/

					} else {
						//notifications.show("Please select correct node", 'error');
						notifications.show(localizer.getString('hpsum.node.pleaseSelectCorrectNode'), 'error');

						$(DEPLOY).attr("disabled", true);
						$(CANCEL).trigger('click');
					}
				}


				function onSelectionChanged(id, value, componentList) {
					var applyfiltersflag = false;
					if (value == true) {
						$(DEPLOY).attr("disabled", false);
					} 
					selectedComponentsCount = componentList.component.length;
					failedDependencyCount = componentList.failed_dependency;
					if ($(APPLY_FILTERS).attr("disabled") != "disabled")
						applyfiltersflag = true;
					if (componentList.component.length > 0 && componentList.failed_dependency == 0 && applyfiltersflag == false)
					{
						//check if ignore warnings is set to true..
						if(ignore_warnings_flag)
						{
							$(DEPLOY).attr("disabled", false);
						}
						else
						{
							$(DEPLOY).attr("disabled", true);
						}
					}
					else
					{
						$(DEPLOY).attr("disabled", true);
					}
				}

				function showInstallationOptions(data) {
					//send getattributes for this node

					if (data && data.hasOwnProperty("hapi")) {
						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;
							
							if ( !rewriteOption  && !downgradeOption )
							{
								$(INSTALLATIONOPTION).val('None');
								firmwareOption = false;
								softwareOption = false;							
							}
							else if ( rewriteOption  && downgradeOption )
							{
								if(firmwareOption && softwareOption)
									$(INSTALLATIONOPTION).val('both');
								else if(firmwareOption)
									$(INSTALLATIONOPTION).val('firmware');
								else if(softwareOption)
									$(INSTALLATIONOPTION).val('software');
							}
							else if ( rewriteOption )
							{
								if(firmwareOption && softwareOption)
									$(INSTALLATIONOPTION).val('rewriteBoth');
								else if(firmwareOption)
									$(INSTALLATIONOPTION).val('rewriteFirmware');
								else if(softwareOption)
									$(INSTALLATIONOPTION).val('rewriteSoftware');
							}
							else if ( downgradeOption )
							{
								if(firmwareOption && softwareOption)
									$(INSTALLATIONOPTION).val('downgradeBoth');
								else if(firmwareOption)
									$(INSTALLATIONOPTION).val('downgradeFirmware');
								else if(softwareOption)
									$(INSTALLATIONOPTION).val('downgradeSoftware');

							}

							$(INSTALLATIONOPTION).selectBox('reset');
						}
					}
				}

				function errormsg() {
					$(INSTALL_ERROR).hide();
					formStateView.reset();
				}

				function showAnalysisSplash(flag) {

					$(SPLASH_DIALOG).dialog({
						modal: true,
						position: "center",
						draggable: false,
						resizable: false,
						show: 'fade',
						dialogClass: 'hp-splash-dialog',
						width: 400
					});
					if(flag)
						$('#hpsum-splash-message').html(localizer.getString("hpsum.group.applyingInstallationOptions"));
					else
						$('#hpsum-splash-message').html(localizer.getString("hpsum.group.applyingSelectionChanges"));
					$(SPLASH_SPINNER).show();
				}

				function closeAnalysisSplash() {
					$(SPLASH_SPINNER).hide();
					$(SPLASH_DIALOG).dialog('destroy');
				}
				function  getInstallationOptions(nodeItem){
			    
					optiondetails.hapi.installation_option ={};
                    var type = $(INSTALLATIONOPTION).val();
								 
					optiondetails.hapi.installation_option.downgrade = false;
					optiondetails.hapi.installation_option.rewrite   = false;
					optiondetails.hapi.installation_option.software = false;
					optiondetails.hapi.installation_option.firmware = false;
					optiondetails.hapi.installation_option.forcesoftware = false;
					optiondetails.hapi.installation_option.forcefirmware = false;
								  
					if ( type == "downgradeFirmware"){
						optiondetails.hapi.installation_option.downgrade = true;
						optiondetails.hapi.installation_option.firmware = true;
						optiondetails.hapi.installation_option.forcefirmware = true;
					}
					else if ( type == "downgradeSoftware"){
						optiondetails.hapi.installation_option.downgrade = true;
						optiondetails.hapi.installation_option.software = true;
						optiondetails.hapi.installation_option.forcesoftware = true;
					}
					else if ( type == "downgradeBoth"){
						optiondetails.hapi.installation_option.downgrade = true;
						optiondetails.hapi.installation_option.firmware = true;
						optiondetails.hapi.installation_option.forcefirmware = true;
						optiondetails.hapi.installation_option.software = true;
						optiondetails.hapi.installation_option.forcesoftware = true;
					}
					else if ( type == "rewriteFirmware"){
						optiondetails.hapi.installation_option.rewrite = true;
						optiondetails.hapi.installation_option.firmware = true;
						optiondetails.hapi.installation_option.forcefirmware = true;
					}
					else if ( type == "rewriteSoftware"){
						optiondetails.hapi.installation_option.rewrite = true;
						optiondetails.hapi.installation_option.software = true;
						optiondetails.hapi.installation_option.forcesoftware = true;
					}
					else if ( type == "rewriteBoth"){
						optiondetails.hapi.installation_option.rewrite = true;
						optiondetails.hapi.installation_option.firmware = true;
						optiondetails.hapi.installation_option.forcefirmware = true;
						optiondetails.hapi.installation_option.software = true;
						optiondetails.hapi.installation_option.forcesoftware = true;
					}
					else if ( type == "firmware"){
						optiondetails.hapi.installation_option.downgrade = true;
						optiondetails.hapi.installation_option.rewrite = true;
						optiondetails.hapi.installation_option.firmware = true;
						optiondetails.hapi.installation_option.forcefirmware = true;
					}
					else if ( type == "software"){
						optiondetails.hapi.installation_option.downgrade = true;
						optiondetails.hapi.installation_option.rewrite = true;
						optiondetails.hapi.installation_option.software = true;
						optiondetails.hapi.installation_option.forcesoftware = true;
					}
					else if ( type == "both"){
						optiondetails.hapi.installation_option.downgrade = true;
						optiondetails.hapi.installation_option.rewrite = true;
						optiondetails.hapi.installation_option.firmware = true;
						optiondetails.hapi.installation_option.forcefirmware = true;
						optiondetails.hapi.installation_option.software = true;
						optiondetails.hapi.installation_option.forcesoftware = true;
					}
			}
				//Apply Installation Options
				function applyInstallationOptions()
				{
					applyOptions = true;
					deploy_flag = false;
					getInstallationOptions(nodeItem);
					if(initialGetattr.hapi.installation_option.downgrade != optiondetails.hapi.installation_option.downgrade ||
						initialGetattr.hapi.installation_option.rewrite != optiondetails.hapi.installation_option.rewrite ||
						initialGetattr.hapi.installation_option.software != optiondetails.hapi.installation_option.software ||
						initialGetattr.hapi.installation_option.firmware != optiondetails.hapi.installation_option.firmware) {

						presenter.setattribute(nodeItem,optiondetails, {
							success : function(data) {
							},
							error : onsetattributeerror
						});
						formStateView.setMessage({
							summary: localizer.getString("hpsum.node.installationOptions.applyingOptions"),
							status: 'ok',
							changing: true,
						});
						showAnalysisSplash(true);
						getNodeStatus();
					}
				}

				function analysis() {
					$(APPLY_FILTERS).attr("disabled",true);

					var inst = $('#all-baselines').data('plugin_hpsumInstallables');
					var componentsList = inst.getComponents();
					var serverTypes = getAllSelectedServerTypes();

					if (serverTypes.length == 0) {
						$(FILTER_NOT_SELECTED).fadeIn(400, function() {});
						formStateView.setMessage({
                       		summary : localizer.getString('hpsum.ilofederation.filternotSelectedError'),
                        	status : "error"
                   		});
					return false;
					}

					componentsList.hapi.serverList = {
						"serverType" : serverTypes
					}
					showAnalysisSplash();
					presenter.analysis(nodeItem, componentsList, {
						node_id: nodeItem.node_id,
						success: function(data) {
							analyzeSuccess(data, this.node_id);
						},
						error: function(errorInfo) {
							analyzeError(errorInfo);
						}
					});
					
					getNodeStatus();
				}
				
				function getNodeStatus()
				{
					var progressTimer = setInterval(function() {
						var sug_uri = "/Session/" + session.getToken() + "/node/ScalableUpdate/" + nodeItem.sug_id;
						rest.getURI(sug_uri + "/getstatus", {

							success: function(data) {

								if (data.hapi.sug_state === "ANALYSIS") {

								} else if (data.hapi.sug_state === "UAN") {
									clearInterval(progressTimer);

									//show install review for all the nodes
									//initInstallReview();
									$('#all-baselines').hpsumInstallables('recalculate');
									closeAnalysisSplash();
									if(applyOptions)
									{
										skipInstallOptions = false;
										formStateView.setMessage({
											summary: localizer.getString("hpsum.node.installationOptions.optionsSuccess"),
											status: 'ok',
											changing: false,
										});
										applyOptions = false;
										loadAttributes();
									}
								} else if (data.hapi.sug_state === "ERROR") {
									clearInterval(progressTimer);
									closeAnalysisSplash();
								}
							},
							error: function(errorInfo) {

							}
						});
					}, 3000);
				}

				function analyzeSuccess(data, nodeid) {

				}

				function analyzeError(error) {
					$(SPLASH_SPINNER).hide();
					$(SPLASH_DIALOG).dialog('destroy');
				}

				function validateTime() {
					var time_val = $(SCHEDULE_TIME).val();
					var time_parse = time_val.split(':');
					var time_pattern = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
					if (!time_val.match(time_pattern)) {
						$(SCHEDULE_TIME_LABEL).addClass("hp-error");
						$(SCHEDULE_TIME_LABEL).show();
					} else {
						var time_hrs = time_parse[0];
						var time_mins = time_parse[1];
						if (time_hrs >= 12) {
							if (time_hrs == 12)
								schedule_time = time_hrs + ':' + time_mins + ' ' + 'PM';
							else {
								var time_hrs_old = time_hrs - 12;
								if ((time_hrs_old) <= 9)
									schedule_time = '0' + time_hrs_old + ':' + time_mins + ' ' + 'PM';
								else
									schedule_time = time_hrs_old + ':' + time_mins + ' ' + 'PM';
							}
						} else if (time_hrs == 0) {
							schedule_time = (parseInt(time_hrs) + 12) + ':' + time_mins + ' ' + 'AM';
						} else if (time_hrs < 12) {
							schedule_time = time_hrs + ':' + time_mins + ' ' + 'AM';
						}
						$(DEPLOY).attr('disabled', 'disabled');
					}
				}

				function setscheduleoptions(nodeItem) {

					var scheduled = "no";
					var date = "";
					var time = "";

					if ($(SCHEDULETOGGLE).attr('checked') === "checked")
						scheduled = 'yes';
					else
						scheduled = 'no';

					if (scheduled_getdata_date_time == "") {
						scheduled_getdata_date_time = " ";
						schedaction = 'create';
					} else
						schedaction = 'update';

					if (scheduled === "yes") {
						date = $(SCHEDULE_DATE).val();
						validateTime();
						time = schedule_time;
					}

					var schedule_information = {
						date: date,
						time: time
					};
					var schedule_date_time = date + ' ' + time;
					if (scheduled !== scheduled_getdata || scheduled_getdata_date_time !== schedule_date_time)
						presenter.ScheduleNodes(nodeItem.node_id, schedaction, scheduled, schedule_information, {
							success: function(data) {
								onScheduleNodesSuccess(data);
							},
							error: function(errorInfo) {
								onScheduleNodesError(errorInfo);
							}
						});
				}

				function loadScheduleoptions(nodeItem) {
					var scheduled_date_time_split;
					var scheduled_time;
					var scheduled_date;
					var scheduled_time_hrs_mins;
					var scheduled_time_hrs;
					var scheduled_time_mins;
					scheduled_getdata_date_time = nodeItem.schedule_date_time;
					scheduled_getdata = nodeItem.scheduled;
					if (scheduled_getdata === "false") {
						scheduled_getdata = "no";
						$(DEPLOY).val(localizer.getString('hpsum.node.deploy'));
						if ($(SCHEDULETOGGLE).attr('checked') === "checked") {
							$(SCHEDULETOGGLE).click();
							$(SCHEDULETOGGLE).removeAttr("checked");
						}
					} else if (scheduled_getdata === "true") {
						scheduled_getdata = "yes";
						$(DEPLOY).val(localizer.getString('hpsum.node.scheduledeploy'));
						if ($(SCHEDULETOGGLE).attr('checked') === undefined) {
							$(SCHEDULETOGGLE).click();
							$(SCHEDULETOGGLE).attr("checked", "checked");
						}
					}
					if (scheduled_getdata_date_time === "") {
						$(SCHEDULE_DATE).val('');
						$(SCHEDULE_TIME).val('');
					} else {
						scheduled_date_time_split = scheduled_getdata_date_time.split(' ');
						scheduled_date = scheduled_date_time_split[0];
						scheduled_time = scheduled_date_time_split[1];
						scheduled_time_hrs_mins = scheduled_time.split(':');
						scheduled_time_hrs = scheduled_time_hrs_mins[0];
						scheduled_time_mins = scheduled_time_hrs_mins[1];

						var scheduled_time_hrs_new;
						var scheduled_time_new;

						if (scheduled_date_time_split[2] == 'PM') {
							if (scheduled_time_hrs < 12) {
								scheduled_time_hrs_new = parseInt(scheduled_time_hrs) + 12;
								scheduled_time_new = scheduled_time_hrs_new + ':' + scheduled_time_mins;
							} else if (scheduled_time_hrs == 12) {
								scheduled_time_hrs_new = parseInt(scheduled_time_hrs) + 0;
								scheduled_time_new = scheduled_time_hrs_new + ':' + scheduled_time_mins;
							}
						} else if (scheduled_date_time_split[2] == 'AM') {
							if (scheduled_time_hrs == 12) {
								scheduled_time_hrs_new = parseInt(scheduled_time_hrs) - 12;
								scheduled_time_new = '0' + scheduled_time_hrs_new + ':' + scheduled_time_mins;
							} else if (scheduled_time_hrs < 12) {
								if (scheduled_time_hrs < 10) {
									scheduled_time_hrs_new = parseInt(scheduled_time_hrs) + 0;
									scheduled_time_new = '0' + scheduled_time_hrs_new + ':' + scheduled_time_mins;
								} else {
									scheduled_time_hrs_new = parseInt(scheduled_time_hrs) + 0;
									scheduled_time_new = scheduled_time_hrs_new + ':' + scheduled_time_mins;
								}
							}
						}

						$(SCHEDULE_DATE).val(scheduled_date);
						$(SCHEDULE_TIME).val(scheduled_time_new);
					}
				}

				function onScheduleNodesError(errorMessage) {
					notifications.show(errorMessage, 'error');
					$(DEPLOY).attr("disabled", true);
					$(CANCEL).trigger('click');
				}

				function onScheduleNodesSuccess(data) {
					var message;
					$(DEPLOY).val(localizer.getString('hpsum.node.scheduledeploy'));
					if (schedaction === "create")
						message = "Schedule for " + nodeItem.name + " created successfully";
					if (schedaction === "update")
						message = "Schedule for " + nodeItem.name + " updated successfully";
					notifications.show(message, 'ok');
				}

				function toggleSchedule(cb) {
					if (cb.target.checked)
						$(DATETIMESECTION).show();
					else
						$(DATETIMESECTION).hide();
					$(DEPLOY).attr('disabled', 'disabled');
				}

				/**
				 * @private
				 * Call presenter's onAnalysis() to check for dependencies for a selected component/baseline to the node
				 */


				function onsetattributeSuccess(item) {
					loadAttributes();
					//do nothing
				}

				function onsetattributeerror(errorMessage) {

					onAnalysisError(errorMessage);
				}
				/**
				 * @private
				 */


				/**
				 * @private
				 */
				function onAnalysisError(errorMessage) {
					notifications.show(errorMessage, 'error');
					formStateView.setMessage({
                       	summary : errorMessage,
                        status : "error"
                    });
					$(DEPLOY).attr("disabled", true);
					$(CANCEL).trigger('click');

				}

				function getAllSelectedServerTypes() {

					var selectedList = [];

					var totalRows = $(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr').size();
					var selectedRows = $(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr.hp-selected').size();
					// If all the rows stay selected, we do not have to filter by any servers
					if (totalRows != selectedRows) {
						$(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr.hp-selected').each(function(index, value) {
							var list = $('td', value);
							selectedList.push($(list[1]).text());
						});
					} else {
						selectedList.push("AllSelected");
					}

					return selectedList;
				}
			
				function onPopulateInstallSet(node_id)
				{
					if(deploy_flag)
					{
						var install = $('#all-baselines').data('plugin_hpsumInstallables');
						failedDependencyCount = install.failedDependencyCount();
						if(failedDependencyCount <= 0 && selectedComponentsCount > 0)
						{
							$(DEPLOY).attr("disabled", true);
							onDeployContinue();
						}
						deploy_flag = false;
					}
				}
			
				/**
				 * @private
				 * Call presenter's deploy() to deploy  a selected component/baseline to the node
				 */
			function onDeploy() {
				var serverTypes = getAllSelectedServerTypes();
				
				if (serverTypes.length == 0) {
					$(FILTER_NOT_SELECTED).fadeIn(400, function() {});
					formStateView.setMessage({
                       	summary : localizer.getString('hpsum.ilofederation.filternotSelectedError'),
                        status : "error"
                    });
					return false;
				} else {
					$(FILTER_NOT_SELECTED).fadeOut(400, function() {});
				}
				if (serverTypes[0] == "AllSelected")
                	serverTypes = [];
					
				deploy_flag = true;
				skipInstallOptions = true;
				formStateView.reset();
				
				loadAttributes();
			}

			function onDeployContinue()
			{
				var serverTypes = getAllSelectedServerTypes();
				if (serverTypes[0] == "AllSelected")
                	serverTypes = [];
				presenter.deploy({
					deploy_mode: 0,
					url_or_path: "",
					server_type_filter: serverTypes,
					sug_id: nodeItem.sug_id
				}, {
					success: function(data) {
						onDeploySuccess(data);
					},
					error: function(error) {
						onDeployError(error);
					}
				});

			}

				/**
				 * @private
				 */
				function onDeploySuccess(item) {
					deploy_flag = false;
					$(CANCEL).trigger('click');
				}

				/**
				 * @private
				 */
				function onDeployError(errorMessage) {
					notifications.show(errorMessage, 'error');
					deploy_flag = false;
					formStateView.setMessage({
                        summary : errorMesage,
                        status : "error"
                    });
					$(DEPLOY).attr("disabled", true);
					$(CANCEL).trigger('click');

				}

				function changeLocation(location) {
					var resource = router.location().split('/');
					resource = resource[1];
					var ROUTE_PREFIX = '/' + resource + '/onlinedeploy';
					if (location.length > ROUTE_PREFIX.length) {
						$(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
					} else {
						$(PANELS).hpStackedPanels('setFirstPanel');
					}
				}

				/**
				 * @private
				 */
				function onPopulateError(errorMessage) {
					notifications.show(errorMessage, 'error');
					$(DEPLOY).attr("disabled", true);
					$(CANCEL).trigger('click');

				}

				function showAssociatedNodes(item) {

					$(FILTERCOLLAPSE).hpCollapsible('expand');
					$("#ilofed-installed-system-type-table > tbody > tr").remove();
					$("#ilofed-installed-system-type-table_filter").remove();
					$("#ilofed-installed-system-type-table_processing").remove();
					if (item.server_types && item.server_types.length > 0) {

						var systemsTable = initSystemsTable();
						systemsTable.fnClearTable();

						// Go ahead and populate all the systems in the systems table
						var idx;
						for (idx = 0; idx < item.server_types.length; idx++) {
							var system = item.server_types[idx];
							var selectedtoggle;
							if((item.selected_server_models.indexOf(system.server_model) != -1) || item.selected_server_models.indexOf("AllSelected") != -1)
								selectedtoggle = '<input id="selectToggle-' + idx + '" class="toggle" type="checkbox" checked/>';
							else
								selectedtoggle = '<input id="selectToggle-' + idx + '" class="toggle" type="checkbox" />';	
							systemsTable.fnAddData([{
								selected: selectedtoggle,
								server_model: system.server_model,
								count: system.count
							}]);
						}

						$(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr').addClass('hp-selected');
						$('.toggle').hpToggle({
							unchecked: localizer.getString("hpsum.oneTouchUpdate.select"),
							checked: localizer.getString("hpsum.oneTouchUpdate.selected")
						});

						$.each(systemsTable.fnGetNodes(), function(index, value) {
   						 	if(!$('.hp-toggle', $(value)).hasClass("hp-checked"))
   						 		$(this).removeClass("hp-selected");
						});

						$(INSTALLED_SYSTEM_TYPE_TABLE + " tbody tr").click(function(e) {
							var srcElem;
							//Check if firefox or (chrome and IE)
							if (e.srcElement) {
								srcElem = e.srcElement;
								//Chrome and IE
							} else {
								srcElem = e.target;
								//Firefox
							}
							var data = systemsTable.fnGetData(this);
							var clickedCellIndex = srcElem.cellIndex;
							var selectid = data.selected.split('"');
							selectid = '#' + selectid[1];
							if (clickedCellIndex === undefined) {
								if (srcElem.className == 'hp-on') {
									$(this).removeClass('hp-selected');
									formStateView.setMessage({
                                        summary : localizer.getString('hpsum.ilofederation.deselectedModel',
                                                        [data.server_model]),
                                        status : "info"
                                    });
									$(selectid).removeAttr('checked');
								} else {
									$(this).addClass('hp-selected');
									formStateView.setMessage({
                                        summary : localizer.getString('hpsum.ilofederation.selectedModel',
                                                        [data.server_model]),
                                        status : "info"
                                    });
                                    $(FILTER_NOT_SELECTED).hide();
									$(selectid).attr('checked', 'checked');
								}
								$(selectid).trigger('change');

							} else {
								if ($(this).hasClass('hp-selected')) {
									formStateView.setMessage({
                                        summary : localizer.getString('hpsum.ilofederation.deselectedModel',
                                                        [data.server_model]),
                                        status : "info"
                                    });
									$(selectid).removeAttr('checked');
								} else {
									formStateView.setMessage({
                                        summary : localizer.getString('hpsum.ilofederation.selectedModel',
                                                        [data.server_model]),
                                        status : "info"
                                    });
                                    $(FILTER_NOT_SELECTED).hide();
									$(selectid).prop('checked', true);
								}
								$(selectid).trigger('change');
								$(this).toggleClass('hp-selected');

							}
							$(APPLY_FILTERS).attr("disabled",false);
							if ($(DEPLOY).attr("disabled") != "disabled")
								$(DEPLOY).attr("disabled",true);

						});
					}
				}

				function initSystemsTable() {

					if ($.fn.DataTable.fnIsDataTable($(INSTALLED_SYSTEM_TYPE_TABLE)[0])) {
						$(INSTALLED_SYSTEM_TYPE_TABLE).dataTable().fnDestroy();
					}

					return $(INSTALLED_SYSTEM_TYPE_TABLE).dataTable({
						bPaginate: false,
						bLengthChange: false,
						bFilter: false,
						bSort: false,
						bInfo: false,
						bAutoWidth: false,
						bRetrieve: true,
						aoColumns: [{
							mDataProp: 'selected',
							"sWidth": "30%"
						}, {
							mDataProp: 'server_model',
							"sWidth": "30%"
						}, {
							mDataProp: 'count',
							"sWidth": "30%"
						}]
					});
				}



				/**
				 * @private
				 */

				function reset() {
					$(INTERFACEILO).text(localizer.getString('hpsum.common.loading'));
					$(NAME).text("");
					$(NONECHECKBOX).attr('checked', false);
					$(USESNMPCHECKBOX).attr('checked', false);
					$(USEAGENTLESSCHECKBOX).attr('checked', false);
					$(USEWEBEMCHECKBOX).attr('checked', false);
					$(DOWNGRADECHKBOXCOMP).attr('checked', false);
					$(REWRITECHKBOXCOMP).attr('checked', false);
					$(FIRMWARECHKBOXCOMP).attr('checked', false);
					$(SOFTWARECHKBOXCOMP).attr('checked', false);


					$(SCHEDULE_DATE).val("");
					$(SCHEDULE_TIME).val("");
					$("#hpsum-osmanagement-options-collapsible").css("display", "none");
					$('#hpsum-installation-options-collapsible').css("display", "block");
					$('#hpsum-force-options-collapsible').css("display", "block");

					$("#hpsum-ilofed-offlinedeploy-collapsible").css("display", "block");

				}

				function loadAttributes() {

					initialGetattr = null;

					var handler = {
						success: function(data) {
							initialGetattr = data;
							if (!skipInstallOptions) {
								showInstallationOptions(data);
							} else {
								analysis();
							}

						},
						error: function(errorInfo) {}
					};

					presenter.otheroption(nodeItem, handler);
				}

				/**
				 * @public
				 */
				this.resume = function() {
					reset();
					presenter.on("itemChange", onItemChange);
					$(PANELS).hpStackedPanels('resume');
					$(SCHEDULE_TIME_LABEL).removeClass("hp-error");
					$(SCHEDULE_TIME_LABEL).hide();
					$(FILTER_NOT_SELECTED).hide();
					$(APPLY_FILTERS).attr("disabled",true);

				};

				this.pause = function() {
					presenter.off("itemChange", onItemChange);
					$('.hpsumInstallables').hpsumInstallables('destroy');
					$(PANELS).hpStackedPanels('pause');
					$(iLOFED_TECH_PREVIEW_WARNING).hide();
					formStateView.reset();
				};

				/**
				 * @public
				 * Initialization funtion for the object
				 * All the controls actions are initialized in this function.
				 */
				this.init = function() {
					// put help in header
					if ($('.hp-details-header-controls', $(FORM).parent()).length === 0) {
						var headerHelp = $(headerHelpHtml);
						localizer.localizeDom(headerHelp);
						$('.hp-details-header', $(FORM).parent()).append(headerHelp);
					}
					$(CANCEL).click(function() {
						formStateView.reset();
						router.go(urlFragment.replaceView(router.location(), 'show'));
					});
					var ROUTE_PREFIX = '/'+ resource +'/onlinedeploy';

					formStateView.init({
                        form : FORM,
                        routePattern : ROUTE_PREFIX + '.*',
                        autoTrack : true
                	});

					$(FILTER_NOT_SELECTED).hide();

					$(DEPLOY).on('click', function(ev) {
						onDeploy.call(this);
						ev.preventDefault();
					});
					$(APPLY_FILTERS).on('click',function(ev) {
						analysis.call(this);
						ev.preventDefault();
					});
					var resource = router.location().split('/');
					resource = resource[1];
					var ROUTE_PREFIX = '/' + resource + '/onlinedeploy';

					//By Default reboot-options value is Never so disable the Reboot delay and Reboot message.
					$(".hpsum-otu-node-deploy-disable").find('input,textarea,select,button').prop("disabled", true);

					$('#hpsum-downgrade-rewrite-text').html(localizer.getString("hpsum.node.installationOptions.message"));
					$('#hpsum-downgrade-rewrite-text').removeClass('hp-collapsed');
					$(INSTALL_ERROR).hide();
					$(INSTALLATIONOPTION).val('None');
					$(INSTALLATIONOPTION).change(function() {
						applyInstallationOptions.call();
					});
					$(INSTALLATIONOPTION).selectBox({
						autoWidth: false
					});


					$(PANELS).hpStackedPanels({
						panelSelector: PANEL_SELECTOR
					});

					$(".hp-collapsible").hpCollapsible();
					$(DATETIMESECTION).hide();
					$(SCHEDULETOGGLE).hpToggle({
						checked: 'On',
						unchecked: 'Off'
					});
					$(SCHEDULETOGGLE).bind('change', toggleSchedule);
					$(SCHEDULE_DATE).datepicker({
						dateFormat: 'yy-mm-dd'
					});
					$(SCHEDULE_TIME).bind('change', validateTime);
					$(SCHEDULE_TIME).bind('keyup', function() {
						$(SCHEDULE_TIME_LABEL).removeClass("hp-error");
						$(SCHEDULE_TIME_LABEL).hide();
					});
					$(SCHEDULE_TIME_LABEL).removeClass("hp-error");
					$(SCHEDULE_TIME_LABEL).hide();
					$(SCHEDULE_DATE).bind('change', function() {
						$(DEPLOY).attr('disabled', 'disabled');
					});
					$("#hpsum-schedule-collapsible").removeClass('hp-collapsed');
					$("#hpsum-ilofed-offlinedeploy-collapsible").removeClass('hp-collapsed');
					$("#hpsum-baseline-collapsible").removeClass('hp-collapsed');
					$(DEPLOY).attr("disabled", true);
					
					$(SELECTALL).on('click', function(ev){
				    	$(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr').each( function () {
			                $(this).addClass('hp-selected');
			                var temptable = $(INSTALLED_SYSTEM_TYPE_TABLE).dataTable();
			                var data = temptable.fnGetData(this);
	                        var selectid = data.selected.split('"');
	                        selectid ='#'+selectid[1];
	                        $(selectid).attr('checked', 'checked');
	                        $(selectid).trigger('change');
			            });
			            $(FILTER_NOT_SELECTED).hide();
			            formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.allselected'),
                            status : "info"
                        });

						if($(DEPLOY).attr("disabled") != "disabled"){
							$(DEPLOY).attr("disabled", true);
						}
						$(APPLY_FILTERS).attr("disabled",false);
				    });
					
					$(DESELECTALL).on('click', function(ev){
				    	$(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr').each( function () {
			            	$(this).removeClass('hp-selected');
			            	var temptable = $(INSTALLED_SYSTEM_TYPE_TABLE).dataTable();
			            	var data = temptable.fnGetData(this);
	                        var selectid = data.selected.split('"');
	                        selectid ='#'+selectid[1];
	                        $(selectid).removeAttr('checked');
	                        $(selectid).trigger('change');
			            });
			            formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.alldeselected'),
                            status : "info"
                        });

						//$(ANALYSIS).attr("disabled", true);

						if($(DEPLOY).attr("disabled") != "disabled"){
							$(DEPLOY).attr("disabled", true);
						}
						$(APPLY_FILTERS).attr("disabled",false);
				    });

					router.watch('Node Deploy section', ROUTE_PREFIX + '.*', {
						parent: ROUTE_PREFIX,
						change: changeLocation
					});


					this.resume();
				};
			}

			return iloOnlineDeployView;
		}());

		return new iloOnlineDeployView();
	});