// (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',
    'hp/core/Router',
    'hp/core/UrlFragment',
    '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'],
function(presenter, router,urlFragment,validator, FormStateView, DialogView, helpMenu,rest, localizer,session, headerHelpHtml) { "use strict";

				var NodeFind = (function() {
					var ADD = '#hpsum-node-add',
					CANCEL = '#hpsum-node-add-close',
					CLOSE = '#hpsum-ipdialog-close',
					RESET = '#hpsum-node-reset',
					PANEL_SELECTOR = '#hpsum-node-add-panel-selector',
					FIRST_ANCHOR = PANEL_SELECTOR + ' a[href]:first',
					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_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',
					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",
					FORM = '#hpsum-node-settings-form',
					SEARCHER = '#hpsum-node-searcher',
					BASELINES = '#hpsum-node-add-baselines-search',
					HOTFIX = '#hpsum-node-add-hotfix-search',
					COLLAPSE = '#hpsum-node-add-bandwidth',
					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_ENTER_CRED = '#hpsum-node-partner-cred-details',
					PARTNER_USERNAME = '#hpsum-node-partner-credential-username',
					PARTNER_PASSWORD = '#hpsum-node-partner-credential-password',
					ROUTE_PREFIX = '/node/find',
					FIND_NODES_BUTTON = '#hpsum-ip-dialog',
					SEARCH_BUTTON = '#hpsum-node-search',
					LDAP_SEARCH_BUTTON = '#hpsum-node-ldap-search',
					IP_FORM_CONTENT = '#hpsum-all-form-content',
					IP_DIALOG_HEADER = '#hp-ip-header',
					IP_DIALOG_FOOTER = '#hp-ip-footer',
					NODE_SEARCH_TYPE = '#hpsum-node-searchType',	
					PORT_LABEL = '#port_to_scan',
					PORT_INPUT = '#hpsum-port-other',
					PORT_SELECTOR_CONTAINER = '#portSelection',
					NODE_PORT_VALUE = '#hpsum-node-portSelect',
					LDAP_CONTAINER = '#hpsum-node-add-ldap-nodes',
					LDAP_SERVER = '#hpsum-ldap-server',
					LDAP_USERNAME = '#hpsum-ldap-username',
					LDAP_PASSWORD = '#hpsum-ldap-password',
					LDAP_MAXRETURN = '#hpsum-ldap-maxreturn',
					IPADDRESS_RANGE = '#hpsum-node-add-nodes',
					IP_START = '#hpsum-ip-start',
					IP_END = '#hpsum-ip-end',
					NODE_COMP = '#hpsum-node-components',
					SEARCH_NODE_ABORT = '#hpsum-node-search-abort',
					SEARCH_NODE_ABORT_BUTTON = '#hpsum-node-search-abort-button',
					SEARCH_NODE = '#hpsum-search-node',
					SEARCH_DIALOG = '#hpsum-search-dialog',
					SEARCH_SPINNER = '#hpsum-search-spinner',
					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',
					GEN10_ILO_CRED_PANEL = '#hpsum-node-settings-ilo-credentials',
					NODESETTINGS_ILO_USERNAME = '#hpsum-node-settings-ilo-credential-username',
					NODESETTINGS_ILO_PASSWORD = '#hpsum-node-settings-ilo-credential-password',
					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',
					NODE_SELECTED = '#hpsum-node-comp-selected',
					NODESETTINGS_CANCEL = '#hpsum-node-settings-close',
					IP_ERR = '#hpsum-node-settings-err',
					LDAP_ERR = '#hpsum-ldap-settings-err',
					ADD_ASSOC_NODES = '#hpsum-node-addassocnodes',
					NODESETTINGS_BASELINE_INPUT = '#hpsum-node-settings-add-baselines-search-input',
					NODESETTINGS_BASELINE_INPUT_ERR = '#hpsum-node-settings-add-baselines-search-input-err',
					NODESETTINGS_HOTFIX_INPUT = '#hpsum-node-settings-add-hotfix-search-input',
					NODESETTINGS_HOTFIX_INPUT_ERR = '#hpsum-node-settings-add-hotfix-search-input-err',
					FIND_ADD_LINUX_BROWSE_PANEL = '#hpsum-find-add-linux-sshkey-browse-panel',
					IP_STRING = 'ip',
					PORT_STRING = 'port',
					INSTALL_PREREQS_PANEL = '#hpsum-node-find-add-install-prereqs-panel',
 		    			INSTALL_PREREQS_DIV = '#hpsum-node-find-add-install-prereqs-div',
	    		    		INSTALL_PREREQS_CHECKBOX = '#hpsum-node-find-add-install-prereqs-checkbox',
	                		INSTALL_PREREQS_WARNING_LABEL = '#hpsum-node-find-add-install-prereqs-warning'; 	
			
			function NodeFind() {
			
			
					var formStateView = new FormStateView(),
					addInProgress = false,
					checkedVal = '',
					useCurrentCredentials = false,
    				useSudoCredentials = false,
					nodeSettingsDialog= null,
					node_table,
                    node_data = [],
					baselines='',
    				hotfixes='',
					nodeIpDialog= null;
					var IpdialogContents;
					var nodeSettingsDialogContents;
    			    var node_details = [];
					var selected_nodes = [];
					var added_nodes = [];
			    	var complex_id;
					var searchInProgress = false;
					var progressTimer;
					var valid_nodes = [];
					var setAdd = false;
					var instNodeFindAddBrowse;
					
			function changeLocation(location) {
						
				if (location.length > ROUTE_PREFIX.length) {
					$(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
				} 
				else {
					$(PANELS).hpStackedPanels('setFirstPanel');
						
				}
			}
			
			function OnResize(){
				var maxWidth = Math.min(920, $(window).width() - 40);
				var BaseLineSearchWidth = maxWidth / 2;
				$(NODESETTINGS_BASELINE).hpSearchCombo({getResults:getBaseline, width:BaseLineSearchWidth});
				$(NODESETTINGS_HOTFIX).hpSearchCombo({getResults: getHotfixes, width:BaseLineSearchWidth});
			}			
			
			function clearCredInput() {
				$(LINUX_SSH_KEY_FILE_USERNAME).val("");
				instNodeFindAddBrowse.setPanelText("");
				$(LINUX_SSH_KEY_FILE_PASSPHRASE).val("");		
				
				$(NODESETTINGS_USERNAME).val("");
				$(NODESETTINGS_PASSWORD).val("");
				
				$(NODESETTINGS_ILO_USERNAME).val("");
				$(NODESETTINGS_ILO_PASSWORD).val("");
			}

			function showPreReqsOption() {
				$(INSTALL_PREREQS_PANEL).show();
				$(INSTALL_PREREQS_CHECKBOX).attr('checked', true);
				if ($(INSTALL_PREREQS_CHECKBOX).is(':checked')) 
				{
					$(INSTALL_PREREQS_WARNING_LABEL).hide(); /* is required when attributes wil get re-loaded */
				}
				else
				{
					$(INSTALL_PREREQS_WARNING_LABEL).show();
				}
				
			}
						
			this.init = function() {
    				var resource = router.location().split('/');
                	resource = resource[1];
                	if(resource === 'node')
                		$(TYPE).val("Unknown");
                	else
                		$(TYPE).val(resource);
                		
                	$(TYPE).selectBox({autoWidth: false});
					$(NODE_SEARCH_TYPE).selectBox({autoWidth: false});
					$(NODE_SEARCH_TYPE).selectBox('value', 'ipAddrRange');
					$(NODE_PORT_VALUE).selectBox({autoWidth: false});
					$(NODE_PORT_VALUE).selectBox('value', '80');
					
					TogglePortOption(false);
					$(PORT_INPUT).hide();
					$(LDAP_CONTAINER).hide();
					
					$(SEARCH_NODE_ABORT).hide();
					
    				 $('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);
  					});
					
					nodeSettingsDialogContents = $(NODESETTINGS_DIALOG).detach().show();
					
					$(APPLY_SETTINGS_BUTTON, IpdialogContents).on('click', function () 
					{
						initnodeSettingsDialog(selected_nodes);
					});
					
                	$(PANELS).hpStackedPanels({
                    	panelSelector : PANEL_SELECTOR
                	});
					$(CLOSE).on('click', function() {
					formStateView.reset();
					searchInProgress = false; 
                    $(SEARCH_NODE_ABORT_BUTTON).bind('click',btnSearchAbort); 
                    $(SEARCH_NODE_ABORT).hide(); 
                    $(SEARCH_BUTTON).addClass("hp-primary").removeClass("hp-disabled"); 

					router.go(urlFragment.replaceView(router.location(), 'show'));
					
					$('#hpsum-node-table_filter').hpSearchCombo("disable");
					
					reset();
					});
                	$(window).on('resize', OnResize);
                	ROUTE_PREFIX = '/'+ resource +'/find';
                	formStateView.init({form: FORM,
                    	routePattern: ROUTE_PREFIX + '.*',
                    	autoTrack: false});
					this.resume();
					
			};
			
			this.resume = function() {
			
					//var IpdialogContents = $(IP_DIALOG).detach().show();
					//reset();
					var resource = router.location().split('/');
					
                	resource = resource[1];
                	if(resource)
					{
					     $(TYPE).selectBox('value', resource);
                    }	
					else
					{
					$(TITLE).text('');
                    }
					//$(SEARCH_NODE_ABORT).hide();
            		/*$('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 +'/find';
  				router.watch('node find section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
            	 //$(RESET).trigger('click');
            	 //$(NAMEERR).hide();
     
            	 //credentialsOptions('two');
            	 /*$(NAME).removeClass("hp-error");
            	 $(USERNAME).removeClass("hp-error");
            	 $(PASSWORD).removeClass("hp-error");
            	 $(TYPEERR).hide();
            	 $(USERNAME_ERR).hide();
            	 $(PASSWORD_ERR).hide();*/
				 //$(ADD_ASSOC_NODES).hide();
				 //$('#hpsum-node-addassoc-description').hide();
				/*$(LINUX_CRED_PANEL).css({"display":"none"});
            	 $(PARTNER_CRED_PANEL).css({"display":"none"});
            	 $(TYPE).bind('change', showPartnerOptions);
            	 $(TYPE).removeClass("hp-error");
            	  	presenter.getAllBaselines({
           					success:getBaselinesSuccess,
           					error: getBaselinesError
           			});*/
				
            	 initIpdialog();
				 //$(SEARCH_NODE_ABORT).bind('click',btnSearchAbort(complex_id));
				 //for find nodes on network..
				 $(NODE_SEARCH_TYPE).bind('change', showNodeSearchType);
				 $(NODE_PORT_VALUE).bind('change', showPortValueTypes);
				 
			};
				
			function showPortValueTypes(){
				formStateView.reset();
				$(PORT_INPUT).val("");
				$(IP_ERR).hide();
				$(PORT_INPUT).removeClass("hp-error");
			    if($(NODE_PORT_VALUE).val().toLowerCase().match(/other/i))
				{
					$(PORT_INPUT).show();
					$(SEARCH_BUTTON).attr('disabled', true);
				}
				else 
			    {					
					$(PORT_INPUT).hide();
					if($(IP_START).val() != '' && $(IP_END).val() != ''){
						$(SEARCH_BUTTON).removeAttr('disabled');
					}
					else
					{
						$(SEARCH_BUTTON).attr('disabled', true);
					}
			    }
			}
			function TogglePortOption(selected)
			{
				if(selected) // true
				{	
					$(PORT_LABEL).show();
					$(PORT_SELECTOR_CONTAINER).show();
				}
				else //false
				{
					$(PORT_LABEL).hide();
					$(PORT_INPUT).hide();
					$(PORT_SELECTOR_CONTAINER).hide();
				}
			}
			function showNodeSearchType(){
			    formStateView.reset();	
				$(IP_ERR).hide();
				clearNodeSearchInputs();
				$(SEARCH_BUTTON).attr("disabled",true);
				$(PORT_INPUT).removeClass("hp-error");
				$(IP_START).removeClass("hp-error");
				$(IP_END).removeClass("hp-error");
			    if($(NODE_SEARCH_TYPE).val().toLowerCase().match(/ipAddrRange/i))
			    {
					$(IPADDRESS_RANGE).show();
					TogglePortOption(false);
					$(LDAP_CONTAINER).hide();
			    }
				else if($(NODE_SEARCH_TYPE).val().toLowerCase().match(/portAddress/i))
				{					
					$(IPADDRESS_RANGE).show();
					TogglePortOption(true);
					$(LDAP_CONTAINER).hide();
				}
				else if($(NODE_SEARCH_TYPE).val().toLowerCase().match(/ldap/i))
				{
					$(IPADDRESS_RANGE).hide();
					TogglePortOption(false);
					$(LDAP_CONTAINER).show();
					$(LDAP_SEARCH_BUTTON).attr("disabled",true);
				}
				// clear the available nodes table.
				
				var node_tableid = '#hpsum-node-table';
				$('#hpsum-node-table_filter').hpSearchCombo("enable");
			    var node_table = $(node_tableid).dataTable();
				if(node_table.length != 0){
					node_table.fnClearTable();
				}
			}
			
			function UpdateSearchButtonStatus()
			{
				$(IP_ERR).hide();
				$(SEARCH_BUTTON).attr('disabled', true);
				if($(IP_START).val() != '' && $(IP_END).val() != ''){
					if(!$(NODE_PORT_VALUE).val().toLowerCase().match(/other/i) || ($(NODE_PORT_VALUE).val().toLowerCase().match(/other/i) && $(PORT_INPUT).val() != ''))
					{
						$(SEARCH_BUTTON).removeAttr('disabled');
					}
				}					
			}
			function initIpdialog()
			{	
				
				$(IP_ERR).hide();
				$(IP_START).val('');
				$(IP_END).val('');				
				$(IP_START).removeClass("hp-error");
				$(IP_END).removeClass("hp-error");
				$(PORT_INPUT).removeClass("hp-error");
				
				$(LDAP_SERVER).removeClass("hp-error");
				$(LDAP_USERNAME).removeClass("hp-error");
				$(LDAP_PASSWORD).removeClass("hp-error");
				$(LDAP_MAXRETURN).removeClass("hp-error");
				$(LDAP_MAXRETURN).val("500");
		        $(SEARCH_BUTTON).attr("disabled",true);
				$(IP_START).bind('keyup', function(){					
					$(IP_START).removeClass("hp-error");
					UpdateSearchButtonStatus();
				});
				$(IP_END).bind('keyup', function(){					
					$(IP_END).removeClass("hp-error");
					UpdateSearchButtonStatus();
					
				});				
				$(PORT_INPUT).bind('keyup', function(){					
					$(IP_ERR).hide();					
					$(PORT_INPUT).removeClass('hp-error');
					if($(PORT_INPUT).val() != '' && $(IP_START).val() != '' && $(IP_END).val() != '')
					{
						$(SEARCH_BUTTON).removeAttr('disabled');
					}
					else
					{
						$(SEARCH_BUTTON).attr('disabled', true);
					}
            	}); 
					
				$(LDAP_SERVER).bind('keyup', function(){
					$(LDAP_ERR).hide();
					$(LDAP_SERVER).removeClass("hp-error");
					if($(LDAP_SERVER).val() != '' && $(LDAP_USERNAME).val() != '' && $(LDAP_PASSWORD).val() != ''){
						$(LDAP_SEARCH_BUTTON).removeAttr('disabled');
					}
					else
					{
						$(LDAP_SEARCH_BUTTON).attr('disabled', true);
					}
				});
				$(LDAP_USERNAME).bind('keyup', function(){
					$(LDAP_ERR).hide();
					$(LDAP_USERNAME).removeClass("hp-error");
					if($(LDAP_SERVER).val() != '' && $(LDAP_USERNAME).val() != '' && $(LDAP_PASSWORD).val() != ''){
						$(LDAP_SEARCH_BUTTON).removeAttr('disabled');
					}
					else
					{
						$(LDAP_SEARCH_BUTTON).attr('disabled', true);
					}
				});
				$(LDAP_PASSWORD).bind('keyup', function(){
					$(LDAP_ERR).hide();
					$(LDAP_PASSWORD).removeClass("hp-error");
					if($(LDAP_SERVER).val() != '' && $(LDAP_USERNAME).val() != '' && $(LDAP_PASSWORD).val() != ''){
						$(LDAP_SEARCH_BUTTON).removeAttr('disabled');
					}
					else
					{
						$(LDAP_SEARCH_BUTTON).attr('disabled', true);
					}
				});
				$(LDAP_MAXRETURN).bind('keyup', function(){
					$(IP_ERR).hide();
					if($(LDAP_MAXRETURN).val() <= 500 && $(LDAP_MAXRETURN).val() > 0 ){
						$(LDAP_MAXRETURN).removeClass("hp-error");
						$(LDAP_SEARCH_BUTTON).removeAttr('disabled');
					}
					else
					{
						$(LDAP_MAXRETURN).addClass("hp-error");
						$(LDAP_SEARCH_BUTTON).attr('disabled', true);
					}
					
				});
				
				$(NODESETTINGS_BASELINE).html('');
				$(NODESETTINGS_HOTFIX).html('');
				$(NODESETTINGS_BASELINE_INPUT).val('');
				$(NODESETTINGS_HOTFIX_INPUT).val('');
				$('.hp-close').css("display","none");
				var node_tableid = '#hpsum-node-table';
				initNodeTable(node_tableid);
				var node_table = $(node_tableid, IpdialogContents).dataTable();
				var node_selected_id = '#hpsum-node-selected-table';
				NodeSelectedTable(node_selected_id);
				var node_selected_table =  $(node_selected_id, IpdialogContents).dataTable();
				
				if($('#hpsum-node-table tr')[1].cells[0].innerHTML == "No nodes found!") // TODO: Logic needs to be changed to not rely on UI message.
				{
				  $('#hpsum-node-table_filter').hpSearchCombo("disable");
				}
				
				   
			
			
				if(node_table.length != 0)	

					node_table.fnClearTable();
					
					
					
				if(node_selected_table.length != 0)
				
					node_selected_table.fnClearTable();
				
				$(APPLY_SETTINGS_BUTTON, IpdialogContents).attr("disabled","true");
				
				$(SEARCH_BUTTON, IpdialogContents).on('click', btnSearchClicked);
				$(LDAP_SEARCH_BUTTON, IpdialogContents).on('click', btnLDAPSearchClicked);
			}
			
			function reset() {
				formStateView.reset();
                addInProgress = false;
				searchInProgress = false;
                $(NAMEERR).hide();
				$(NAME).removeClass("hp-error");
            	$(USERNAME).removeClass("hp-error");
            	$(PASSWORD).removeClass("hp-error");
            	$(TYPEERR).hide();
            	$(USERNAME_ERR).hide();
            	$(PASSWORD_ERR).hide();
				$(NODESETTINGS_USERNAME).val('');
            	$(NODESETTINGS_PASSWORD).val('');
                $(NODESETTINGS_USERNAME).removeClass("hp-error");
            	$(NODESETTINGS_PASSWORD).removeClass("hp-error");
            	$(NODESETTINGS_USERNAME_ERR).hide();
            	$(NODESETTINGS_PASSWORD_ERR).hide();
				$(NODESETTINGS_ILO_USERNAME).val('');
            	$(NODESETTINGS_ILO_PASSWORD).val('');
				$(NODESETTINGS_BASELINE).html('');
				$(NODESETTINGS_HOTFIX).html('');
				$(NODESETTINGS_BASELINE_INPUT).val('');
				$(NODESETTINGS_HOTFIX_INPUT).val('');
				$('.hp-close').css("display","none");
				$(NODESETTINGS_BASELINE_INPUT).removeClass("hp-error");
				$(NODESETTINGS_HOTFIX_INPUT).removeClass("hp-error");
				$(NODE_SEARCH_TYPE).selectBox('value', 'ipAddrRange');
				$(NODE_PORT_VALUE).selectBox('value', '80');
				clearNodeSearchInputs();
				showNodeSearchType();
				$(NODESETTINGS_BASELINE_INPUT_ERR).hide();
				$(NODESETTINGS_HOTFIX_INPUT_ERR).hide();
				nodesettingscredentialsOptions('two');				
            }
			
			//clear all input fields and set default values..
			function clearNodeSearchInputs()
			{	
				$(IP_START).val("");
				$(IP_END).val("");
				$(PORT_INPUT).val("");
				$(NODE_PORT_VALUE).selectBox('value', '80');
				$(LDAP_SERVER).val("");
				$(LDAP_USERNAME).val("");
				$(LDAP_PASSWORD).val("");
				$(LDAP_MAXRETURN).val("500");
			}
			
			function validateLDAPCredentials()
			{
				var success = true;
				if($(LDAP_SERVER).val() == ''){
            		$(LDAP_SERVER).addClass("hp-error");            		
            		$(LDAP_SERVER).bind('keyup', function(){
            			$(LDAP_ERR).hide();
            			$(LDAP_SERVER).removeClass('hp-error');
            		}); 
            		success= false;
            	}
				if($(LDAP_USERNAME).val() == ''){
            		$(LDAP_USERNAME).addClass("hp-error");
            		$(LDAP_USERNAME).bind('keyup', function(){
            			$(LDAP_ERR).hide();
            			$(LDAP_USERNAME).removeClass('hp-error');
            		});
            		success= false;
            	}
            	if($(LDAP_PASSWORD).val() == ''){
            		$(LDAP_PASSWORD).addClass("hp-error");
            		$(LDAP_PASSWORD).bind('keyup', function(){
            			$(LDAP_ERR).hide();
            			$(LDAP_PASSWORD).removeClass('hp-error');
            		}); 
            		success= false;
            	}
				if($(LDAP_MAXRETURN).val() == ''){
            		$(LDAP_MAXRETURN).addClass("hp-error");
            		$(LDAP_MAXRETURN).bind('keyup', function(){
            			$(LDAP_MAXRETURN).removeClass('hp-error');
            		}); 
            		success= false;
            	}				
				return success;
			}
			
			function initnodeSettingsDialog(selected_nodes)
			{
				$(NODESETTINGS_RESET).click();
				//reset.call();
				var useCurrentCredentials = false;
				nodeSettingsDialog =  new DialogView({contents: nodeSettingsDialogContents,
                	position : "center", 
					cancel: function () { }
                    });
                    
                var options = 	{
									command : 'init',
									panelLabel: "hpsum.common.SshKeyFile",
									panelLabelStyle: "",
						            panelHelp: "",
						            panelBrowseText: "hpsum.common.browse",
						            bshowFile: true
						        };
				$(FIND_ADD_LINUX_BROWSE_PANEL, nodeSettingsDialogContents).hpsumBrowse(options);
				
				instNodeFindAddBrowse = $(FIND_ADD_LINUX_BROWSE_PANEL, nodeSettingsDialogContents).data('plugin_hpsumBrowse');
					
				presenter.getAllBaselines({
           					success:getBaselinesSuccess,
           					error: getBaselinesError
           			});
				
				valid_nodes = [];
				presenter.getAllNodes({
                            success: function(data) {
								for(var i=0; i<selected_nodes.length; i++) {
									var nodeExists = false;
									for (var j=0; j< data.hapi.output_data.nodes.node.length; j++) {
										if(data.hapi.output_data.nodes.node[j].node_name == selected_nodes[i].node_ip){
											nodeExists = true;
											break;
										}	
									}
									if(nodeExists == false)
										valid_nodes.push(selected_nodes[i]);
								}
							},
							error : function(errorInfo) {
							}
				}); 
                   
				$(NODESETTINGS_BASELINE).bind('change',function(){
					if(!setAdd){
						$(NODESETTINGS_BASELINE_INPUT_ERR).hide();
						$(NODESETTINGS_BASELINE_INPUT).removeClass('hp-error');
					}
					setAdd = false;
				});
								
				$(NODESETTINGS_HOTFIX).bind('change',function(){
					if(!setAdd){
						$(NODESETTINGS_HOTFIX_INPUT_ERR).hide();
						$(NODESETTINGS_HOTFIX_INPUT).removeClass('hp-error');
					}
					setAdd = false;
				});	
				   
				$(NODESETTINGS_ADD, nodeSettingsDialogContents).live('click', function(ev) {
						setAdd = true;
                   		onNodeSettingsAddItem.call(this);
                    	ev.preventDefault();
				});

				$(INSTALL_PREREQS_DIV).attr('tooltip', localizer.getString('hpsum.node.prereqsHelp')).hpTooltip();
                		$(INSTALL_PREREQS_CHECKBOX).click(function () {
					    if ($(INSTALL_PREREQS_CHECKBOX).is(':checked')) {
					        $(INSTALL_PREREQS_WARNING_LABEL).hide();
					    }
					    else {
					        $(INSTALL_PREREQS_WARNING_LABEL).show();
					
					    }
				});
				showPreReqsOption();
				$(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);
            	$('#hpsum-node-add-alreadyExist').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_ILO_USERNAME).val('');
				$(NODESETTINGS_ILO_PASSWORD).val('');
            	$(NODESETTINGS_USERNAME_ERR).hide();
            	$(NODESETTINGS_PASSWORD_ERR).hide();
				$(NODESETTINGS_BASELINE).html('');
				$(NODESETTINGS_HOTFIX).html('');
				$(NODESETTINGS_BASELINE_INPUT).val('');
				$(NODESETTINGS_HOTFIX_INPUT).val('');
				$('.hp-close').css("display","none");
				$(NODESETTINGS_BASELINE_INPUT).removeClass("hp-error");
				$(NODESETTINGS_HOTFIX_INPUT).removeClass("hp-error");
				$(NODESETTINGS_BASELINE_INPUT_ERR).hide();
				$(NODESETTINGS_HOTFIX_INPUT_ERR).hide();
				$('#hpsum-node-settings-close', nodeSettingsDialogContents).click(function () {
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                });
				
				
				 
			}
			  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 validateBaseline(){
				var errorFound = false;
				if($(NODESETTINGS_BASELINE).val()){
					var baselinedetails = presenter.getBaselineDetailsforId($(NODESETTINGS_BASELINE).val());
					if(!baselinedetails){
						errorFound = true;
						$(NODESETTINGS_BASELINE_INPUT_ERR).text(localizer.getString('hpsum.node.invalidBaseline'));	
						$(NODESETTINGS_BASELINE_INPUT).addClass("hp-error");
						$(NODESETTINGS_BASELINE_INPUT_ERR).show();
						$(NODESETTINGS_BASELINE_INPUT).bind('keyup',function(){
							$(NODESETTINGS_BASELINE_INPUT_ERR).hide();
							$(NODESETTINGS_BASELINE_INPUT).removeClass('hp-error');
						});
					}
				}
				if($(NODESETTINGS_HOTFIX).val()){
					var baselinedetails = presenter.getBaselineDetailsforId($(NODESETTINGS_HOTFIX).val());
					if(!baselinedetails){
						errorFound = true;
						$(NODESETTINGS_HOTFIX_INPUT_ERR).text(localizer.getString('hpsum.node.invalidAdtPackage'));	
						$(NODESETTINGS_HOTFIX_INPUT).addClass("hp-error");
						$(NODESETTINGS_HOTFIX_INPUT_ERR).show();
						$(NODESETTINGS_HOTFIX_INPUT).bind('keyup',function(){
							$(NODESETTINGS_HOTFIX_INPUT_ERR).hide();
							$(NODESETTINGS_HOTFIX_INPUT).removeClass('hp-error');
						});
					}
				}	
				// Return if the baseline or additional package is invalid
				if(errorFound)
					return false;
				else
					return true;
			}
			
			function validateNodeSettingsCredentials(){
				var success = true;
            	if($('input[name="hpsum-node-settings-credential"]:checked').val() == "one")
            		success = true;
				else if($('input[name="hpsum-node-settings-credential"]:checked').val() == "two") {
            	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;
            	}
				} else if($('input[name="hpsum-node-settings-credential"]:checked').val() == "three") {
					var sshKeyFile_username = $.trim($(LINUX_SSH_KEY_FILE_USERNAME).val());
					var sshKeyFile_location = $.trim(instNodeFindAddBrowse.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){
							instNodeFindAddBrowse.addInputClass("hp-error");
							$(LINUX_SSH_KEY_FILE_PATH_ERR).show();
							instNodeFindAddBrowse.setInputEvent('onkeyup', function(){
								$(LINUX_SSH_KEY_FILE_PATH_ERR).hide();
								instNodeFindAddBrowse.removeInputClass('hp-error');
							});
							success= false;
						}	
					}
				}
				
            	return success;
            }
			function onNodeSettingsAddItem() {
        	if(validateBaseline() && validateNodeSettingsCredentials()){
				var node_object = {
						hapi:{
							nodes:{
                                auto_inventory : false,
								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($(NODESETTINGS_BASELINE).val());
            	}

				var baselineinfo = {
						baseline:[]
						};
				var errorFound = false;
				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.name
							};
						baselineinfo.baseline.push(baselinedata);
					}
				}
            
				for (var i = 0; i < valid_nodes.length; i++) {
					var node = {
						ip : valid_nodes[i].node_ip,
						selected :true,                        
						baselines : baselineinfo,                        
						skip_prereqs : !($(INSTALL_PREREQS_CHECKBOX).is(':checked')),
						authentication :{
							username : $(NODESETTINGS_USERNAME).val(),
							password : $(NODESETTINGS_PASSWORD).val(),
							use_current_credentials : useCurrentCredentials,
							auto_add_assoc_nodes : false,
							ilo_username : $(NODESETTINGS_ILO_USERNAME).val(),
							ilo_password : $(NODESETTINGS_ILO_PASSWORD).val()													
						}                       
					};  
					// add ssh key file credential
					if($('input[name="hpsum-node-settings-credential"]:checked').val() == "three") {
						node.authentication.use_sshkeyfile = true;
						node.authentication.sshkeyfile_username = $.trim($(LINUX_SSH_KEY_FILE_USERNAME).val());
						node.authentication.sshkeyfile_location = $.trim(instNodeFindAddBrowse.getLocation()).split('\\').join('/');
						node.authentication.sshkeyfile_passphrase = $.trim($(LINUX_SSH_KEY_FILE_PASSPHRASE).val());
					} else 
						node.authentication.use_sshkeyfile = false;
						
					node_object.hapi.nodes.node.push(node);

				}
				var data;
				if(!addInProgress && node_object.hapi.nodes.node.length) {
              		addInProgress = true;
					nodeSettingsDialog.cancel();
					formStateView.setMessage({summary: localizer.getString("hpsum.node.AddingNodesMsg"), status: 'unknown', changing: true});									
                    presenter.addItems(node_object, true, {
							success : function(data) {
							onItemsAddSuccess(data); 
							},
                        	error : function(data) {
								onItemsAddError(data);
							}
						}
                    );
				}
                        
					
				else if (!node_object.hapi.nodes.node.length) {
					addInProgress = false;
					$(NODESETTINGS_BASELINE).hpSearchCombo("destroy");	
					$(NODESETTINGS_HOTFIX).hpSearchCombo("destroy");
					nodeSettingsDialog.cancel();
					addselected();
					}
				}

    		}
			function baselinesAvailable(data){
    			//data = {count: data.count, members: data};
            //	$(BASELINES).hpSearchCombo({getResults: presenter.getResults});
            }
            
            function getBaseline(string, handlers, count, start){
            	//var results=[];
				var results=baselines;
            		if (string && string.length > 0) {
              			 results =
                		    $.grep(baselines, function(option, index) {
                    		    return (option.name.match(
                  	         			 new RegExp(string.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i')));
                  		  });	
           			 }
            		handlers.success({count: results.length, members: results, start: 0, total: results.length});
        	}
          
          	function getHotfixes(string, handlers, count, start){
          		  	//var results=[];
					var results=hotfixes;
            		if (string && string.length > 0) {
              			 results =
                		    $.grep(hotfixes, function(option, index) {
                    		    return (option.name.match(
                  	         			 new RegExp(string.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i')));
                  		  });	
           			 }
            		handlers.success({count: results.length, members: results, start: 0, total: results.length});
          	}
			 function credentialsOptions(value){
          		if(value.target)
            		value = value.target.value;
            	if(value == "one"){
            		$(ENTER_CRED).hide();
            		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'));
            		}
            	}
            	if(value == "two"){
            		$(ENTER_CRED).show();
            		$(USERNAME).removeClass("hp-error");
            		$(PASSWORD).removeClass("hp-error");
            		useCurrentCredentials= false;
            		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'));
            		}
            	}
            		
            }
            
			function nodesettingscredentialsOptions(value){
				$(NODESETTINGS_CRED).hide();
				$(LINUX_SSH_KEY_FILE_PANEL).hide();
				clearCredInput();
				useCurrentCredentials= false;
				
          		if(value.target)
            		value = value.target.value;
					
            	if(value == "one"){
            		useCurrentCredentials =true;
            	}else if(value == "two"){
            		$(NODESETTINGS_CRED).show();
            		$(NODESETTINGS_USERNAME).removeClass("hp-error");
            		$(NODESETTINGS_PASSWORD).removeClass("hp-error");
            	} else if(value == "three") {
					$(LINUX_SSH_KEY_FILE_PANEL).show();
					$(LINUX_SSH_KEY_FILE_PANEL).css({"display":""});
					$(LINUX_SSH_KEY_FILE_USERNAME).removeClass("hp-error");
					instNodeFindAddBrowse.removeInputClass("hp-error");
					$(LINUX_SSH_KEY_FILE_USERNAME_ERR).hide();
					$(LINUX_SSH_KEY_FILE_PATH_ERR).hide();
            	}
            		
            }
            
			
			function validatefindnodesip(ip){
            	//ipv4 match
            	if(ip == '0.0.0.0' | ip == '255.255.255.255'){
					return "invalid";
            	}
            	var patt = /^(?:(?: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]?)$/
            	if(ip.match(patt))
            		return "ip";
            	else{
            		patt = /^((([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}))|:)))(%.+)?$/
            		if(ip.match(patt))
            			return "ipv6";
					else{
            			return "invalid";
            		}
            	}
            		
           }
		   function onItemsAddSuccess(data) {
			  addInProgress = false;
			  $(NODESETTINGS_BASELINE).hpSearchCombo("destroy");	
			  $(NODESETTINGS_HOTFIX).hpSearchCombo("destroy");
			  nodeSettingsDialog.cancel();
			  addselected(data);
			  formStateView.setMessage({summary: localizer.getString("hpsum.node.AddingNodesSuccessMsg"), status: 'ok', changing: false});			  
			}
			
			function onItemsAddError(data) {
				$(NODESETTINGS_BASELINE).hpSearchCombo("destroy");	
				$(NODESETTINGS_HOTFIX).hpSearchCombo("destroy");			
				reset();			  
				addInProgress = false;				  
				 
				addselected(data);
           }
           
		   function showSearchSplash(){
				
				 $(SEARCH_DIALOG).dialog({
			        modal : true,
			        position : "center",
			        draggable : false,
			        resizable : false,
			        show : 'fade',
			        dialogClass : 'hp-splash-dialog',
			        width : 400
			    });
			    
			    $(SEARCH_SPINNER).show();	
			}
			function closeSearchSplash()
			{
			$(SEARCH_SPINNER).hide();
			$(SEARCH_DIALOG).dialog('destroy');
			}
            function isValidRange() {
                //Simple range validation for ipv4 only
                var startIP = $(IP_START).val();
                var endIP = $(IP_END).val();
                var validRange = true;
                if(startIP.indexOf(".") != -1 && endIP.indexOf(".") != -1){
                    var startArray = startIP.split(".");
                    var endArray = endIP.split(".");
                    
                    if(startArray[0] != endArray[0] ||
                       startArray[1] != endArray[1] || 
                       startArray[2] != endArray[2] ||
                       parseInt(startArray[3]) > parseInt(endArray[3]))
                        validRange = false;
                }
                return validRange;
            }
            function btnSearchAbort()
			{
				var uri = '/session/'+session.getToken() + '/Complex/' + complex_id + '/Abort';
				
				searchInProgress = false;
				rest.postObject(uri, null, {
                        success : function(data) {
                            if (data.hapi.hcode == 0) {
                                $(SEARCH_NODE_ABORT_BUTTON).bind('click',btnSearchAbort);
								searchInProgress=false;
								$(SEARCH_NODE_ABORT).hide();
								$(SEARCH_BUTTON).addClass("hp-primary").removeClass("hp-disabled");
							}
                        },
                        error: function (){
							//$(SEARCH_NODE_ABORT).hide();
                        }
                    }, null);
					var node_tableid = '#hpsum-node-table';
					var node_table = $(node_tableid).dataTable();
					var nNodes = node_table.fnGetNodes( );
					var selected_node_tableid = '#hpsum-node-selected-table';
					var selected_node_table = $(selected_node_tableid).dataTable();
					var nSelectedNodes =  selected_node_table.fnGetNodes( );
						
					if(nNodes.length == 0){									
						$('#hpsum-node-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noFoundNodes');
						if(nSelectedNodes.length == 0)
						{
						$('#hpsum-node-selected-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noAddedNodes');
						}
					}
					
			}
			
			function btnLDAPSearchClicked()
			{
				selected_nodes = [];
				added_nodes = [];
				if(validateLDAPCredentials()){					
					if(!searchInProgress)
					{	
						searchInProgress = true;
						$(SEARCH_NODE_ABORT).show();
						$('#hpsum-node-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noNodesFoundYet');
						var selected_node_tableid = '#hpsum-node-selected-table';
						var selected_node_table = $(selected_node_tableid).dataTable();
						var nSelectedNodes =  selected_node_table.fnGetNodes( );
						if(nSelectedNodes.length == 0)
						{
						$('#hpsum-node-selected-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noNodesAddedYet');
						}
						
						var object={
							hapi: {
								ldap_server : $(LDAP_SERVER).val(),
								username : $(LDAP_USERNAME).val(),
								password : $(LDAP_PASSWORD).val(),
								max_returns : $(LDAP_MAXRETURN).val(),
								type : $(NODE_SEARCH_TYPE).val().toLowerCase() //should be "ldap".
							}
						};
						
						presenter.FindNodes(object, {
								 
							success : function(data) {
							onFindNodesSuccess(data); 
							},
							error : function(errorInfo) {
									onFindNodesError(errorInfo);
								}
						});
					}				
				}
				else
				{
					$(LDAP_ERR).show();
				}
			}
			
			function validatePortNumber(portvalue)
			{
				if(portvalue == "other"){
					portvalue = $(PORT_INPUT).val().toLowerCase();
					if(!portvalue.match(/^\d+$/)){
            			portvalue = "invalid";
					}				
				}
				return portvalue;
			}
			function btnSearchClicked()
			{
				selected_nodes = [];
				added_nodes = [];
				
				var ipstarttype = validatefindnodesip($(IP_START).val());
				var ipendtype = validatefindnodesip($(IP_END).val());
				var port_number = "0";
				var type = ipstarttype;
				if ($(NODE_SEARCH_TYPE).val().toLowerCase().match(/portAddress/i)) // if its IP search, pass 0 as port number.. 
				{
					type = PORT_STRING;					
					port_number = validatePortNumber($(NODE_PORT_VALUE).val().toLowerCase());
				}
				if((ipstarttype === ipendtype) && (!ipstarttype.match(/invalid/i)) && (!ipendtype.match(/invalid/i)) && isValidRange() && (!port_number.match(/invalid/i)))
				{
					if(!searchInProgress)
					{
						searchInProgress = true;
						$(SEARCH_NODE_ABORT).show();
						$('#hpsum-node-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noNodesFoundYet');
						var selected_node_tableid = '#hpsum-node-selected-table';
						var selected_node_table = $(selected_node_tableid).dataTable();
						var nSelectedNodes =  selected_node_table.fnGetNodes( );
						if(nSelectedNodes.length == 0)
						{
						$('#hpsum-node-selected-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noNodesAddedYet');
						}
						var ip_start = $(IP_START).val();
						var ip_end = $(IP_END).val();
						var max_returns = 255;
						
						var find_object = {
							hapi: 
							{
								ip_start : ip_start,
								ip_end : ip_end,
								max_returns : max_returns,
								type : IP_STRING
							}
						}
						
						if(type === PORT_STRING){
							find_object.hapi.port = port_number;
						}
					
						presenter.FindNodes(find_object, {
								 
							success : function(data) {
							onFindNodesSuccess(data); 
							},
							error : function(errorInfo) {
									onFindNodesError(errorInfo);
								}
						});
					}
				}
				else
				{	
					$(IP_ERR).show();
					if(ipstarttype.match(/invalid/i))
						$(IP_START).addClass("hp-error");
					if(ipendtype.match(/invalid/i))
						$(IP_END).addClass("hp-error");
					if(port_number.match(/invalid/i))
						$(PORT_INPUT).addClass("hp-error");
					$(SEARCH_BUTTON).attr("disabled",true);
				}
			}
			
			function addselected(data)
           {
			if(data != undefined && data.hapi.nodes.node.length > 0)
			{
				for(var nodeDataCount =0; nodeDataCount < data.hapi.nodes.node.length; nodeDataCount++)
				{
					// if found and is already added node, remove it from validnodes array.
					for(var validNodesCount=0; validNodesCount < valid_nodes.length; validNodesCount++)
					{
						if(valid_nodes[validNodesCount].node_ip == data.hapi.nodes.node[nodeDataCount].ip && data.hapi.nodes.node[nodeDataCount].exists){
							valid_nodes.splice(validNodesCount, 1);
							break;
						}
					}
				}
			}
			// add entries to the table..
			 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();
			 
			 var status_col = 2;
			 node_selected_table.fnClearTable();
		
			// add all valid nodes first.
			 if(valid_nodes.length > 0){
				node_selected_table.fnAddData(valid_nodes);
			}
							
			 selected_nodes = [];
			 
			 var nNodes = node_table.fnGetNodes( );
			 var aRow = new Array();
			 for( var row=0; row<nNodes.length; row++) {
				var nodeDetails = node_table.fnGetData(nNodes[row]);
				var nodeAdded = false;
				if ( $(nNodes[row]).hasClass("hp-selected") ) {
					if(valid_nodes.length > 0){
						for (var validNodesCount =0; validNodesCount<valid_nodes.length; validNodesCount++)
						{
							if(nodeDetails.node_ip == valid_nodes[validNodesCount].node_ip){
								aRow.push($(nNodes[row]).closest('tr')[0]);
							}
							else
							{
								// find the reason for the node for not being added.
								var messageAssigned = false;
								$(nNodes[row]).removeClass("hp-selected");
								$(nNodes[row]).addClass("hp-disabled");
								$(nNodes[row]).find("td:eq(2)").addClass("hp-error");	
								for(var nodeDataCount =0; nodeDataCount < data.hapi.nodes.node.length; nodeDataCount++)
								{
									if(nodeDetails.node_ip == data.hapi.nodes.node[nodeDataCount].ip && data.hapi.nodes.node[nodeDataCount].exists)
									{
										node_table.fnUpdate(data.hapi.nodes.node[nodeDataCount].hmessage, row, status_col);
										messageAssigned = true;
										break;
									}													
								}
								if(!messageAssigned)
								{
									node_table.fnUpdate(localizer.getString('hpsum.node.thisNodeAlready'), row, status_col);
								}
							}	
						}
						
					}
					else
					{
						// find the reason for the node for not being added.
						var messageAssigned = false;
						$(nNodes[row]).removeClass("hp-selected");
						$(nNodes[row]).addClass("hp-disabled");
						$(nNodes[row]).find("td:eq(2)").addClass("hp-error");
						if(data != undefined){
							for(var nodeDataCount =0; nodeDataCount < data.hapi.nodes.node.length; nodeDataCount++)
							{
								if(nodeDetails.node_ip == data.hapi.nodes.node[nodeDataCount].ip && data.hapi.nodes.node[nodeDataCount].exists)
								{																											
									node_table.fnUpdate(data.hapi.nodes.node[nodeDataCount].hmessage, row, status_col);
									messageAssigned = true;
									break;
								}													
							}
						}
						if(!messageAssigned)
						{
							node_table.fnUpdate(localizer.getString('hpsum.node.thisNodeAlready'), row, status_col);
						}
					}
					var selected_table = $("#hpsum-node-selected-table").dataTable();					
					var nNodesSelected = selected_table.fnGetNodes( );
					if(nNodesSelected.length == 0){
						$('#hpsum-node-selected-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noNodesAddedYet');
						}
				}	
			 } 
			 
			 for( var j=0;j<aRow.length;j++)
			 {
				node_table.fnDeleteRow(aRow[j]);
			 }
			 nNodes = node_table.fnGetNodes( );
			 
			 $(APPLY_SETTINGS_BUTTON).attr("disabled","disabled");
            }
		   
            function NodeSelectedTable(tableid) {
              
			  var oTab = $(tableid).dataTable({
			  oLanguage: {
					sEmptyTable: localizer.getString('hpsum.node.noAddedNodes'),
					sSearch: localizer.getString('hpsum.common.search'),
					sZeroRecords: localizer.getString('hpsum.node.noAddedNodes')
						},
				bPaginate : false,
				bProcessing : true,
				bFilter : false,
				bSort : true,
				bAutoWidth : false,
				bInfo : false,
				bRetrieve : true,
				bDestroy : true,
				//aaData: data,
				aoColumns : [
				{mDataProp: 'node_ip', sWidth: '300px'},
				{mDataProp: 'node_name'}
				],
				aaSorting: [[ 0, "asc" ]],
				fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
					//$(nRow).attr('id', aData.component_file_name);
					return nRow;
            }
          
			});
			}
			
			function onFindNodesError(errorInfo){                
                    $(IP_ERR).show();					                    					
					$(SEARCH_BUTTON).attr("disabled",true);
					searchInProgress=false;
					$(SEARCH_NODE_ABORT).hide();
			}
			
			function onFindNodesSuccess(data)
			{
				complex_id = data.hapi.complex_id;
				var node_uri = "/Session/" + session.getToken() + "/complex/" + complex_id ;
				
				var node_tableid = '#hpsum-node-table';
				$('#hpsum-node-table_filter').hpSearchCombo("enable");
			    var node_table = $(node_tableid).dataTable();
				if(node_table.length != 0)
					node_table.fnClearTable();
				$(SEARCH_NODE_ABORT).show();
				$(SEARCH_BUTTON).removeClass("hp-primary").addClass("hp-disabled");
				$(SEARCH_NODE_ABORT_BUTTON).bind('click',btnSearchAbort);	

				$(document).bind('keypress', function(e) {
					if(e.keycode == 27)
					btnSearchAbort();
					});
				$('#hpsum-node-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noNodesFoundYet');
				progressTimer = setInterval(function () {
				
				rest.getURI(node_uri + "/getstatus", {
				            success : function(data) {
							if(data.hapi.command_status === 1)
							{
								if(!searchInProgress)
									clearInterval(progressTimer);
							}
							else if(data.hapi.command_status === 0)
							{
								node_details = [];
                                clearInterval(progressTimer);
                                //closeSearchSplash();		
								searchInProgress = false;
								$(SEARCH_NODE_ABORT).hide();
								$(SEARCH_BUTTON).removeClass("hp-disabled").addClass("hp-primary");
								$(SEARCH_NODE_ABORT_BUTTON).unbind('click',btnSearchAbort);

								for(var j=0; j<data.hapi.nodes.node.length; j++)
								{                
									var node_data = [{
									'node_name':data.hapi.nodes.node[j].node_name,
									'node_ip':data.hapi.nodes.node[j].node_address,
									'status':''
									}];
									node_table.fnAddData(node_data); 									
								}
								var nNodes = node_table.fnGetNodes( ); 
								var selected_table = $("#hpsum-node-selected-table").dataTable();
								var nNodesSelected = selected_table.fnGetNodes( );
								if(nNodes.length == 0){
									$('#hpsum-node-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noFoundNodes');
									if(nNodesSelected.length == 0){									
										$('#hpsum-node-selected-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noAddedNodes');
									}
								}
								else{																
									if(nNodesSelected.length == 0){										
										$('#hpsum-node-selected-table tr')[1].cells[0].innerHTML = localizer.getString('hpsum.node.noNodesAddedYet');
									}
								}
								
								$(node_tableid + " tbody tr").click(function(e) 
								{
									node_details = node_table.fnGetData();
									var srcElem;
									//Check if firefox or (chrome and IE)
									if (e.srcElement) 
									{
										//Chrome and IE
										srcElem = e.srcElement;                                    
									} 
									else 
									{
										//Firefox
										srcElem = e.target;                          
									}
									var clickedCellIndex = srcElem.cellIndex
									if (clickedCellIndex === undefined) 
                                        $(APPLY_SETTINGS).attr("disabled",true);
									var bselected = false;									
									
									var nodedetails = node_table.fnGetData( this );
									if ( $(this).hasClass('hp-disabled') ) 
										return;
									if ( $(this).hasClass('hp-selected') ) {										
										bselected = false;
									}
									else {
										bselected = true;
									}
									$(this).toggleClass('hp-selected');
									if(bselected)
									{										
										selected_nodes.push(nodedetails);
									}
									else
									{										
										selected_nodes.pop(nodedetails);
									}
									if(selected_nodes.length === 0)
										$(APPLY_SETTINGS_BUTTON).attr("disabled",true);
									else
										$(APPLY_SETTINGS_BUTTON).removeAttr("disabled");
								});
							}							
							},
							error : function(errorInfo) {							
							}
						});
		          }, 3000);
			}
			
			function initNodeTable(tableid) 
			{            	
  				var oTab = $(tableid).dataTable({
					oLanguage: {
					    sEmptyTable: localizer.getString('hpsum.node.noFoundNodes'),
					    sSearch: localizer.getString('hpsum.common.search'),
					    sZeroRecords: localizer.getString('hpsum.node.noFoundNodes')
							},
				    bPaginate : false,
				    bProcessing : true,
				    bFilter : true,
				    bSort : true,
				    bAutoWidth : false,
				    bInfo : false,
				    bRetrieve : true,
				    bDestroy : true,
				    //aaData: data,
				    aoColumns : [
						{mDataProp: 'node_ip', sWidth: '300px'},
						{mDataProp: 'node_name'},
						{mDataProp: 'status'}
					  ],
					aaSorting: [[ 0, "asc" ]],
				    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
				        //$(nRow).attr('id', aData.component_file_name);
				        return nRow;
					}
					
			});
			}
		}
			
			return NodeFind;
    }());
	return new NodeFind();
	});
	