// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['hpsum/presenter/group/GroupPresenter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/Notifications',
    'hp/view/FormStateView',
    'hp/core/Localizer',
	'hp/model/Session',
	'hp/services/REST',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'hp/lib/jquery.hpSearchCombo',
	'hpsum/view/node/jquery.hpsumSchedule',
	'lib/jquery-ui-timepicker-addon',
    'lib/jquery.selectBox'],

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

	var GroupInventoryView = ( function() {

			//Consts can go here
			var OK = '#hpsum-group-stage-ok',
			    CANCEL = '#hpsum-group-inventory-close',
			    PANEL_SELECTOR = '#hpsum-group-inventory-panel-selector',
			    PANELS = '#hpsum-group-inventory-panels',
			    FORM = '#hpsum-group-inventory-form',
			    FAILEDMSG = '#hpsum-group-inventory-failed-details',
			    FAILEDPANEL = '#hpsum-group-inventory-failed',
			    BASELINES = '#hpsum-group-baselines-search',
			    ASSOCBASELINE = '#hpsum-group-baseline',
			    HOTFIX = '#hpsum-group-addpackage-search',
			    ASSOCHOTFIX = '#hpsum-group-addpackage',
			    NAME = '#hpsum-group-inventory-name',
			    ROUTE_PREFIX = '/group/inventory',
			    REMOVEBASELINE = '#hpsum-group-baseline-remove',
        		REMOVEHOTFIX = '#hpsum-group-addpackage-remove',
        		THROBBER = '#hpsum-group-inventory-throbber',
        		BASELINE_WARNING = '#hpsum-group-inventory-baseline-warning',
        		NOBASELINE_WARNING = '#hpsum-group-inventory-no-baseline-warning',
        		NOBASELINE_NODES_TABLE = '#hpsum-group-stage-view-nodes',
        		NOBASELINE_DETAILS = '#hpsum-group-inventory-nobaseline-nodes',
				SCHEDULEINFO = '#hpsum-group-schedule-info',
				BASELINE_INPUT = '#hpsum-group-baselines-search-input',
				HOTFIX_INPUT = '#hpsum-group-addpackage-search-input',
				BASELINE_INPUT_ERR = '#hpsum-group-baselines-search-input-err',
				HOTFIX_INPUT_ERR = '#hpsum-group-addpackage-search-input-err',
				STAGE_FLAG = '#hpsum-group-stage',
				SCHEUDLED_STAGED = '#hpsum-stage-scheduled',
				MASTER_NODE_CURRENT_TIME,
				GROUP_SCHEUDLED_DATE_TIME,
				SKIP_INEVENTORIED_NODES = '#hpsum-nodegroup-skip-nodes',
				STAGE_NODES_TABLE = '#hpsum-group-stage-nodes-table-div',
				DIRECT_DEPLOY_INST_OPTION = '#hpsum-group-deploy-installation-options',
				DIRECT_DEPLOY_DESCRIPTION = '#hpsum-node-stage-directdeploy-general-description',
				SPLASH_SPINNER = '#hpsum-temporary-dialog';
		var stage_mode = 0;
		var groupItemStage;
		var isStageScheduled = false;
		var tempAbortInProgress = false;
		var scheduleDetails = {
				isScheduled : false,
				tempAbort : false,
				stageMode : "",
				schduledDateTime : "",
				baselines : ""
				};
		var scheduleDetailsIsSet = false;
		var groupScheduledFlag = false;

			/**
			 * Constructor
			 */
			function GroupInventoryView() {

				var formStateView = new FormStateView();
				var inventoryInProgress = false,
				    groupItem = null,
				    baselines = '',
				    hotfixes = '',
				    assocBaseline = '',
				    newBaseline = null,
				    newHotFix = null,
				    assocHotFix = '',
				    searchResults = [],
					allNodesDetials = [],
					date_time_new = '',
					time_value = '',
					date_value = '';
				var setOk = false;

				function onItemChange(item) {
					item = item.hapi;
					$("#schedule").hpsumSchedule('setTimeinSchedulePlugin',item.group_local_date_time,item.group_schedule_date_time);
               		$("#schedule").hpsumSchedule('setMasterNodeTimer',item.group_local_date_time);
					if(item.group_state.match("REMOTE_STAGING_SCHEDULED"))
					{
						
						if(item.group_schedule_date_time)
						{
							$(SPLASH_SPINNER).dialog({
								modal : true,
								position : "center",
								draggable : false,
								resizable : false,
								show : 'fade',
								dialogClass : 'hp-splash-dialog',
								width : 400
							});
							$(SPLASH_SPINNER).show();
							$(SPLASH_SPINNER).focus();
							//$("#schedule").hpsumSchedule('selectScheduled');
							/*for temporary abort of scheduled stage nodes*/
							if(item.group_scheduled == "true")
							{
								tempAbortForScheduledNodes(item);
							}
						}					
					}
					
               		 if( $(STAGE_FLAG).length != 0 ){
		                    groupItemStage = item;
		                    if((item.group_phase.match(/UserActionNeeded/i) || item.group_state.match(/installdone/i) ||
		                            item.group_state.match(/error/i)))
		                    {
		                         //Then this page was rerouted from the deploy view.
		                         //The user want to do a direct stage and deploy 
		                        //In this state we send both stage and deploy, If stage mode is 1. This is done internally in the state
		                        //machine. 
		                        if( item.group_state.match(/idle/i) ||  item.group_state.match(/installdone/i) ||
		                            item.group_state.match(/error/i)){
		                            stage_mode = 1;
										
		                            //$(STAGE_HEADING).text(localizer.getString('hpsum.server.stage'));
		                            $(OK).prop('value',localizer.getString('hpsum.server.stage'));
		                            /*var list= $(START_DEPLOY_PANEL);
		                            $(START_DEPLOY_PANEL).show();
		                            $(BASELINE_PANEL).show();*/
		                        }
		                    }
                		}


					if (item) {
						$(NAME).text(item.group_name);
						$(ASSOCBASELINE).text('');
						$(ASSOCHOTFIX).text('');
						$(REMOVEBASELINE).hide();
                    	$(REMOVEHOTFIX).hide();
						groupItem = item;
						newBaseline = null;
						newHotFix = null;
						if (item.group_baselines) {
							for (var i = 0; i < item.group_baselines.length; i++) {
								var baseline = presenter.getBaselineDetailsforId(item.group_baselines[i]);
								if (baseline) {
									if (baseline.name.match(/^Additional Package/i)) {
										$(ASSOCHOTFIX).text(baseline.name);
										$(REMOVEHOTFIX).show();
										$(HOTFIX).hpSearchCombo('set', {id: baseline.id, name: baseline.name});
										$(NOBASELINE_WARNING).hide();
										assocHotFix = baseline;
									} else {
										$(ASSOCBASELINE).text(baseline.name);
										$(REMOVEBASELINE).show();
										$(BASELINES).hpSearchCombo('set', {id: baseline.id, name: baseline.name});
										$(NOBASELINE_WARNING).hide();
										assocBaseline = baseline;
									}
								}
							}
						}
						getNodeDataFromPresenter(groupItem);
						if(item.group_state.match(/idle/i))
						{
							if($(SPLASH_SPINNER).is(":visible"))
								$(SPLASH_SPINNER).dialog('destroy');
						}
					} else {
						$(CANCEL).trigger('click');
					}
					formStateView.reset();					
				}
				
				function getNodeDataFromPresenter(groupItem)
				{
					presenter.getNodesData(groupItem, {
							success : function(data) {
								allNodesDetials = [];
								if (data.hasOwnProperty('hapi')) {
									allNodesDetials = data.hapi.output_data.nodes.node;
									showScheduleWarning();
								}
								if(groupItem.group_state.match(/idle/i))
								{
									if($(SPLASH_SPINNER).is(":visible"))
										$(SPLASH_SPINNER).dialog('destroy');
								}
								populateStageableNodeTable();
							},
							error : function(data) {
							}
						});
				}
				
				function tempAbortForScheduledNodes(item)
				{
					//show splash screen					
					scheduleDetails.isScheduled = true;	
					scheduleDetails.schduledDateTime = item.group_schedule_date_time;
					scheduleDetails.baselines = item.group_baselines;
					scheduleDetails.stageMode = item.operation_mode;

					if (! tempAbortInProgress) {
					   tempAbortInProgress = true;
					   var object = { hapi : { clearScheduleDateTime : false} };
					    presenter.abortItem(item, object,{
								success : function(dataItem) {
									groupItem.group_scheduled = dataItem.hapi.group_scheduled;
									groupScheduledFlag = groupItem.group_scheduled;
									tempAbortInProgress = false;
									inventoryInProgress = false;
									var progressTimer = setInterval(function () {
											var group_uri = "/Session/" + session.getToken() + '/node/group/' + item.group_id;
											rest.getURI(group_uri + "/getstatus", {
											success : function(data) {
												if(data.hapi.group_state === "IDLE")
												{
													scheduleDetails.tempAbort = true;
													item.group_state = data.hapi.group_state;
													clearInterval(progressTimer);													
												}
											},
											error : function(errorInfo) {
												$(SPLASH_SPINNER).dialog('destroy');
											}
										});
										}, 5000);	
									
								},
								error : function(message) {
									tempAbortInProgress = false;
									scheduleDetails.isScheduled = false;						
									scheduleDetails.tempAbort = false;
									$(SPLASH_SPINNER).dialog('destroy');
								}
							});
					}
				
				}
				
				function convertDateTime(date_time)
				{
					date_value = '';
					time_value = '';
					date_time_new = '';
					if(date_time !== "")
					{
						var date_time_split = date_time.split(' ');
						var time_hrs_mins = date_time_split[1].split(':');
						var time_hrs = time_hrs_mins[0];
						date_value = date_time_split[0];
						time_value = '';
						date_time_new = '';
						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_new = date_value + ' ' + time_value;
					}
				}
				
				function showScheduleWarning()
				{
					var nodeScheduled=false;
					$('#hpsum-group-schedule-info').hide();
					var tableContents = "<table><thead><tr><th>Node IP</th><th>Schedule DateTime</th></tr></thead>";
						
					for(var idx = 0; idx <allNodesDetials.length; idx++)
					{
						if(allNodesDetials[idx].node_state.match(/scheduled/i))
						{
							nodeScheduled = true;
							convertDateTime(allNodesDetials[idx].schedule_date_time);
							tableContents += "<tr><td>" + allNodesDetials[idx].name + "</td><td>" + date_time_new + "</td></tr>";
						}
					}
					tableContents += "</table>";
					if(nodeScheduled)
					{
						$('#hpsum-group-schedule-info').show();
						$('#hpsum-group-schedule-nodes').html(tableContents);
					}

				}

				function onInventoryError(errorMessage) {
					$(OK).attr('disabled', false);
					$(THROBBER).hide();
					$(FAILEDPANEL).show();
					$(FAILEDMSG).text(errorMessage);
					inventoryInProgress = false;
				}

				function onInventorySuccess(item) {
					$(OK).attr('disabled', false);
					$(THROBBER).hide();
					inventoryInProgress = false;
					formStateView.reset();
					$(CANCEL).trigger('click');
				}
				
				function performInventory() {
					groupItem.set_group_schedule_date_time = $("#schedule").hpsumSchedule('getScheduledDateTime');
					groupItem.operation_mode = stage_mode;
					if($(SKIP_INEVENTORIED_NODES).is(':checked') ){
						groupItem.skip_nodes = 1;	
					}
					else
					{
						groupItem.skip_nodes = 0;
					}
					
					inventoryInProgress = true;
					presenter.startInventory(groupItem, {
						success : onInventorySuccess,
						error : onInventoryError
					});
				}
				function doAllNodeshaveBL()
				{

					for (var idx = 0; idx < allNodesDetials.length; idx++) {
						if (allNodesDetials[idx].baselines.length == 0) {
							return false;
						}
					}
					return true;
				}
				function onInventory() {
					var doAllNodesHaveBls = doAllNodeshaveBL();
					var fail = false;
					var finalBaseline;
					var finalHotFix;
					var baselineJson = [];
					if (!inventoryInProgress) {
						var errorfound = false;
						var baselinedetails = false;
						if($(BASELINES).val() != ''){
							baselinedetails = presenter.getBaselineDetailsforId($(BASELINES).val());
						}
						else
						{
							if($(HOTFIX).val() != ''){
								baselinedetails = presenter.getBaselineDetailsforId($(HOTFIX).val());
							}						
						}
						if(!baselinedetails && !doAllNodesHaveBls){
							errorfound = true;
							$(BASELINE_INPUT_ERR).text(localizer.getString('hpsum.node.invalidBaseline'));	
							$(BASELINE_INPUT).addClass("hp-error");
							$(BASELINE_INPUT_ERR).show();
						}

						if( $(STAGE_FLAG).length != 0 ){
							var schduledDateTime = $("#schedule").hpsumSchedule('getScheduledDateTime');
	                        if(schduledDateTime != ""){
	                            isStageScheduled = true;	                            
	                            if(!$("#schedule").hpsumSchedule('validateUserEnteredTime',groupItemStage.group_local_date_time))
	                            {
	                                errorfound = true;
	                            }
	                        }
                    	}
						
						if (errorfound == true){
							inventoryInProgress = false;
							return;
						}
						$(OK).attr('disabled', true);
						$(THROBBER).show();
						if ((newBaseline == null) && (assocBaseline == null))
							finalBaseline = null;
						else if (newBaseline == null)
							finalBaseline = assocBaseline;
						else
							finalBaseline = newBaseline;
						if ((newHotFix == null) && (assocHotFix == null))
							finalHotFix = null;
						else if (newHotFix == null)
							finalHotFix = assocHotFix;
						else
							finalHotFix = newHotFix;

						if ((finalHotFix == null) && (finalBaseline == null) && !doAllNodesHaveBls)
						{
							$(BASELINE_INPUT_ERR).text(localizer.getString('hpsum.node.invalidBaseline'));	
							$(BASELINE_INPUT).addClass("hp-error");
							$(BASELINE_INPUT_ERR).show();
							fail = true;
						}
						else if((finalHotFix != null) || (finalBaseline != null))
						{
							/* push ABL if provided by user */
							if (finalHotFix != null)
							{
								baselineJson.push(finalHotFix.id);								
							}
							/* Push BL if provided by user */
							if(finalBaseline != null)
							{
								baselineJson.push(finalBaseline.id);
							}
						}

						
						if(fail == false)
						{
							$(BASELINE_INPUT_ERR).hide();
							$(BASELINE_INPUT).removeClass('hp-error');
							$(HOTFIX_INPUT_ERR).hide();
							$(HOTFIX_INPUT).removeClass('hp-error');
						
							if (baselineJson[0] == null) {
								baselineJson.splice(0, 1);
							}
							groupItem.baselines = baselineJson;
						}
							
						if (baselineJson.length == 0) {
							var NoBaselinesNodes = [],
							    CanPerformInventory = true;

							$(NOBASELINE_NODES_TABLE).dataTable().fnClearTable();
									
							for (var idx = 0; idx < allNodesDetials.length; idx++) {
								if (allNodesDetials[idx].baselines.length == 0) {
									CanPerformInventory = false;
									$(NOBASELINE_DETAILS).show();
									
									var nodeData = allNodesDetials[idx],
										status = 'unknown',
										change = false,
										nodeStatus = nodeData.node_status,
										rebootRequired = "",
										nodeBaseline = localizer.getString('hpsum.group.noBaseline'),
										adtPackage = localizer.getString('hpsum.group.noAdtPackage'),
										name = "";

									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.node_status.match(/No applicable/i)) {
											status = 'ok';
										} else {
											status = 'warning';
										}
									} 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/i)) {
											status = 'error';
										} else {
											status = 'warning';
										}
									}

									if (nodeData.baselines) {
										for (var i = 0; i < nodeData.baselines.length; i++) {
											var baseline = presenter.getBaselineDetailsforId(nodeData.baselines[i]);
											if (baseline) {
												if (baseline.name.match(/^Additional Package/i)) {
													adtPackage = baseline.name;
												} else {
													nodeBaseline = baseline.name;
												}
											}
										}
									}
									
									name = '<a href="#/node' + '/show/r' + nodeData.node_uri + '/getdata">' + nodeData.name + '</a>';
									
									$(NOBASELINE_NODES_TABLE).dataTable().fnAddData({
										status : status,
										change : change,
										name : name
									});
								}
							}

							if (!CanPerformInventory) {
								onInventoryError(localizer.getString('hpsum.group.noBaselineNodes'));	
							}
							else {
								performInventory();
							}
						} else {
							performInventory();
						}
					}
				}

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

				this.resume = function() {
					
					$(DIRECT_DEPLOY_INST_OPTION).hide();
					$(THROBBER).hide();
					$(NOBASELINE_WARNING).show();
					$(BASELINE_WARNING).hide();
					$(NOBASELINE_NODES_TABLE).dataTable().fnClearTable();
					$(NOBASELINE_DETAILS).hide();
					$(BASELINE_INPUT).removeClass("hp-error");
					$(HOTFIX_INPUT).removeClass("hp-error");
					$(BASELINE_INPUT_ERR).hide();
					$(HOTFIX_INPUT_ERR).hide();
					assocBaseline = null;
					assocHotFix = null;
					$(BASELINES).hpSearchCombo('set', {
						id : '',
						name : ''
					});
					$(HOTFIX).hpSearchCombo('set', {
						id : '',
						name : ''
					});
					presenter.on('itemChange', onItemChange);
					presenter.getAllBaselines({
						success : getBaselinesSuccess,
						error : getBaselinesError
					});
					$(PANELS).hpStackedPanels('resume');
					$(FAILEDPANEL).hide();
					$('#hpsum-group-schedule-info').hide();

					if($(STAGE_FLAG).length != 0 )
					{
						stage_mode = 1;						
					}
					$(SKIP_INEVENTORIED_NODES).attr('checked', false);					
				};

				this.pause = function() {
					presenter.off('itemChange', onItemChange);
					$(PANELS).hpStackedPanels('pause');
				};

				function baselinesAvailable(data) {
				}

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

				function getHotfixes(string, handlers, count, start) {
					var results = 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')));
					});

				}

				function getBaselinesError(msg) {

				}

				/* populate the table containing nodes which will be staged */
				function populateStageableNodeTable()
				{
					var nodeScheduled=false;
					$(STAGE_NODES_TABLE).html("");
					$(STAGE_NODES_TABLE).show();
					var tableContents = "<table><thead><tr><th>Node IP</th><th>Node Status</th></tr></thead>";
					var flag = $(SKIP_INEVENTORIED_NODES).is(':checked');
					var invNodeCount = 0;
					var bAnyNodeShown = false;
					for(var idx = 0; idx <allNodesDetials.length; idx++)
					{
						if(allNodesDetials[idx].type.match(/Windows|Linux/i) && !allNodesDetials[idx].node_id.match(/N1localhost/i))
						{
							if(flag)
							{
								/* if check box is checked, don't show UAN state nodes */
								if(allNodesDetials[idx].node_state != "UAN")
								{
									tableContents += "<tr><td>" + allNodesDetials[idx].name + "</td><td>" + allNodesDetials[idx].node_status + "</td></tr>";
									bAnyNodeShown = true;
								}
								else
								{
									invNodeCount ++;
								}
							}
							else
							{
								/* if check box is not checked show all Win/Lin nodes irrespective of their states */
								tableContents += "<tr><td>" + allNodesDetials[idx].name + "</td><td>" + allNodesDetials[idx].node_status + "</td></tr>";
								bAnyNodeShown = true;
								if(allNodesDetials[idx].node_state == "UAN")
								{
									invNodeCount ++;
								}
							}
						}						
					}
					$(STAGE_NODES_TABLE).html(tableContents); /* load the table to the div */
					
					if (invNodeCount > 0 && invNodeCount <= allNodesDetials.length)
					{
						$(SKIP_INEVENTORIED_NODES).attr('disabled', false); // enable the checkbox
					}
					else
					{
						$(SKIP_INEVENTORIED_NODES).attr('disabled', true);
					}
					
					// Disable Stage button if all nodes get excluded
					if (true == bAnyNodeShown)
					{
						$(OK).attr('disabled', false); // enable stage button						
					}
					else
					{
						$(OK).attr('disabled', true);
					}
				}

				/**
				 * @public
				 */
				this.init = function() {
				$(DIRECT_DEPLOY_DESCRIPTION).text(localizer.getString('hpsum.server.stage') + localizer.getString('hpsum.server.stagedirectdeployDescription') + ".");
				
				$("#schedule").hpsumSchedule({
					enableButton: function(){
                        $(OK).removeAttr("disabled");
                        
                    },
                    disableButton: function(){
                        $(OK).attr("disabled", "disabled");
                    }
				});

					$(SKIP_INEVENTORIED_NODES).click(function(){
						populateStageableNodeTable();

					});
					
					$(OK).on('click', function(ev) {
						setOk = true;
						onInventory();
						ev.preventDefault();
					});

					$(CANCEL).click(function() {
						//send previous request if the node is scheduled
						if(groupItem.group_schedule_date_time && (groupItem.group_scheduled == "false" || groupScheduledFlag == "false"))
						{
							groupItem.set_group_schedule_date_time	= groupItem.group_schedule_date_time;							
							inventoryInProgress = true;	
							//performInventory();
							groupItem.operation_mode = 1;
							presenter.startInventory(groupItem, {
								success : onInventorySuccess,
								error : onInventoryError
							});						
						}
						router.go(urlFragment.replaceView(router.location(), 'show'));
					});
					$(FAILEDPANEL).hide();
					$(PANELS).hpStackedPanels({
						panelSelector : PANEL_SELECTOR
					});

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

					presenter.getAllBaselines({
						success : getBaselinesSuccess,
						error : getBaselinesError
					});

					$(BASELINES).hpSearchCombo({
						getResults : getBaseline
					});
					$(HOTFIX).hpSearchCombo({
						getResults : getHotfixes
					});
					$(BASELINES).change(function(ev, value) {
						$(BASELINE_INPUT_ERR).hide();
						$(BASELINE_INPUT).removeClass('hp-error');
						$(HOTFIX_INPUT_ERR).hide();
						$(HOTFIX_INPUT).removeClass('hp-error');
						
						var item = presenter.getBaselineDetailsforId(value);
						if (item) {
							$(ASSOCBASELINE).text(item.name);
							$(REMOVEBASELINE).show();
							newBaseline = item;
						} else {
							if(assocBaseline != null){
								$(ASSOCBASELINE).text(assocBaseline.name);
								$(REMOVEBASELINE).show(); 
							}
							newBaseline = null;
						}
						$(FAILEDPANEL).hide();
						
						if (value != "") {
							$(NOBASELINE_WARNING).hide();
						}
						
						if (value == "" && $(HOTFIX).val() == "") {
							$(BASELINE_WARNING).hide();
							$(NOBASELINE_WARNING).show();
						} else {
							$(BASELINE_WARNING).show();
						}
						
						/*if (value != "") {
							$(NOBASELINE_WARNING).hide();
						} else {
							$(NOBASELINE_WARNING).show();
						}*/
						
						if (value == "") {
							$(ASSOCBASELINE).text('');
							$(REMOVEBASELINE).hide();
							assocBaseline = null;
						}
						if(!setOk){
							$(BASELINE_INPUT_ERR).hide();
							$(BASELINE_INPUT).removeClass('hp-error');
						}
						setOk = false;
					});
					$(HOTFIX).change(function(ev, value) {
						$(BASELINE_INPUT_ERR).hide();
						$(BASELINE_INPUT).removeClass('hp-error');
						$(HOTFIX_INPUT_ERR).hide();
						$(HOTFIX_INPUT).removeClass('hp-error');
						
						var item = presenter.getBaselineDetailsforId(value);
						if (item) {
							$(ASSOCHOTFIX).text(item.name);
							$(REMOVEHOTFIX).show();
							newHotFix = item;
						} else {
							if (assocHotFix != null) {
								$(ASSOCHOTFIX).text(assocHotFix.name);
								$(REMOVEHOTFIX).show();
							}
							newHotFix = null;
						}

						$(FAILEDPANEL).hide();
						
						if (value != "") {
							$(NOBASELINE_WARNING).hide();
						}
						
						if (value == "" && $(BASELINES).val() == "") {
							$(BASELINE_WARNING).hide();
							$(NOBASELINE_WARNING).show();
						} else {
							$(BASELINE_WARNING).show();	
						}
						
						/*if (value != "") {
							$(NOBASELINE_WARNING).hide();
						} else {
							$(NOBASELINE_WARNING).show();
						}*/
						
						if (value == "") {
							$(ASSOCHOTFIX).text('');
							$(REMOVEHOTFIX).hide();
							assocHotFix = null;
						}
						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 inventory section', ROUTE_PREFIX + '.*', {
						parent : ROUTE_PREFIX,
						change : changeLocation
					});

					$(NOBASELINE_NODES_TABLE).dataTable({
						oLanguage : {
						    sEmptyTable: localizer.getString("hpsum.group.noMoreNodesAvailable"),
						    sSearch: localizer.getString('hpsum.common.search')
						},
						bPaginate : false,
						sScrollY: "450px",
						bFilter : false,
						bInfo : false,
						bAutoWidth : false,
						bRetrieve : true,
						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>';
                                return statusCode;
							},
							sWidth: '10px', sClass: "hp-icon"
						},{
							mDataProp : 'name'
						}/*,{
							mDataProp : 'type'
						}, {
							mDataProp : 'node_status'
						},{
							mDataProp : 'baseline'
						}, {
							mDataProp : 'adtPackage'
						}*/],
						aaSorting : [[1, "asc"]],
						bScrollCollapse : true
					});
					
					this.resume();
				};
			}

			return new GroupInventoryView();
		}());

	return GroupInventoryView;
});

