// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (GroupAddView)
 * This is a view class for adding a new Group.
 */
define(['hpsum/presenter/group/GroupPresenter',
	'hpsum/presenter/node/NodePresenter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/HashManager',
    'hp/core/Validator',
    'hp/view/FormStateView',
    'hp/core/HelpMenu',
    'hp/core/Localizer',
	'text!hpPages/core/header_help.html',
	'hp/view/DialogView',
	'text!hpsumpages/group/dialog.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, hashManager, validator, FormStateView, helpMenu, localizer, headerHelpHtml, DialogView, dialogHtml, nodeGroupWarningHtml) {
    "use strict";
    	

	var AddView = ( function() {
			// consts can go here
			var ADD = '#hpsum-group-add',
			    CANCEL = '#hpsum-group-add-close',
			    RESET = "#hpsum-group-reset",
			    PANEL_SELECTOR = '#hpsum-group-add-panel-selector',
			    PANELS = '#hpsum-group-add-panels',
			    NAME = '#hpsum-group-name',
			    NAMEERR = '#hpsum-group-name-error',
			    DESC = '#hpsum-group-description',
			    ADD_NODES_TABLE = '#hpsum-group-add-nodes-table',
			    FORM = '#hpsum-group-add-form',
			    ROUTE_PREFIX = '/group/add',
			    BASELINES = '#hpsum-group-add-baselines-search',
            	HOTFIX = '#hpsum-group-add-hotfix-search',
            	SELECT = '#hpsum-group-select-all-nodes',
            	DESELECT = '#hpsum-group-deselect-all-nodes',
            	THROBBER = '#hpsum-group-add-throbber',
            	BASELINE_WARNING = '#hpsum-group-add-baseline-warning',
				BASELINE_INPUT = '#hpsum-group-add-baselines-search-input',
				HOTFIX_INPUT = '#hpsum-group-add-hotfix-search-input',
				BASELINE_INPUT_ERR = '#hpsum-group-add-baselines-search-input-err',
				HOTFIX_INPUT_ERR = '#hpsum-group-add-hotfix-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';
			var NODE_INSTALLABLE_STATUS_UPDATE_REQ = 0;
			var MENU = '.hp-search-combo-menu';
		var HEADER = '.hp-header';
		var FOOTER = MENU + ' .hp-footer';
				
			/**
			 * @constructor
			 */
			function AddView() {

				var formStateView = new FormStateView(),
				    nodes = [],
				    addInProgress = false,
				    selectedAddNodes = [],
				    baselines='',
    				hotfixes='',
    				selectedBaselines = [],
					nodeScheduled = false,
    				selectNodes = [];
				var setAdd = false;

				function changeLocation(location) {

					if (location.length > ROUTE_PREFIX.length) {
						$(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
					} else {
						$(PANELS).hpStackedPanels('setFirstPanel');
					}
				}

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

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

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

				function reset() {
					formStateView.reset();
					addInProgress = false;
					$(NAMEERR).hide();
					$(NAME).removeClass("hp-error");
					$(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();
					onDeselectAll.call(this);
					$(BASELINE_WARNING).hide();
				}

				function validate() {
					return validateName();
				}

				function validateName() {
					var success = true;
					var groupName = $(NAME).val();
					if ($(NAME).val() == '') {
						$(NAMEERR).text(localizer.getString('hpsum.node.required'));
						$(NAME).addClass("hp-error");
						$(NAMEERR).show();
						$(NAME).keyup(onNameEdit);
						success = false;
					} else if (!groupName.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 = false;
					} 
					
					return success;
				}

				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() {
					var retValue = true,
					 isDifferentState = false,
					 isDifferentGroup = false,
					 isDifferentBaseline = false,
					 nodeGrpList = [],
					 matchCount = 0;
					
					for(var idx = 0; idx <selectedAddNodes.length; idx++)
					{
						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[idx]) {
						        var nodeData = nodes[nodeidx];
						        if(nodeData)
						        {
								    for (var count = 0; count < nodeData.baselines.length; count++) {
									    var baseline = presenter.getBaselineDetailsforId(nodeData.baselines[count]);
									    if (baseline) {
									        if (baseline.name.match(/^Additional Package/i)) {
									            currentABL = baseline.name;
									        } else {
									            currentBL = baseline.name;
									        }
									    }
									    else if (nodeData.baselines[count].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[count])) {
									                    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 (!nodeData.node_state.match(/idle/i))
								{
									isDifferentState = true;
								}
	
								var groupBaseline = [];
								var grpBL = 0;
								for (var count = 0; count < selectedBaselines.length; count++) {
								    if ((selectedBaselines[count])) {
								        groupBaseline[grpBL] = selectedBaselines[count];
								        grpBL++;
								        }
								    }
							

								if (nodeData.baselines.length)
								{
								    for (var bCount = 0; bCount < nodeData.baselines.length; bCount++) {
								        if (groupBaseline.length > 0) {
								                if (groupBaseline.indexOf(nodeData.baselines[bCount]) == -1) {
								                    isDifferentBaseline = true;
								                    break;
								                }
								            }
								        else {
								            isDifferentBaseline = true;
								            break;
								        }
								    }
								    
								    }
										
								    nodeGrpList.push(groupdata);
							    }//node data
						    }//nodes and selected node check
						}//nodes loop
					}//selectedNodeCount loop
					
					
					if(isDifferentState == true || isDifferentBaseline == true || isDifferentGroup == true)
					{
						var contents = $(nodeGroupWarningHtml);		
					
						
						localizer.localizeDom(contents);		
						var dialogView = new DialogView();
						dialogView.init({contents: contents,
							 ok: function (element) {
								 	addCallback(retValue);
                                                 },
                            cancel: function (element) {
								retValue = false;
								addCallback(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>');
						}
						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>');
						}
						
						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>');
															
						}
						
						$(ADD_NODE_WARNING,contents).show();
							$(WARNING_NODE_GROUP_TABLE , contents).show();
						var tbl = initWarningTable();
								tbl.fnClearTable();
								for(var count = 0; count<nodeGrpList.length; count++)
								{
										tbl.fnAddData({
										'node' : nodeGrpList[count].nodeAddress,
									   'current_group' : nodeGrpList[count].currentGrp,
									   'current_node_baseline' : nodeGrpList[count].currentBaseline,
									   'current_node_additional_package' :nodeGrpList[count].currentAddPckg
										
										});
								}		
								
					}
					else
					{
						 addCallback(retValue);
					}
				
				}
				
				function getSelectedNodes() {					
					return selectedAddNodes;
				}
			
				function OnResize(){
					var BaseLineSearchWidth = ($(window).width() / 3);
					$(BASELINES).hpSearchCombo({getResults:getBaseline, width:BaseLineSearchWidth});
					$(HOTFIX).hpSearchCombo({getResults: getHotfixes, width:BaseLineSearchWidth});
				}

				function getSelectedBaselines() {					
					selectedBaselines = [];
					if (($(BASELINES).val() != '' ) && ($(HOTFIX).val() != '')) {
						selectedBaselines = selectedBaselines.concat($(BASELINES).val());
						selectedBaselines = selectedBaselines.concat($(HOTFIX).val());
					} else if (($(BASELINES).val() == '') && ($(HOTFIX).val() != '')) {
						selectedBaselines = selectedBaselines.concat($(HOTFIX).val());
					} else if (($(BASELINES).val() != '') && ($(HOTFIX).val() == '')){
						selectedBaselines = selectedBaselines.concat($(BASELINES).val());
					}
				}
				
				function onAddItem() {
					$(ADD).attr('disabled', true);
					if (validate()) {
						$(ADD).attr('disabled', true);
						$(THROBBER).show();
						if (!addInProgress) {
							addInProgress = true;
						
							getSelectedBaselines();
							
							var errorFound = false;
							for (var tmp = 0; tmp < selectedBaselines.length; tmp++) {
								if(selectedBaselines[tmp]){
									var baselinedetails = presenter.getBaselineDetailsforId(selectedBaselines[tmp]);
										if(!baselinedetails){
											errorFound = true;
											if (selectedBaselines[tmp] == $(BASELINES).val()) {
												$(BASELINE_INPUT_ERR).text(localizer.getString('hpsum.node.invalidBaseline'));	
												$(BASELINE_INPUT).addClass("hp-error");
												$(BASELINE_INPUT_ERR).show();
												$(BASELINE_INPUT).unbind('keyup').bind('keyup',function(){
													$(BASELINE_INPUT_ERR).hide();
													$(BASELINE_INPUT).removeClass('hp-error');
												});	
											} 
											if (selectedBaselines[tmp] == $(HOTFIX).val()) {
												$(HOTFIX_INPUT_ERR).text(localizer.getString('hpsum.node.invalidAdtPackage'));	
												$(HOTFIX_INPUT).addClass("hp-error");
												$(HOTFIX_INPUT_ERR).show();
												$(HOTFIX_INPUT).unbind('keyup').bind('keyup',function(){
													$(HOTFIX_INPUT_ERR).hide();
													$(HOTFIX_INPUT).removeClass('hp-error');
												});
											}
										}
										$(THROBBER).hide();
										$(ADD).attr('disabled', false);
								} 
							}
							if (errorFound){
								addInProgress = false;
								return;
							}
							validateNodes();
							
						}
					}
					else
					{
					$(ADD).attr('disabled', false);
					}
				}

				 function addCallback(value){
					 	var selectedNodes = getSelectedNodes();
							var trimmedGroupName = $.trim($(NAME).val());
								 if(value == true)
								 {
									  presenter.addItem({
								name : trimmedGroupName,
								description : $(DESC).val(),
								nodes : selectedNodes,
								baselines : selectedBaselines
							}, true, {
								success : onItemAddSuccess,
								error : onItemAddError
							}); 
								 }
								 else
								 {
								$(THROBBER).hide();
								addInProgress = false;
								$(ADD).attr('disabled', false);
								 }
							 }
							 
				function getNodesSuccess(results) {
					selectedAddNodes = [];
					nodes = results.hapi.output_data.nodes.node;
					selectNodes = [];
					ipsSortedAsc = sortNodes(nodes,'asc','sortedIps');
					ipsSortedDesc = ipsSortedAsc.slice().reverse();
					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 == -2 || nodeData.return_code == -3) {
									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.node_phase.match(/Unknown|Initialize|Inventory|Analyzing|Deploying/i)) {
							    selectNodes.push(nodeData);
							}

							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];
							            }
								    }
							    }

							
								$(ADD_NODES_TABLE).dataTable().fnAddData({
									status : status,
									change : change,
									uri : nodeData.node_uri,
									node_id : nodeData.node_id,
									name : nodeData.node_name,
									type : displayILO(nodeData.type),
									node_status : nodeStatus,
									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();
								$(ADD_NODES_TABLE + ' tbody tr').click(function(e) {
								 if ($(this).hasClass('hp-disabled')) 
								 {  
									 return;  
								 }
							 });
					
					}
					
				}
				
				function onTableRow(e) {
						var aData = $(ADD_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) {
								$(DESELECT).attr('disabled', true);
							}
							else if (selectedAddNodes.length < nodes.length) {
								$(SELECT).attr('disabled', false);
							}
 						}
						else if(!$(this).hasClass('hp-disabled'))
						{
							$(this).addClass('hp-selected');
							selectedAddNodes = selectedAddNodes.concat(aData.node_id);
							$(DESELECT).attr('disabled', false);
							if (selectedAddNodes.length == nodes.length) {
								$(SELECT).attr('disabled', true);
							}
							else if (selectedAddNodes.length < nodes.length) {
								$(SELECT).attr('disabled', false);
							}
						}
				}
				
				function getNodesError(msg) {
				}

				function getBaseline(string, handlers, count, start) {
					var results = baselines;
					handlers.success({
						count : results.length,
						members : results, 
						start: 0, 
						total: results.length
					});
					if(results.length >= 1)
					{
						$(HEADER).hide();
						$(FOOTER).hide();
					}
					else
					{
						$(BASELINE_INPUT).attr("disabled", true);
						$('#hpsum-group-add-baselines-search-item').find('.hp-search-combo-menu').hide();
						$(HEADER).hide();
					}
				}

				function getHotfixes(string, handlers, count, start) {
					var results = hotfixes;
				handlers.success({
						count : results.length,
						members : results, 
						start: 0, 
						total: results.length
					});
					if(results.length >= 1)
					{
						
						$(HEADER).hide();
						$(FOOTER).hide();
					}
					else
					{
						$(HOTFIX_INPUT).attr("disabled", true);
						$('#hpsum-group-add-hotfix-search-item').find('.hp-search-combo-menu').hide();
						$(HEADER).hide();
					}
				}
          	
				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(errorMsg) {

				}

				function onSelectAll() {
				    $(SELECT).attr('disabled', true);
				    $(DESELECT).attr('disabled', false);
					var rows = $(ADD_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]).addClass('hp-selected');
					    }
					}
					selectedAddNodes = [];
					for (var idx = 0; idx < selectNodes.length; ++idx) { //selectNodes will not contain nodes with error and ing state nodes
					    selectedAddNodes = selectedAddNodes.concat(selectNodes[idx].node_id);
					}
				}
				
				function onDeselectAll() {
					$(ADD_NODES_TABLE + ' tbody tr').removeClass('hp-selected');
					$(DESELECT).attr('disabled', true);			
					$(SELECT).attr('disabled', false);
					selectedAddNodes = [];
				}
				
				/**
				 * @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 dummyNodeData = [];

					$(ADD_NODES_TABLE).dataTable({
						oLanguage : {
						    sEmptyTable: localizer.getString("hpsum.group.noMoreNodesAvailable"),
						    sSearch: localizer.getString('hpsum.common.search')
						},
						bPaginate : false,
						bFilter : true,
						bInfo : false,
						bAutoWidth : false,
						bRetrieve : true,
						aaData : dummyNodeData,
						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;
								/*
								 * Disable for now 
								 return '<div class="hp-switch hp-card"> <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))
							{
                                nRow.className += 'hp-disabled';
                                $(this).removeClass('hp-selected');
                                $(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
					});
					
					//subscribe to 'ip-sorting' custom sorting function from utility.js file
					extendSorting();

					$(SELECT).live('click', function(ev) {
						onSelectAll.call(this);
						ev.preventDefault();
					});
					// 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);
                    }
					
					$(DESELECT).live('click', function(ev) {
						onDeselectAll.call(this);
						ev.preventDefault();
					});
					
					$(CANCEL).live('click', function (ev) {
					    $(ADD_NODES_TABLE + " tbody").off('click', 'tr', onTableRow);
					    //router.go(urlFragment.replaceView(router.location(), 'show'));
					    var resource = router.location().split('/');
					    resource = resource[1];
					    hashManager.replaceHash('/' + resource + '/show');
						//ev.preventDefault();
					});
					
					$(ADD).live('click', function(ev) {
						setAdd = true;
						nodeScheduled = false;
						var tableContents = "<table style='margin:20px;'><thead><tr><th><b>Node IP</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 () {
									onAddItem.call(this);
								},
								cancel: function () {
								}
							});
						} else{
							onAddItem.call(this);
							ev.preventDefault();
						}
					});

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

					$(BASELINES).change(function (ev, value) {
						if (value == "" && $(HOTFIX).val() == "") {
							$(BASELINE_WARNING).hide();
						} else {
						    $('#hpsum-group-add-baseline-warning-label').text(localizer.getString('hpsum.group.baselineWarning', new Array("")));
                            $(BASELINE_WARNING).show();
						}
						if(!setAdd){
							$(BASELINE_INPUT_ERR).hide();
							$(BASELINE_INPUT).removeClass('hp-error');
						}
						setAdd = false;
					});
					
					$(HOTFIX).change(function (ev, value) {
						if (value == "" && $(BASELINES).val() == "") {
							$(BASELINE_WARNING).hide();
						} else {
						    $('#hpsum-group-add-baseline-warning-label').text(localizer.getString('hpsum.group.baselineWarning', new Array("")));
							$(BASELINE_WARNING).show();
						}
						if(!setAdd){
							$(HOTFIX_INPUT_ERR).hide();
							$(HOTFIX_INPUT).removeClass('hp-error');
						}
						setAdd = false;
					});
					
					router.watch('group add section', ROUTE_PREFIX + '.*', {
						parent : ROUTE_PREFIX,
						change : changeLocation
					});
					$(window).on('resize', OnResize);
					//set width for baseline and additional package search box.
					OnResize();
                	$(BASELINE_WARNING).hide();
					this.resume();
				};

				/**
				 * @public
				 * Resume the group edit view.
				 */
				this.resume = function() {
					$(ADD_NODES_TABLE).dataTable().fnClearTable(true);
					$(ADD_NODES_TABLE + " tbody").on('click', 'tr', onTableRow);
					$(BASELINE_WARNING).hide();
				    $(ADD).attr('disabled', false);
					$(SELECT).attr('disabled', false);
					$(DESELECT).attr('disabled', true);
					$(THROBBER).hide();
					$(BASELINE_INPUT_ERR).hide();
					$(HOTFIX_INPUT_ERR).hide();
					$(BASELINE_INPUT).removeClass("hp-error");
					$(HOTFIX_INPUT).removeClass("hp-error");
					
					$(BASELINES).hpSearchCombo('set', {
						id : '',
						name : ''
					});
					$(HOTFIX).hpSearchCombo('set', {
						id : '',
						name : ''
					});
					$(RESET).trigger('click');
					$(NAMEERR).hide();
					$(NAME).removeClass("hp-error");
					nodePresenter.getNodeDataForGroup({
					    success: getNodesSuccess,
					    error: getNodesError
					});
					
					presenter.getAllBaselines({
           					success:getBaselinesSuccess,
           					error: getBaselinesError
           			});
				};

				/**
				 * @public
				 * Pause the group edit view.
				 */
				this.pause = function() {

				};
			}

			return AddView;
		}());

	return new AddView();

	});


