// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (GroupEditView)
 * This is a view class for Editing Group.
 */

define(['hpsum/presenter/group/GroupPresenter',
	'hpsum/presenter/node/NodePresenter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/Validator',
    'hp/view/FormStateView',
    'hp/core/HelpMenu',
    'hp/core/Localizer',
    'hp/core/Notifications',
	'hp/view/DialogView',
	'text!hpsumpages/group/dialog.html',
	'text!hpPages/core/header_help.html',
	'text!hpsumpages/group/nodegroup_warning_dialog.html',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'lib/jquery.selectBox',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpSearchCombo',
    'hp/lib/jquery.hpToggle',
	'hpsum/common/utility'],
function(presenter, nodePresenter, router, urlFragment, validator, FormStateView, helpMenu, localizer, notifications, DialogView, dialogHtml,headerHelpHtml,nodeGroupWarningHtml) { "use strict";
 
	var EditGroupView = ( function() {
			// consts can go here
			var FORM = '#hpsum-group-edit-form',
			    ADD = '#hpsum-group-edit',
			    CANCEL = '#hpsum-group-edit-close',
			    RESET = "#hpsum-group-reset", 
			    PANEL_SELECTOR = '#hpsum-group-edit-panel-selector',
			    PANELS = '#hpsum-group-edit-panels',
			    TITLE = '#hpsum-group-title',
			    NAME = '#hpsum-group-name',
			    NAMEERR = '#hpsum-group-name-error',
			    DESC = '#hpsum-group-description',
			    ADD_GROUP_NODES_TABLE = '#hpsum-group-add-group-nodes-table',
			    REMOVE_NODES_TABLE = '#hpsum-remove-group-nodes-table',
			    USERNAME = '#hpsum-group-user-name',
			    USERNAMEERR = '#hpsum-group-user-name-error',
			    PASSWORD = '#hpsum-group-password',
			    PASSWORDERR = '#hpsum-group-password-error',
			    ROUTE_PREFIX = '/group/edit',
			    BASELINES = '#hpsum-group-edit-baselines-search',
			    ASSOCBASELINE = '#hpsum-group-edit-baseline',
			    HOTFIX = '#hpsum-group-edit-addpackage-search',
			    ASSOCHOTFIX = '#hpsum-group-edit-addpackage',
			    REMOVEBASELINE = '#hpsum-group-edit-baseline-remove',
        		REMOVEHOTFIX = '#hpsum-group-edit-addpackage-remove',
        		ADDSELECT = '#hpsum-group-edit-add-select-all-nodes',
        		ADDDESELECT = '#hpsum-group-edit-add-deselect-all-nodes',
        		REMOVESELECT = '#hpsum-group-edit-remove-select-all-nodes',
        		REMOVEDESELECT = '#hpsum-group-edit-remove-deselect-all-nodes',
        		THROBBER = '#hpsum-group-edit-throbber',
        		BASELINE_WARNING = '#hpsum-group-edit-baseline-warning',
				BASELINE_INPUT = '#hpsum-group-edit-baselines-search-input',
				BASELINE_INPUT_ERR = '#hpsum-group-edit-baselines-search-input-err',
				HOTFIX_INPUT = '#hpsum-group-edit-addpackage-search-input',
				HOTFIX_INPUT_ERR = '#hpsum-group-edit-addpackage-search-input-err',
				WARNING_NODE_GROUP_TABLE = '#node-group-warning-table',
				ADD_NODE_WARNING = '#add-node-group-warning',
				NODE_GROUP_DIFFERENT_STATE = '#node-group-different-state',
				NODE_GROUP_DIFFERENT_BASELINE = '#node-group-different-baseline',
				NODE_WITH_DIFFERENT_GROUP = '#node-with-different-group',
				WARNING_DIALOG_OK = '#hpsum-group-node-ok';
				
			var NODE_INSTALLABLE_STATUS_UPDATE_REQ = 0;
      
			/**
			 * @constructor
			 */
			function EditGroupView() {
				var formStateView = new FormStateView(),
				    nodes = [],
				    groupCurrentNodes = [],
				    groupItem = null,
				    tableAddNodes = [],
				    tableRemoveNodes = [],
				    selectedAddNodes = [],
				    selectedRemoveNodes = [],
				    selectedBaselines = [],
				    editInProgress = false,
				    closeEditWindow = false,
				    editGroupSuccess = false,
				    baselines = '',
				    hotfixes = '',
				    assocBaseline = '',
					groupState = '',
				    newBaseline = null,
				    newHotFix = null,
				    assocHotFix = '',
				    searchResults = [],
				    attributes = {
				    	hapi: {
				    		username: "",
				    		password: ""
				    	}
				    },
				    groupExistingBaselines = [],
				    currentBaseline = null,
				    currentHotFix = null,
					nodeScheduled,
					setOk = false,
					errorFound = false,
					newAddpkg = false,
					newBase = false,
					currentAddpkg = null,
					currentBase = null,
                    installSets = [],
                    installSetObjList = [],
					isGroupHasAllGen10orAboveServer = false,
                    tableAddNodesName = [];
				
				var SUCCESS_VAL = 0;
				
				function onItemChange(item) {
					if(item != null)
					{
						reset();
						groupItem = item.hapi;

						if (groupItem && groupItem.hasOwnProperty("group_id")) {
							getGroupDataSuccess(item);
							$(TITLE).text(groupItem.group_name);
							$(NAME).attr('placeholder', groupItem.group_name);
							$(DESC).attr('placeholder', groupItem.group_description);
							$(ASSOCBASELINE).text('');
							$(ASSOCHOTFIX).text('');
							$(REMOVEBASELINE).hide();
							$(REMOVEHOTFIX).hide();							
							$(USERNAME).val('');
							$(PASSWORD).val('');

							if (groupItem.is_Gen10_or_above == true)
							    isGroupHasAllGen10orAboveServer = true;

							initializeInstallSet();

							//Removed the condition for checking for the default group(QXCR1001377000: SUM 7.2 Node Groups: Edit not proper for node group which is added first)
							newBaseline = newHotFix = currentBaseline = currentHotFix = null;
							groupExistingBaselines = [];
							if (groupItem.group_baselines) {
								groupExistingBaselines = groupItem.group_baselines;
							    populateDefaultBaseline(groupExistingBaselines);
							}
						} else {
							$(CANCEL).trigger('click');
						}
					}

			
				}
				function populateDefaultBaseline(defaultBaselines)
				{
				    for (var idx = 0; idx < defaultBaselines.length; idx++) {
				        var baseline = presenter.getBaselineDetailsforId(defaultBaselines[idx]);
									if (baseline) {
									    if (baseline.name.match(/^Additional Package/i)) {
									        $(ASSOCHOTFIX).text(baseline.name);
									        $(REMOVEHOTFIX).show();
									        $(HOTFIX).hpSearchCombo('set', { id: baseline.id, name: baseline.name });
									        assocHotFix = baseline;
									        currentHotFix = baseline;
									        if (newAddpkg) {
									            currentAddpkg = baseline.id;
									            newAddpkg = false;
									        }

									    } else {
									        $(ASSOCBASELINE).text(baseline.name);
									        $(REMOVEBASELINE).show();
									        $(BASELINES).hpSearchCombo('set', { id: baseline.id, name: baseline.name });
									        assocBaseline = baseline;
									        currentBaseline = baseline;
									        if (newBase) {
									            currentBase = baseline.id;
									            newBase = false;
									        }
									    }
									}
				        else {//installset
				            var installSetDetails = getInstallSetDetailforId(defaultBaselines[idx]);
				            if (installSetDetails) {
									        $(ASSOCBASELINE).text(installSetDetails.name);
									        $(REMOVEBASELINE).show();
									        $(BASELINES).hpSearchCombo('set', { id: installSetDetails.id, name: installSetDetails.name });
									        assocBaseline = installSetDetails;
									        currentBaseline = installSetDetails;
									        if (newBase) {
									            currentBase = installSetDetails.id;
									            newBase = false;
									        }
									    }
									}
								}
							}

				function initializeInstallSet()
				{
					if (isGroupHasAllGen10orAboveServer == true) {
					    presenter.getInstallSetAndTaskQueue({

					        success: function (installSetList, taskQueueFlag) {

					            installSets = installSetList
					            var isTaskQueuePresent = taskQueueFlag; //not needed for edit page

					            installSetObjList = [];
					                for (var i = 0 ; installSets.length > i; i++) {
					                    var installSetObj = {
					                        name: installSets[i].iloinstallset_name,
					                        id: installSets[i].iloinstallset_name
					                    }
					                    installSetObjList.push(installSetObj);
					                }
					        },
					        error: function (errorMessage) {
					            notifications.show(errorMessage, 'error');
					        }
					    });
					}
				}
				
				function changeLocation(location) {
					if (location.length > ROUTE_PREFIX.length) {
						$(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
					} else {
						$(PANELS).hpStackedPanels('setFirstPanel');
					}
				}

				function onNameEdit() {
					$(NAMEERR).hide();
					$(NAME).removeClass("hp-error");
					$(NAME).unbind('keyup', onNameEdit);
					$(ADD).attr("disabled", false);
				}
				
				function onDescEdit(){
					$(ADD).attr("disabled", false);
				}

				function onUserNameEdit() {
					$(USERNAMEERR).hide();
					$(USERNAME).removeClass("hp-error");
					$(USERNAME).unbind('keyup', onUserNameEdit);
					$(ADD).attr("disabled", false);
				}
				
				function onPasswordEdit() {
					$(PASSWORDERR).hide();
					$(PASSWORD).removeClass("hp-error");
					$(PASSWORD).unbind('keyup', onPasswordEdit);
					$(ADD).attr("disabled", false);
				}

				function onGroupEditSuccess(data) {
					$(ADD).attr('disabled', false);
					$(THROBBER).hide();
					if (data.hapi.hcode == 5030) {
						$(NAMEERR).text(localizer.getString('hpsum.group.groupAlreadyExists'));
						$(NAME).addClass("hp-error");
						$(NAMEERR).show();
						$(NAME).keyup(onNameEdit);
						editGroupSuccess = false;
						closeEditWindow = false;
					}
					else {
					reset();
					editGroupSuccess = true;
					closeEditWindow = true;
					$(CANCEL).trigger('click');
					}
				}

				function onGroupEditError(msg) {
					$(ADD).attr('disabled', false);
					$(THROBBER).hide();
					editInProgress = false;
					$(NAMEERR).text(msg);
					$(NAME).addClass("hp-error");
					$(NAMEERR).show();
				}

				function reset() {
					formStateView.reset();
					editInProgress = false;
					$(NAMEERR).hide();
					$(NAME).removeClass("hp-error");
					$(ADD).attr('disabled', true);
					$(BASELINES).html('');
					$(HOTFIX).html('');
					$('.hp-close').css("display","none");
					$(BASELINE_INPUT).removeClass("hp-error");
					$(HOTFIX_INPUT).removeClass("hp-error");
					$(BASELINE_INPUT_ERR).hide();
					$(HOTFIX_INPUT_ERR).hide();
					onAddDeselectAll.call(this);
					onRemoveDeselectAll.call(this);
					$(ASSOCBASELINE).text('');
					$(ASSOCHOTFIX).text('');
					$(REMOVEBASELINE).hide();
                    $(REMOVEHOTFIX).hide();
					$(BASELINE_WARNING).hide();
				}


				function getSelectedBaselines() {
					var fail = false;
					var finalBaseline;
					var finalHotFix;
					var baselineJson = [];
					if ((newBaseline == null) && (assocBaseline == null))
						finalBaseline = null;
					else
						finalBaseline = newBaseline;
					if ((newHotFix == null) && (assocHotFix == null))
						finalHotFix = null;
					else
						finalHotFix = newHotFix;

					if ((finalHotFix == null) && (finalBaseline == null))
						fail = true;
					else if (finalHotFix == null) {
						baselineJson.push(finalBaseline.id);
						newBaseline = finalBaseline;
					}
					else if (finalBaseline == null) {
						baselineJson.push(finalHotFix.id);
						newHotFix = finalHotFix;
					}
					else {
						baselineJson.push(finalBaseline.id);
						newBaseline = finalBaseline;
						baselineJson.push(finalHotFix.id);
						newHotFix = finalHotFix;
					}
					if (fail == false) {
						selectedBaselines = baselineJson;
						for (var idx = 0; idx < selectedBaselines.length; idx++) {
							if (selectedBaselines[idx] == null) {
								selectedBaselines.splice(idx, 1);
							}
						}
						
				        var validatedBaselines = [],
							foundExistingBaselines = 0;
						
				        validatedBaselines = selectedBaselines;
				        for (var idx = 0; idx < validatedBaselines.length; idx++) {
				            if (-1 != $.inArray(validatedBaselines[idx], groupExistingBaselines)) {
								foundExistingBaselines++;
							}
						}
						if (foundExistingBaselines == selectedBaselines.length && foundExistingBaselines == groupExistingBaselines.length) {
							selectedBaselines = [];
						}	
					}
				    else {
				        selectedBaselines = [];
				}
				
				}
				
				function validate() {
					
					if (!validateCredentialsValues) {
						return false;			
					}
					
					return validateName() || validateDescription() || validateSelectedNodes() || validateCredentials() || validateBaselines();
				}

				function validateName() {
					var success = true;
					var trimmedGroupName = $.trim($(NAME).val());
					if ((!trimmedGroupName.match(new RegExp(/^[a-z][a-z-0-9 ]*$/i))) ||
						(groupItem.group_name == trimmedGroupName) ||
						(trimmedGroupName == '')) {
						success = false;
					}

					return success;
				}

				function validateDescription() {
					var success = true;
					if ($(DESC).val() == '') {
						success = false;
					}
					return success;
				}

				function validateSelectedNodes() {
					return getSelectedAddNodes().length > 0 || getSelectedRemoveNodes().length > 0;
				}

				function validateCredentialsValues() {
					var success = true;
					if ($(USERNAME).val() == '' && $(PASSWORD).val() != '') {
						$(USERNAMEERR).text(localizer.getString('hpsum.group.requiredUserName'));
						$(USERNAME).addClass("hp-error");
						$(USERNAMEERR).show();
						$(USERNAME).keyup(onUserNameEdit);
						success = false;
					}
					else if ($(USERNAME).val() != '' && $(PASSWORD).val() == '') {
						$(PASSWORDERR).text(localizer.getString('hpsum.group.requiredPassword'));
						$(PASSWORD).addClass("hp-error");
						$(PASSWORDERR).show();
						$(PASSWORD).keyup(onPasswordEdit);
						success = false;
					}
					
					return success;
				}
				
				function validateCredentials() {
					var success = true;
					if ($(USERNAME).val() == '' && $(PASSWORD).val() == ''){
						success = false;
					}
					return success;
				}
				
				function validateBaselines() {
					getSelectedBaselines();
					var latestBaseline = "",
					    latestHotFix = "",
					    currBaseline = "",
					    currHotFix = "";
					if (newBaseline) {
						latestBaseline = newBaseline.id;
					}
					if (currentBaseline) {
						currBaseline = currentBaseline.id;
					}
					if (newHotFix) {
						latestHotFix = newHotFix.id;
					}
					if (currentHotFix) {
						currHotFix = currentHotFix.id;
					}
					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());
					}
					errorFound = false;
					for (var tmp = 0; tmp < baselineJson.length; tmp++) {
					    if (baselineJson[tmp]) {
					        var baselinedetails = presenter.getBaselineDetailsforId(baselineJson[tmp]);
						    if (!baselinedetails) {
						        var installSetDetails = getInstallSetDetailforId(baselineJson[tmp]);
						        if (installSetDetails == null) {
						            errorFound = true;
						            if (baselineJson[tmp] == $(BASELINES).val()) {
						                $(BASELINE_INPUT_ERR).text(localizer.getString('hpsum.node.invalidBaseline'));
						                $(BASELINE_INPUT).addClass("hp-error");
						                $(BASELINE_INPUT_ERR).show();
						            }
						            if (baselineJson[tmp] == $(HOTFIX).val()) {
						                $(HOTFIX_INPUT_ERR).text(localizer.getString('hpsum.node.invalidAdtPackage'));
						                $(HOTFIX_INPUT).addClass("hp-error");
						                $(HOTFIX_INPUT_ERR).show();
						            }
						        }
							}	
						}
					}
					if(errorFound)
						return errorFound;
					
					return latestBaseline != currBaseline || latestHotFix != currHotFix;
				}
				
				function initWarningTable()
				{
					var dummyNodeData = [];
					return $(WARNING_NODE_GROUP_TABLE).dataTable({
						oLanguage : {
						    sEmptyTable: localizer.getString("hpsum.group.noNodesInGroup")
						},
						bPaginate : false,						
						bFilter : false,
						bInfo : false,
						bAutoWidth : false,
						bRetrieve : false,
						aaData : dummyNodeData,
						aoColumns : [
						{
						mDataProp : 'node', fnRender: function (oObj) {
								
								return oObj.aData.node;
						}
						}, {
						mDataProp : 'current_group', fnRender: function (oObj) {
								
								return oObj.aData.current_group;
						}},
						{
						mDataProp : 'current_node_baseline', fnRender: function (oObj) {
								
								return oObj.aData.current_node_baseline;
						}},
						{
						mDataProp : 'current_node_additional_package', fnRender: function (oObj) {
								
								return oObj.aData.current_node_additional_package;
						}}],
						
					fnCreatedRow: function (nRow, aData, iDataIndex) {
		                nRow.className += aData.name;
		            },
		            fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
		                return nRow;
		            },
		            "fnDrawCallback": function (oSettings) {
		                if (oSettings.aiDisplay.length == 0) {
		                    return;
		                }
		            },
					bScrollCollapse : true,
		            "sDom": 'lfr<"giveHeight"t>ip'
					});	
				}
			
				function validateNodes(groupItem) {
					var retValue = true,
					 isDifferentState = false,
					 isDifferentStateDoInventory = false,
					 isDifferentGroup = false,
					 isDifferentBaseline = false,
					 changeAllNodesState = false,
					 nodeGrpList = [],
					 isDifferentBaseline = false,
					 isNodeAndGrpInUAN = false;
				
					for(var gCount = 0; gCount <selectedAddNodes.length; gCount++)
					{
						var currentBL = localizer.getString('hpsum.common.notApplicable'),
						currentABL = localizer.getString('hpsum.common.notApplicable'),
						currentgrp = localizer.getString('hpsum.common.notApplicable');
					
						for (var nodeidx = 0; nodeidx < nodes.length; nodeidx++) {
						    if (nodes[nodeidx].node_id === selectedAddNodes[gCount]) {
						        var nodeData = nodes[nodeidx];
						        if (nodeData) {
						            for (var idx = 0; idx < nodeData.baselines.length; idx++) {
						                var baseline = presenter.getBaselineDetailsforId(nodeData.baselines[idx]);
						                if (baseline) {
						                    if (baseline.name.match(/^Additional Package/i)) {
						                        currentABL = baseline.name;
						                    } else {
						                        currentBL = baseline.name;
						                    }
						                }
						                else if (nodeData.baselines[idx].charAt(0) == 'I') {
						                    if (nodeData.hasOwnProperty('installsets') == true && nodeData.installsets.hasOwnProperty('installset')) {
						                        var nodeInstallSet = nodeData.installsets.installset;
						                        for (var installSetCount in nodeInstallSet) {
						                            if (nodeInstallSet[installSetCount].iloinstallset_id.match(nodeData.baselines[idx])) {
						                                currentBL = nodeInstallSet[installSetCount].iloinstallset_name;
						                                break;
						            }
						                        }
						                    }
						                }
						            }

						            if (nodeData.group_name) {
						                isDifferentGroup = true;
						                currentgrp = nodeData.group_name;
						            }
						     
						            var groupdata = {
						                nodeAddress: nodeData.node_name,
						                currentGrp: currentgrp,
						                currentBaseline: currentBL,
						                currentAddPckg: currentABL
						            };


						            if ((groupState.match(/UAN/i) && (nodeData.node_state.match(/idle/i)))) {

						                isDifferentStateDoInventory = true;
						            }
						            else if ((groupState.match(/UAN/i) && (nodeData.node_state.match(/UAN/i)))) {
						                isNodeAndGrpInUAN = true;
						            }
                        else if (groupState == nodeData.node_state) {
						                //do nothing
						            }
						            else if (!nodeData.node_state.match(/idle/i)) {

						                isDifferentState = true;
						            }
						            
						           

                					 var grpBaseline = [];
						             grpBaseline = getFinalBaseline();
						            
									if (nodeData.baselines.length > 0) {
						                for (var bCount = 0; bCount < nodeData.baselines.length; bCount++) {
						                    if (grpBaseline.length <= 0) {
						                        isDifferentBaseline = true;
						                    }
						                    else {
						                        var nodeInstallsetName = "";
						                        if (nodeData.baselines[bCount].charAt(0) == 'I') {
						                            if (nodeData.hasOwnProperty('installsets') == true && nodeData.installsets.hasOwnProperty('installset')) {
						                                var nodeInstallSet = nodeData.installsets.installset;
						                                for (var installSetCount in nodeInstallSet) {
						                                    if (nodeInstallSet[installSetCount].iloinstallset_id.match(nodeData.baselines[bCount])) {
						                                        nodeInstallsetName = nodeInstallSet[installSetCount].iloinstallset_name;
						                                        break;
						                                    }
						                                }
						                            }
						                        }

						                        if((grpBaseline.indexOf(nodeData.baselines[bCount]) == -1) && (grpBaseline.indexOf(nodeInstallsetName) == -1))
                                                {
						                                isDifferentBaseline = true;
						                                break;
						                            }
						                        }
						                    }
						                }
										else{
											if (grpBaseline.length > 0) {
											    isDifferentBaseline = true;
											}
										}

						            nodeGrpList.push(groupdata);
						        } //nodedata present
						    }//nodes and selected node check
						}//nodes loop
					}//selectedNodeCount loop
			
					
					if (isDifferentState == true || isDifferentBaseline == true || isDifferentGroup == true || isDifferentStateDoInventory == true)
					{
				
						var contents = $(nodeGroupWarningHtml);		
					
						localizer.localizeDom(contents);		
						var dialogView = new DialogView();
						$(WARNING_DIALOG_OK).attr('disabled' , false);
						dialogView.init({contents: contents,
							 ok: function (element) {
					
								 	editCallback(retValue);
                                                 },
                            cancel: function (element) {
								retValue = false;
								editCallback(retValue);
                            }
						});		
		    							
						if(isDifferentState == true)
						{ 
							var wMsgTable = '<table><tr><td><div class="hp-status"><div class="hp-status-value hp-status-warning"><span class="hp-value">warning</span></div></div></td><td>';
							$(NODE_GROUP_DIFFERENT_STATE , contents).html(wMsgTable.concat(localizer.getString('hpsum.group.nodeAndGrpStateNotSame'))+ '</td></tr></table>');
						}
						else if(isDifferentStateDoInventory == true)
						{
							var wMsgTable = '<table><tr><td><div class="hp-status"><div class="hp-status-value hp-status-warning"><span class="hp-value">warning</span></div></div></td><td>';
							$(NODE_GROUP_DIFFERENT_STATE , contents).html(wMsgTable.concat(localizer.getString('hpsum.group.nodeAndGrpStateNotSameDoInventory')) + '</td></tr></table>');
						}
						
						
						if(isDifferentGroup == true)
						{
							var wMsgTable = '<table><tr><td><div class="hp-status"><div class="hp-status-value hp-status-warning"><span class="hp-value">warning</span></div></div></td><td>';
							$(NODE_WITH_DIFFERENT_GROUP , contents).html(wMsgTable.concat(localizer.getString('hpsum.group.nodePartOfOtherGrp'))+ '</td></tr></table>');					
						}
						
						if (isNodeAndGrpInUAN == true && isDifferentBaseline == true)
						{
						    var wMsgTable = '<table><tr><td><div class="hp-status"><div class="hp-status-value hp-status-warning"><span class="hp-value">warning</span></div></div></td><td>';
						    $(NODE_WITH_DIFFERENT_GROUP, contents).html(wMsgTable.concat(localizer.getString('hpsum.group.nodeAndGrpInUANWithNotSameBaseline')) + '</td></tr></table>');
						}
						else if (isDifferentBaseline == true) {
						    var wMsgTable = '<table><tr><td><div class="hp-status"><div class="hp-status-value hp-status-warning"><span class="hp-value">warning</span></div></div></td><td>';
						    $(NODE_GROUP_DIFFERENT_BASELINE, contents).html(wMsgTable.concat(localizer.getString('hpsum.group.nodeAndGrpBaselineNotSame')) + '</td></tr></table>');
						}

						$(ADD_NODE_WARNING,contents).show();
						$(WARNING_NODE_GROUP_TABLE , contents).show();
						var warningTable = initWarningTable();
								warningTable.fnClearTable();
								for(var count = 0; count<nodeGrpList.length; count++)
								{
										warningTable.fnAddData({
										'node' : nodeGrpList[count].nodeAddress,
									   'current_group' : nodeGrpList[count].currentGrp,
									   'current_node_baseline' : nodeGrpList[count].currentBaseline,
									   'current_node_additional_package' :nodeGrpList[count].currentAddPckg
										});
								}		
					}
					else
					{
						 editCallback(retValue);
					}
				
				}
				
				function getFinalBaseline()
				{
				    var grpBaseline = [];
				    if (newBaseline) {
				        grpBaseline.push(newBaseline.id);
				    }

				    if (newHotFix) {
				        grpBaseline.push(newHotFix.id);
				    }
				    return grpBaseline;
				}

				function updateBaseline()
				{
				    if (validateBaselines()) {
				        presenter.setAttributes(groupItem, {
				            hapi: {
				                baselines: {
				                    remove_existing_baselines: 'true',
				                    baseline: selectedBaselines
				                }
				            }
				        }, {
				            success: function (data) {
				                editGroupSuccess = true;
				            },
				            error: function (errorMessage) {
				                notifications.show(errorMessage, 'error');
				            }
				        });
				        closeEditWindow = true;
				    }
				}

				function getSelectedAddNodes() {
					return selectedAddNodes;
				}

				function getSelectedRemoveNodes() {
					return selectedRemoveNodes;
				}

				function onEditGroup() {
				    errorFound = false;
					if (validate()) {
					 if (errorFound)
							return;
					 if (groupItem && groupItem.hasOwnProperty("group_id")) {
					 	$(ADD).attr('disabled', true);
						$(THROBBER).show();
						if (!editInProgress) {
							editInProgress = true;

							if (validateCredentials()) {
								attributes.hapi.username = $(USERNAME).val();
								attributes.hapi.password = $(PASSWORD).val();

								presenter.setAttributes(groupItem, attributes, {
									success : function(data) {
										editGroupSuccess = true;
									},
									error : function(errorMessage) {
										notifications.show(errorMessage, 'error');
									}
								});
								closeEditWindow = true;
							}
						
							if (getSelectedRemoveNodes().length > 0) {
								var selectedRemoveNodes = getSelectedRemoveNodes();
								presenter.removeNodes(groupItem, {
									nodes : selectedRemoveNodes
								}, {
									success : function(data) {
										editGroupSuccess = true;
									},
									error : function(errorMessage) {
										notifications.show(errorMessage, 'error');
									}
								}, true);
								closeEditWindow = true;
							}

							if (!groupItem.group_state.match(/idle/i)) {
							    var grpBaseline = getFinalBaseline();
							    if (grpBaseline.length <= 0)
							    {
							        //If the Group is not idle we need to have a valid baseline
							        $("<div></div>").dialog({
							            buttons: {
							                "Ok": function () {
							                    $(this).dialog("close");
							                }
							            },
							            close: function (event, ui) { $(this).remove(); },
							            resizable: false,
							            title: "Edit",
							            modal: true
							        }).text(localizer.getString('hpsum.node.pleaseSelectAPorB'));
							        $(ADD).attr('disabled', false);
							        $(THROBBER).hide();
							        editInProgress = false;
							        return;
							    }
							}
							
							if (getSelectedAddNodes().length > 0 || validateName() || validateDescription())
							{
							    if (errorFound == false) {
							        validateNodes(groupItem);
							    }
							    else {
							        $(ADD).attr('disabled', false);
							        $(THROBBER).hide();
							        editInProgress = false;
							    }
							}
							else {
							    updateBaseline();
								$(ADD).attr('disabled', false);
								$(THROBBER).hide();
								if (editGroupSuccess) {
									notifications.show(localizer.getString("hpsum.group.editedGroup") + ' ' + groupItem.group_name, 'ok');
								}
								reset();
								$(CANCEL).trigger('click');
							}
							
							
							
						}
					  } else {
					  	$(CANCEL).trigger('click');
					  }
					} else {
						$(CANCEL).trigger('click');
					}
				}

				
				 function editCallback(value){
					 if(value == true)
					 {
					     updateBaseline();
					     var selectedAddNodes = getSelectedAddNodes();
						presenter.editItem(groupItem, {
						name : $(NAME).val(),
						description : $(DESC).val(),
						nodes : selectedAddNodes
						}, {
						success : onGroupEditSuccess,
						error : function(errorMessage) {
							notifications.show(errorMessage, 'error');
						}});
		
						$(ADD).attr('disabled', false);
						$(THROBBER).hide();
						if (editGroupSuccess) {
							notifications.show(localizer.getString("hpsum.group.editedGroup") + ' ' + groupItem.group_name, 'ok');
						}
						reset();
						$(CANCEL).trigger('click');
					 }
					 else{
						$(ADD).attr('disabled', false);
						$(THROBBER).hide();
					 }
					  editInProgress = false;	
				}

				function getAllNodesSuccess(results) {
					$(ADD_GROUP_NODES_TABLE).dataTable().fnClearTable(true);
					$(REMOVE_NODES_TABLE).dataTable().fnClearTable(true);
					nodes = results.hapi.output_data.nodes.node;
					ipsSortedAsc = sortNodes(nodes,'asc','sortedIps');
					ipsSortedDesc = ipsSortedAsc.slice().reverse();
					tableAddNodes = [];
					tableAddNodesName = [];
					tableRemoveNodes = [];
					selectedAddNodes = [];
					selectedRemoveNodes = [];
					var haveAddNodes = false,
						haveGroupNodes =  false;

					for (var idx = 0; idx < nodes.length; ++idx) {
								var nodeData = nodes[idx],
								    status = 'unknown',
								    change = false,
								    nodeStatus = nodeData.node_status,
								    rebootRequired = "",
								    nodeBaseline = localizer.getString('hpsum.group.noBaseline'),
								    adtPackage = localizer.getString('hpsum.group.noAdtPackage');
								if (nodeData.node_state.match(/inventory|analysis|install$/i) || nodeData.node_phase.match(/initialize/i)) {
									status = 'unknown';
									change = true;
								}else if (nodeData.node_state.match(/error/i) || nodeData.node_phase.match(/initialize|InActive/i)) {
									status = 'error';
								} else if (nodeData.node_state.match(/uan/i)) {
									if(nodeData.installable_state == NODE_INSTALLABLE_STATUS_UPDATE_REQ){									
										status = 'warning';
									} else {
										status = 'ok';
									}
								} else if (nodeData.node_state.match(/scheduled|REMOTE_STAGING_SCHEDULED/i) && 
										   nodeData.node_phase.match(/scheduled|Inventory/i)) {
										status = 'scheduled';
								} else if (nodeData.node_state.match(/installdone/i)) {
									if(nodeData.return_code < SUCCESS_VAL) {									
										status = 'error';
										nodeStatus = localizer.getString('hpsum.node.installDoneWithErrors');
									} else {
										status = 'ok';
									}

									if (nodeData.return_code == 1) {
										rebootRequired = localizer.getString('hpsum.node.rebootRequired')
									}
								} else if (nodeData.node_state.match(/idle/i)) {
									if (nodeData.node_phase.match(/unknown|error/i)) {
										status = 'error';
									} else {
										status = 'warning';
									}
								}
				
								if (nodeData.baselines) {
								    for (var i = 0; i < nodeData.baselines.length; i++) {
								        if (nodeData.baselines[i].match('/')) {
								            var baseline = presenter.getBaselineDetailsforId(nodeData.baselines[i]);
								            if (baseline) {
								                if (baseline.name.match(/^Additional Package/i)) {
								                    adtPackage = baseline.name;
								                } else {
								                    nodeBaseline = baseline.name;
								                }
								            }
								        }
								        else if (nodeData.baselines[i].charAt(0) == 'I') {
								            if (nodeData.hasOwnProperty('installsets') == true && nodeData.installsets.hasOwnProperty('installset')) {
								                var nodeInstallSet = nodeData.installsets.installset;
								                for (var count in nodeInstallSet) {
								                    if (nodeInstallSet[count].iloinstallset_id.match(nodeData.baselines[i])) {
								                        nodeBaseline = nodeInstallSet[count].iloinstallset_name;
								                    }
								                }
								            }
								        }
								        else {
								            nodeBaseline = nodeData.baselines[i];
								        }
									}
								}
						
								
								if ($.inArray(nodeData.node_id, groupCurrentNodes) != -1) {
										$(REMOVE_NODES_TABLE).dataTable().fnAddData({
										status : status,
										change : change,
										node_id : nodeData.node_id,
										name : nodeData.node_name,
										type : displayILO(nodeData.type),
										node_status : nodeStatus,
										uri : nodeData.uri,
										state : nodeData.node_state,
										return_code : nodeData.return_code,
										reboot : rebootRequired,
										baseline : nodeBaseline,
										adtPackage : adtPackage,
										group_name : nodeData.group_name
									});
									
									$(REMOVESELECT).attr('disabled', false);
									tableRemoveNodes.push(nodeData.node_id);
									
								} else {
									$(ADD_GROUP_NODES_TABLE).dataTable().fnAddData({
										status : status,
										change : change,
										node_id : nodeData.node_id,
										name : nodeData.node_name,
										type : displayILO(nodeData.type),
										node_status : nodeStatus,
										uri : nodeData.uri,
										state : nodeData.node_state,
										return_code : nodeData.return_code,
										reboot : rebootRequired,
										baseline : nodeBaseline,
										adtPackage : adtPackage,
										group_name : nodeData.group_name,
										phase : nodeData.node_phase
									});
										$('.tooltip').hpTooltip();
										$(ADDSELECT).attr('disabled', false);
										if (!nodeData.node_phase.match(/Unknown|Initialize|Inventory|Analyzing|Deploying/i))
										{
										    tableAddNodes.push(nodeData.node_id);
										    tableAddNodesName.push(nodeData.node_name);
										}
									
								$(ADD_GROUP_NODES_TABLE + ' tbody tr').click(function(e) {
						
									if ($(this).hasClass('hp-disabled'))
									{
										 return;  
									}
								});
								}
					}
					if (newBaseline != null)
					    refreshAvailableNodesTable(newBaseline);
				}
				
                
				function onAddTableRow(e) {
					var aData = $(ADD_GROUP_NODES_TABLE).dataTable().fnGetData(this),
							selectdNodesLenght = selectedAddNodes.length,
						    idx;
						if ($(this).hasClass('hp-selected')) {
							$(this).removeClass('hp-selected');
							for (idx = 0; idx < selectdNodesLenght; idx += 1) {
								if (selectedAddNodes[idx] === aData.node_id) {
									selectedAddNodes.splice(idx, 1);
									break;
								}
							}
							if (0 == selectedAddNodes.length) {
								$(ADDDESELECT).attr('disabled', true);
								$(ADDSELECT).attr('disabled', false);
							}
							else if (selectedAddNodes.length < tableAddNodes.length) {
								$(ADDSELECT).attr('disabled', false);
							}
						} else if(!$(this).hasClass('hp-disabled'))
						{
							$(this).addClass('hp-selected');
							selectedAddNodes = selectedAddNodes.concat(aData.node_id)
							$(ADDDESELECT).attr('disabled', false);
							$(ADD).attr("disabled", false);
							if (selectedAddNodes.length == tableAddNodes.length) {
								$(ADDSELECT).attr('disabled', true);
							}
							else if (selectedAddNodes.length < tableAddNodes.length) {
								$(ADDSELECT).attr('disabled', false);
							}
						}
				}
				
				function onRemoveTableRow(e) {
					var aData = $(REMOVE_NODES_TABLE).dataTable().fnGetData(this),
							selectdNodesLenght = selectedRemoveNodes.length,
						    idx;
						if ($(this).hasClass('hp-selected')) {
							$(this).removeClass('hp-selected');
							for (idx = 0; idx < selectdNodesLenght; idx += 1) {
								if (selectedRemoveNodes[idx] === aData.node_id) {
									selectedRemoveNodes.splice(idx, 1);
									break;
								}
							}
							if (0 == selectedRemoveNodes.length) {
								$(REMOVEDESELECT).attr('disabled', true);
								$(REMOVESELECT).attr('disabled', false);
							}
							else if (selectedRemoveNodes.length < tableRemoveNodes.length) {
								$(REMOVESELECT).attr('disabled', false);
							}
						} else {
							$(this).addClass('hp-selected');
							selectedRemoveNodes = selectedRemoveNodes.concat(aData.node_id)
							$(REMOVEDESELECT).attr('disabled', false);
							$(ADD).attr("disabled", false);
							if (selectedRemoveNodes.length == tableRemoveNodes.length) {
								$(REMOVESELECT).attr('disabled', true);
							}
							else if (selectedRemoveNodes.length < tableRemoveNodes.length) {
								$(REMOVESELECT).attr('disabled', false);
							}
						}
				}
				
				function getAllNodesError(data) {
				}

				function getGroupDataSuccess(groupData) {
					groupCurrentNodes = groupData.hapi.group_nodes.group_node;
					groupState = groupData.hapi.group_state;
					nodePresenter.getNodeDataForGroup({
						success : getAllNodesSuccess,
						error : getAllNodesError
					});
				}

				function getBaseline(string, handlers, count, start) {
				    var results = baselines.concat(installSetObjList);
					if (string && string.length > 0) {
						results = $.grep(baselines, function(option, index) {
							return (option.name.match(new RegExp(string.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i')));
						});
					}
					handlers.success({
						count : results.length,
						members : results, 
						start: 0, 
						total: results.length
					});
				}

				function getHotfixes(string, handlers, count, start) {
					var results = hotfixes;
					if (string && string.length > 0) {
						results = $.grep(hotfixes, function(option, index) {
							return (option.name.match(new RegExp(string.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i')));
						});
					}
					handlers.success({
						count : results.length,
						members : results, 
						start: 0, 
						total: results.length
					});
				}

				function getBaselinesSuccess(searchResults) {
					baselines = $.grep(searchResults, function(option, index) {
						return !(option.name.match(new RegExp('^Additional', 'i')));
					});
					hotfixes = $.grep(searchResults, function(option, index) {
						return (option.name.match(new RegExp('^Additional', 'i')));
					});
					populateDefaultBaseline(groupExistingBaselines);
				}

				function getBaselinesError(msg) {
				}
          
				function onAddSelectAll() {
				    $(ADDSELECT).attr('disabled', true);
					$(ADDDESELECT).attr('disabled', false);
					$(ADD).attr("disabled", false);
					selectedAddNodes = [];
					var selectedInstallSetFoundForNode = false;
					var rows = $(ADD_GROUP_NODES_TABLE).dataTable().fnGetNodes();
					for (var idx = 0; idx < tableAddNodes.length; ++idx) {
					    selectedAddNodes = selectedAddNodes.concat(tableAddNodes[idx]);
					}
	
					for (var row_idx = 0; row_idx < rows.length; row_idx++) { // go through each row and check for available baseline for that node
					    var cells = rows[row_idx].getElementsByTagName('td');
					    var nodeId = cells[1]; //node name
					    if (tableAddNodesName.indexOf(nodeId.textContent) != -1) { //check if that node is valid to select
					        if ((newBaseline != undefined) && !newBaseline.id.match('/')) {       //selection/deselection of node is for install set only
					            var status = cells[0]; //node status
					                 for (var node_idx = 0; node_idx < nodes.length; ++node_idx) {
					                    var nodeData = nodes[node_idx];
					                    if (nodeData.node_name == nodeId.textContent) {
					                        if ((nodeData.installsets.hasOwnProperty('installset') == true) && nodeData.installsets.installset.length > 0) {
					                            var nodeInstallSet = nodeData.installsets.installset;
					                            for (var count in nodeInstallSet) {
					                                if ((nodeInstallSet[count].iloinstallset_name.match(newBaseline.name))) {
					                                    selectedInstallSetFoundForNode = true;
					                                    break;
					                                }
					                            }
					                        }

					                        //If selected Install Set is not found for current node,disable and grey out the row
					                        if (selectedInstallSetFoundForNode == false) {
					                            $(rows[row_idx]).addClass('hp-disabled');
					                            $(rows[row_idx]).removeClass('hp-selected');
					                            $(rows[row_idx]).css('background', '#C6C9CA');
					                            AddToolTipAttrAndClass(rows[row_idx]);

					                            //If user selected a node and then selected some Install Set which is not applicable to this node then remove 
					                            //that node from selected node list
					                            var index = selectedAddNodes.indexOf(nodeData.node_id);
					                            if (index > -1) {
					                                selectedAddNodes.splice(index, 1);
					                            }
					                        }
					                        else {
					                            $(rows[row_idx]).addClass('hp-selected');
					                        }
					                        selectedInstallSetFoundForNode = false;
					                        break;
					                    }
					                }
					        }
					        else {
					            $(rows[row_idx]).addClass('hp-selected');
					        }
					    }
					}
				}
				
          		function onAddDeselectAll() {
          		    $(ADD_GROUP_NODES_TABLE + ' tbody tr').removeClass('hp-selected');
					$(ADDSELECT).attr('disabled', false);			
					$(ADDDESELECT).attr('disabled', true);
					selectedAddNodes = [];
				}
				
				function onRemoveSelectAll() {
					$(REMOVE_NODES_TABLE + ' tbody tr').addClass('hp-selected');
					$(REMOVESELECT).attr('disabled', true);
					$(REMOVEDESELECT).attr('disabled', false);
					$(ADD).attr("disabled", false);
					selectedRemoveNodes = [];
					for (var idx = 0; idx < tableRemoveNodes.length; ++idx) {
						selectedRemoveNodes = selectedRemoveNodes.concat(tableRemoveNodes[idx]);
					}
				}
				
				function onRemoveDeselectAll() {
					$(REMOVE_NODES_TABLE + ' tbody tr').removeClass('hp-selected');
					$(REMOVEDESELECT).attr('disabled', true);			
					$(REMOVESELECT).attr('disabled', false);
					selectedRemoveNodes = [];
				}

				function getInstallSetDetailforId(installSetId) {
				    if (installSetId == '')
				        return null;
				    for (var idx = 0; idx < installSetObjList.length; idx++) {
				        if (installSetObjList[idx].id.match(installSetId))
				            return installSetObjList[idx];
				    }
				    return null;
				}

				function AddToolTipAttrAndClass(source) {
				    $(source).attr('tooltip', localizer.getString('hpsum.group.groupBLNotPresentInNode')).hpTooltip();
				}

				function removeToolTipAttrAndClass(source) {
				    var attr = $(source).attr('data-tooltip');
				    if (typeof attr !== typeof undefined && attr !== false) {
				        $(source).removeClass('hp-tooltipped').removeAttr('tooltip data-tooltip');
				    }
				}

				function refreshAvailableNodesTable(groupBaseline)
				{
				    var rows = $(ADD_GROUP_NODES_TABLE).dataTable().fnGetNodes();
				    if ((groupBaseline != undefined) && !groupBaseline.id.match('/')) {
                        //for Install Set
				        var selectedInstallSetFoundForNode = false;
				        for (var i = 0; i < rows.length; i++) { // go through each row and check for available baseline for that node
				            var cells = rows[i].getElementsByTagName('td');
				            var nodeIdInTable = cells[1].textContent; //get nodeid from table cell
				            var status = cells[0];
				            if (!status.innerHTML.match("/img/hp-piano/status-error.png")) { //change only if node is not in unknown/error state
				                for (var idx = 0; idx < nodes.length; ++idx) {
				                    var nodeData = nodes[idx];
				                    if (nodeData.node_name == nodeIdInTable) {
				                        if ((nodeData.installsets.hasOwnProperty('installset') == true) && nodeData.installsets.installset.length > 0) {
				                            var nodeInstallSet = nodeData.installsets.installset;
				                            for (var count in nodeInstallSet) {
				                                if ((nodeInstallSet[count].iloinstallset_name.match(groupBaseline.name))) {
				                                    selectedInstallSetFoundForNode = true;
				                                    break;
				                                }
				                            }
				                        }

                                        //If selected Install Set is not found for current node,disable and grey out the row
				                        if (selectedInstallSetFoundForNode == false) {
				                            $(rows[i]).addClass('hp-disabled');
				                            $(rows[i]).removeClass('hp-selected');
				                            $(rows[i]).css('background', '#C6C9CA');
				                            AddToolTipAttrAndClass(rows[i]);

				                            //If user selected a node then selected some Install Set which is not applicable to this node then remove 
				                            //that node from selected node list
				                            var index = selectedAddNodes.indexOf(nodeData.node_id);
				                            if (index > -1) {
				                                selectedAddNodes.splice(index, 1);
                                       }

				                        }
				                        selectedInstallSetFoundForNode = false;
				                        break;
				                    }
				                }
				            }
				        }
				    }
				    else {
                            for (var i = 0; i < rows.length; i++) { // go through each row and check for available baseline for that node
				            var cells = rows[i].getElementsByTagName('td');
				            var status = cells[0];
				            if (!status.innerHTML.match("/img/hp-piano/status-error.png") && (!status.innerHTML.match("hp-status-changing"))) {
				                $(rows[i]).removeClass('hp-disabled');
				                $(rows[i]).css('background', 'transparent');
				                removeToolTipAttrAndClass(rows[i]);
				            }
				        }
				    }
				}
				/**
				 * @public
				 * Intialize the group edit view.
				 */
				this.init = function() {
				    $(PANELS).hpStackedPanels({
						panelSelector : PANEL_SELECTOR
					});

					$(CANCEL).click(function() {
						router.go(urlFragment.replaceView(router.location(), 'show'));
					});

					var dummyRemoveNodesData = [];
					$(REMOVE_NODES_TABLE).dataTable({
						oLanguage : { sEmptyTable :
							localizer.getString("hpsum.group.noNodesInGroup"),
						    sSearch: localizer.getString('hpsum.common.search')
						},
						bPaginate : false,
						bProcessing : true,
						bFilter : true,
						bInfo : false,
						bAutoWidth : false,
						bRetrieve : true,
						bDestroy : true,
						aaData : dummyRemoveNodesData,
						aoColumns : [
						{mDataProp: 'status',
							fnRender: function (oObj) {
								var statusCode;
								if (oObj.aData.change == true )
									statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-changing"></div></div>';
								else if(oObj.aData.status == "ok")
                                    statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-ok"><span class="hp-value">ok</span></div></div>';
                                else if(oObj.aData.status == "error")
                                	statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-error"><span class="hp-value">error</span></div></div>';
                                else if(oObj.aData.status == "warning")
                                	statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-warning"><span class="hp-value">warning</span></div></div>';
                                else if(oObj.aData.status == "unknown")
                                	statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-unknown"><span class="hp-value">unknown</span></div></div>';
								else if(oObj.aData.status == "scheduled")
                                	statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-scheduled"><span class="hp-value">scheduled</span></div></div>';
                                
                                return statusCode;
                                
								/*return '<div class="hp-switch"> <ol class="hp-up-ports">' +
								'<li class="hp-up-port">' + ' <div class="hp-condensed">' + statusCode +
								' </div>' + 
								'<div class="hp-full">' +
								statusCode + 
								'<div class="hp-form-contents"> ' +
								'<fieldset>' + '<ol> ' + ' <li> ' +
								'<div><a href="#/node' + '/show/r' + oObj.aData.uri + '/getData">' + oObj.aData.name + '</a><div></li>' +
								' <li> ' + '<div>' + oObj.aData.type + '</div>' + ' </li> ' +
								' <li> ' + '<div>' + oObj.aData.state + '</div>' + ' </li> ' +
								' <li> ' + '<div>' + oObj.aData.node_status + '</div>' + ' </li> ' +
								' <li> ' + '<div>' + oObj.aData.reboot + '</div>' + ' </li> ' +
								'</ol></fieldset></div></li></ol></div>';
								*/
							},
							sWidth: '10px', sClass: "hp-icon"
						}, {
							mDataProp : 'name',
							"sType": "ip-sorting"
						}, {
							mDataProp : 'type'
						}, {
							mDataProp : 'node_status'
						}, {
							mDataProp : 'baseline'
						}, {
							mDataProp : 'adtPackage'
						}],
						aaSorting : [[1, "asc"]],
						bScrollCollapse : true
					});
					//subsribe to 'ip-sorting' custom sorting function from utility.js file
					extendSorting();
					
					var dummyAddNodesData = [];
					$(ADD_GROUP_NODES_TABLE).dataTable({
						oLanguage : { sEmptyTable :
							localizer.getString("hpsum.group.noMoreNodesAvailable"),
						    sSearch: localizer.getString('hpsum.common.search')
						},
						bPaginate : false,
						bProcessing : true,
						bFilter : true,
						bInfo : false,
						bAutoWidth : false,
						bRetrieve : true,
						bDestroy : true,
						aaData : dummyRemoveNodesData,
						aoColumns : [
						{mDataProp: 'status',
							fnRender: function (oObj) {
								var statusCode;
								if (oObj.aData.change == true )
								{
										statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-changing"></div></div>';
								}
								else if(oObj.aData.status == "ok")
                                    statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-ok"><span class="hp-value">ok</span></div></div>';
                                else if(oObj.aData.status == "error")
								{
									if(oObj.aData.phase.match(/Unknown/i))
									{
									    statusCode = '<div class="hp-status"><img src="/img/hp-piano/status-error.png" width="100%" height="80%"><span class="hp-value">error</span></img></img>';
									}
									else{
										statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-error"><span class="hp-value">error</span></div></div>';
									}
								}
                                else if(oObj.aData.status == "warning")
                                	statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-warning"><span class="hp-value">warning</span></div></div>';
                                else if(oObj.aData.status == "unknown")
                                	statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-unknown"><span class="hp-value">unknown</span></div></div>';
                                else if(oObj.aData.status == "scheduled")
                                	statusCode =  '<div class="hp-status"><div class="hp-status-value hp-status-scheduled"><span class="hp-value">scheduled</span></div></div>';
                                return statusCode;
                                
                                /*
								return '<div class="hp-switch"> <ol class="hp-up-ports">' +
								'<li class="hp-up-port">' + ' <div class="hp-condensed">' + statusCode +
								' </div>' + 
								'<div class="hp-full">' +
								statusCode + 
								'<div class="hp-form-contents"> ' +
								'<fieldset>' + '<ol> ' + ' <li> ' +
								'<div><a href="#/node' + '/show/r' + oObj.aData.uri + '/getData">' + oObj.aData.name + '</a><div></li>' +
								' <li> ' + '<div>' + oObj.aData.type + '</div>' + ' </li> ' +
								' <li> ' + '<div>' + oObj.aData.state + '</div>' + ' </li> ' +
								' <li> ' + '<div>' + oObj.aData.node_status + '</div>' + ' </li> ' +
								' <li> ' + '<div>' + oObj.aData.reboot + '</div>' + ' </li> ' +
								'</ol></fieldset></div></li></ol></div>';
								*/
							},
							sWidth: '10px', sClass: "hp-icon"
						}, {
							mDataProp : 'name',
							"sType": "ip-sorting"
						}, {
							mDataProp : 'type'
						}, {
							mDataProp : 'node_status'
						}, {
							mDataProp : 'baseline'
						}, {
							mDataProp : 'adtPackage'
						}],
						fnCreatedRow: function (nRow, aData, iDataIndex) {
						    if (aData.phase.match(/Unknown|Initialize|Inventory|Analyzing|Deploying/i)) {
						        //$(this).removeClass('hp-selected'); //still selectable
						        nRow.className += 'hp-disabled';
						        $(this).removeClass('hp-selected'); //still selectable
						        $(nRow).css('background', '#C6C9CA');

						        $(nRow).hover( //keep curser anywhere on row ,tooltip will be shown
                                    function () {
                                        if (aData.phase.match(/Unknown/i)) {
                                            $(this).attr('tooltip', localizer.getString('hpsum.group.nodeError')).hpTooltip();
                                        }
                                        else {
                                            $(this).attr('tooltip', localizer.getString('hpsum.group.nodeProcessingError', [aData.phase])).hpTooltip();
                                        }
                                    },
                                    function () {
                                        $(this).removeAttr('tooltip');
                                    }
                                );
						    }
							},
							fnRowCallback : function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                                                                                //nRow.className += ' ' + aData.group_id;
                                                                                return nRow;
							},
							
						aaSorting : [[1, "asc"]],
						bScrollCollapse : true
					});
						
				  $(NAME).change(function(ev, value) {
					var trimmedGroupName = $.trim($(NAME).val());
					var success = false;
					if (!trimmedGroupName.match(new RegExp(/^[a-z][a-z-0-9 ]*$/i))) {
						$(NAMEERR).text(localizer.getString('hpsum.group.inValidGroupName'));
						$(NAME).addClass("hp-error");
						$(NAMEERR).show();
						$(NAME).keyup(onNameEdit);
						success = true;
					}
				  }); 
					
					$(NAME).keyup(onNameEdit);
					$(DESC).keyup(onDescEdit);
					$(USERNAME).keyup(onUserNameEdit);
					$(PASSWORD).keyup(onPasswordEdit);
					
					$(CANCEL).live('click', function(ev) {
						$(ADD_GROUP_NODES_TABLE + " tbody").off('click','tr', onAddTableRow);
						$(REMOVE_NODES_TABLE + " tbody").off('click','tr', onRemoveTableRow);
						ev.preventDefault();
					});
					
					$(ADDSELECT).live('click', function(ev) {
						onAddSelectAll.call(this);
						ev.preventDefault();
					});
					
					$(ADDDESELECT).live('click', function(ev) {
						onAddDeselectAll.call(this);
						ev.preventDefault();
					});
					
					$(REMOVESELECT).live('click', function(ev) {
						onRemoveSelectAll.call(this);
						ev.preventDefault();
					});
					
					$(REMOVEDESELECT).live('click', function(ev) {
						onRemoveDeselectAll.call(this);
						ev.preventDefault();
					});
					
					$(ADD).live('click', function(ev) {
						setOk = true;
						nodeScheduled = false;
						var tableContents = "<table style='margin:20px;'><thead><tr><th><b>Node IP</b></th><th><b>Schedule DateTime</b></th><th><b>Schedule Status</b></th></tr></thead>";
						
						for(var idx = 0; idx <selectedAddNodes.length; idx++)
						{
							for(var nodeidx = 0; nodeidx < nodes.length; nodeidx++)
							{
								if(nodes[nodeidx].node_id === selectedAddNodes[idx])
								{
									var status = '';
								    if(nodes[nodeidx].node_state.match(/remote_staging_scheduled/i))
									{
										status = "Staged";
									}
									else if(nodes[nodeidx].node_state.match(/scheduled/i))
									{
										status = "Deploy";
									}
									
									if(nodes[nodeidx].node_state.match(/remote_staging_scheduled/i) || nodes[nodeidx].node_state.match(/scheduled/i))
									{
										nodeScheduled = true;
										var date_time_split = nodes[nodeidx].schedule_date_time.split(' ');
										var time_hrs_mins = date_time_split[1].split(':');
										var time_hrs = time_hrs_mins[0];
										var date_value = date_time_split[0];
										var time_value = '';
										var date_time_final = '';
										
										if((date_time_split[2] == 'PM') && (parseInt(time_hrs) < 12))
										{
											time_hrs = parseInt(time_hrs) + 12;
										}
										else if(date_time_split[2] == 'AM')
										{
											if (parseInt(time_hrs) < 10 && parseInt(time_hrs) < 12)
											{
												time_hrs = '0' + parseInt(time_hrs);
											}
											else if (parseInt(time_hrs) == 12)
											{
												time_hrs = parseInt(time_hrs) - 12;
												time_hrs = '0' + parseInt(time_hrs);
											}
										}
										time_value = time_hrs + ':' + time_hrs_mins[1];
										date_time_final = date_value + ' ' + time_value;
										tableContents += "<tr><td>" + nodes[nodeidx].node_name + "</td><td>" + date_time_final + "</td><td>" + status +"</td></tr>";
									
									}
								}
							}
						}
						tableContents += "</table>";

						if(nodeScheduled){
							var contents = $(dialogHtml);
							$('#hpsum-groups-message',contents).html(localizer.getString('hpsum.group.scheduleAddWarning'));
							$('#hpsum-groups-schedule-info',contents).show();
							$('#hpsum-group-cancel',contents).show();
							$('#hpsum-groups-schedule-info',contents).html(tableContents);
							
							localizer.localizeDom(contents);
							var dialogView = new DialogView();
							dialogView.init({contents: contents,
								ok: function () {
									onEditGroup.call(this);
								},
								cancel: function () {
								}
							});
						} else{
							onEditGroup.call(this);
							ev.preventDefault();
						}
					});

					$(RESET).live('click', function() {
						reset.call();
					});

					$(BASELINES).hpSearchCombo({
						getResults : getBaseline
					});
					
					$(HOTFIX).hpSearchCombo({
						getResults : getHotfixes
					});
					
					// 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);
					}
					
					$(BASELINES).change(function (ev, value) {
					    var item = presenter.getBaselineDetailsforId(value);
					    var installSetDetails = getInstallSetDetailforId(value);
					    if (item) {
					        $(ASSOCBASELINE).text(item.name);
					        $(REMOVEBASELINE).show();
					        newBaseline = item;
					        if (currentBase != item.id)
					            $(ADD).attr('disabled', false);
					    }
					    else if (installSetDetails) {
					        $(ASSOCBASELINE).text(installSetDetails.name);
					        $(REMOVEBASELINE).show();
					        newBaseline = installSetDetails;
					        if (currentBase != installSetDetails.id)
					            $(ADD).attr('disabled', false);
					    }
					    else {
					        if (assocBaseline != null) {
					            $(ASSOCBASELINE).text(assocBaseline.name);
					            $(REMOVEBASELINE).show();
					        }
					        newBaseline = null;
					    }
					    if (!item && installSetDetails) {
					        $(HOTFIX).hpSearchCombo('disable');
					        $(HOTFIX).hpSearchCombo('set', {
					            id: '',
					            name: ''
					        });
					    }
					    else {
					        $(HOTFIX).hpSearchCombo('enable');
					    }

					    if (value == "" && $(HOTFIX).val() == "") {
					        $(BASELINE_WARNING).hide();
					    } else {
					        $(BASELINE_WARNING).show();
					        if (installSetObjList.length > 0) {
					            $('#hpsum-group-edit-baseline-warning-label').text(localizer.getString('hpsum.group.baselineWarning', new Array("or a saved iLO Install Set")));
					        }
					        else {
					            $('#hpsum-group-edit-baseline-warning-label').text(localizer.getString('hpsum.group.baselineWarning', new Array("")));
					        }
					    }

					    if (value == "") {
					        $(ASSOCBASELINE).text('');
					        $(REMOVEBASELINE).hide();
					    }
					    if (!setOk) {
					        $(BASELINE_INPUT_ERR).hide();
					        $(BASELINE_INPUT).removeClass('hp-error');
					    }
					    setOk = false;
					    onAddDeselectAll.call(this);
					    if (newBaseline != null) {
					        refreshAvailableNodesTable(newBaseline);
					    }
					    else {
					        var rows = $(ADD_GROUP_NODES_TABLE).dataTable().fnGetNodes();

					        for (var i = 0; i < rows.length; i++) { // go through each row and check for available baseline for that node
					            var cells = rows[i].getElementsByTagName('td');
					            var status = cells[0];
					            if (!status.innerHTML.match("/img/hp-piano/status-error.png") && (!status.innerHTML.match("hp-status-changing"))) {
					                $(rows[i]).removeClass('hp-disabled');
					                $(rows[i]).css('background', 'transparent');
					                removeToolTipAttrAndClass(rows[i]);
					            }

					        }
					    }
					    });
					
					

					$(HOTFIX).change(function(ev, value) {
				
					        var item = presenter.getBaselineDetailsforId(value);
					        if (item) {
					            $(ASSOCHOTFIX).text(item.name);
					            $(REMOVEHOTFIX).show();
					            newHotFix = item;
					            if (currentAddpkg != item.id)
					                $(ADD).attr('disabled', false);
					        } else {
					            if (assocHotFix != null) {
					                $(ASSOCHOTFIX).text(assocHotFix.name);
					                $(REMOVEHOTFIX).show();
					            }
					            newHotFix = null;
					        }

					        if (value == "" && $(BASELINES).val() == "") {
					            $(BASELINE_WARNING).hide();
					        } else {
					            if (installSetObjList.length > 0) {
					                $('#hpsum-group-edit-baseline-warning-label').text(localizer.getString('hpsum.group.baselineWarning', new Array("or a saved iLO Install Set")));
					            }
					            else {
					                $('#hpsum-group-edit-baseline-warning-label').text(localizer.getString('hpsum.group.baselineWarning', new Array("")));
					            }
					            $(BASELINE_WARNING).show();

					        }

					        if (value == "") {
					            $(ASSOCHOTFIX).text('');
					            $(REMOVEHOTFIX).hide();
					        }
					        if (!setOk) {
					            $(HOTFIX_INPUT_ERR).hide();
					            $(HOTFIX_INPUT).removeClass('hp-error');
					        }
					        setOk = false;
					    
					});
					
					$(BASELINE_INPUT).unbind('keyup').bind('keyup',function(){
												$(BASELINE_INPUT_ERR).hide();
												$(BASELINE_INPUT).removeClass('hp-error');
											});
					
					$(HOTFIX_INPUT).unbind('keyup').bind('keyup',function(){
												$(HOTFIX_INPUT_ERR).hide();
												$(HOTFIX_INPUT).removeClass('hp-error');
											});	
											
					$(REMOVEBASELINE).on('click', function(ev) {
						assocBaseline = null;
						$(BASELINES).hpSearchCombo('set', {
							id : '',
							name : ''
						});
						$(ASSOCBASELINE).text('');
						$(REMOVEBASELINE).hide();
					});
					
					$(REMOVEHOTFIX).on('click', function(ev) {
						assocHotFix = null;
						$(HOTFIX).hpSearchCombo('set', {
							id : '',
							name : ''
						});
						$(ASSOCHOTFIX).text('');
						$(REMOVEHOTFIX).hide();
					}); 
					
					router.watch('group edit section', ROUTE_PREFIX + '.*', {
						parent : ROUTE_PREFIX,
						change : changeLocation
					});
                    this.resume();
				};

				/**
				 * @public
				 * Resume the group edit view.
				 */
				this.resume = function() {
					$('#hpsum-group-add-group').show();
					$('#hpsum-group-add-group-nodes').show();
					$('#hpsum-group-remove-group-nodes').show();
					$(ADD_GROUP_NODES_TABLE).dataTable().fnClearTable(true);
					$(REMOVE_NODES_TABLE).dataTable().fnClearTable(true);
					$(ADD_GROUP_NODES_TABLE + " tbody").on('click','tr', onAddTableRow);
					$(REMOVE_NODES_TABLE + " tbody").on('click','tr', onRemoveTableRow);
					$(THROBBER).hide();
					$(BASELINE_WARNING).hide();
					$(NAME).attr('disabled', false);
					$(DESC).attr('disabled', false);
					$(ADDSELECT).attr('disabled', true);
					$(ADDDESELECT).attr('disabled', true);
					$(REMOVESELECT).attr('disabled', true);
					$(REMOVEDESELECT).attr('disabled', true);
					$(ASSOCHOTFIX).text('');
					$(ASSOCBASELINE).text('');
					$(RESET).trigger('click');
					$(NAMEERR).hide();
					$(NAME).removeClass("hp-error");
					$(BASELINE_INPUT_ERR).hide();
					$(HOTFIX_INPUT_ERR).hide();
					$(BASELINE_INPUT).removeClass("hp-error");
					$(HOTFIX_INPUT).removeClass("hp-error");
					$(REMOVEBASELINE).hide();
                    $(REMOVEHOTFIX).hide();
					newAddpkg = true;
					newBase = true;
					$(USERNAME).val('');
					$(PASSWORD).val('');
					$(BASELINES).hpSearchCombo('set', {
						id : '',
						name : ''
					});
					
					$(HOTFIX).hpSearchCombo('set', {
						id : '',
						name : ''
					});
					
					presenter.on("itemChange", onItemChange);
					
					presenter.getAllBaselines({
						success : getBaselinesSuccess,
						error : getBaselinesError
					});
					
					presenter.fireItemChange();
				};

			
				/**
				 * @public
				 * Pause the group edit view.
				 */
				this.pause = function() {
					presenter.off("itemChange", onItemChange);
				};

			}

			return EditGroupView;
		}());

	return new EditGroupView();

    		
});

