// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (NodeAddView)
 * This is a view class for Node Add menu option.
 */

define(['hpsum/presenter/node/NodePresenter',
	'hpsum/presenter/group/GroupPresenter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/HashManager',
    'hp/core/Validator',
    'hp/view/FormStateView',
	'hp/view/DialogView',
    'hp/core/HelpMenu',
	'hp/services/REST',
    'hp/core/Localizer',
	'hp/model/Session',
    'text!hpPages/core/header_help.html',
	'jquery',
	'hpsum/view/node/jquery.hpsumInstallables',
    'hp/lib/jquery.hpStackedPanels',
    'lib/jquery.selectBox',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpSearchCombo',
    'hp/lib/jquery.hpToggle',
	'hpsum/common/jquery.hpsumBrowse',
	'hpsum/common/utility'],
function(presenter, groupPresenter, router,urlFragment, hashManager, validator, FormStateView, DialogView, helpMenu,rest, localizer,session, headerHelpHtml) { "use strict";
    	
    	var AddView = (function() {
    	    var ADD = '#hpsum-node-add',
				FIND = '#hpsum-find-nodes-button',
            	CANCEL = '#hpsum-node-add-close',
             	RESET = '#hpsum-node-reset',
				PANEL_SELECTOR = '#hpsum-node-add-panel-selector',
            	PANELS = '#hpsum-node-add-panels',
           		NAME = '#hpsum-node-name',
           		NAMEERR = '#hpsum-node-name-error',
           		DESC = '#hpsum-node-description',
           		TYPE = '#hpsum-node-type',
           		TYPEERR = '#hpsum-node-type-error',
           		ENTER_CRED = '#hpsum-node-cred-details',
				ENTER_VCENTER_CRED = '#hpsum-node-vcenter-cred-details',
				ENTER_LINUX_CRED = '#hpsum-linux-node-cred-details',
           		USERNAME = '#hpsum-node-credential-username',
           		USERNAME_ERR = '#hpsum-node-username-err',
           		PASSWORD = '#hpsum-node-credential-password',
           		PASSWORD_ERR = '#hpsum-node-password-err',
				ILO_USERNAME ='#hpsum-node-ilo-credential-username',
				ILO_PASSWORD ='#hpsum-node-ilo-credential-password',
				VCENTERPANEL = '#vmware-node-credentials',
				VCENTERUSERNAME = '#hpsum-node-vcenter-credential-username',
				VCENTERUSERNAME_ERR = '#hpsum-node-vcenter-username-err',
				VCENTERPASSWORD = '#hpsum-node-vcenter-credential-password',
				VCENTERPASSWORD_ERR = '#hpsum-node-vcenter-password-err',
				VCENTERIPADDR = '#hpsum-node-vcenter-credential-ipaddress',
				VCENTERIPADDR_ERR = '#hpsum-node-vcenter-ipaddress-err',
				LINUX_CRED_PANEL = '#hpsum-linux-node-add-credentials',
				LINUXUSERNAME = '#hpsum-linux-node-credential-username',
				LINUXUSERNAME_ERR = '#hpsum-linux-node-username-err',
           		LINUXPASSWORD_ERR = '#hpsum-linux-node-password-err',
				LINUXPASSWORD = '#hpsum-linux-node-credential-password',
				LINUX_SSH_KEY_FILE_SELECTION = '#hpsum-linux-node-credential-ssh-key-file-selection',
				LINUX_SSH_KEY_FILE_PANEL = '#hpsum-linux-node-cred-ssh-key-file-details',
				LINUX_SSH_KEY_FILE_USERNAME = '#hpsum-linux-node-credential-ssh-key-file-username',
				LINUX_SSH_KEY_FILE_USERNAME_ERR = '#hpsum-linux-node-credential-ssh-key-file-username-err',
				LINUX_SSH_KEY_FILE_PATH_ERR = "#hpsum-linux-node-credential-ssh-key-file-path-err",
				LINUX_SSH_KEY_FILE_PASSPHRASE = "#hpsum-linux-node-credential-ssh-key-file-passphrase",
				GEN10_ILO_CRED_PANEL = "#hpsum-node-ilo-credential-details",
				ILO_CRED_LABEL = "#hpsum-ilo-credentials-label",
           		FORM = '#hpsum-node-add-form',
            	BASELINES = '#hpsum-node-add-baselines-search',
            	HOTFIX = '#hpsum-node-add-hotfix-search',
            	PARTNER_TYPE = '#hpsum-node-add-partner',
            	PARTNER_CRED_PANEL = '#hpsum-node-add-partner-credentials',
            	PARTNER_IP_LABEL = '#hpsum-node-partner-ip',
            	PARTNER_IP_VALUE = '#hpsum-node-partner-ip-value',
            	PARTNER_IP_OPTMSG_LABEL = '#hpsum-node-partner-ip-opt-msg',
            	PARTNER_ENTER_CRED = '#hpsum-node-partner-cred-details',
            	PARTNER_USERNAME = '#hpsum-node-partner-credential-username',
           		PARTNER_PASSWORD = '#hpsum-node-partner-credential-password',
           		PARTNER_USERNAME_ERR = '#hpsum-node-partner-credential-username-err',
           		PARTNER_PASSWORD_ERR = '#hpsum-node-partner-credential-password-err',
           		PARTNER_IP_LIST = '#hpsum-node-add-partner-ip-list',
            	ROUTE_PREFIX = '/node/add',
				IP_DIALOG = '#hpsum-node-ip-dialog',
				APPLY_SETTINGS_BUTTON = '#hpsum-apply-settings',
				NODESETTINGS_DIALOG = '#hpsum-node-settings-dialog',
				NODESETTINGS_CRED = '#hpsum-node-settings-cred-details',
           		NODESETTINGS_USERNAME = '#hpsum-node-settings-credential-username',
           		NODESETTINGS_USERNAME_ERR = '#hpsum-node-settings-username-err',
           		NODESETTINGS_PASSWORD = '#hpsum-node-settings-credential-password',
           		NODESETTINGS_PASSWORD_ERR = '#hpsum-node-settings-password-err',
				NODESETTINGS_BASELINE = '#hpsum-node-settings-add-baselines-search',
				NODESETTINGS_HOTFIX = '#hpsum-node-settings-add-hotfix-search',
				NODESETTINGS_ADD = '#hpsum-node-settings-add',
				NODESETTINGS_RESET = '#hpsum-node-settings-reset',
				NODESETTINGS_CANCEL = '#hpsum-node-settings-close',
				NODE_ADD_THROBBER = '#hpsum-node-add-throbber',
				ADD_ASSOC_NODES = '#hpsum-node-addassocnodes',
				NODE_ADD_TYPE = '#hpsum-node-addType',
				ADD_SINGLE_NODE = '#hpsum-node-addSingleNode',
				ADD_FIND_NODE = '#hpsum-node-findNode',
				ADD_BASELINE = '#hpsum-node-add-baseline',
				ADD_ALREADYEXISTS = '#hpsum-node-add-alreadyExist',
				ADD_CREDENTIALS = '#hpsum-node-add-credentials',
				SELECT_GROUP = '#hpsum-node-group-select',
				VC_OPTIONS = '#hpsum-vc-options-text',
				ADD_GROUP = '#hpsum-node-add-group',
				BASELINE_INPUT = '#hpsum-node-add-baselines-search-input',
				HOTFIX_INPUT = '#hpsum-node-add-hotfix-search-input',
				BASELINE_INPUT_ERR = '#hpsum-node-add-baselines-search-input-err',
				HOTFIX_INPUT_ERR = '#hpsum-node-add-hotfix-search-input-err',
				HEADER_TYPE = '#hpsum-node-type-header',
				ADD_LINUX_BROWSE_PANEL = '#hpsum-add-linux-sshkey-browse-panel',
				NODE_CREDENTIAL_CURRENT = '#hpsum-node-credential-current-selection',
				NODE_CREDENTIAL_KEY = '#hpsum-node-credential-key',
				NODE_CREDENTIAL_KEY_LABEL = '#hpsum-node-credential-key-label',
				ILO_CREDENTIALS_NOTE = '#hpsum-ilo-credentials-note',
				MOONSHOT_ADD_CREDENTIALS = "#hpsum-moonshot-add-credentials",
				MOONSHOT_SWITCH_CREDENTIALS = '#hpsum-moonshot-switch-credentials',
				MOONSHOT_SWITCHB_CREDENTIALS = '#hpsum-moonshot-switchB-credentials',
				MOONSHOT_ENTER_SWITCH_CREDENTIALS = '#hpsum-moonshot-enter-switch-credentials',
				MOONSHOT_SWITCH_SAME_CREDENTIALS = '#hpsum-moonshot-switch-same-credentials',
				MOONSHOT_SWITCH_CREDENTIALS_NOT_SET = '#hpsum-moonshot-switch-credentials-not-set',
				MOONSHOT_SWITCH_CREDENTIALS_PWD = '#hpsum-moonshot-switch-authentication-pwd',
				MOONSHOT_SWITCH_CREDENTIALS_FULL = '#hpsum-moonshot-switch-full-authentication',
				MOONSHOT_SWITCHB_CREDENTIALS_NOT_SET = '#hpsum-moonshot-switchb-credentials-not-set',
				MOONSHOT_SWITCHB_CREDENTIALS_PWD = '#hpsum-moonshot-switchb-authentication-pwd',
				MOONSHOT_SWITCHB_CREDENTIALS_FULL = '#hpsum-moonshot-switchb-full-authentication',
				MOONSHOT_SWITCH_CREDENTIALS_TEXT_BOX = '.hpsum-moonshot-switch-credentials-text-box',
				MOONSHOT_SWITCHB_CREDENTIALS_TEXT_BOX = '.hpsum-moonshot-switchB-credentials-text-box',
				MOONSHOT_SWITCH_CREDENTIALS_USERNAME = '#hpsum-moonshot-switch-credentials-username',
				MOONSHOT_SWITCH_CREDENTIALS_PASSWORD = '#hpsum-moonshot-switch-credentials-password',
				MOONSHOT_SWITCH_CREDENTIALS_ENABLE_PASSWORD = '#hpsum-moonshot-switch-credentials-enablePassword',
				MOONSHOT_SWITCHB_CREDENTIALS_USERNAME = '#hpsum-moonshot-switchB-credentials-username',
				MOONSHOT_SWITCHB_CREDENTIALS_PASSWORD = '#hpsum-moonshot-switchB-credentials-password',
				MOONSHOT_SWITCHB_CREDENTIALS_ENABLE_PASSWORD = '#hpsum-moonshot-switchB-credentials-enablePassword',
				STACKED_PANEL_ACTIVE = '.hp-stacked-panel.hp-active',
    		    INSTALL_PREREQS_PANEL = '#hpsum-node-add-install-prereqs-panel',
    		    INSTALL_PREREQS_DIV = '#hpsum-node-add-install-prereqs-div',
    		    INSTALL_PREREQS_CHECKBOX = '#hpsum-node-add-install-prereqs-checkbox',
                INSTALL_PREREQS_WARNING_LABEL = '#hpsum-node-add-install-prereqs-warning',
                ILO_APPTOKEN_DIV = '#hpsum-node-add-app-token-div',
                ILO_APP_TOKEN_CHECKBOX = '#hpsum-node-add-app-token-checkbox',
                ILO_APP_TOKEN_WARNING_LABEL = '#hpsum-node-add-app-token-warning',
                BASELINE_COMBOBOX = '#hpsum-node-add-baselines-search',
    	        ADDITIONAL_BASELINE_COMBOBOX = '#hpsum-node-add-hotfix-search';
				var MENU = '.hp-search-combo-menu';
		var HEADER = '.hp-header';
		var FOOTER = MENU + ' .hp-footer';
           		
    		function AddView(){
    			
    			var formStateView = new FormStateView(),
					useCurrentCredentials = false,
    				useSudoCredentials = false,
					useSuCredentials = false,
					partnerUsername='',
    				partnerPassword='',
    				baselines = '',
                    groups = '',
    				hotfixes='',
    				addInProgress = false,
					checkedVal = '',
					nodeSettingsDialog= null,
					localhostType='';
					var IpdialogContents;
					var nodeSettingsDialogContents;
    			    var node_details = [];
					var selected_nodes = [];
					var added_nodes = [];
					var searchInProgress = false;
					var ipRangeNodeAdd = false;
					var setAdd = false;
					var instAddLinuxSshkeyBrowse;
					var errorDetails = '';
					var ipv4Pattern = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; // check if it is ipv4 address.
					var ipv6Pattern = /^((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))?$/;  
					var isIpv4Range = false;
					var switchAuthenticationMode = $("input[name='hpsum-moonshot-switch-authentication']:checked").val();
					
    		function changeLocation(location) {
                	
              if (location.length > ROUTE_PREFIX.length) {
                   $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
               	} else {
                   $(PANELS).hpStackedPanels('setFirstPanel');
                }
            }
            
			function OnResize(){
				var BaseLineSearchWidth = ($(window).width() / 3);
				$(BASELINES).hpSearchCombo({getResults:getBaseline, width:BaseLineSearchWidth});
				$(HOTFIX).hpSearchCombo({ getResults: getHotfixes, width: BaseLineSearchWidth });
				$(SELECT_GROUP).hpSearchCombo({ getResults: getAllGroups, width: BaseLineSearchWidth });
			}
			
			function clearCredInput() {
				$(LINUX_SSH_KEY_FILE_USERNAME).val("");
				instAddLinuxSshkeyBrowse.setPanelText("");
				$(LINUX_SSH_KEY_FILE_PASSPHRASE).val("");		
				
				$(USERNAME).val("");
				$(PASSWORD).val("");
				
				$(ILO_USERNAME).val("");
				$(ILO_PASSWORD).val("");
			}
			
			function clearvCenterCredInput() {				
				$(VCENTERIPADDR).val("");
				$(VCENTERUSERNAME).val("");
				$(VCENTERPASSWORD).val("");
			}
			
			function hideLinuxCredSshKeyFileSelection() {
				$(LINUX_SSH_KEY_FILE_SELECTION).hide();
				$(NODE_CREDENTIAL_KEY).attr('checked',true);
				credentialsOptions('two');
				clearCredInput();	
			}
			
			function showLinuxCredSshKeyFileSelection() {
				$(LINUX_SSH_KEY_FILE_SELECTION).show();
				$(NODE_CREDENTIAL_KEY).attr('checked',true);
				credentialsOptions('two');
				clearCredInput();
			}
			
           function onItemAddSuccess(data) {
			  addInProgress = false;
			  var node_ip = trimString($(NAME));
			  if(data.hapi.hcode > 0)
			  {
			  onItemAddError(localizer.getString('hpsum.node.invalidIP'));
			  }
			  else if(data.hapi.hmessage == "The specified node" + " " + node_ip + " " + "already exists.")
			  {
			  onItemAddError(localizer.getString('hpsum.node.duplicateNode'));
			  }
			  else {
			  	/*groupPresenter.editItem({group_id: 'g1'}, {
					nodes : data.hapi.node_id
					}, {
						success : function(data) {},
						error : function(errorMessage) {}
				});
				
			 var userSelectedGroup = $(SELECT_GROUP).val();
			 if (!userSelectedGroup.match(/g1$/i)) {
				groupPresenter.editItem({group_id: $(SELECT_GROUP).val()}, {
					nodes : data.hapi.node_id
					}, {
						success : function(data) {},
						error : function(errorMessage) {}
				});
			}*/ 
				$(NODE_ADD_THROBBER).hide();
				$(ADD).removeAttr("disabled");
				$(ADD).attr('disabled', true);
			  	$(CANCEL).trigger('click');
			  }
           }
		   
		   function onItemsAddSuccess(data) {
			  addInProgress = false;
			  nodeSettingsDialog.cancel();
			  addselected();
			  formStateView.setMessage({summary: localizer.getString("hpsum.node.AddingNodesSuccessMsg"), status: 'ok', changing: false});
			}
			function onAddItemsSuccess(data) {
				formStateView.setMessage({summary: localizer.getString("hpsum.node.AddingNodesSuccessMsg"), status: 'ok', changing: false}); 				
				$(CANCEL).trigger('click');
		   }
		   function addselected()
           {
             var node_selected_id = '#hpsum-node-selected-table';
			 var node_tableid = '#hpsum-node-table';

             var node_selected_table =  $(node_selected_id).dataTable();
			 var node_table = $(node_tableid).dataTable();
			 
			 for( var j=0;j<selected_nodes.length;j++)
			 {
				added_nodes.push(selected_nodes[j]);
				node_details.pop(selected_nodes[j]);				
			 }
			 if(node_selected_table.length != 0)
				node_selected_table.fnClearTable();
             node_selected_table.fnAddData(added_nodes); 
			 				
			 selected_nodes = [];
			 
			 var nNodes = node_table.fnGetNodes( );
			 var aRow = new Array();
			 for( var i=0;i<nNodes.length;i++)
			 {
				if ( $(nNodes[i]).hasClass('hp-selected') ) 
				{					
					aRow.push($(nNodes[i]).closest('tr')[0]);
				}
			 }
			 
			 for( var j=0;j<aRow.length;j++)
			 {
				node_table.fnDeleteRow(aRow[j]);
			 }
			 nNodes = node_table.fnGetNodes( );
			 
			 $(APPLY_SETTINGS_BUTTON).attr("disabled","disabled");
            }
		   
		   
		   function onItemsAddError(data) {			                
				reset();			  
				addInProgress = false;
				// ASSIGN ERROR MESSAGE TO ERROR FormStateView
				if(data != undefined && data.hapi.nodes.hasOwnProperty("node"))
				{	
					var errorDetails = '';
					for(var nodeCount =0; nodeCount < data.hapi.nodes.node.length; nodeCount++)
					{
						if(data.hapi.nodes.node[nodeCount].exists)
						{
							errorDetails += '<p style="margin-left:20px">' + "\n" + "For " + data.hapi.nodes.node[nodeCount].ip + " : " + data.hapi.nodes.node[nodeCount].hmessage + '</p>';
						}
					}
					
					formStateView.setMessage({
						summary: localizer.getString("hpsum.node.addnodesError"),
						status: 'error',
						changing: false,
						details: errorDetails});				
				}
           }
           
           function onTypeEdit(){
           		$(TYPEERR).hide();
            	$(TYPE).removeClass("hp-error");
            	$(TYPE).off('change', onTypeEdit);
           }
		   function showNodeAddType(){
		   formStateView.reset();
		   if($(NODE_ADD_TYPE).val().toLowerCase().match(/addSingleNode/i))
		   {
		   $(ADD_SINGLE_NODE).show();
		   $(ADD_FIND_NODE).hide();
		   $(TYPE).selectBox('value', "selectType");
		   $(NODE_ADD_TYPE).selectBox('value', "addSingleNode");
		   $(ADD_BASELINE).show();
		   $(ADD_CREDENTIALS).show();
		   $(ADD_GROUP).show();
		   $(ADD).show();
		   $(RESET).show();
		   $(VCENTERPANEL).hide();
		   }
		   else if($(NODE_ADD_TYPE).val().toLowerCase().match(/findNode/i))
		   {
		   $(ADD_SINGLE_NODE).hide();
		   $(ADD_BASELINE).hide();
		   $(ADD_ALREADYEXISTS).hide();
		   $(ADD_CREDENTIALS).hide();
		   $(LINUX_CRED_PANEL).hide();
		   hideLinuxCredSshKeyFileSelection();
		   $(PARTNER_CRED_PANEL).hide();
		   $(ADD_GROUP).hide();
		   $(MOONSHOT_ADD_CREDENTIALS).hide();
		   $(ADD_FIND_NODE).show();
		   $(ADD).hide();
		   $(RESET).hide();
		   $(GEN10_ILO_CRED_PANEL).hide();
		   $(ILO_CRED_LABEL).hide();
		   $(ILO_CREDENTIALS_NOTE).hide();
		   }
		   }

            
    	   /* function to show or hide CHIF installation option in add node page */
		   function showhidePreReqsOption() {
		       var curNodeSelectionType = $(TYPE).val().toLowerCase();
		       /* show the install check box ony where node type selected is either WINDOWS/LINUX or UNKNOWN */
		       if (curNodeSelectionType.match(/windows|linux|ilo|unknown/i)) {
		           $(INSTALL_PREREQS_PANEL).show();
		           $(INSTALL_PREREQS_WARNING_LABEL).show();
		       }
		       else {
		           $(INSTALL_PREREQS_PANEL).hide();
		       }
		   }

    	   /* function to show or hide App token creation option in add node page */
		   function showhideAppTokenOption() {
		       var curNodeSelectionType = $(TYPE).val().toLowerCase();
		       /* show the install check box ony where node type selected is either WINDOWS/LINUX or UNKNOWN */
		       if (curNodeSelectionType.match(/windows|linux|unknown/i)) {
		           $(ILO_APPTOKEN_DIV).show();
		           $(ILO_APP_TOKEN_WARNING_LABEL).show();
		       }
		       else {
		           $(ILO_APPTOKEN_DIV).hide();
		       }
		   }

           function showPartnerOptions() {
           	$('> li:visible' , PANELS).last().css("padding-bottom", "0px");
            	//$(TYPE).unbind('mousedown', onTypeEdit);
            	$(ADD_CREDENTIALS).show();
            	var nodeType = $(TYPE).val().toLowerCase();
            	
            	//following are applicable only for VC node
            	//so by default do not show these messages
            	$(VC_OPTIONS).html("");
            	$(PARTNER_IP_OPTMSG_LABEL).html("");
            	//
            	//Show partner IP field by default, only for VC node this is hidden
            	$(PARTNER_IP_LIST).show();
            	
            	showhidePreReqsOption();
            	if(nodeType.match(/Windows/i)) {
					$(ADD_ALREADYEXISTS).show();
					$(NODE_CREDENTIAL_CURRENT).show();
					$(NODE_CREDENTIAL_KEY).show();
				}
				else if (nodeType.match(/Linux/i) || nodeType.match(/hpux/i)) {
					$(ADD_ALREADYEXISTS).show();
					$(NODE_CREDENTIAL_CURRENT).hide();
					$(NODE_CREDENTIAL_KEY).show();
				}
            	else {
            		$(ADD_ALREADYEXISTS).hide();
					$(NODE_CREDENTIAL_CURRENT).hide();
					$(NODE_CREDENTIAL_KEY).hide();
				}
            	
				var CredentialTypeSelected = $("input[name='hpsum-node-credential']:checked").val(); // CredentialTypeSelected to check which radio option is selected. 
				if(nodeType.match(/vmware/i)){
						$(NODE_CREDENTIAL_KEY).show();
						clearvCenterCredInput();
            			$(VCENTERPANEL).show();	
						if(CredentialTypeSelected == 'four'){
							$(ENTER_VCENTER_CRED).show();
							$(ENTER_CRED).hide();
						}
						else if(CredentialTypeSelected == 'two'){
							$(ENTER_CRED).show();
						}
						else{
							$(ENTER_CRED).hide();
						}
				} else{
						$(VCENTERPANEL).hide();		
						$(ENTER_VCENTER_CRED).hide();
						if(CredentialTypeSelected == 'two'){
							$(ENTER_CRED).show();
						}
						else {
							$(ENTER_CRED).hide();
						}
				}
            	
				
				if(nodeType.match(/Linux|hpux/i)) {
					showLinuxCredSshKeyFileSelection();
                    if(localhostType.match(/Windows/i)) {
                        $(NODE_CREDENTIAL_KEY_LABEL).html(localizer.getString('hpsum.oneTouchUpdate.enterCredentials'));
                    }
                } else {
					hideLinuxCredSshKeyFileSelection();
                    $(NODE_CREDENTIAL_KEY_LABEL).html(localizer.getString('hpsum.common.enterAdministratorCredentials'));
                }
							
				if(nodeType.match(/Linux|hpux/i)) {
					$(LINUX_CRED_PANEL).css({"display":""});
					$(LINUXUSERNAME).removeClass("hp-error");
					$(LINUXPASSWORD).removeClass("hp-error");
					$(LINUXUSERNAME_ERR).hide();
					$(LINUXPASSWORD_ERR).hide();
					$(ENTER_LINUX_CRED).hide();
					
					var value = $("input[name='hpsum-node-credential']:checked").val();
					
					if(value == 'one'){
						$('input[name="hpsum-linux-node-credential"]').attr("disabled",true);
						$('#hpsum-linux-access-level-label').html(localizer.getString('hpsum.common.linuxcredentialsApplicable'));
					}
					else {
						$('input[name="hpsum-linux-node-credential"]').attr("disabled",false);
						$('#hpsum-linux-access-level-label').html(localizer.getString('hpsum.common.linuxcredentials'));
					}
				}
				else
					$(LINUX_CRED_PANEL).css({"display":"none"});
            		
            	if(nodeType.match(/sas_switch/i) || nodeType.match(/vc/i) || nodeType.match(/pdu/i)) {
                    if(nodeType.match(/pdu/i)){
            				$(PARTNER_TYPE).html(localizer.getString('hpsum.common.PartnerIpduCredentials'));
            				$(PARTNER_IP_LABEL).html(localizer.getString('hpsum.common.PartnerIpduIP'));
            			}
						else if ($(TYPE).val().toLowerCase().match(/vc/i))
						{
						$(VC_OPTIONS).html(localizer.getString('hpsum.node.vcOptionsMsg'));
						$(PARTNER_TYPE).html(localizer.getString('hpsum.common.associatedOACredentials'));
            			$(PARTNER_IP_LABEL).html(localizer.getString('hpsum.common.associatedOAIp'));
            			$(PARTNER_IP_OPTMSG_LABEL).html(localizer.getString('hpsum.common.associatedOAIpOptMsg'));
            			$(PARTNER_IP_LIST).hide();
						}
            			else{
            				$(PARTNER_TYPE).html(localizer.getString('hpsum.common.associatedOACredentials'));
            				$(PARTNER_IP_LABEL).html(localizer.getString('hpsum.common.associatedOAIp'));
            				$(VC_OPTIONS).html("");
            				$(PARTNER_IP_LIST).hide();
            			}
            				
            			$(PARTNER_CRED_PANEL).css({"display":""});
            			$('input[name="hpsum-node-partner-credential"]').click(partnerCredentialsOptions);
            			partnerCredentialsOptions("one");
            		}
            	else
            		$(PARTNER_CRED_PANEL).css({"display":"none"});
				
				if(nodeType.match(/vc/i) ||	nodeType.match(/sas_switch/i) || nodeType.match(/enclosure/i) ||
				    nodeType.match(/switch/i) || nodeType.match(/ilo/i) ) 
				{
							$(".hpsum-add-assoc-nodes").show();
				}
            	else {	
						$(".hpsum-add-assoc-nodes").hide();
				}
            
            				
				//Moonshot
				if(nodeType.match(/moonshot/i)) {
				    $(MOONSHOT_ADD_CREDENTIALS).show();
				    $('.moonshot').removeClass('hp-error');
				    $('.moonshot-errmsg').hide();
				    $(ADD_CREDENTIALS).hide();
				} else {
				    $(MOONSHOT_ADD_CREDENTIALS).hide();
           }
				
				if(nodeType.match(/Linux|Windows|Unknown/i))
				{
					$(GEN10_ILO_CRED_PANEL).show();
					$(ILO_CRED_LABEL).show();
					showhideAppTokenOption();
				}
				else
				{
					$(GEN10_ILO_CRED_PANEL).hide();	
					$(ILO_CRED_LABEL).hide();
					$(ILO_APPTOKEN_DIV).hide();
				}
				
				if(nodeType.match(/ilo/i))
				{
					$(ILO_CREDENTIALS_NOTE).show();
				}
				else
				{
					$(ILO_CREDENTIALS_NOTE).hide();
				}
				
           $(PANELS).hpStackedPanels("reset");
           }
           
		   function linuxCredentialOptions(){
				useSudoCredentials= false;
				useSuCredentials = false;
				$(ENTER_LINUX_CRED).hide();
				checkedVal = $('input[name="hpsum-linux-node-credential"]:checked').val();
				if(checkedVal == "one"){					
					useSudoCredentials =true;
				}
				if(checkedVal == "two"){
					useSuCredentials = true;
					$(ENTER_LINUX_CRED).show();
					
				}
				
            }
			
           function partnerCredentialsOptions(value)
           {
           	    if(value.target)
            		value = value.target.value;
            	if(value == "one"){
            		$(PARTNER_ENTER_CRED).hide();
            		partnerUsername= $(USERNAME).val();
            		partnerPassword= $(PASSWORD).val();
            		//useCurrentCredentials =true;
            	}
            	if(value == "two"){
            		$(PARTNER_ENTER_CRED).show();
            	}
           	
           }

    		    //replace(/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces
    		    //replace(/[ ]{2,}/gi, " "). // replaces multiple spaces with one space 
    		    //replace(/\n +/, "\n"); // Removes spaces after newlines
           function trimString(el) {
               el[0].value = el[0].value.replace(/(^\s*)|(\s*$)/gi, "").replace(/[ ]{2,}/gi, " ").replace(/\n +/, "\n"); // Removes spaces after newlines
               return el[0].value;
           }
           
           function onNameEdit(){
           		$(NAMEERR).hide();
            	$(NAME).removeClass("hp-error");
            	$(NAME).unbind('keyup',onNameEdit);
           }
           
          function onItemAddError(msg) {	
              addInProgress = false;
              $(NAMEERR).text(msg);
              $(NAME).addClass("hp-error");
              $(NAMEERR).show();
              $('#hp-node-name-error-divid').removeClass("hp-empty");
              $(NAME).keyup(onNameEdit);
			  $(NODE_ADD_THROBBER).hide();
			  $(ADD).attr('disabled', false);;
           }

           
          function reset() {
				formStateView.reset();
                addInProgress = false;
				searchInProgress = false;
				useSudoCredentials = false,
				useSuCredentials = false,
                $(NAMEERR).hide();
                $(".hpsum-add-assoc-nodes").hide();
				$(ADD_ALREADYEXISTS).hide();
				
				$(USERNAME_ERR).hide();
				$(PASSWORD_ERR).hide();
				
				$(VCENTERIPADDR_ERR).hide();
				$(VCENTERUSERNAME_ERR).hide();
				$(VCENTERPASSWORD_ERR).hide();		
				
				$(PARTNER_USERNAME_ERR).hide();
				$(PARTNER_PASSWORD_ERR).hide();
		
                $(PARTNER_CRED_PANEL).css({"display":"none"});
				$(LINUX_CRED_PANEL).css({"display":"none"});
				hideLinuxCredSshKeyFileSelection();
            	$(NAME).removeClass("hp-error");
				$(NODESETTINGS_USERNAME).removeClass("hp-error");
            	$(NODESETTINGS_PASSWORD).removeClass("hp-error");
            	$(NODESETTINGS_USERNAME_ERR).hide();
            	$(NODESETTINGS_PASSWORD_ERR).hide();
            	$(TYPE).selectBox('value', "selectType");
            	showhidePreReqsOption();
            	showhideAppTokenOption();
				$(NODE_ADD_TYPE).selectBox('value', "addSingleNode");
				$(ADD_SINGLE_NODE).show();
				$(ADD_FIND_NODE).hide();
				showNodeAddType();
            	credentialsOptions('two');
				$(ADD_CREDENTIALS).show();
				$(BASELINES).html('');
				$(HOTFIX).html('');
				$(SELECT_GROUP).html('');
				$('.hp-close').css("display","none");
				$(BASELINE_INPUT).removeClass("hp-error");
				$(HOTFIX_INPUT).removeClass("hp-error");
				$(BASELINE_INPUT_ERR).hide();
				$(HOTFIX_INPUT_ERR).hide();
				$(MOONSHOT_ADD_CREDENTIALS).hide();
				$(MOONSHOT_SWITCHB_CREDENTIALS).hide();
				$(MOONSHOT_SWITCH_CREDENTIALS).hide();
				$(NODE_CREDENTIAL_CURRENT).hide();
				$(NODE_CREDENTIAL_KEY).hide();
				$(MOONSHOT_SWITCH_CREDENTIALS_TEXT_BOX).attr('disabled', false);
				$(MOONSHOT_SWITCHB_CREDENTIALS_TEXT_BOX).attr('disabled', false);
            }
            
            function validate()
            {
            	var returnValue;
            	var validatename, validatetype, validatebaseline, validatecredentials, validatesudocredentials;
            	validatename = validateName(trimString($(NAME)));
				validatetype = validateType();
				validatebaseline = validateBaseline();
				validatecredentials = validateCredentials();
				validatesudocredentials = validateSudoCredentials();
				
            	if($(TYPE).val().match(/Linux/i))
				{
					returnValue = validatename && validatetype && validatebaseline && validatecredentials && validatesudocredentials;
				}
				else 
				{

					returnValue = validatename && validatetype && validatebaseline && validatecredentials;
				}
						
				return returnValue;	
            }
			
			
			
			function initnodeSettingsDialog(selected_nodes)
			{
				$(NODESETTINGS_RESET).click();
				//reset.call();
				var useCurrentCredentials = false;
				nodeSettingsDialog =  new DialogView({contents: nodeSettingsDialogContents,
                	position : "center", 
					cancel: function () { }
                    });
					
				presenter.getAllBaselines({
           					success:getBaselinesSuccess,
           					error: getBaselinesError
           			});
                                  
				$(NODESETTINGS_ADD, nodeSettingsDialogContents).live('click', function(ev) {
						var node_tableid = '#hpsum-node-table';
						var node_table = $(node_tableid).dataTable();
						var nNodes = node_table.fnGetNodes( );
						var aRow = [];
						for( var i=0;i<nNodes.length;i++)
						{
							if ( $(nNodes[i]).hasClass('hp-selected') ) 
							{
								var nodedetails = node_table.fnGetData( nNodes[i] );
								aRow.push(nodedetails);
							}
						}
                   		onNodeSettingsAddItem.call(this,aRow);
                    	ev.preventDefault();
				});
				
				$(NODESETTINGS_CANCEL,nodeSettingsDialogContents).on('click', function () {
                    nodeSettingsDialog.cancel();
                });
				
				//set width for baseline and additional package search box.
				OnResize();
				$(NODESETTINGS_RESET, nodeSettingsDialogContents).live('click', function() {
					reset.call();
				});
				$('input[name="hpsum-node-settings-credential"]').click(nodesettingscredentialsOptions);
            	$(ADD_ALREADYEXISTS).hide();
				$('#hpsum-node-settings-credential-key').attr('checked',true);
            	nodesettingscredentialsOptions('two');
				$(NODESETTINGS_USERNAME).val('');
            	$(NODESETTINGS_PASSWORD).val('');
            	$(NODESETTINGS_USERNAME).removeClass("hp-error");
            	$(NODESETTINGS_PASSWORD).removeClass("hp-error");
            	$(NODESETTINGS_USERNAME_ERR).hide();
            	$(NODESETTINGS_PASSWORD_ERR).hide();
				$(BASELINE_INPUT).val('');
				$(HOTFIX_INPUT).val('');
				$(BASELINE_INPUT).removeClass("hp-error");
				$(HOTFIX_INPUT).removeClass("hp-error");
				$(BASELINE_INPUT_ERR).hide();
				$(HOTFIX_INPUT_ERR).hide();
				$('#hpsum-node-settings-close', nodeSettingsDialogContents).click(function () {
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                });
				 
			}
            
            function validateType(){
                var type = $(TYPE).val();
            	if(type.match(/SelectType/i)){
					errorDetails += '<p style="margin-left:20px">' + localizer.getString("hpsum.node.nodeTypeErrorMessage") + '</p>';
            	    $(TYPEERR).text(" \t " + localizer.getString('hpsum.node.nodeTypeErrorMessage'));
            		$(TYPE).on('change', onTypeEdit);
            		$(TYPEERR).show();
            		return false;
            	}
            	return true;	
            }
            
			function validateBaseline(){
					var errorFound = false;
					if($(BASELINES).val()){
						var baselinedetails = presenter.getBaselineDetailsforId($(BASELINES).val());
						if(!baselinedetails){
							errorFound = true;
							$(BASELINE_INPUT_ERR).text(localizer.getString('hpsum.node.invalidBaseline'));	
							$(BASELINE_INPUT).addClass("hp-error");
							$(BASELINE_INPUT_ERR).show();
							$(BASELINE_INPUT).unbind('keyup').bind('keyup',function(){
								$(BASELINE_INPUT_ERR).hide();
								$(BASELINE_INPUT).removeClass('hp-error');
							});
						}
					}
					if($(HOTFIX).val()){
						var baselinedetails = presenter.getBaselineDetailsforId($(HOTFIX).val());
						if(!baselinedetails){
							errorFound = true;
							$('#hpsum-node-add-msg-container').removeClass("hp-empty");
							$(HOTFIX_INPUT_ERR).text(localizer.getString('hpsum.node.invalidAdtPackage'));	
							$(HOTFIX_INPUT).addClass("hp-error");
							$(HOTFIX_INPUT_ERR).show();
							$(HOTFIX_INPUT).unbind('keyup').bind('keyup',function(){
								$(HOTFIX_INPUT_ERR).hide();
								$(HOTFIX_INPUT).removeClass('hp-error');
							});
						}
					}	
					// Return if the baseline or additional package is invalid
					if(errorFound)
						return false;
					else
						return true;
			}
			
            function validateCredentials(){
            	
            	var success = true;
            	
            	if($('input[name="hpsum-node-partner-credential"]:checked').val() == "two") {
            		if($(PARTNER_USERNAME).val() == ''){
            			$(PARTNER_USERNAME).addClass("hp-error");
	            		$(PARTNER_USERNAME_ERR).show();
	            		$(PARTNER_USERNAME).bind('keyup', function(){
	            			$(PARTNER_USERNAME_ERR).hide();
	            			$(PARTNER_USERNAME).removeClass('hp-error');
	            		});
	            		success= false;
            		}
            		
            		if($(PARTNER_PASSWORD).val() == ''){
	            		$(PARTNER_PASSWORD).addClass("hp-error");
	            		$(PARTNER_PASSWORD_ERR).show();
	            		$(PARTNER_PASSWORD).bind('keyup', function(){
	            			$(PARTNER_PASSWORD_ERR).hide();
	            			$(PARTNER_PASSWORD).removeClass('hp-error');
	            		}); 
	            		success= false;
                    }   
            	}
            	
            	if(success == false)
            		return success;
            	           
            	//Moonshot
            	if($(TYPE).val().match(/moonshot/i)) {
            	    if($('.moonshot').each(function() {
            	        if($(this).val() == '' && $(this).is(":visible")) {
            	           $(this).addClass("hp-error");
            	           var errID = "#" + $(this).attr('id') + "-err";
            	           $(errID).show();
            	           $(this).bind('keyup', function(){
            	               $(errID).hide();
            	               $(this).removeClass('hp-error'); 
            	           });
            	           success = false;
            	        }
            	    }));
            	} else {
            		var nodeType = $(TYPE).val().toLowerCase();
            		if($('input[name="hpsum-node-credential"]:checked').val() == "one")
            			success = true;
            		else if($('input[name="hpsum-node-credential"]:checked').val() == "two"){
		            	if($(USERNAME).val() == ''){
		            		$(USERNAME).addClass("hp-error");
		            		$(USERNAME_ERR).show();
		            		$(USERNAME).bind('keyup', function(){
		            			$(USERNAME_ERR).hide();
		            			$(USERNAME).removeClass('hp-error');
		            		});
		            		success= false;
		            	} 
			    //Since empty password is a valid configuration in iLO, hence same is supported for ILO targets
   			    if(!(nodeType.match(/ilo/i))) {
		            	if($(PASSWORD).val() == ''){

		            		$(PASSWORD).addClass("hp-error");
		            		$(PASSWORD_ERR).show();
		            		$(PASSWORD).bind('keyup', function(){
		            			$(PASSWORD_ERR).hide();
		            			$(PASSWORD).removeClass('hp-error');
		            		}); 
		            		success= false;
		        		}
				}
		        	} else if($('input[name="hpsum-node-credential"]:checked').val() == "three"){
						var sshKeyFile_username = $.trim($(LINUX_SSH_KEY_FILE_USERNAME).val());
						var sshKeyFile_location = $.trim(instAddLinuxSshkeyBrowse.getLocation()).split('\\').join('/');
						var sshKeyFile_passphrase = $.trim($(LINUX_SSH_KEY_FILE_PASSPHRASE).val());
						if(!sshKeyFile_username || !sshKeyFile_location || !sshKeyFile_passphrase) {
							if(!sshKeyFile_username){
								$(LINUX_SSH_KEY_FILE_USERNAME).addClass("hp-error");
								$(LINUX_SSH_KEY_FILE_USERNAME_ERR).show();
								$(LINUX_SSH_KEY_FILE_USERNAME).bind('keyup', function(){
									$(LINUX_SSH_KEY_FILE_USERNAME_ERR).hide();
									$(LINUX_SSH_KEY_FILE_USERNAME).removeClass('hp-error');
								});
								success= false;
							}   
							
							if(!sshKeyFile_location){
								$(LINUX_SSH_KEY_FILE_PATH).addClass("hp-error");
								$(LINUX_SSH_KEY_FILE_PATH_ERR).show();
								$(LINUX_SSH_KEY_FILE_PATH).bind('keyup', function(){
									$(LINUX_SSH_KEY_FILE_PATH_ERR).hide();
									$(LINUX_SSH_KEY_FILE_PATH).removeClass('hp-error');
								});
								$(LINUX_SSH_KEY_FILE_BROWSE_LOCATION).bind('click', function(){
									$(LINUX_SSH_KEY_FILE_PATH_ERR).hide();
									$(LINUX_SSH_KEY_FILE_PATH).removeClass('hp-error');
								});
								success= false;
							}
						}
					} else if($('input[name="hpsum-node-credential"]:checked').val() == "four"){
            			if($(VCENTERIPADDR).val() == ''){
		            		$(VCENTERIPADDR).addClass("hp-error");
		            		$(VCENTERIPADDR_ERR).show();
							$(VCENTERIPADDR_ERR).text(localizer.getString('hpsum.node.nodeNameErrorMessage'));
		            		$(VCENTERIPADDR).bind('keyup', function(){
		            			$(VCENTERIPADDR_ERR).hide();
		            			$(VCENTERIPADDR).removeClass('hp-error');
		            		});
		            		success= false;
		            	}
						else{ // validate ip address value.
							if(!validateVCenterIP($(VCENTERIPADDR).val())){
								$(VCENTERIPADDR).addClass("hp-error");
								$(VCENTERIPADDR_ERR).text(localizer.getString('hpsum.node.invalidIPV4orIPV6'));								
								$(VCENTERIPADDR_ERR).show();
								$(VCENTERIPADDR).bind('keyup', function(){
									$(VCENTERIPADDR_ERR).hide();
									$(VCENTERIPADDR).removeClass('hp-error');
								});
								success =  false;							
								}
						}
						if($(VCENTERUSERNAME).val() == ''){
		            		$(VCENTERUSERNAME).addClass("hp-error");
		            		$(VCENTERUSERNAME_ERR).show();
		            		$(VCENTERUSERNAME).bind('keyup', function(){
		            			$(VCENTERUSERNAME_ERR).hide();
		            			$(VCENTERUSERNAME).removeClass('hp-error');
		            		});
		            		success= false;
		            	}
		            	if($(VCENTERPASSWORD).val() == ''){
		            		$(VCENTERPASSWORD).addClass("hp-error");
		            		$(VCENTERPASSWORD_ERR).show();
		            		$(VCENTERPASSWORD).bind('keyup', function(){
		            			$(VCENTERPASSWORD_ERR).hide();
		            			$(VCENTERPASSWORD).removeClass('hp-error');
		            		}); 
		            		success= false;
		        		}
            		} else {
		            	if($(USERNAME).val() == ''){
		            		$(USERNAME).addClass("hp-error");
		            		$(USERNAME_ERR).show();
		            		$(USERNAME).bind('keyup', function(){
		            			$(USERNAME_ERR).hide();
		            			$(USERNAME).removeClass('hp-error');
		            		});
		            		success= false;
		            	}
		            	if($(PASSWORD).val() == ''){
		            		$(PASSWORD).addClass("hp-error");
		            		$(PASSWORD_ERR).show();
		            		$(PASSWORD).bind('keyup', function(){
		            			$(PASSWORD_ERR).hide();
		            			$(PASSWORD).removeClass('hp-error');
		            		}); 
		            		success= false;
		        		}
		        	}   
				}
				if(success == false) {
					errorDetails += '<p style="margin-left:20px">' + localizer.getString("hpsum.node.nodeCredentialsErrorMessage") + '</p>';
				}
            	
            	return success;
            }
            
		function validateVCenterIP(ipaddr){
			//test ipv4
			if(ipaddr == '0.0.0.0' | ipaddr == '255.255.255.255'){
            		return false;
            	}            	
            	if(ipaddr.match(ipv4Pattern)){
            		return true;
				}
            	else{            		
            		if(ipaddr.match(ipv6Pattern)){
            			return true;
					}
                    if(isDNSName(ipaddr)){
						return true;
					}
				}	
			return false;
		}
			
			function validateSudoCredentials(){
				var value = $('input[name="hpsum-linux-node-credential"]:checked').val();
				if((value == "one") || (value == "none") || (value == undefined))
            		return true;
            	var success = true;
            	if($(LINUXUSERNAME).val() == ''){
            		$(LINUXUSERNAME).addClass("hp-error");
            		$(LINUXUSERNAME_ERR).show();
            		$(LINUXUSERNAME).bind('keyup', function(){
            			$(LINUXUSERNAME_ERR).hide();
            			$(LINUXUSERNAME).removeClass('hp-error');
            		});
            		success = false;
            	}
            	if($(LINUXPASSWORD).val() == ''){
            		$(LINUXPASSWORD).addClass("hp-error");
            		$(LINUXPASSWORD_ERR).show();
            		$(LINUXPASSWORD).bind('keyup', function(){
            			$(LINUXPASSWORD_ERR).hide();
            			$(LINUXPASSWORD).removeClass('hp-error');
            		}); 
            		success= false;
            	}
            	return success;
			}
	    
	    	function validateNodeSettingsCredentials(){
            	if($('input[name="hpsum-node-settings-credential"]:checked').val() == "one")
            		return true;
            	var success = true;
            	if($(NODESETTINGS_USERNAME).val() == ''){
            		$(NODESETTINGS_USERNAME).addClass("hp-error");
            		$(NODESETTINGS_USERNAME_ERR).show();
            		$(NODESETTINGS_USERNAME).bind('keyup', function(){
            			$(NODESETTINGS_USERNAME_ERR).hide();
            			$(NODESETTINGS_USERNAME).removeClass('hp-error');
            		});
            		success= false;
            	}
            	if($(NODESETTINGS_PASSWORD).val() == ''){
            		$(NODESETTINGS_PASSWORD).addClass("hp-error");
            		$(NODESETTINGS_PASSWORD_ERR).show();
            		$(NODESETTINGS_PASSWORD).bind('keyup', function(){
            			$(NODESETTINGS_PASSWORD_ERR).hide();
            			$(NODESETTINGS_PASSWORD).removeClass('hp-error');
            		}); 
            		success= false;
            	}
            	return success;
            }
			
            function validateIPHiphenRange(ip, errorstr){
				var iprange = ip.split("-");
				if(iprange.length>2){
					errorstr.val = localizer.getString('hpsum.node.iprangeError1');
					return false;
				}
				
				 // if it is ipv4 address take index of .            	
				
            	if(iprange[0].match(ipv4Pattern) && iprange[1].match(ipv4Pattern))
				{
					isIpv4Range = true;            		
				}
				else if(iprange[0].match(ipv6Pattern) && iprange[1].match(ipv6Pattern))
				{
					isIpv4Range = false;
				}
				else 
				{
					errorstr.val = localizer.getString('hpsum.node.iprangeError5');
					return false;
				}
				var strtIP = getEndOfIP(iprange[0]);
				var endIP = getEndOfIP(iprange[1]);;
				
				if(strtIP==endIP){
					errorstr.val = localizer.getString('hpsum.node.iprangeError2');
					return false;
				}
				else if(strtIP>endIP){
					errorstr.val = localizer.getString('hpsum.node.iprangeError3');
					return false;
				}
				var firstThreeSubnetStrtIP = iprange[0].substring(0, iprange[0].lastIndexOf("."));
				var firstThreeSubnetEndIP = iprange[1].substring(0, iprange[1].lastIndexOf("."));
				if(firstThreeSubnetStrtIP != firstThreeSubnetEndIP){
					errorstr.val = localizer.getString('hpsum.node.iprangeError4');
					return false;
				}
				for(var j=0;j<iprange.length;j++){
					if(!validateName(iprange[j]))
					return false;
				}
				return true;
			}
            
			function validateName(ip){			
				if(ip == ''){
					onItemAddError(localizer.getString('hpsum.node.nodeNameErrorMessage'));
					errorDetails += '<p style="margin-left:20px">' + localizer.getString("hpsum.node.nodeNameErrorMessage") + '</p>';
					return false;
				}
				
				if(ip.indexOf(",")>=0 || ip.indexOf("-")>=0)//IP range has been entered
				{
					ipRangeNodeAdd = true;
					ip=ip.replace(/ /g,'');
					var ips = ip.split(",");
					for(var i=0;i<ips.length;i++){
						if(ips[i].indexOf("-")>=0){
							var errorstr={};
							if(!validateIPHiphenRange(ips[i], errorstr) && !isDNSName(ips[i])) {
								onItemAddError(errorstr.val);
								return false;
							}
						}
						else if(!validateName(ips[i])) {
							return false;
						}
					}
					
					return true;
				}
				
				
            	if(ip.toLowerCase() == 'localhost')
            		return true;
            		//ipv4 match
            	if(ip == '0.0.0.0' | ip == '255.255.255.255'){
            		onItemAddError(localizer.getString('hpsum.node.ipCannotBe') + ' ' + ip);
            		return false;
            	}
            	
            	if(ip.match(ipv4Pattern))
            		return true;
            	else{
            		if(ip.match(ipv6Pattern))
            			return true;
                    var patt = /^[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)*\.([a-zA-Z]{2,4})$/;
                    //FQDN match
                    if(ip.match(patt))
                        return true;                           
            		else{
            			//check for unqualified domain name or netbios hostname
            			var hostnamepatt = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";
            			if(ip.match(hostnamepatt))
                        	return true;
                        	
            			onItemAddError(localizer.getString('hpsum.node.notValidIpOrDns'));
            			return false;
            		}
            	}
            		
           }
           
           
           function computeIPHiphenRange(nodeIPs, ip)
			{
				var strtEndIP = ip.split("-");
				var tmp = [];
				tmp = findRange(strtEndIP);
				var length = nodeIPs.length+tmp.length;
				var k=0;
				for(var j=nodeIPs.length; j<length; j++)
				nodeIPs[j]=tmp[k++];
				return nodeIPs;
			}		   
		function onAddItem() {
            $(ADD).attr("disabled", true);
			formStateView.reset();
			errorDetails = '';
        	if(validate()) {
                var nodeUsername = $(USERNAME).val();
                var nodePassword = $(PASSWORD).val();
            	var nodeType, assocnodeType='';
		var nodeIPs = [];
            	switch ($(TYPE).val().toLowerCase()){
            		case "vmware":
            				nodeType = 'vmware';
            				break;
            		case "enclosure":
            				nodeType = 'oa';
            				break;
					case "sdx":
            				nodeType = 'sdx';
            				break;
					case "sdflex":
            				nodeType = 'sdflex';
            				break;
					case "moonshot":
            				nodeType = 'moonshot';
            				break;
            		case "sas_switch":
            				nodeType = 'sas_switch';
            				assocnodeType = 'oa';
            				break;
            		case "switch":
            				nodeType = 'fc_switch';
            				break;
            		case "pdu":
            				nodeType = 'ipdu';
            				assocnodeType = 'ipdu';
            				break;
            		case "vc":
            				nodeType = 'virtual_connect';
            				assocnodeType  = 'oa';
            				break;
            		default:
            			nodeType = $(TYPE).val().toLowerCase();
            			break;
            	}
            	var baselineJson = [];
            	if(($(BASELINES).val() != '' ) && ($(HOTFIX).val() != '')){
					baselineJson.push($(BASELINES).val());
            		baselineJson.push($(HOTFIX).val());
            	}else if($(BASELINES).val() == ''){
            		baselineJson.push($(HOTFIX).val());
            	}else {
            		baselineJson.push($(BASELINES).val());
            	}
            	
                /* Code for CHIF installation option */
            	var bIsInstallPreReqsChecked = false;
            	if (nodeType.match(/windows|linux|ilo|unknown/i)) {
            	    bIsInstallPreReqsChecked = ($(INSTALL_PREREQS_CHECKBOX).is(':checked'));
            	}

            	var bIsAppTokenChecked = false;
            	if (nodeType.match(/windows|linux|unknown/i)) {
            	    bIsAppTokenChecked = $(ILO_APP_TOKEN_CHECKBOX).is(':checked');
            	}
            	
            	var assocTargetDetails = null;
            	var pUsername, pPassword;
				if(nodeType.match(/virtual_connect|sas_switch|ipdu/))
            	{
            		var value = $("input[name='hpsum-node-partner-credential']:checked").val(); 
            			if(value == "one"){
            				pUsername = $(USERNAME).val();
            				pPassword = $(PASSWORD).val();
            			}else {
            				pUsername = $(PARTNER_USERNAME).val();
            				pPassword = $(PARTNER_PASSWORD).val();
            			}
            			
            		assocTargetDetails = {
            				ip: $(PARTNER_IP_VALUE).val(),
            				type :assocnodeType,
            				username : pUsername,
            				password : pPassword
            		};
            	}
				
				var susername,spassword;
				var useSshKeyFile = false,
				    sshKeyFile_username = "",
				    sshKeyFile_location = "",
				    sshKeyFile_passphrase = "";
					
				if(nodeType.match(/Linux|hpux/i)){
					if(useSudoCredentials){
						susername = "";
						spassword = "";
					}
					else{
						susername = $(LINUXUSERNAME).val();
						spassword = $(LINUXPASSWORD).val();
					}
					
					if($('input[name="hpsum-node-credential"]:checked').val() == "three"){
						useSshKeyFile = true;
						sshKeyFile_username = $.trim($(LINUX_SSH_KEY_FILE_USERNAME).val());
						sshKeyFile_location = $.trim(instAddLinuxSshkeyBrowse.getLocation()).split('\\').join('/');
						sshKeyFile_passphrase = $.trim($(LINUX_SSH_KEY_FILE_PASSPHRASE).val());
				}
				}
				
				//Moonshot
				var switchAUser, switchAPassword, switchAEnablePwd;
				var switchBUser, switchBPassword, switchBEnablePwd;
				
				if(nodeType.match(/moonshot/i)) {
				    nodeUsername = $('#hpsum-moonshot-admin-credentials-username').val();
				    nodePassword = $('#hpsum-moonshot-admin-credentials-password').val();
					
				    if($(MOONSHOT_SWITCH_CREDENTIALS_NOT_SET).is(':checked')) {
						switchAUser = 'None';
						switchAPassword = '';
						switchAEnablePwd = '';
					} else if($(MOONSHOT_SWITCH_CREDENTIALS_PWD).is(':checked')) {
						switchAUser = '';
						switchAPassword = $(MOONSHOT_SWITCH_CREDENTIALS_PASSWORD).val();
						switchAEnablePwd = '';
					} else {
						switchAUser = $(MOONSHOT_SWITCH_CREDENTIALS_USERNAME).val();
						switchAPassword = $(MOONSHOT_SWITCH_CREDENTIALS_PASSWORD).val();
						switchAEnablePwd = $(MOONSHOT_SWITCH_CREDENTIALS_ENABLE_PASSWORD).val();
					}	
				    if($(MOONSHOT_SWITCH_SAME_CREDENTIALS).is(":checked")) {
				        switchBUser = switchAUser;
				        switchBPassword = switchAPassword;
				        switchBEnablePwd = switchAEnablePwd;
				    } else if($(MOONSHOT_SWITCHB_CREDENTIALS_NOT_SET).is(':checked')) {
						switchBUser = 'None';
						switchBPassword = '';
						switchBEnablePwd = '';
					} else if($(MOONSHOT_SWITCHB_CREDENTIALS_PWD).is(':checked')) {
						switchBUser = '';
						switchBPassword = $(MOONSHOT_SWITCHB_CREDENTIALS_PASSWORD).val();
						switchBEnablePwd = '';
					} else {
                        switchBUser = $(MOONSHOT_SWITCHB_CREDENTIALS_USERNAME).val();
                        switchBPassword = $(MOONSHOT_SWITCHB_CREDENTIALS_PASSWORD).val();
                        switchBEnablePwd = $(MOONSHOT_SWITCH_CREDENTIALS_ENABLE_PASSWORD).val();
				    }
				}
				if(nodeType.match(/Windows|Linux|Unknown/i))
				{
					var ilo_Username = $(ILO_USERNAME).val();
					var ilo_Password = $(ILO_PASSWORD).val();
				}
				//Vcenter credentials.. 
				var vcenteripaddress, vcenterusername, vcenterpassword, usevcenter;
				usevcenter = false;
				if(nodeType.match(/vmware/i)){					
					if($("input[name='hpsum-node-credential']:checked").val() == 'four'){
						usevcenter = true;
						vcenteripaddress = $(VCENTERIPADDR).val();
						vcenterusername = $(VCENTERUSERNAME).val();
						vcenterpassword = $(VCENTERPASSWORD).val();					
					}
				}
				
				
				//var auto_add_associated_nodes = $("input[name='hpsum-node-autoadd']:checked").val();
				var auto_add_assoc_nodes;
				if(nodeType.match(/virtual_connect|sas_switch|oa|fc_switch|ilo/i)){
					if($(ADD_ASSOC_NODES).is(':checked'))
						auto_add_assoc_nodes = true;
					else
						auto_add_assoc_nodes = false;
				}
            	
            	var node_skip = $("input[name='hpsum-node-active']:checked").val();
            	if(node_skip == "one")
            		node_skip = true;
            	else 
            		node_skip = false;
        		var node_object = {
						hapi:{
							nodes:{
								auto_inventory : false,
								node:[]
							}
						}
					};
			
        		var ipRange = trimString($(NAME)).toLowerCase();
				ipRange= ipRange.replace(/ /g,'');
				var ips = ipRange.split(",");
				for(var i=0;i<ips.length;i++){
					if(ips[i].indexOf("-")>=0) {
						var nodes = [];
						nodes = computeIPHiphenRange(nodes, ips[i]);
						if(nodes.length <= 0 && isDNSName(ips[i])) {
							nodeIPs.push(ips[i]);	
						}
						else
						{
							nodeIPs.push.apply(nodeIPs, nodes);	
						}
					}		
					else
						nodeIPs.push(ips[i]);
				}
				
				var baselineinfo = {
					baseline:[]
					};
				
				for (var tmp = 0; tmp < baselineJson.length; tmp++) {
					if(baselineJson[tmp]){
						var baselinedetails = presenter.getBaselineDetailsforId(baselineJson[tmp]);
						var baselinedata = {
							uri:baselinedetails.uri,
							bundle_name:baselinedetails.id
						};
						baselineinfo.baseline.push(baselinedata);
					}
				}		
					
				if(nodeIPs.length == 1)
				{
					$(ADD).attr("disabled", "disabled");
					$(NODE_ADD_THROBBER).show();
					presenter.getAllNodes({
                            success: function(data){
									var nodeExists = false;
									for (var nodeid=0; nodeid<data.hapi.output_data.nodes.node.length; nodeid++) {
										if(data.hapi.output_data.nodes.node[nodeid].node_name == nodeIPs){
											nodeExists = true;
											onItemAddError(localizer.getString('hpsum.node.duplicateNode'));
											break;
										}	
									}
									if(nodeExists == false){
										presenter.addItem({
												category: nodeType,
												name: trimString($(NAME)).toLowerCase(),
												description: $(DESC).val(),
												status: 'Init',
												moonshot_switch_credentials: {
													switch_username: switchAUser,
													switch_password: switchAPassword,
													switch_enable: switchAEnablePwd,
													switchb_username: switchBUser,
													switchb_password: switchBPassword,
													switchb_enable: switchBEnablePwd
												},
												username: nodeUsername,
												password: nodePassword,																								
												ilo_username : ilo_Username,
												ilo_password: ilo_Password,
												skip_apptoken: !bIsAppTokenChecked,
												group: $(SELECT_GROUP).val(),
												su_username: susername,
												su_password: spassword,
												use_sudo: useSudoCredentials,
												use_sshkeyfile: useSshKeyFile,
												sshkeyfile_username: sshKeyFile_username,
												sshkeyfile_location: sshKeyFile_location,
												sshkeyfile_passphrase: sshKeyFile_passphrase,
												baseline: baselineJson,
												associated_node:assocTargetDetails,
												use_current_credentials : useCurrentCredentials,												
												use_vcenter: usevcenter,
												vcenter_ip: vcenteripaddress,
												vcenter_username: vcenterusername,
												vcenter_password: vcenterpassword,
												stateDetails: null,
												node_skip: node_skip,
                                                skip_prereqs : (!bIsInstallPreReqsChecked),
												auto_add_assoc_nodes: auto_add_assoc_nodes,
												uri:null,
												phase: null,
												index:null,
												}, true,{
													success : onItemAddSuccess,
													error : onItemAddError
											});
									}
							},
							error : function() {
							}
						});
				} else {
					for (var i = 0; i < nodeIPs.length; i++) {
						var node = {
							ip : nodeIPs[i],
							name: trimString($(NAME)).toLowerCase(),
							selected :true,
							baselines : baselineinfo,
							group: $(SELECT_GROUP).val(),
							description: $(DESC).val(),
							type: nodeType,
							category: nodeType,
							uri:null,
							phase: null,
							index:null,
							associated_node:assocTargetDetails,
							stateDetails: null,
							node_skip: node_skip,
							skip_prereqs: (!bIsInstallPreReqsChecked),
							authentication :{
								username : nodeUsername,
								password : nodePassword,
								use_current_credentials : useCurrentCredentials,
								use_sshkeyfile: useSshKeyFile,
								sshkeyfile_username: sshKeyFile_username,
								sshkeyfile_location: sshKeyFile_location,
								sshkeyfile_passphrase: sshKeyFile_passphrase,
								use_vcenter: usevcenter,
								vcenter_ip: vcenteripaddress,
								vcenter_username: vcenterusername,
								vcenter_password: vcenterpassword,
								ilo_username: ilo_Username,
								ilo_password: ilo_Password,
								linux : {
									user_with_privileges: susername,
									password: spassword,
									use_sudo: useSudoCredentials,
									use_su : useSuCredentials								
								},
								auto_add_assoc_nodes : auto_add_assoc_nodes
							},
							skip_apptoken: !bIsAppTokenChecked
						};  
						node_object.hapi.nodes.node.push(node);
					}
					
				  if(! addInProgress) {
						addInProgress = true;
						formStateView.setMessage({summary: localizer.getString("hpsum.node.AddingNodesMsg"), status: 'unknown', changing: true});
						presenter.addItems(node_object, true, {
								success : onAddItemsSuccess,
								error : onItemsAddError
						});                        
						}
					}
				}
				else 
				{
					formStateView.setMessage({
                                summary: localizer.getString("hpsum.node.validationErrorMsg"),
                                status: 'error',
                                details: errorDetails});
					$(ADD).attr('disabled', false);

				}
    		}	
    		
			function getEndOfIP(ipaddr)
			{
				var endIP = 0;				
            	if(isIpv4Range)
				{
					endIP = parseInt(ipaddr.substring(ipaddr.lastIndexOf(".")+1));
				}
				else 
				{
					endIP = parseInt(ipaddr.substring(ipaddr.lastIndexOf(":")+1));
				}
				return endIP;
			}
			function findRange(strtEndIP){
				var range = [], j=0;
				var strtIP = getEndOfIP(strtEndIP[0]);
				var endIP = getEndOfIP(strtEndIP[1]);
				var firstThreeSubnet = 0;
				var splitChar = ".";
				if(isIpv4Range)
				{
					firstThreeSubnet = strtEndIP[0].substring(0, strtEndIP[0].lastIndexOf("."));
				}
				else
				{
					firstThreeSubnet = strtEndIP[0].substring(0, strtEndIP[0].lastIndexOf(":"));
					splitChar = ":";
				}
				
				for(var i = strtIP; i<=endIP; i++)
				{
					range[j++] = firstThreeSubnet + splitChar + i;
				}
				return range;
			}
			
			function onNodeSettingsAddItem(selected_nodes) {
        	if(validateNodeSettingsCredentials()){
				var node_object = {
						hapi:{
							nodes:{
								node:[]
							}
						}
					};
            	var baselineJson = [];
            	if(($(NODESETTINGS_BASELINE).val() != '' ) && ($(NODESETTINGS_HOTFIX).val() != '')){
					baselineJson.push($(NODESETTINGS_BASELINE).val());
            		baselineJson.push($(NODESETTINGS_HOTFIX).val());
            	}else if($(NODESETTINGS_BASELINE).val() == ''){
            		baselineJson.push($(NODESETTINGS_HOTFIX).val());
            	}else {
            		baselineJson.push($(BASELINES).val());
            	}

				var baselineinfo = {
						baseline:[]
						};
				for (var tmp = 0; tmp < baselineJson.length; tmp++) {
					if(baselineJson[tmp]){
						var baselinedetails = presenter.getBaselineDetailsforId(baselineJson[tmp]);
						var baselinedata = {
								uri:baselinedetails.uri,
								bundle_name:baselinedetails.id
							};
						baselineinfo.baseline.push(baselinedata);
					}
				}
            
				for (var i = 0; i < selected_nodes.length; i++) {
					var node = {
						ip : selected_nodes[i].node_ip,
						selected :true,
						baselines : baselineinfo,
						authentication :{
							username : $(NODESETTINGS_USERNAME).val(),
							password : $(NODESETTINGS_PASSWORD).val(),
							use_current_credentials : useCurrentCredentials,
							auto_add_assoc_nodes : false
						}
					};  
					node_object.hapi.nodes.node.push(node);

				}

				if(! addInProgress) {
              		addInProgress = true;
                    presenter.addItems(node_object, true, {
                        	success : onItemsAddSuccess,
                        	error : onItemsAddError
                    });
                        
                    }
				}

    		}

    		
            function getBaseline(string, handlers, count, start){
            	var results=baselines;
            		
            		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-add-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-add-hotfix-search-item').find('.hp-search-combo-menu').hide();
						$(HEADER).hide();
					}
          	}

          	function getAllGroups(string, handlers, count, start) {
          	    var results = groups;
          	    if (string && string.length > 0) {
          	        results =
                       $.grep(groups, 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 credentialsOptions(value){
				$(ENTER_CRED).hide();
				$(LINUX_SSH_KEY_FILE_PANEL).hide();
				clearCredInput();
				clearvCenterCredInput();
	    		useCurrentCredentials= false;
				$(ENTER_VCENTER_CRED).hide();
				
          		if(value.target)
            		value = value.target.value;
            	if(value == "one"){
            		useCurrentCredentials =true;
            		if($(TYPE).val().toLowerCase().match(/Linux/i))
            		{
            			$('input[name="hpsum-linux-node-credential"]').attr("disabled",true);
            			$('#hpsum-linux-access-level-label').html(localizer.getString('hpsum.common.linuxcredentialsApplicable'));
            		}
            	} else if(value == "two"){
            		$(ENTER_CRED).show();
            		$(USERNAME).removeClass("hp-error");
            		$(PASSWORD).removeClass("hp-error");
            		if($(TYPE).val().toLowerCase().match(/Linux/i))
            		{
            			$('input[name="hpsum-linux-node-credential"]').attr("disabled",false);
            			$('#hpsum-linux-access-level-label').html(localizer.getString('hpsum.common.linuxcredentials'));
            		}
            	} else if(value == "three"){
					$(LINUX_SSH_KEY_FILE_PANEL).show();
					$(LINUX_SSH_KEY_FILE_USERNAME).removeClass("hp-error");
					instAddLinuxSshkeyBrowse.removeInputClass("hp-error");
					$(LINUX_SSH_KEY_FILE_USERNAME_ERR).hide();
					$(LINUX_SSH_KEY_FILE_PATH_ERR).hide();
            	} else if(value == "four"){
            		
					$(ENTER_VCENTER_CRED).show();
					$(VCENTERIPADDR).removeClass("hp-error");
            		$(VCENTERUSERNAME).removeClass("hp-error");
            		$(VCENTERPASSWORD).removeClass("hp-error");
					$(VCENTERIPADDR_ERR).hide();
					$(VCENTERUSERNAME_ERR).hide();
					$(VCENTERPASSWORD_ERR).hide();
            		useCurrentCredentials= false;            		
            	}
            		
            }
            
			function nodesettingscredentialsOptions(value){
          		if(value.target)
            		value = value.target.value;
            	if(value == "one"){
            		$(NODESETTINGS_CRED).hide();
            		useCurrentCredentials =true;
            	}
            	if(value == "two"){
            		$(NODESETTINGS_CRED).show();
            		$(NODESETTINGS_USERNAME).removeClass("hp-error");
            		$(NODESETTINGS_PASSWORD).removeClass("hp-error");
            		useCurrentCredentials= false;
            	}
            		
            }
            
            function getlocalhostType(data) {
                for (var i=0; i< data.hapi.output_data.nodes.node.length; i++) {
                    if(data.hapi.output_data.nodes.node[i].node_name === 'localhost')
                    {
                        localhostType = data.hapi.output_data.nodes.node[i].type;
                    }
                }
            }

            function updateBaselineSelection(groupId)
            {
                var baselineItemId = '';
                $(BASELINES).hpSearchCombo('set', { id: '', name: '' });
                $(HOTFIX).hpSearchCombo('set', { id: '', name: '' });
                //find the baselineid of the group
                for (var gidx = 0; gidx < groups.length; gidx++)
                {
                    if (groups[gidx].id == groupId)
                        baselineItemId = groups[gidx].group_baselines;
                }
                var baseline = presenter.getBaselineDetailsforId(baselineItemId);
                if (baseline) {
                    if (baseline.name.match(/^Additional/i)) {
                        $(HOTFIX).hpSearchCombo('set', { id: baseline.id, name: baseline.name });
                    } else {
                        $(BASELINES).hpSearchCombo('set', { id: baseline.id, name: baseline.name });
                    }
                }                
            }
			
			function updateUserInterfaceForOEM()
			{
				var sessionDataHandlers = {
					success : function(data) {
						// if hcode is 0 then session is alive and set session cookies
						if(data.hapi.hcode == 0) {
							var mfg = data.hapi.manufacturer;
							if (mfg != "HP" && mfg != "HPE") {
								// Remove HPE only node types. OEM doesn't need them.
								$('#hpsum-node-type option[value="enclosure"]').remove();
								$('#hpsum-node-type option[value="sdx"]').remove();
								$('#hpsum-node-type option[value="sas_switch"]').remove();
								$('#hpsum-node-type option[value="switch"]').remove();
								$('#hpsum-node-type option[value="moonshot"]').remove();
								$('#hpsum-node-type option[value="vc"]').remove();
								$('#hpsum-node-type').selectBox('reset');
								$('#hpsum-node-privacy_policy').hide();

								// Update the localization rel attribute to the simplified text for OEM
								$('#hpsum-node-add-install-prereqs-warning').text(localizer.getString('hpsum.node.installPrereqsWarningOEM'));
;							}
						}
						else
						{
							// if session is expired or any other error, then goto login page
							session.eraseAll();
							document.location.href = "/#/login";
						}
					},
					error : function(jqXHR) {
						// getsessiondata failed, so goto login page
						session.eraseAll();
						document.location.href = "/#/login";
					}
				};

				//get session data and set user and login details for the session
				session.getSessionData(sessionDataHandlers);
			}
            
            	this.init = function() {
			
    				var resource = router.location().split('/');
                	resource = resource[1];
					$(VCENTERPANEL).hide();
					$(ENTER_VCENTER_CRED).hide();
                	
                	var options = 	{
									command : 'init',
									panelLabel: "hpsum.common.SshKeyFile",
									panelLabelStyle: "",
						            panelHelp: "",
						            panelBrowseText: "hpsum.common.browse",
						            bshowFile: true
						        };
								
					updateUserInterfaceForOEM();
					
					$(ADD_LINUX_BROWSE_PANEL).hpsumBrowse(options);
					
					instAddLinuxSshkeyBrowse = $(ADD_LINUX_BROWSE_PANEL).data('plugin_hpsumBrowse');
					$(INSTALL_PREREQS_CHECKBOX).click(function () {
					    $(INSTALL_PREREQS_WARNING_LABEL).show();
					});
					switch (resource.toUpperCase()) {
					
					    case "ILO": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNewIlo')); break;
					    case "NODE": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNode')); break;
					    case "VC": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNewVC')); break;

					    case "IPDU": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNewIpdu')); break;
					    case "MOONSHOT": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNewMoonshot')); break;
					    case "SDFLEX": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNewSdFlex')); break;
						case "SWITCH": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNewSwitch')); break;
					    case "SERVER": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNewServer')); break;
					    case "ENCLOSURE": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNewEnclosure')); break;
					    case "VMWARE": $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNewVM'));
					        $(VCENTERPANEL).show();
					        var isVcenterSelected = $("input[name='hpsum-node-credential']:checked").val();
					        if (isVcenterSelected == 'four') {
					            $(ENTER_VCENTER_CRED).show();
					        }
					        break;
					    default:
					        $(HEADER_TYPE).text(localizer.getString('hpsum.node.addNew') + ' ' + resource);
					}

			$('#hpsum-node-namehelp').attr('tooltip', localizer.getString('hpsum.common.ipDnshelp')).hpTooltip();
			//$(INSTALL_PREREQS_CHECKBOX).attr('tooltip', localizer.getString('hpsum.node.prereqsHelp')).hpTooltip();
			$(INSTALL_PREREQS_DIV).attr('tooltip', localizer.getString('hpsum.node.prereqsHelp')).hpTooltip();
			$(ILO_APPTOKEN_DIV).attr('tooltip', localizer.getString('hpsum.node.apptokenHelp')).hpTooltip();
			$('#hpsum-node-additionalpackagehelp').attr('tooltip', localizer.getString('hpsum.node.additionalPackageshelp')).hpTooltip();
			$('#hpsum-node-grouphelp').attr('tooltip', localizer.getString('hpsum.node.assignTohelp')).hpTooltip();
			$('#hpsum-node-addHelp').attr('tooltip', localizer.getString('hpsum.node.addHelp')).hpTooltip();
			$('#hpsum-node-addassocnodes').attr('tooltip', localizer.getString('hpsum.common.typetoaddhelp')).hpTooltip();
                	if(resource === 'node')
                		$(TYPE).val("Unknown");
                	else
                		$(TYPE).val(resource);
                	
					if ((navigator.appVersion.indexOf("X11")!=-1) ||
				       (navigator.appVersion.indexOf("Linux")!=-1)) { 
				    	$('#hpsum-node-type option[value="windows"]').remove();
					    $(TYPE).selectBox('reset');
				      }
					
                	$(TYPE).selectBox({autoWidth: false});
					$(NODE_ADD_TYPE).selectBox({autoWidth: false});
    				
    				 $('a[data-panel-id]').each(function(index) {
                		var currentLink = $(this).attr('href');
                		if(currentLink  == undefined)
                			return;
                		var current = currentLink.split('/');
                		current[1] = resource;
                		currentLink =current.join('/');
                		$(this).attr('href',currentLink);
  					});
					IpdialogContents = $(IP_DIALOG).detach().show();
					nodeSettingsDialogContents = $(NODESETTINGS_DIALOG).detach().show();
					
					$(APPLY_SETTINGS_BUTTON, IpdialogContents).on('click', function (event) 
					{
						initnodeSettingsDialog(selected_nodes);
                                                event.preventDefault();
					});
					
					$("input").bind("keypress", function(event) {
                    var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
                    if (keycode == 13) { // keycode for enter key
                        $(ADD).trigger('click');
                        event.preventDefault();
                      }
                    });

                	$(PANELS).hpStackedPanels({
                    	panelSelector : PANEL_SELECTOR
                	});
                	$('input[name="hpsum-node-credential"]').click(credentialsOptions);
             		$('input[name="hpsum-linux-node-credential"]').click(linuxCredentialOptions);
              		$(CANCEL).live('click', function() {
						var resource = router.location().split('/');
                		resource = resource[1];
						hashManager.replaceHash('/'+ resource +'/show');
                	});
                	ROUTE_PREFIX = '/'+ resource +'/add';
                	formStateView.init({form: FORM,
                    	routePattern: ROUTE_PREFIX + '.*',
                    	autoTrack: false});

					// for find button click,
					$(FIND).live('click', function(ev){
						var resource = router.location().split('/');
                		resource = resource[1];
						hashManager.replaceHash('/'+ resource +'/find');
					});	
					ROUTE_PREFIX = '/'+ resource +'/find';
                	formStateView.init({form: FORM,
                    	routePattern: ROUTE_PREFIX + '.*',
                    	autoTrack: false});

		// 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);
                }
                
                    presenter.getAllNodes({
                        success: function(data) {
                                    getlocalhostType(data);
                                },
                        error : function(errorInfo) {
                                }
                    });

           			presenter.getAllBaselines({
           					success:getBaselinesSuccess,
           					error: getBaselinesError
           			});
                    
					$(BASELINES).bind('change',function(){
						if(!setAdd){
							$(BASELINE_INPUT_ERR).hide();
							$(BASELINE_INPUT).removeClass('hp-error');
						}
						setAdd = false;
					});
					
					$(HOTFIX).bind('change',function(){
						if(!setAdd){
							$(HOTFIX_INPUT_ERR).hide();
							$(HOTFIX_INPUT).removeClass('hp-error');
						}
						setAdd = false;
					});
						
					$(SELECT_GROUP).bind('change', function () {
					    //if any group is selected, disable the baseline selection.
					    if ($(SELECT_GROUP).val() != "") {
                            //set current group baseline to baseline combo and disable. 
					        $(BASELINE_COMBOBOX).hpSearchCombo('disable');
					        $(ADDITIONAL_BASELINE_COMBOBOX).hpSearchCombo('disable');
					        $('#hpsum-node-edit-baseline-list').attr('tooltip', localizer.getString('hpsum.node.editingDisabledDueToGroup')).hpTooltip();
					        $('#hpsum-node-additionalpackagehelp').attr('tooltip', localizer.getString('hpsum.node.editingDisabledDueToGroup')).hpTooltip();
					        updateBaselineSelection($(SELECT_GROUP).val());
					    }
					    else {
					        $(BASELINE_COMBOBOX).hpSearchCombo('enable');
					        $(ADDITIONAL_BASELINE_COMBOBOX).hpSearchCombo('enable');
					        $('#hpsum-node-edit-baseline-list').attr('tooltip', "").hpTooltip();
					        $('#hpsum-node-additionalpackagehelp').attr('tooltip', localizer.getString('hpsum.node.additionalPackageshelp')).hpTooltip();
					    }
					});

                	$(ADD).off('click').on('click', function(ev) {
						setAdd = true;
                   		onAddItem.call(this);
                    	ev.preventDefault();
                	});
					$(window).on('resize', OnResize);
					 OnResize();
                	$(RESET).live('click', function() {
                    	reset.call();
                	});
                	
                //Moonshot
                $(MOONSHOT_SWITCH_SAME_CREDENTIALS).click(function(){
                    $(MOONSHOT_SWITCHB_CREDENTIALS).toggle();
					$(MOONSHOT_SWITCHB_CREDENTIALS_TEXT_BOX).val('');
					$(MOONSHOT_SWITCHB_CREDENTIALS_TEXT_BOX).attr('disabled', false);
					$(MOONSHOT_SWITCHB_CREDENTIALS_NOT_SET).attr('checked', false);
					if($(MOONSHOT_SWITCH_SAME_CREDENTIALS).is(":checked")) {
						$(MOONSHOT_SWITCHB_CREDENTIALS).hide();
					}
					else
					{
						if($(MOONSHOT_SWITCHB_CREDENTIALS_FULL).is(':checked')){
							$('#hpsum-moonshot-switchB-credentials-username-help').attr('style', 'display:none');
							$('#hpsum-moonshot-switchB-credentials-password-help').attr('style', 'display:none');
							$('#hpsum-moonshot-switchB-credentials-enablePasswordhelp').attr('style', 'display:none');
						}
					}
                });
				
				$(MOONSHOT_ENTER_SWITCH_CREDENTIALS).click(function(){
                    $(MOONSHOT_SWITCH_CREDENTIALS).toggle();
					$(MOONSHOT_SWITCH_CREDENTIALS_TEXT_BOX).val('');
					$(MOONSHOT_SWITCH_CREDENTIALS_TEXT_BOX).attr('disabled', false);
					$(MOONSHOT_SWITCH_CREDENTIALS_NOT_SET).attr('checked', false);
					$(MOONSHOT_SWITCH_SAME_CREDENTIALS).attr('checked', true);
					if($(MOONSHOT_ENTER_SWITCH_CREDENTIALS).is(":unchecked")){
						$(MOONSHOT_SWITCHB_CREDENTIALS).hide();
					}
					else{
						if($(MOONSHOT_SWITCH_CREDENTIALS_FULL).is(':checked')){
							$('#hpsum-moonshot-switch-credentials-username-help').attr('style', 'display:none');
							$('#hpsum-moonshot-switch-credentials-password-help').attr('style', 'display:none');
							$('#hpsum-moonshot-switch-credentials-enablePasswordhelp').attr('style', 'display:none');
						}
					}
                });
				
				$(MOONSHOT_SWITCH_CREDENTIALS_NOT_SET).click(function(){
					switchAuthenticationMode = $("input[name='hpsum-moonshot-switch-authentication']:checked").val();
					if(switchAuthenticationMode == "none") {
						$(MOONSHOT_SWITCH_CREDENTIALS_TEXT_BOX).val('');
						$(MOONSHOT_SWITCH_CREDENTIALS_TEXT_BOX).attr('disabled', true).attr('style', 'background-color:#DEDEDE');
						$('#hpsum-moonshot-switch-credentials-username-help').removeAttr('style', 'display:none');
						$('#hpsum-moonshot-switch-credentials-password-help').removeAttr('style', 'display:none');
						$('#hpsum-moonshot-switch-credentials-enablePasswordhelp').removeAttr('style', 'display:none');
					}
                });
				$(MOONSHOT_SWITCH_CREDENTIALS_PWD).click(function(){
					switchAuthenticationMode = $("input[name='hpsum-moonshot-switch-authentication']:checked").val();
					if(switchAuthenticationMode == "one") {
						$(MOONSHOT_SWITCH_CREDENTIALS_USERNAME).attr('disabled', true).attr('style', 'background-color:#DEDEDE').val('');
						$(MOONSHOT_SWITCH_CREDENTIALS_PASSWORD).attr('disabled', false).removeAttr('style', 'background-color:#DEDEDE').val('');
						$(MOONSHOT_SWITCH_CREDENTIALS_ENABLE_PASSWORD).attr('disabled', true).attr('style', 'background-color:#DEDEDE').val('');
						$('#hpsum-moonshot-switch-credentials-username-help').removeAttr('style', 'display:none');
						$('#hpsum-moonshot-switch-credentials-password-help').attr('style', 'display:none');
						$('#hpsum-moonshot-switch-credentials-enablePasswordhelp').removeAttr('style', 'display:none');
					}
                });
				$(MOONSHOT_SWITCH_CREDENTIALS_FULL).click(function(){
					switchAuthenticationMode = $("input[name='hpsum-moonshot-switch-authentication']:checked").val();
					if(switchAuthenticationMode == "two") {
						$(MOONSHOT_SWITCH_CREDENTIALS_USERNAME).attr('disabled', false).removeAttr('style', 'background-color:#DEDEDE').val('');
						$(MOONSHOT_SWITCH_CREDENTIALS_PASSWORD).attr('disabled', false).removeAttr('style', 'background-color:#DEDEDE').val('');
						$(MOONSHOT_SWITCH_CREDENTIALS_ENABLE_PASSWORD).attr('disabled', false).removeAttr('style', 'background-color:#DEDEDE').val('');
						$('#hpsum-moonshot-switch-credentials-username-help').attr('style', 'display:none');
						$('#hpsum-moonshot-switch-credentials-password-help').attr('style', 'display:none');
						$('#hpsum-moonshot-switch-credentials-enablePasswordhelp').attr('style', 'display:none');
					}
                });
				$(MOONSHOT_SWITCHB_CREDENTIALS_NOT_SET).click(function(){
					switchAuthenticationMode = $("input[name='hpsum-moonshot-switchb-authentication']:checked").val();
					if(switchAuthenticationMode == "none") {
						$(MOONSHOT_SWITCHB_CREDENTIALS_TEXT_BOX).val('');
						$(MOONSHOT_SWITCHB_CREDENTIALS_TEXT_BOX).attr('disabled', true).attr('style', 'background-color:#DEDEDE');
						$('#hpsum-moonshot-switchB-credentials-username-help').removeAttr('style', 'display:none');
						$('#hpsum-moonshot-switchB-credentials-password-help').removeAttr('style', 'display:none');
						$('#hpsum-moonshot-switchB-credentials-enablePasswordhelp').removeAttr('style', 'display:none');
					}
                });
				$(MOONSHOT_SWITCHB_CREDENTIALS_PWD).click(function(){
					switchAuthenticationMode = $("input[name='hpsum-moonshot-switchb-authentication']:checked").val();
					if(switchAuthenticationMode == "one") {
						$(MOONSHOT_SWITCHB_CREDENTIALS_USERNAME).attr('disabled', true).attr('style', 'background-color:#DEDEDE').val('');
						$(MOONSHOT_SWITCHB_CREDENTIALS_PASSWORD).attr('disabled', false).removeAttr('style', 'background-color:#DEDEDE').val('');
						$(MOONSHOT_SWITCHB_CREDENTIALS_ENABLE_PASSWORD).attr('disabled', true).attr('style', 'background-color:#DEDEDE').val('');
						$('#hpsum-moonshot-switchB-credentials-username-help').removeAttr('style', 'display:none');
						$('#hpsum-moonshot-switchB-credentials-password-help').attr('style', 'display:none');
						$('#hpsum-moonshot-switchB-credentials-enablePasswordhelp').removeAttr('style', 'display:none');
					}
                });
				$(MOONSHOT_SWITCHB_CREDENTIALS_FULL).click(function(){
					switchAuthenticationMode = $("input[name='hpsum-moonshot-switchb-authentication']:checked").val();
					if(switchAuthenticationMode == "two") {
						$(MOONSHOT_SWITCHB_CREDENTIALS_USERNAME).attr('disabled', false).removeAttr('style', 'background-color:#DEDEDE').val('');
						$(MOONSHOT_SWITCHB_CREDENTIALS_PASSWORD).attr('disabled', false).removeAttr('style', 'background-color:#DEDEDE').val('');
						$(MOONSHOT_SWITCHB_CREDENTIALS_ENABLE_PASSWORD).attr('disabled', false).removeAttr('style', 'background-color:#DEDEDE').val('');
						$('#hpsum-moonshot-switchB-credentials-username-help').attr('style', 'display:none');
						$('#hpsum-moonshot-switchB-credentials-password-help').attr('style', 'display:none');
						$('#hpsum-moonshot-switchB-credentials-enablePasswordhelp').attr('style', 'display:none');
					}
                });

                this.resume();
            };
            
            this.resume = function () {
				reset();
				$(NODE_ADD_THROBBER).hide();
                $(ADD).attr('disabled', false);
                groupPresenter.getGroupIndexDetails({
				    success: function (searchResults) {
				        groups = $.grep(searchResults, function (option, index ) {
				            return (option.group_state.match(new RegExp('^IDLE', 'i')));
				        });
					},
					error: function(erroData){		
					}
				});
            	var resource = router.location().split('/');
                	resource = resource[1];
                	if(resource)
					{
                    }	
					else
					{
					$(TITLE).text('');
                    }
            		$('a[data-panel-id]').each(function(index) {
                		var currentLink = $(this).attr('href');
                		if(currentLink  == undefined)
                			return;
                		var current = currentLink.split('/');
                		current[1] = resource;
                		currentLink =current.join('/');
                		$(this).attr('href',currentLink);
  					});
  					ROUTE_PREFIX = '/'+ resource +'/add';
  				router.watch('node add section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
            	 $(RESET).trigger('click');
            	 $(NAMEERR).hide();
            	 $('input[name="hpsum-node-credential"]').click(credentialsOptions);
            	 $(ADD_ALREADYEXISTS).hide();
            	 $(NAME).removeClass("hp-error");
            	 $(USERNAME).removeClass("hp-error");
            	 $(PASSWORD).removeClass("hp-error");
				 $(VCENTERUSERNAME).removeClass("hp-error");
            	 $(VCENTERPASSWORD).removeClass("hp-error");
				 $(VCENTERPANEL).hide();
				 $(ENTER_VCENTER_CRED).hide();
            	 $(TYPEERR).hide();
            	 $(USERNAME_ERR).hide();
            	 $(PASSWORD_ERR).hide();
				 $(GEN10_ILO_CRED_PANEL).hide();
				 $(ILO_CRED_LABEL).hide();
				 $(ILO_CREDENTIALS_NOTE).hide();
				 $(VCENTERIPADDR_ERR).hide();
				 $(VCENTERUSERNAME_ERR).hide();
				 $(VCENTERPASSWORD_ERR).hide();
				 
            	 $(PARTNER_USERNAME).removeClass("hp-error");
            	 $(PARTNER_PASSWORD).removeClass("hp-error");
            	 $(PARTNER_USERNAME_ERR).hide();
            	 $(PARTNER_PASSWORD_ERR).hide();
            	 $(PARTNER_IP_LIST).show();
            	 $(".hpsum-add-assoc-nodes").show();
				 $(LINUX_CRED_PANEL).css({"display":"none"});
				 hideLinuxCredSshKeyFileSelection();
            	 $(PARTNER_CRED_PANEL).css({"display":"none"});
            	 $(TYPE).bind('change', showPartnerOptions);
				 $(NODE_ADD_TYPE).bind('change', showNodeAddType);
				 $(TYPE).removeClass("hp-error");
            	  	presenter.getAllBaselines({
           					success:getBaselinesSuccess,
           					error: getBaselinesError
           			});
           			if(resource)
					{
						if (resource == 'node') {
							//$(TYPE).selectBox('value', 'unknown');
						} else if (resource == 'server') {
							$(TYPE).selectBox('value', 'windows');
						}else {
							$(TYPE).selectBox('value', resource.toLowerCase());
						}
						showPartnerOptions();
                    }
            };

            this.pause = function () {
             //   formStateView.reset();
             $(BASELINES).hpSearchCombo('set', {id:'', name: ''});
             $(HOTFIX).hpSearchCombo('set', { id: '', name: '' });
             $(SELECT_GROUP).hpSearchCombo('set', { id: '', name: '' });
			 $(STACKED_PANEL_ACTIVE).removeClass('hp-active');
            };
    		
    	}	
    	return AddView;
    }());
    	
    return new AddView();	
    		
    });

