// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (BaselineShowView)
 * This is a view class for Baseline.
 * Provides functions to show details pane for a baseline item
 */
define(['hpsum/presenter/baseline/BaselinePresenter',
    'hp/view/DetailsShowView',
    'hp/view/NotificationsView',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/Notifications',
    'hp/core/Localizer',
    'hp/view/DialogView',
    'hp/model/Session',
	'hp/services/IndexService',
	'hp/core/HashManager',
    'text!hpsumpages/baseline/component_info_dialog.html',  
	'text!hpsumpages/baseline/abort_confirm.html',
	'text!hpsumpages/baseline/addbaseline_createcustom.html',
	'jquery',
    //These two modules required to show table for contents section in details pane
    'lib/jquery.dataTables',
    'lib/jquery.dateFormat',
    'hp/lib/jquery.hpToggle',
    'lib/jquery.dataTables.rowReordering',
    //
	'hpsum/common/jquery.hpsumBrowse',
    'hp/lib/jquery.hpDropMenu',
    'hp/lib/jquery.hpSelect',
    'hp/lib/jquery.hpStackedPanels'],
function(presenter, DetailsShowView, NotificationsView, router, urlFragment, notifications, localizer, DialogView, session, indexService, hashManager, componentDialogHtml, abortConfirmHtml, addBaselineCreateCustomHtml) { "use strict";

    var BaselineShowView = (function() {
      
        var VIEW = '#hpsum-baselines-show',
            HEADER = '#hpsum-baselines-show .hp-details-header',
            TITLE = '#hpsum-baselines-details-title',
            LANGUAGES = '#hpsum-baseline-languages',
            ENHANCEMENTS = '#hpsum-baseline-enhancements',
            PANEL_SELECTOR = '#hpsum-baselines-show-panel-selector',
            PANELS = '#hpsum-baselines-show-panels',
            REPORTS_ACTION = '#hpsum-baseline-action-reports',
            VALIDATE_ACTION = '#hpsum-baseline-action-validate',
            ABORT_ACTION = '#hpsum-baselines-abort-action',
            DELETE_ACTION = '#hpsum-baselines-delete-action',
			CREATECUSTOM_ACTION ='#hpsum-baseline-action-createcustom',
            DELETE_DIALOG = '#hpsum-baselines-delete-confirm',
			DELETE_IN_PROGRESS_SPAN = '#hpsum-delete-baseline-in-progress-span',
			DELETE_BUTTON_NAME = '#hpsum-baseline-delete-ok',
			REVALIDATE_BUTTON ='#hpsum-baseline-revalidate-ok',
			CLOSE_BUTTON_NAME = '#hpsum-baseline-delete-cancel',
            DELETE_NAME = '#hpsum-baselines-delete-name',
            DELETE_TITLE = '#hpsum-baseline-delete-title',
			REVALIDATE_TITLE ='#hpsum-baseline-revalidate-title',
            ABORT_DIALOG = '#hpsum-baseline-abort-confirm',
            ABORT_TITLE = '#hpsum-baseline-abort-title',
            COMPONENT_DIALOG = '#hpsum-component-dialog',
	    COMPONENT_CONFIG_DIALOG = '#hpsum-component-config-dialog',
            COMPONENT_TABLE = '#baselines-contents-table',
			MISSINGCOMPONENT_TABLE='#baselines-missingcontents-table',
            ROUTE_PREFIX = '/baseline/show',
			SPLASH_DIALOG = '#hpsum-abort-wait-dialog',
			SPLASH_SPINNER = '#hpsum-abort-spinner',
			ADD_BASELINE = '#hpsum-add-baselinebtn',
			ADD_BASELINE_CREATECUSTOM_DIALOG = '#hpsum-addbaseline-createcustom-dialog',
			CREATE_CUSTOM = '#hpsum-action-createcustombaseline',
			DIALOG_CONTAINER = '.hp-dialog-container-wrapper';
      		var SCHEDULE_DIALOG = '#hpsum-baseline-schedule-information';
      		var PAGE = '#hpsum-baseline-page';
      		var scheduleDialogContents;
			var SCHEDULE_DATE_AND_TIME = "#hpsum-baseline-schedule-date-time",
				SCHEDULE_TYPE = "#hpsum-baseline-schedule-type",
				SCHEDULE_RECURS = "#hpsum-baseline-schedule-recurring";
		var CANCEL = '#hpsum-component-config-cancel';
		var DELETE_DIALOG_ERROR = '#hpsum-baseline-delete-information';
		var REVALIDATE_DIALOG_ERROR ='#hpsum-baseline-revalidate-information';
		var DELETE_BASELINE_NODES_TABLE = '#hpsum-delete-baseline-nodes-table';
		var REVALIDATE_BASELINE_NODES_TABLE = '#hpsum-revalidate-baseline-nodes-table';
		var EXPORT_CONFIG = "#hpsum-comp-cfg-export",
			IMPORT_CONFIG = "#hpsum-comp-cfg-import",
			SAVE_CONFIG = "#hpsum-comp-cfg-save",
			EXPORT_CONFIG_DIALOG = "#hpsum-component-config-export-dialog",
			IMPORT_CONFIG_DIALOG = "#hpsum-component-config-import-dialog",
			IMPORT_CONFIRM_DIALOG = "#hpsum-import-config-confirm",
			IMPORT_CONFIG_ERROR = "#hpsum-import-config-error",
			EXPORT_CONFIG_ERROR = "#hpsum-export-config-error",
			EXPORT_CREDENTIALS_CHKBOX = "#hpsum-export-credentials-chkbox",
			IMPORT_OK_BUTTON = "#hpsum-import-ok",
			EXPORT_OK_BUTTON = "#hpsum-export-ok",
			IMPORT_CANCEL = "#hpsum-import-cancel",
			EXPORT_CANCEL = "#hpsum-export-cancel",
			EXPORT_WARNING = "#hpsum-export-config-warning",
			EXPORT_ERROR_MSG = "#hpsum-export-config-errorMsg",
			IMPORT_ERROR_MSG = "#hpsum-import-config-errorMsg",
			CONFIG_DIALOG_MSG = "#hpsum-comp-msg",
			EXPORT_CONFIG_BROWSE = "#hpsum-compconfig-export-browse",
			IMPORT_CONFIG_BROWSE = "#hpsum-compconfig-import-browse",
			BASELINE_WARNING_IMG = "#hpsum-baselines-warning-image";
		var REBOOT_REQ_DETAILS_REQUIRED = "Required",
			REBOOT_REQ_DETAILS_NO = "No",
			REBOOT_REQ_DETAILS_YES = "yes",
			REBOOT_REQ_DETAILS_OPTIONAL = "Optional",
			REBOOT_REQ_DETAILS_ENVIRONMENTDEPENDENT = "Environment Dependent",
			REBOOT_DEFAULT_NO = false,
			REBOOT_DEFAULT_YES = true,
			REVALIDATEALL_BUTTON = '#hpsum-baselines-revalidateall';
			
		var deleteInfoDialog;
		var revalidateInfoDialog;
		var abortInfoDialog;
		var canbedeleted = false;
		var canberevalidated = false;
		var abortBaselineItem;
		var browserType = 0;
		var compData;
		var GETSTATUS_TIMER = 15000;
		var timeOut = 0;
		var baselineInventoryInProgress=false;
        /**
         * Constructor
         */
        function BaselineShowView() {
          
            var detailsShowView = new DetailsShowView(),
                notificationsView = new NotificationsView(),
                deleteInProgress = false,
				revalidateInProgress=false,
                abortInProgress = false,
                errorMessage = null,
                componentDialogContents,
                componentConfigDialogContents,
				exportConfigDialogContents,
				importConfigDialogContents,
				instExportConfigBrowse,
				instImportConfigBrowse,
				importConfirmDialogContents,
                timer = null,
				revalidateTimer=null,
                baselineItem = null,
                prevBaselineuri = null,
                deleteDialogContents,
				export_Config = false,
                aborttimer = null,
				currItem = null;
			var abortWaitDialog;
            var baselinedetails =   {location_id : "",
					        		 baseline_id : "",
									 baseline_url : "",
									 baseline_isWritable : false
				        			};    
            function onItemChange(item) {
			if(timer) {
		            clearInterval(timer);
		            timer = null;
		    }
			if(timeOut)
			{
				clearTimeout(timer);
				timeOut = 0;
			}
			if(revalidateTimer)
			{
				clearInterval(revalidateTimer);
		            revalidateTimer = null;
			}
			if(revalidateInProgress)
			{
				revalidateInProgress=false;	
			}
			notificationsView.clear();

                if (item && item.hasOwnProperty("hapi")) {
                    var hapi = item.hapi;
                    baselineItem = hapi;
					currItem = item;
		            //Changes done as part of HFS requirement changes dated 07/25/2014                    
                    //For Custom Baseline -- Ex: item.hapi.baseline_name --> Testing this-ok 2014 08 11,item.hapi.baseline_version --> 2014.08.11.A
                    var appendingVersion=item.hapi.baseline_version.substr(0,item.hapi.baseline_version.lastIndexOf(".")).replace(/\./g," ");                                   
                                     //For Additional Baseline
                    if(item.hapi.baseline_version.toUpperCase().match("N/A") || item.hapi.baseline_name.match(/^Additional Package/i)){
					 
					var urlstr=item.hapi.baseline_url;
					if(urlstr.length>30)
					  urlstr=urlstr.substr(0,urlstr.indexOf("/")+1)+"..."+urlstr.substr(urlstr.length-25);
                      $(TITLE).html(localizer.getString("hpsum.group.additionalPackage") +" "+ "<span style='font-size:18px;color:grey' >" + localizer.getString('hpsum.common.locationStr') + " " + urlstr + "</span>");
					 
					}

                    //For Custom Baseline
                    //For SPP Baseline
                    else{
                      $(TITLE).html(item.hapi.baseline_name+" "+ "<span style='font-size:18px;color:grey' >" + localizer.getString('hpsum.common.version') + " " + item.hapi.baseline_version + "</span>");                      
                    }
                    $(DELETE_NAME).html(item.hapi.baseline_name);
                    $(LANGUAGES).html(item.hapi.baseline_languages);
                    var i,html;
                    html="";
                    
					baselinedetails.location_id = item.hapi.location_id;
					baselinedetails.baseline_id = item.hapi.baseline_id;
					baselinedetails.baseline_url = item.hapi.baseline_url;
					baselinedetails.baseline_isWritable = item.hapi.baseline_isWritable;
					baselinedetails.location_type = item.hapi.location_type;
   
                    if(hapi.baseline_uri != prevBaselineuri) {
						if (!hapi.location_type.match(/http|https/i)) {
							prevBaselineuri = hapi.baseline_uri;
						}
    					//populate os details
                        $('#os ol').html(localizer.getString('hpsum.common.loading'));
    					presenter.getOsInfo(hapi.baseline_uri, {
    							success : function(data) {
    								if (data.hapi.hasOwnProperty("baseline_os")) {
										data.hapi.baseline_os.os.sort();
    									for ( i = 0; i < data.hapi.baseline_os.os.length; i++) {
    										html = html + '<li>' + data.hapi.baseline_os.os[i] + '</li>';
    									}
    
    									$('#os ol').html(html);
    								}
    							},
    							error : function(data) {
    							}
    					}); 

                        var get_revision_enhancement_data = function(revision_enhancement) {
                            function get_by_lang(language) {
                                for (var idx = 0; idx < revision_enhancement.length; idx++) {
                                    var revEnhancement = revision_enhancement[idx];
                                    if (revEnhancement && 
                                        revEnhancement.hasOwnProperty('language_enhancement') && 
                                        revEnhancement.hasOwnProperty('lang') &&
                                        revEnhancement.lang == language) {
                                            return revEnhancement.language_enhancement; 
                                    }
                                }
                                return null;
                            }
                            // Try to retrieve by current language.
                            var result = get_by_lang(hp.getLang());
                            if (result === null) {
                                // Otherwise default to english
                                result = get_by_lang('en');
                            }
                            return result;
                        };

    					//populate enhacements
    					$(ENHANCEMENTS).html(localizer.getString('hpsum.common.loading'));
    					presenter.getEnhancements(hapi.baseline_uri, {
    							success : function(data) {
    								if (data.hapi.hasOwnProperty("baseline_enhancements")) {
    									var htmlContent = '<ol>';
    									for ( i = 0; i < data.hapi.baseline_enhancements.length; i++) {
    										var baselineEnhancement = data.hapi.baseline_enhancements[i];
    										if (baselineEnhancement.hasOwnProperty('revision_enhancement') && 
											   (get_revision_enhancement_data(baselineEnhancement.revision_enhancement))) {
                                                htmlContent += '<li>' + get_revision_enhancement_data(baselineEnhancement.revision_enhancement) + '</li>';
    										}
											else {
												htmlContent += '';
											}
    									}
    									htmlContent += '</ol>';
    									$(ENHANCEMENTS).html(htmlContent);
    									//open hyperlinks in the new tab
    									$(ENHANCEMENTS + " a[href]").off("click").on("click", function(event){
											window.open($(this).attr("href")); 
											event.preventDefault(); 
										});
    								}
    							},
    							error : function(data) {
    							}
    						}); 
    					changeLocation('/baseline/show/languages');
						//populate components table						
						presenter.getComponents(hapi.baseline_uri, {
							success : function (data) {
							var dataItem = {hapi:{location_type:item.hapi.location_type,location_id:item.hapi.location_id,baseline_id:item.hapi.baseline_id, components:data.hapi.components}};
								if (currItem.hapi.baseline_id === item.hapi.baseline_id) {							
									populateComponentTable(dataItem);
									populateMissingComponentTable(dataItem);
								}
							},
							error : function (data) {
							}
						});
                    }
	          
					if (hapi.baseline_state === "inventory_needed") {					
						notificationsView.clear();
							
						if (hapi.location_type.match(/ftp|http|https/i)) {
							currprogress = 0.1;
	                		var bState = "hpsum.baseline.compDownloadInProgress";
							
							//Because of some delay between the add click for baseline and downloading of components starting point , below notification is added.
							if (hapi.location_type.match(/ftp|http|https/i)) {
							notificationsView.add({
								status : 'info',
								//summary : "Component download in progress",
								summary: localizer.getString(bState),
								timestamp : (new Date().toISOString()),
								changing : true,
								progress : currprogress
							}); 
							}
							
							var uri = {
								location_id: item.hapi.location_id,
					        	baseline_id: item.hapi.baseline_id
					        };
					    
							//To show the progress for downloading of components and inventory progress in every 3 seconds.
							showInventoryProgress(uri);	
	                	}
						else
						{
							$(ABORT_ACTION).addClass('hp-disabled');
						}
							
					
							//$(ABORT_ACTION).addClass('hp-disabled');
							if (hapi.location_type.match(/local|Unc|ftp|http/i)) {
								presenter.startInventory({uri: hapi.baseline_uri + '/getBaselineData'}, {
								success : function (data) {
	                			 
								 /*
								  var currComps = hapi.baseline_state_detail.current_progress,
	                		totalComps = hapi.baseline_state_detail.total_no_component;
	                		currprogress = 0.1;
	                		
	                		if (0 != totalComps) {
	                			currprogress = (currComps/totalComps) * 100;
	                		} 
	                		
							//show notification details
							notificationsView.add({
									status : 'running',
									summary : localizer.getString(bState),
									timestamp : (new Date().toISOString()),
									changing : true,
									progress : currprogress,
									step : hapi.baseline_state_detail.detail,
								
							});  
								*/
	                			},
	                			error : function (data) {
	                			}});
							}
						}
	                if(hapi.baseline_state === "inventory_in_progress" || 
	                   hapi.baseline_state === "comp_download_in_progress" ||
					   hapi.baseline_state === "reading_web_catalog" ||
					   hapi.baseline_state === "reading_manifest_xml" ||
					   hapi.baseline_state === "manifest_component_processing") {
						
	                	
						// Fix for QXCR1001418972. For HTTP baseline, we should not enable 'abort' action when inventory is in progress.
						if (hapi.location_type.match(/http/i) && hapi.baseline_state === "inventory_in_progress") {
	                		$(ABORT_ACTION).addClass('hp-disabled').attr('style', '');
	                	}
						
						$(DELETE_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
						// Disable the Reports and Validate option in Actions menu
						$(REPORTS_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
						$(REPORTS_ACTION).bind('click',false);
						$(VALIDATE_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
						$(VALIDATE_ACTION).bind('click',false);

	                	var currComps = hapi.baseline_state_detail.current_progress,
	                		totalComps = hapi.baseline_state_detail.total_no_component,
	                		currprogress = 0.1;
						
						var bState = "";
						var bStep = "";						

						if (hapi.baseline_state === "comp_download_in_progress"){
							bState = "hpsum.baseline.compDownloadInProgress";							
							if(totalComps > 0 && currComps > 0){
								bStep = localizer.getString('hpsum.baseline.show.downloadingComponents' , [currComps,totalComps]);
							}
						} 
						else {
							bState = "hpsum.baseline.show.inventoryInProgress";
							if(totalComps > 0 && currComps > 0){
								bStep = localizer.getString('hpsum.baseline.show.processingComponents' , [currComps,totalComps]);
							}
						}
	                		
						if (0 != totalComps) {
							currprogress = (currComps/totalComps) * 100;
						} 
	                		
						//show notification details
						notificationsView.add({
								status : 'running',
								summary : localizer.getString(bState),
								timestamp : (new Date().toISOString()),
								changing : true,
								progress : currprogress,
								step : bStep,
								details : hapi.baseline_state_detail.detail
								
						});
							
	                	var uri = 	{
	                					location_id: item.hapi.location_id,
					        			baseline_id: item.hapi.baseline_id
					        		};
					    
	                	showInventoryProgress(uri);
	                }
	               	else if(hapi.baseline_state === "inventory_completed") {
						if(hapi.baseline_state_detail.detail !== "Revalidation in progress.")
						{
							$(ABORT_ACTION).addClass('hp-disabled').attr('style', '');
							$(REVALIDATEALL_BUTTON).attr('disabled',false);
							// Enable the reports, validate and delete option in action menu
							$(REPORTS_ACTION).removeClass('hp-disabled').addClass('company-a');
							$(REPORTS_ACTION).unbind('click');
							$(VALIDATE_ACTION).removeClass('hp-disabled').addClass('company-a');
							$(VALIDATE_ACTION).unbind('click');
							$(DELETE_ACTION).removeClass('hp-disabled').addClass('company-a');
                   
							if(item.hapi.baseline_version.toUpperCase().match("N/A") || item.hapi.baseline_name.match(/^Additional Package/i)){
								$(VALIDATE_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
								$(VALIDATE_ACTION).bind('click',false); 
							}
							if(timer)
								clearInterval(timer);
							var details='';
							var compAdded;
							if(hapi.hasOwnProperty("components")) {
								compAdded = hapi.components.component.length;
								details = localizer.getString('hpsum.baseline.show.totalComponents') + " " + compAdded;
							}
							var status = 'info',
							detail = localizer.getString('hpsum.baseline.show.processedComponents', [hapi.baseline_state_detail.current_progress]),
							summary= localizer.getString("hpsum.baseline.show.inventoryCompleted");
							$(BASELINE_WARNING_IMG).hide();
						
							//show notification details
							var comp_missing = hapi.baseline_missing_comp_count;
							var total_components = hapi.total_no_of_component;
							var component_downloaded = parseInt(total_components) - parseInt(comp_missing);
							if(comp_missing > 0)
							{	
								var ftp_summary = '<br></br>'+ localizer.getString("hpsum.baseline.show.componentDownloaded").bold()+":\t"+component_downloaded+"\t\t"+localizer.getString("hpsum.baseline.show.componentMissing").bold()+":\t"+comp_missing;
								var notify_ftp = hapi.location_type.match(/ftp/i)?ftp_summary:"";
								$(BASELINE_WARNING_IMG).show();
								detail = '<p>' + localizer.getString("hpsum.baseline.show.baselineComponentWarnings")+ '<a class="hp-anchor-uri" data-panel-id="hpsum-baselines-show-missingfixes"'+'href="#/baseline/show/missingfixes"> '+localizer.getString("hpsum.baseline.show.seeComponentWarnings")+'</a>' + '</p>';
								status='warning';
							}
						
							notificationsView.add({
								status: status,
								summary:summary,
								timestamp: (new Date().toISOString()),
								step: hapi.baseline_state_detail.detail,
								details: detail
							});
						}
						else
						{
							disableActionsForReval();
							var uri = {
									location_id: item.hapi.location_id,
									baseline_id: item.hapi.baseline_id
								};
							showRevalidationProgress(uri);
						}					
	               	}
					else if(hapi.baseline_state === "inventory_Failed") {
	               		
	               		if(timer)
	               			clearInterval(timer);
															
						var details = '</br><a id="hpsum-start-failed-inventory">' + localizer.getString("hpsum.baseline.show.reinventory") + '</a>';
						
	                	//show notification details
		                notificationsView.add({
	                            status: 'Failed',
	                            summary: localizer.getString("hpsum.baseline.show.inventoryFailed"),
	                            sourceName: item.hapi.baseline_name,
	                            sourceUri: item.hapi.baseline_url,
	                            details: hapi.baseline_state_detail.detail + details
	                   	});
	               	}
	               	else if (hapi.baseline_state === "inventory_needed") {
					
					
					$(ABORT_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
					$(ABORT_ACTION).bind('click',false);
	               		//show notification details
	               		// In case of PFW we need to show the Start Inventory Link
	            /*   		if (hapi.location_type == "FTP") {
	               			//var detailed = '<a id="hpsum-schedule-pfw-inventory" href="javascript:void(0);">' + localizer.getString("hpsum.baseline.schedule_download") + '</a>';
	               			var detailsfornow = '<a id="hpsum-schedule-pfw-inventory-now" href="javascript:void(0);">' + localizer.getString("hpsum.baseline.download_now") + '</a>';
		            		notificationsView.add({
	                        status: 'info',
	                        summary: localizer.getString("hpsum.baseline.show.downloadNeeded"),
	                        sourceName: item.hapi.baseline_name,
	                        sourceUri: item.hapi.baseline_url,
	                        //details:  detailed + " or " + detailsfornow
	                        details:  detailsfornow
	                   	});
	                   	$('#hpsum-schedule-pfw-inventory').click(function (e) {	                   		
	                   		showScheduleDialog(item);	                   		
	                   	});
	                   	$('#hpsum-schedule-pfw-inventory-now').click(function (e) {	  
	                   		presenter.startPFWInventory({
                    		scheduled: "Off",
                    		scheduleDate: "",
                    		scheduleTime: "",
                    		scheduleType: "",
                    		scheduleRecurs: "",
                    		uri: item.hapi.baseline_uri
                    	});
                    	notificationsView.add({
	                        status: 'info',
	                        summary: localizer.getString("hpsum.baseline.starting_download")	                        
	                   	});	                   		
	                   	});
	                  }*/
	              }
				  //Added to show proper notification while abort is in abort_in_progress or abort_completed status. 
				  else if (hapi.baseline_state === "abort_in_progress"){ 
				            notificationsView.clear();
							notificationsView.add({
									status : 'running',
									summary : "Abort is in progress",
									timestamp : (new Date().toISOString()),
									changing : true
							}); 
				  }
				  else if (hapi.baseline_state === "abort_completed"){ 
				            notificationsView.clear();
							notificationsView.add({
									status : 'running',
									summary : "Abort is successful",
									timestamp : (new Date().toISOString()),
									changing : false
							}); 
				  }
                } else {
                    $(TITLE).html('');
                }
            }
            $('#hpsum-start-failed-inventory').live('click', function(ev) {
				 presenter.startInventory({uri: baselineItem.baseline_uri + '/getBaselineData'}, {
					success : function (data) {
						var currComps = baselineItem.baseline_state_detail.current_progress,
	                		totalComps = baselineItem.baseline_state_detail.total_no_component,
	                		currprogress = 0.1;
	                		
	                	if (0 != totalComps) {
							currprogress = (currComps/totalComps) * 100;
	                	} 
	                		
						//show notification details
						notificationsView.add({
								status : 'running',
								summary : localizer.getString(bState),
								timestamp : (new Date().toISOString()),
								changing : true,
								progress : currprogress,
								step : currComps + " of " + totalComps,
								details : hapi.baseline_state_detail.detail
								
						});
							
					},
					error : function (data) {
					}});
				});
            /*function showScheduleDialog(item){
		 var timer_uri = 	{
	                		location_id: item.hapi.location_id,
					baseline_id: item.hapi.baseline_id
				};

				$(SCHEDULE_TYPE, scheduleDialogContents).hpSelect().on('change',function(){
					if ($(SCHEDULE_TYPE).val() == 'daily')
						$('#rec-every-for-schedule',scheduleDialogContents).text('Day(s)');
					else if ($(SCHEDULE_TYPE).val() == 'weekly')
						$('#rec-every-for-schedule',scheduleDialogContents).text('Week(s)');
					else if ($(SCHEDULE_TYPE).val() == 'monthly')
						$('#rec-every-for-schedule',scheduleDialogContents).text('Month(s)');
					else if ($(SCHEDULE_TYPE).val() == 'onetime')
						$('#rec-every-for-schedule',scheduleDialogContents).text('Once');
					else
						$('#rec-every-for-schedule',scheduleDialogContents).text('');
				});

            	var dialogView = new DialogView();
            	dialogView.init({contents: scheduleDialogContents,	
                	position : "center",
                    ok: function (elem) {
                    	var schedule_date = $(SCHEDULE_DATE_AND_TIME).datetimepicker("getDate");
                    	presenter.startPFWInventory({
                    		scheduled: "On",
                    		scheduleDate: $.format.date(schedule_date, "yyyy-MM-dd"),
                    		scheduleTime: $.format.date(schedule_date, "hh:mm:ss"),
                    		scheduleType: $(SCHEDULE_TYPE).val(),
                    		scheduleRecurs: $(SCHEDULE_RECURS).val(),
                    		uri: item.hapi.baseline_uri
                    	});
                    	notificationsView.add({
	                        status: 'info',
	                        summary: localizer.getString("hpsum.baseline.starting_download")	                        
	                   	});

            		showInventoryProgress(timer_uri);
                    },
                    cancel: function () {   
                    	$(SCHEDULE_RECURS).val('1');
                    	$(SCHEDULE_DATE_AND_TIME).val('');
                    }
                });
            } */
            
            //Populate component/fixes table
            function populateComponentTable(item){
	                var oTable = $(COMPONENT_TABLE).dataTable();
					if(oTable[0] == undefined)
					{
						return;
					}
					if(oTable.length>0)
	                oTable.fnClearTable();
	                if(item.hapi.hasOwnProperty("components")) {
						if (item.hapi.components.component_available.length == 0)
						{
							oTable.fnSettings().oLanguage.sEmptyTable = localizer.getString("hpsum.baseline.show.noComponentsFound");
							return;
						}
						for( var comp = 0; comp < item.hapi.components.component_available.length; comp++) {
							var component = item.hapi.components.component_available[comp];
							if( component.revision != '')
							{
								component.component_version += '('+ component.revision + ')';
							}
						}
	                   oTable.fnAddData(item.hapi.components.component_available);
	                   //select first record
	                   $(COMPONENT_TABLE + ' tbody tr').first().addClass('hp-selected');
					   
					   //ToolTip for Components reboot value
					   for( var comp = 0; comp < item.hapi.components.component_available.length; comp++) {
						   var compid = item.hapi.components.component_available[comp].component_id;
						   compid = compid.replace(/(:|\.)/g,'');
						if(item.hapi.components.component_available[comp].reboot_details.length == 0)
						{
						   if(item.hapi.components.component_available[comp].reboot_required == false )
							  $('#hpsum-'+compid).attr('tooltip',localizer.getString('hpsum.common.reboot_details.text.No')).hpTooltip();
							else if(item.hapi.components.component_available[comp].reboot_required == true)
							  $('#hpsum-'+compid).attr('tooltip',localizer.getString('hpsum.common.reboot_required.text.yes')).hpTooltip();		
						}
					   else{
						   for(var reb = 0; reb < item.hapi.components.component_available[comp].reboot_details.length; reb++)
							{
							if(item.hapi.components.component_available[comp].reboot_details[reb].value == REBOOT_REQ_DETAILS_REQUIRED)
							 $('#hpsum-'+compid).attr('tooltip',localizer.getString('hpsum.common.reboot_details.text.Required')).hpTooltip();
						   else if(item.hapi.components.component_available[comp].reboot_details[reb].value == REBOOT_REQ_DETAILS_OPTIONAL)
							 $('#hpsum-'+compid).attr('tooltip',localizer.getString('hpsum.common.reboot_details.text.Optional')).hpTooltip();
						   else if(item.hapi.components.component_available[comp].reboot_details[reb].value == REBOOT_REQ_DETAILS_ENVIRONMENTDEPENDENT)
							$('#hpsum-'+compid).attr('tooltip',localizer.getString('hpsum.common.reboot_details.text.EnvironmentDependent')).hpTooltip();
						   else if(item.hapi.components.component_available[comp].reboot_details[reb].value == REBOOT_REQ_DETAILS_NO)
							  $('#hpsum-'+compid).attr('tooltip',localizer.getString('hpsum.common.reboot_details.text.No')).hpTooltip();
						   else if(item.hapi.components.component_available[comp].reboot_details[reb].value == REBOOT_REQ_DETAILS_YES)
							  $('#hpsum-'+compid).attr('tooltip',localizer.getString('hpsum.common.reboot_required.text.yes')).hpTooltip();
							}
						}
					 }
	                   //to enable click event for a row
	                   $(COMPONENT_TABLE + " tbody tr").click( function( e ) {
							var data = oTable.fnGetData( this );
					        if ( $(this).hasClass('hp-selected') ) {
					            $(this).removeClass('hp-selected');
					        }
					        else {
					        	$(COMPONENT_TABLE + ' tr.hp-selected').removeClass('hp-selected');
					            $(this).addClass('hp-selected');
					        }
					        //call REST API to get component data and show it to user in a dialog
					        var uri = {location_id: item.hapi.location_id,
					        			baseline_id: item.hapi.baseline_id,
					        			component_id: data.component_id,
						 				filter: "compInfo"
					        			};
							
							var srcElem, browserType = 0;
                            var bPopulateConfigUI=false;
							//Check if firefox or (chrome and IE)
							if(e.srcElement)
							{
								srcElem = e.srcElement;//Chrome and IE
                                if((!srcElem.cellIndex) && srcElem.parentElement.cellIndex !=0)
                                    bPopulateConfigUI=true;
							}
							else
							{
								srcElem = e.target;//Firefox
								browserType = 1;
								if((!srcElem.cellIndex) && srcElem.parentElement.cellIndex !=0)
                                    bPopulateConfigUI=true;
							}
                            
							 if(bPopulateConfigUI === true)
							 {
								
					        	presenter.getCompConfDetail(uri, 
								{
									success : function(compdata) {
									onComponentConfigDataSuccess(uri, compdata, browserType);
									},
									error : function(errorInfo) {
									onComponentDataError(errorInfo);
									}
								});
							 }
							 else
							 {
								presenter.getComponentData(uri, {
									success : function(compdata) {
										onComponentDataSuccess(compdata);
									},
									error : function(errorInfo) {
										onComponentDataError(errorInfo);
									}
								});
							}
					    });
	                
                }
            }
            
			/*populating missingcomponents table*/
			function populateMissingComponentTable(item){
	                var oTable = $(MISSINGCOMPONENT_TABLE).dataTable();
					if(oTable[0] == undefined)
					{
						return;
					}
					var comp_missing;
	                oTable.fnClearTable();
					var rowId=0;
					var type=item.hapi.location_type;
					var missing_count =0;     
					if(item.hapi.components.hasOwnProperty("component_sigfile_missing") || item.hapi.components.hasOwnProperty("component_signature_invalid"))
						{
							$(REVALIDATEALL_BUTTON).show();
							$(REVALIDATEALL_BUTTON).unbind('click').bind('click', onRevalidateItem);
						}	
						else
						{
							$(REVALIDATEALL_BUTTON).hide();
						}	
					if(item.hapi.components.hasOwnProperty("componentinfo_missing") || item.hapi.components.hasOwnProperty("component_missing") || item.hapi.components.hasOwnProperty("component_downloadfailed") || item.hapi.components.hasOwnProperty("componentProcessing_failed") || item.hapi.components.hasOwnProperty("component_sigfile_missing") || item.hapi.components.hasOwnProperty("component_signature_invalid"))
					{
							if(item.hapi.components.hasOwnProperty("component_missing"))
							{
							   comp_missing = item.hapi.components.component_missing;
							   rowId = addToTable(comp_missing,"Missing",rowId,type);
							   missing_count =missing_count+item.hapi.components.component_missing.length;
							}
							if(item.hapi.components.hasOwnProperty("componentinfo_missing"))
							{
								comp_missing = item.hapi.components.componentinfo_missing;
								rowId = addToTable(comp_missing,"MissingInfo",rowId,type);
								missing_count =missing_count+item.hapi.components.componentinfo_missing.length;
							}
							if(item.hapi.components.hasOwnProperty("component_downloadfailed")) 
                            {
                                comp_missing = item.hapi.components.component_downloadfailed;
                                rowId = addToTable(comp_missing,"DownloadFailed",rowId,type);
								missing_count =missing_count+item.hapi.components.component_downloadfailed.length;
                            }
                            if(item.hapi.components.hasOwnProperty("componentProcessing_failed")) 
                            {
                                comp_missing = item.hapi.components.componentProcessing_failed;
                                rowId = addToTable(comp_missing,"ProcessingFailed",rowId,type);
								missing_count =missing_count+item.hapi.components.componentProcessing_failed.length;
                            }
							if(item.hapi.components.hasOwnProperty("component_sigfile_missing"))
							{
								comp_missing = item.hapi.components.component_sigfile_missing;
                                rowId = addToTable(comp_missing,"component_sigfile_missing",rowId,type);
								missing_count =missing_count+item.hapi.components.component_sigfile_missing.length;
							}
							if(item.hapi.components.hasOwnProperty("component_signature_invalid"))
							{
								comp_missing = item.hapi.components.component_signature_invalid;
                                rowId = addToTable(comp_missing,"component_signature_invalid",rowId,type);
								missing_count =missing_count+item.hapi.components.component_signature_invalid.length;
							}
							if(comp_missing.length > 0)
							{	
									var ftp_summary = '<br></br>'+ localizer.getString("hpsum.baseline.show.componentDownloaded").bold()+":\t"+item.hapi.components.component_available.length+"\t\t"+localizer.getString("hpsum.baseline.show.componentMissing").bold()+":\t"+missing_count;
									$(BASELINE_WARNING_IMG).show();
									var notify_ftp = item.hapi.location_type.match(/ftp/i)?ftp_summary:"";
									$(BASELINE_WARNING_IMG).show();
									var detail = '<p>' + localizer.getString("hpsum.baseline.show.baselineComponentWarnings")+ '<a class="hp-anchor-uri" data-panel-id="hpsum-baselines-show-missingfixes"'+'href="#/baseline/show/missingfixes"> '+localizer.getString("hpsum.baseline.show.seeComponentWarnings")+'</a>' + '</p>';
									var status='warning';
									var summary= localizer.getString("hpsum.baseline.show.inventoryCompleted");
							notificationsView.add({
									status: status,
									//summary: localizer.getString("hpsum.baseline.show.inventoryCompleted"),
									summary:summary,
								timestamp: (new Date().toISOString()),
									//details: '' 
									details:detail
								});	
							}
									
							$(MISSINGCOMPONENT_TABLE + " tbody tr").click( function( e ) {
								if($(this).hasClass('hp-disabled'))
									return;
							var data = oTable.fnGetData( this );
							if ( $(this).hasClass('hp-selected') ) {
								$(this).removeClass('hp-selected');
							}
							else {
								$(MISSINGCOMPONENT_TABLE + ' tr.hp-selected').removeClass('hp-selected');
								$(this).addClass('hp-selected');
							}
					        //call REST API to get component data and show it to user in a dialog
					        var uri = {location_id: item.hapi.location_id,
					        			baseline_id: item.hapi.baseline_id,
					        			component_id: data.component_id,
						 				filter: "compInfo"
					        			};
							
							var srcElem, browserType = 0;
                            var bPopulateConfigUI=false;
							//Check if firefox or (chrome and IE)
							if(e.srcElement)
							{
								srcElem = e.srcElement;//Chrome and IE
                                if((!srcElem.cellIndex) && srcElem.parentElement.cellIndex !=0)
                                    bPopulateConfigUI=true;
							}
							else
							{
								srcElem = e.target;//Firefox
								browserType = 1;
								if((!srcElem.cellIndex) && srcElem.parentElement.cellIndex !=0)
                                    bPopulateConfigUI=true;
							}
                            
							 if(bPopulateConfigUI === true)
							 {
								
					        	presenter.getCompConfDetail(uri, 
								{
									success : function(compdata) {
									onComponentConfigDataSuccess(uri, compdata, browserType);
									},
									error : function(errorInfo) {
									onComponentDataError(errorInfo);
									}
								});
							 }
							 else
							 {
								presenter.getComponentData(uri, {
									success : function(compdata) {
										onComponentDataSuccess(compdata);
									},
									error : function(errorInfo) {
										onComponentDataError(errorInfo);
									}
								});
							}
					    });						
					}
					else
					{
						oTable.fnSettings().oLanguage.sEmptyTable = localizer.getString("hpsum.baseline.show.noMissingComponents");
					}
				}
			function onRevalidateItem()
			{
				canberevalidated = false;
				var text, textMessage, noofnodes;
				$(REVALIDATE_BASELINE_NODES_TABLE).dataTable().fnClearTable();
				if (! revalidateInProgress) {
                    revalidateInProgress = true;
					presenter.getAssociatedNodes(baselineItem, {
                        success : function(data) {
							var tableNodes = [];
							var l_nodelist = data.hapi.nodes.node;
							noofnodes = l_nodelist.length;
							var showWarningPopup =false;
							if(noofnodes!=0)
							{
								if (data.hapi.nodes.actively_using_nodes == 0) {
									canberevalidated = true;
								}
								else {
									canberevalidated = false;
								}
								for (var idx = 0; idx < noofnodes; ++idx) {
									if(l_nodelist[idx].node_state != "IDLE")
									{
										tableNodes.push({
											nodeurl: '<a id="hpsum-revalidate-baseline-node-click" href="#/node' + '/show/r' + l_nodelist[idx].node_uri + '/getdata">' + l_nodelist[idx].node_name + '</a>',
											type : l_nodelist[idx].type,
											status : l_nodelist[idx].node_status
										});
										showWarningPopup= true;
									}
								}
								if(showWarningPopup)
								{
									revalidateInfoDialog.dialog({
										modal : true,
										dialogClass : 'hp-simple-dialog',
										position : "center",
										draggable : false,
										resizable : false,
										width : 700	
									});
								}
								$(REVALIDATE_BASELINE_NODES_TABLE).dataTable().fnAddData(tableNodes);
								$(REVALIDATE_BUTTON).removeAttr("disabled");
								$(CLOSE_BUTTON_NAME).removeAttr("disabled");
								if (canberevalidated == true) {
								$('#hpsum-baseline-revalidate-ok').show();
									if (noofnodes != 0) {
										text = localizer.getString("hpsum.baseline.remove.baseline") + baselineItem.baseline_url + localizer.getString("hpsum.baseline.remove.association") + noofnodes + localizer.getString("hpsum.baseline.remove.nodes") + localizer.getString("hpsum.baseline.add.continueReval");
										textMessage = localizer.getString("hpsum.baseline.add.revalidateMessage");
									}
									else{
										text = localizer.getString("hpsum.baseline.remove.delWarningNoNode");
										textMessage = "";
										$('#hpsum-delete-baseline-nodes-span').hide ();
									}
									$(REVALIDATE_TITLE).text (text);
									$('#hpsum-baseline-revalidate-title-message').text (textMessage);
									if(showWarningPopup)
									{
										revalidateInfoDialog.dialog("open");
									}
								}
								else {
									$('#hpsum-baseline-revalidate-ok').hide();
									text = localizer.getString("hpsum.baseline.remove.baseline") +baselineItem.baseline_url + localizer.getString("hpsum.baseline.remove.currentlyAssign") +noofnodes + localizer.getString("hpsum.baseline.remove.assignNodes");
									textMessage = localizer.getString("hpsum.baseline.add.revalWarning") + data.hapi.nodes.actively_using_nodes + localizer.getString("hpsum.baseline.remove.activelyUse");
									$(REVALIDATE_TITLE).text (text);
									$('#hpsum-baseline-revalidate-title-message').text (textMessage);
									revalidateInfoDialog.dialog("open");
								}
								if(showWarningPopup == false)
								{
									revalbaseline();
								}
							}
							else
							{
								revalbaseline();
							}
						},
						error : function(data) {
						}
                    });				
                }
			}
			
			function disableActionsForReval()
			{
				$(DELETE_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
				$(REPORTS_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
				$(REPORTS_ACTION).bind('click',false);
				$(VALIDATE_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
				$(VALIDATE_ACTION).bind('click',false);
				$(ABORT_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
				$(ABORT_ACTION).bind('click',false);
				$(DELETE_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
				$(DELETE_ACTION).bind('click',false);
				$(REVALIDATEALL_BUTTON).attr("disabled", "disabled");
				revalidateInProgress = true;
			}
			function revalbaseline()
			{
				var baseline = baselinedetails.location_id +"/"+baselinedetails.baseline_id;
				var input;
				var handlers={success:function(data)
					{
						if(data.hapi.hcode == 0)
						{
							//alert("revalidation command successful");
						}
						else
						{
							//alert("revalidation command not successful");
						}	
					},
					error:function(){}
				};
				presenter.revalidate(input,baseline,handlers);
				disableActionsForReval();
				var uri = {
							location_id: baselinedetails.location_id,
							baseline_id: baselinedetails.baseline_id
						};
				showRevalidationProgress(uri);
			}
			//Add the components to missing table//
			function addToTable(compList,typeComp,rowId,type)
                {
                    var reboot_required;
                    var statusMessage;
                    var oTable = $(MISSINGCOMPONENT_TABLE).dataTable();
                    var component_name;
                    for(var count=0;count<compList.length;count++)
                    {
                        if (typeComp != "Missing" && typeComp != "MissingInfo" && typeComp !="ProcessingFailed") {
                            if (compList[count].reboot_details.length == 0) {
                                if (compList[count].reboot_required == true) {
                                    reboot_required = localizer.getString("hpsum.common.reboot_details.value.required");
                                }
                                else if (compList[count].reboot_required == false) {
                                    reboot_required = localizer.getString("hpsum.common.reboot_details.value.no");
                                }
                            }
                            else {
                                for (var index = 0; index < compList[count].reboot_details.length; index++) {
                                    var reb_value = compList[count].reboot_details[index].value;
                                    switch (reb_value) {
                                        case REBOOT_REQ_DETAILS_REQUIRED:
                                            reboot_required = localizer.getString("hpsum.common.reboot_details.value.required"); break;
                                        case REBOOT_REQ_DETAILS_OPTIONAL:
                                            reboot_required = localizer.getString("hpsum.common.reboot_details.value.optional"); break;
                                        case REBOOT_REQ_DETAILS_ENVIRONMENTDEPENDENT:
                                            reboot_required = localizer.getString("hpsum.common.reboot_details.value.environmentdependent"); break;
                                        case REBOOT_REQ_DETAILS_YES:
                                            reboot_required = localizer.getString("hpsum.common.reboot_details.value.required"); break;
                                        default:
                                            reboot_required = localizer.getString("hpsum.common.reboot_details.value.no"); break;
                                    }
                                }
                            }
                        }
                        if(typeComp=="ProcessingFailed")
                            {
                                component_name=compList[count].component_id;
                                statusMessage = compList[count].error_message;
								compList[count].showConfigLink =false;
                            }
                        else if(typeComp == "MissingInfo")
                            {
                                statusMessage = "Missing";
                                component_name=compList[count].component_file_name;
								compList[count].showConfigLink =false;
                            }
                        else if(typeComp == "component_sigfile_missing"){
                                statusMessage = '<div class="tooltip" tooltip="'+ localizer.getString("hpsum.baseline.show.sigFileMissingHover") +'"><span style ="color:orange">'+localizer.getString("hpsum.baseline.show.sigFileMissingWarning")+'</span></div>';
                                component_name =compList[count].component_file_name;
								compList[count].showConfigLink = true;
                            }
						else if(typeComp == "component_signature_invalid"){
							 statusMessage = '<div class="tooltip" tooltip="'+localizer.getString("hpsum.baseline.show.invalidSignatureHover")+'"><span style ="color:red">'+localizer.getString("hpsum.baseline.show.invalidSignatureError")+'</span></div>';
                             component_name =compList[count].component_file_name;
							 compList[count].showConfigLink =false;
						}
						else{
							statusMessage = typeComp;
                            component_name =compList[count].component_id;
						}
						compList[count].component_file_name = component_name;
                        compList[count].reboot_required = reboot_required;
                        compList[count].status = statusMessage;
						compList[count].type = typeComp;
						rowId++;
                    }
					oTable.fnAddData(compList);
					$('.tooltip').hpTooltip();
                    return rowId;
                }
            
			function showRevalidationProgress(uri)
			{
				notificationsView.clear();
				//show notification details
				notificationsView.add({
	                status: 'info',
	                summary: localizer.getString("hpsum.baseline.show.revalidationInProgress"),
	                timestamp: (new Date().toISOString()),
	                changing: 1,
	                details: localizer.getString("hpsum.baseline.show.revalidationInProgress")
	            });
				revalidateTimer = setInterval(function () {
					//var bStopTimer = false;
					presenter.getBaselineStatus(uri, {
						success : function(data) {
							var bState;
							if(data.hapi.baseline_state_detail.detail === "Revalidation in progress.")
							{
								bState = "hpsum.baseline.show.revalidationInProgress";
							}
							else if(data.hapi.baseline_state_detail.detail ==="Revalidation completed.") {	
								//bStopTimer=true;
								revalidateInProgress=false;							
								bState = "hpsum.baseline.show.inventoryCompleted";
								$(REVALIDATEALL_BUTTON).attr('disabled',false);
								$(DELETE_ACTION).removeClass('hp-disabled').addClass('company-a');
								// Disable the Reports and Validate option in Actions menu
								$(REPORTS_ACTION).removeClass('hp-disabled').addClass('company-a');
								$(REPORTS_ACTION).bind('click',true);
								$(VALIDATE_ACTION).removeClass('hp-disabled').addClass('company-a');
								$(VALIDATE_ACTION).bind('click',true);
								$(ABORT_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
								$(ABORT_ACTION).bind('click',false);
								$(DELETE_ACTION).removeClass('hp-disabled').addClass('company-a');
								$(DELETE_ACTION).bind('click',true);
								clearInterval(revalidateTimer);	
								presenter.getComponents(baselineItem.baseline_uri, {
									success : function(data) {
										var dataItem = {hapi:{location_type:baselinedetails.location_type,location_id:baselinedetails.location_id,baseline_id:baselinedetails.baseline_id, components:data.hapi.components, baseline_state:data.hapi.baseline_state}};
										populateComponentTable(dataItem);
										populateMissingComponentTable(dataItem);
									},
									error : function(errorInfo) {
									}
								});
							}
							//To Clear the previous message from info panel.
							notificationsView.clear();
							//show notification details
							notificationsView.add({
								status: 'info',
								summary: localizer.getString(bState),
								//summary: localizer.getString("hpsum.baseline.show.inventoryInProgress"),
								timestamp: (new Date().toISOString()),
								changing: 1,
								details: data.hapi.baseline_state_detail.detail 
							});
						},
						error : function(errorInfo) {
							onBaselineStatusError(errorInfo);	
							clearInterval(revalidateTimer);
						}
					});
				}, 3000);
			}
            //get baseline inventory progress/status every 3 seconds and update UI 
            function showInventoryProgress(uri){		
            	timer = setTimeout(function () {
            		var bStopTimer = false;
            		presenter.getBaselineStatus(uri, {
            					item: uri,
                				success : function(data) {
                    				onBaselineStatusSuccess(data, this.item);
									if (data.hapi.baseline_state === "abort_completed")
									{
										clearInterval(timer);
										timer = null;
										return;
									}
                    				if(data.hapi.baseline_state === "inventory_completed") {
                    					bStopTimer = true;
										$(REVALIDATEALL_BUTTON).attr('disabled',false);
										
									//To Clear the previous message from info panel.
									notificationsView.clear();
									
									var status = 'info',
										detail = '',
										summary= localizer.getString("hpsum.baseline.show.inventoryCompleted");;
 										
									//show notification details
									var comp_missing = data.hapi.baseline_missing_comp_count;
									if(comp_missing > 0)
									{	
										$(BASELINE_WARNING_IMG).show();
										detail = '<p>' + localizer.getString("hpsum.baseline.show.baselineComponentWarnings")+ '<a class="hp-anchor-uri" data-panel-id="hpsum-baselines-show-missingfixes"'+'href="#/baseline/show/missingfixes"> '+localizer.getString("hpsum.baseline.show.seeComponentWarnings")+'</a>' + '</p>';
										status='warning';
									}
									
									notificationsView.add({
										status: status,
										//summary: localizer.getString("hpsum.baseline.show.inventoryCompleted"),
										summary:summary,
									timestamp: (new Date().toISOString()),
									step: data.hapi.baseline_state_detail.detail,
										//details: '' 
										details:detail
									});	
                    				}
                    		 	},
                    			error : function(errorInfo) {
                        			onBaselineStatusError(errorInfo);
                    			}
                			});
                	
                	if(bStopTimer){
	                	if(timer)
		                {
		                	clearTimeout(timer);
							timer = '';
							timeOut =0;
		                }
		          	}
					else
					{
						showInventoryProgress(uri);
						timeOut = GETSTATUS_TIMER;
						
                	}		
                }, timeOut);
            }
            
            function onBaselineStatusSuccess(data, item) {
            	//show inventory progress
            	//if(data.hapi.baseline_state === "inventory_in_progress" || data.hapi.baseline_state === "manifest_component_processing") {
            	if(data.hapi.baseline_state === "inventory_in_progress" || data.hapi.baseline_state === "manifest_component_processing" ||
            	   data.hapi.baseline_state === "comp_download_in_progress" || data.hapi.baseline_state === "reading_manifest_xml" ||
				   data.hapi.baseline_state === "reading_web_catalog" ||  data.hapi.baseline_state === "inventory_web_catalog_downloading") {	
            		//currently finding the progress by extracting the total components and current components processed data
            		//baseline_state_detail need to be changed to object format, so that we can handle this in proper manner.
            		var totalComps, currComps;
					$(REVALIDATEALL_BUTTON).attr("disabled", "disabled");
            		currComps = data.hapi.baseline_state_detail.current_progress;
            		totalComps = data.hapi.baseline_state_detail.total_no_component;
            		var currprogress = 0.1;
            		if (0 != totalComps) {
            			currprogress = (currComps/totalComps) * 100;
            		}
					
					var bState = "";
					var bStep = "";						

					if (data.hapi.baseline_state === "comp_download_in_progress"){
						bState = "hpsum.baseline.compDownloadInProgress";							
						if(totalComps > 0 && currComps > 0){
							bStep = localizer.getString('hpsum.baseline.show.downloadingComponents' , [currComps,totalComps]);
							$(DELETE_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
						}
					}
					else {
						bState = "hpsum.baseline.show.inventoryInProgress";
						if(totalComps > 0 && currComps > 0){
							bStep = localizer.getString('hpsum.baseline.show.processingComponents' , [currComps,totalComps]);
							$(ABORT_ACTION).addClass('hp-disabled').attr('style', '');
							$(DELETE_ACTION).removeClass('company-a').addClass('hp-disabled').attr('style', 'color: rgb(128, 128, 128);');
						}
					}

					//To Clear the previous message from info panel.
					notificationsView.clear();
	                //show notification details
	                notificationsView.add({
	                        status: 'info',
	                        summary: localizer.getString(bState),
	                        //summary: localizer.getString("hpsum.baseline.show.inventoryInProgress"),
	                        timestamp: (new Date().toISOString()),
	                        changing: 1,
							progress : currprogress,
							step : bStep,
	                        details: data.hapi.baseline_state_detail.detail 
	               });
	           	}
	           	else if(data.hapi.baseline_state === "inventory_completed") {
	                //show notification details
					$(REVALIDATEALL_BUTTON).attr('disabled',false);
					var comp_missing = data.hapi.baseline_state_detail.missing_component_count;
					if(comp_missing > 0)
					{
						$(BASELINE_WARNING_IMG).show();
						var detail = '<p>' + localizer.getString("hpsum.baseline.show.baselineComponentWarnings")+ '<a class="hp-anchor-uri" data-panel-id="hpsum-baselines-show-missingfixes"'+'href="#/baseline/show/missingfixes"> '+localizer.getString("hpsum.baseline.show.seeComponentWarnings")+'</a>' + '</p>';
						var status='warning';
					}
					else
					{
						$(BASELINE_WARNING_IMG).hide();
						var summary= localizer.getString("hpsum.baseline.show.inventoryCompleted");
						var status='info';
						var detail='';
					}
	                notificationsView.add({
										status: status,
										//summary: localizer.getString("hpsum.baseline.show.inventoryCompleted"),
										summary:summary,
										timestamp: (new Date().toISOString()),
										step: data.hapi.baseline_state_detail.detail,
										//details: '' 
										details:detail
									});
	                /*notificationsView.add({
	                        status: 'info',
	                        summary: localizer.getString("hpsum.baseline.show.inventoryCompleted"),
	                        timestamp: (new Date().toISOString()),
	                        step: data.hapi.baseline_state_detail.detail,
	                        details: '' 
	               });*/
                 
                 // Enable the reports, validate and delete options in action menu
				 $(ABORT_ACTION).addClass('hp-disabled').attr('style', '');
                 $(REPORTS_ACTION).removeClass('hp-disabled').addClass('company-a');
				 $(REPORTS_ACTION).unbind('click');
                 $(VALIDATE_ACTION).removeClass('hp-disabled').addClass('company-a');
				 $(VALIDATE_ACTION).unbind('click');
                 $(DELETE_ACTION).removeClass('hp-disabled').addClass('company-a');
	               
	               //populate fixes/components table
	               //presenter.getBundleIndexData(item, {
				    var loc_id=data.hapi.location_id;
	                var base_id=data.hapi.baseline_id; 
					var loc_type=data.hapi.location_type;
	               	presenter.getComponents(baselineItem.baseline_uri, {
        					success : function(data) {
							    var dataItem = {hapi:{location_type:loc_type,location_id:loc_id,baseline_id:base_id, components:data.hapi.components, baseline_state:data.hapi.baseline_state}};
                				populateComponentTable(dataItem);
								populateMissingComponentTable(dataItem);
                		 	},
                			error : function(errorInfo) {
                    			
                			}
                	});
					
					presenter.getOsInfo(baselineItem.baseline_uri, {
    							success : function(data) {
									var idx, html ="";
    								if (data.hapi.hasOwnProperty("baseline_os")) {
										data.hapi.baseline_os.os.sort();
    									for ( idx = 0; idx < data.hapi.baseline_os.os.length; idx++) {
    										html = html + '<li>' + data.hapi.baseline_os.os[idx] + '</li>';
    									}
    
    									$('#os ol').html(html);
    								}
    							},
    							error : function(data) {
    						}
    				}); 
                	
                	if(timer)
	                {
	                	clearInterval(timer);
	                	timer = null;
	                }
                }
            }
            
            function onBaselineStatusError(errorInfo) {
            }
            
            function onComponentDataSuccess(data) {
				var componentDialogContents  =$(componentDialogHtml);
            	localizer.localizeDom(componentDialogContents);
            	//show component dialog
            	var dialog = new DialogView();
            	dialog.init({contents: componentDialogContents,
                    ok: function (elem) {
                        return true;
                    },
                    cancel: function () {
                    }
                });
                var component= data.hapi.component_data;
                $('#component_title',componentDialogContents).html(localizer.getString("hpsum.oneTouchUpdate.componentDetailsFor", [component.component_file_name]));
                $('#hpsum-component-name',componentDialogContents).html(component.package_name);
	            $('#hpsum-comp-inst-notes',componentDialogContents).show();
	            $('#hpsum-comp-prerequisite',componentDialogContents).show();
	            if(component.hasOwnProperty('compInfo')){
	            				$('#hpsum-comp-description',componentDialogContents).html(component.compInfo.componentInfo.description);
	            		}
				$('#hpsum-component-id',componentDialogContents).html(component.component_file_name);
				if(component.hasOwnProperty('compInfo'))
				{
					var component_version= component.compInfo.componentInfo;
					var htmlContents='';
					var version = component_version.version;
					if(component_version.revision != '')
						version += '('+ component_version.revision + ')';
					htmlContents+='<div><b><u>Version</u></b></br>'+ version+ '</br>';
					var enhancement, fixes;
					enhancement = component_version.enhancement;
					fixes = component_version.fixes;
					if(enhancement == '' || enhancement == undefined)
						enhancement =  'None';
					if(fixes == '' || fixes == undefined)
						fixes ='None';
								
							
					htmlContents+='<div><b><u>Enhancements</u></b></br>'+enhancement+ '</br>'+
									'<b><u>Fixes</u></b></br>' + fixes+ '</br></div></div>';
					
					//creating anchor links for the normal text URLs
					var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig; 
					htmlContents = htmlContents.replace(/\<p>/ig, ' <p>');
    				htmlContents = htmlContents.replace(regex, "<a href='$1' target='_blank'>$1</a>");
    
					$('#hpsum-component-installation-notes').html(htmlContents);

					var prerequisiteContents= '';
					//'<div><b><u>Applicable OS</u></b></br>'+ version+ '</br>';
					component_version.prerequisite.sort();
					for(var i=0; i<component_version.prerequisite.length; i++){
						prerequisiteContents += 	component_version.prerequisite[i] + '</br>';
					}
					var prerequisiteContentsHtml = '<div><b><u>Applicable OS</u></b></br>'+ prerequisiteContents;
					$('#hpsum-comp-prerequisite').html(prerequisiteContentsHtml);
				}

				}
			
			function onComponentConfigDataSuccess(item, compdata, browserType) {
				if(compdata && compdata.hapi && compdata.hapi.component_config_data && compdata.hapi.component_config_data.config_file_data)
				{
					var data = compdata.hapi.component_config_data.config_file_data;
					
					data = data.replace(/&quot;/g,'"'); //Replace all &quot; with '"'.
					data = data.replace(/[\r\n]+(?=[^\r\n])/g,''); //Replace all new line and carriage returns
					data = data.replace(/\s{2,}/g, '');//Remove all Tabs
					
					data = JSON.parse(data);
					
					//show component config dialog
					var dialog = new DialogView();
					dialog.init({contents: componentConfigDialogContents,
						ok: function (elem) {
						//build the saveconfig hapi request
						var outData,k=0,strJSON, saveRequired = true;
						outData = data;
						if(!data.parameter.length)
						{
							if(elem.form[0].type == "radio")
							{								
								if(elem.form[0].checked == true)
								{									
									strJSON = "{\"param\":{\"value__attr\":\"" + elem.form[0].value + "\", \"name__attr\":\"" + data.parameter.name__attr +"\"}}";
									outData = {hapi:{component_id:compdata.hapi.component_id,config_file_data:strJSON }};
								}
							}
							else
							{
								elem.form[0].value = elem.form[0].value.replace(/\\/g, '\\\\');
								strJSON = "{\"param\":{\"value__attr\":\"" + elem.form[0].value + "\", \"name__attr\":\"" + data.parameter.name__attr +"\"}}";
								outData = {hapi:{component_id:compdata.hapi.component_id,config_file_data:strJSON }};
							}							
						}
						else
						{
							var keys = new Array();
							var values = new Array();
							var savedParamValues = {};
							var formInputCount = 0;
							while(k<data.parameter.length)
							{
						
								if(data.parameter[k].requirements.input_requirements.user_visible.value__attr == "no")
								{
									k++;
									continue;
								}
								else 
								{								
									if(!(elem.form[formInputCount].type == "radio"))
									{
										if((outData.parameter[k].requirements.required_for_installation.value__attr.toLowerCase() == "yes" || outData.parameter[k].requirements.required_for_installation.value__attr.toLowerCase() == "y") && (!elem.form[formInputCount].value || elem.form[formInputCount].value == ""))
										{
											$('<p style="color: red">'+localizer.getString('hpsum.common.fieldRequired')+'</p>').appendTo($('#'+outData.parameter[k].name__attr));
											return false;
										}
										values[formInputCount]=elem.form[formInputCount].value;
										values[formInputCount] = values[formInputCount].replace(/\\/g, '\\\\');
										keys[formInputCount]=outData.parameter[k].name__attr;
										savedParamValues[outData.parameter[k].name__attr]=outData.parameter[k].output.value__attr;
										formInputCount++;
										k++;
									}
									else
									{
										while(elem.form[formInputCount].type == "radio")
										{
											if(elem.form[formInputCount].checked == true)
											{
												values[formInputCount]=elem.form[formInputCount].value;
												keys[formInputCount]=outData.parameter[k].name__attr;
												savedParamValues[outData.parameter[k].name__attr]=outData.parameter[k].output.value__attr;
												k++;
											}
											formInputCount++;
										}
									}
								}
							}
							var strObj = "{\"param\":[";
							saveRequired = false;
							for(var i=0; i<keys.length; i++){
							if(keys[i] !== undefined && values[i] !== undefined && savedParamValues[keys[i]].toLowerCase() != values[i].toLowerCase()){						
								strObj = strObj + "{\"value__attr\":\""+values[i]+"\", \"name__attr\":\""+keys[i]+"\"},";
								saveRequired = true;
								}
							}
							if(saveRequired)
							{
								strObj = strObj.substr(0,strObj.length - 1);
								strObj = strObj + "]}";
								outData = {hapi:{component_id:compdata.hapi.component_id,config_file_data:strObj}};
							}
							else//Send atleast one key value pair so that engine marks the component as configured
							{
								for(var i=0; i<keys.length; i++){
									if(keys[i] && values[i]){
									strObj = strObj + "{\"value__attr\":\""+values[i]+"\", \"name__attr\":\""+keys[i]+"\"}]}";
									break;
									}
								}
								outData = {hapi:{component_id:compdata.hapi.component_id,config_file_data:strObj}};
							}
						}
						presenter.saveComponentConfig(item, outData, {
										success : function(compdatareturn) {
										if(compdatareturn.hapi.hcode==0)
										{
 										var compId=item.component_id;
 										compId = compId.replace(/(:|\.)/g,'');
 										$('#hpsum-NC-'+compId).hide();
 										$('#hpsum-C-'+compId).show();
 										$(CANCEL).trigger('click');
											return true;											
										}
										else{
											$('#hpsum-component-config-error').show();
											return false;
										}
										},
										error : function(errorInfo) {
											onComponentDataError(errorInfo);
										}}
										);
								return false;
						},
						cancel: function () {
						}
					});                
					var valueField,i,defaultValue;
					//Clear all the entries and add the header
					$('#hpsum-component-config-param tr').html('<thead><tr><td>' + localizer.getString('hpsum.baseline.show.parDesc') + '</td><td>' + localizer.getString('hpsum.baseline.show.value') + '</td><td>' + localizer.getString('hpsum.baseline.show.parName') + '</td></tr></thead>');
					var title = localizer.getString('hpsum.baseline.show.componentConfigFor', [item.component_id]);
					$('#component_config_title').html(title);
					var radioValue;
					$('#hpsum-component-config-error').hide();
					$(SAVE_CONFIG).unbind('click').bind('click', function(ev) {
						saveConfig.call(this, item, data, compdata);
					});
					$(EXPORT_CONFIG).unbind('click').bind('click', function(ev) {
						export_Config = true;
						saveConfig.call(this, item, data, compdata);
						//$(CANCEL).trigger('click');
					});

					$(IMPORT_CONFIG).unbind('click').bind('click', function(ev) {
						importConfig.call(this, item.component_id);
					});
					$(CONFIG_DIALOG_MSG).hide();
					if(!data.parameter.length)
					{
						var values = data.parameter["default"].value__attr;
						var valuesArray = '';
						if (values)
						{
							if(values.indexOf(";") >= 0)
							{
								valuesArray = values.split(";");
							}
							else if(values.indexOf(":") >= 0)
							{
								valuesArray = values.split(":");
							}
						}
						
						var maxLen = data.parameter.requirements.input_requirements.maximum_length;
						var minLen = data.parameter.requirements.input_requirements.minimum_length;
						
						if(data.parameter.requirements.input_requirements.user_visible.value__attr == "no")
						{
							//Invisible
							//So ignore
						}
						else if((values == "" && (($.trim(data.parameter.requirements.input_requirements.required_format)).toLowerCase() == "y" || ($.trim(data.parameter.requirements.input_requirements.required_format)).toLowerCase() == "n")) || (values != "" && valuesArray.length <= 1 && (($.trim(data.parameter.requirements.input_requirements.required_format)).toLowerCase() == "y" || ($.trim(data.parameter.requirements.input_requirements.required_format)).toLowerCase() == "n" || ($.trim(data.parameter.requirements.input_requirements.required_format)).toLowerCase() == "*")))
						{
							//Radio button
							var rYesId,rNoId;
							radioValue = $.trim(data.parameter.output.value__attr).toLowerCase();
							rYesId = data.parameter.name__attr + 'y';
							rNoId = data.parameter.name__attr + "n";
							if(radioValue == "yes" || radioValue == "y")
							{
								valueField = "<label>" + localizer.getString('hpsum.common.button.yes') + "</label><input id = \""+rYesId+"\" type=\"radio\" name=\""+data.parameter.name__attr+"\" value=\"Yes\" checked>&nbsp;&nbsp;&nbsp;&nbsp;<label>" + localizer.getString('hpsum.common.button.no') + "</label><input id = \""+rNoId+"\" type=\"radio\" name=\""+data.parameter.name__attr+"\" value=\"No\">";
							}
							else if(radioValue == "no" || radioValue == "n"|| radioValue == "")
							{
								valueField = "<label>" + localizer.getString('hpsum.common.button.yes') + "</label><input id = \""+rYesId+"\" type=\"radio\" name=\""+data.parameter.name__attr+ "\" value=\"Yes\">&nbsp;&nbsp;&nbsp;&nbsp;<label>" + localizer.getString('hpsum.common.button.no') + "</label><input id = \""+rNoId+"\" type=\"radio\" name=\""+data.parameter.name__attr+"\" value=\"No\" checked>";
							}
						}
						else if(values == "" && maxLen < 26)
						{
							//input type text
							//check for password field
							if(data.parameter.requirements.input_requirements.password_field.value__attr == "yes")
							{
								valueField = "<input type=\"password\" value=\"" + data.parameter.output.value__attr + "\">";							
								//password field
							}
							else
							{
								valueField = "<input type=\"text\" value=\"" + data.parameter.output.value__attr + "\">";
							}						
						}
						else if(values == "" && maxLen > 24)
						{
							//text area
							valueField = "<textarea rows=\"4\" cols=\"50\">" + data.parameter.output.value__attr + "<\/textarea>";								
						}
						else if(valuesArray.length > 1)
						{
							//Combo box
							var j, comboField = "<select value=\"" + data.parameter.output.value__attr + "\">" ;
							for(j=0;j<valuesArray.length;j++)
							{
								if(valuesArray[j]==data.parameter.output.value__attr)
								{
									comboField = comboField + "<option selected>" + valuesArray[j] + "</option>";
								}
								else
								{
									comboField = comboField + "<option>" + valuesArray[j] + "</option>";
								}
							}
							valueField = comboField + "</select>";
						}
						
						$('#hpsum-component-config-param tr:last').after('<tr><td>' + data.parameter.user_prompt + '</td><td>'+valueField+'</td><td>' + data.parameter.name__attr + '</td></tr>');
					}
					else
					{
						var tdid,rYesId,rNoId;
						//Determine the value of valufield for each parameter
						for(i=0;i<data.parameter.length;i++)
						{
							var values = data.parameter[i]["default"].value__attr;
							var valuesArray, isMultiValueField = false;
							tdid = data.parameter[i].name__attr;
							
							if (values)
							{
								if(values.indexOf(";") >= 0)
								{
									valuesArray = values.split(";");
									isMultiValueField = true;
								}
								else if(values.indexOf(":") >= 0)
								{
									valuesArray = values.split(":");
									isMultiValueField = true;
								}
							}
							var maxLen = data.parameter[i].requirements.input_requirements.maximum_length;
							var minLen = data.parameter[i].requirements.input_requirements.minimum_length;
							
							if(data.parameter[i].requirements.input_requirements.user_visible.value__attr == "no")
							{
								//Invisible
								//So ignore
								continue;
							}
							else if(!isMultiValueField && (($.trim(data.parameter[i].requirements.input_requirements.required_format)).toLowerCase() == "y" || ($.trim(data.parameter[i].requirements.input_requirements.required_format)).toLowerCase() == "n") || (($.trim(data.parameter[i].requirements.input_requirements.required_format)).toLowerCase() == "*" && data.parameter.length == 1  && (($.trim(values)).toLowerCase() == "n" || ($.trim(values)).toLowerCase() == "y")))
							{ 
								//Radio button
								rYesId = tdid + 'y';
								rNoId = tdid + "n";
								radioValue = $.trim(data.parameter[i].output.value__attr).toLowerCase();
								if(radioValue == "yes" || radioValue == "y")
								{
									valueField = "<label>" + localizer.getString('hpsum.common.button.yes') + "</label><input id = \""+rYesId+"\" type=\"radio\" name=\""+data.parameter[i].name__attr+"\" value=\"Yes\" checked>&nbsp;&nbsp;&nbsp;&nbsp;<label>" + localizer.getString('hpsum.common.button.no') + "</label><input id = \""+rNoId+"\" type=\"radio\" name=\""+data.parameter[i].name__attr+"\" value=\"No\">";
								}
								else if (radioValue == "no" || radioValue == "n" || radioValue == "")
								{
									valueField = "<label>" + localizer.getString('hpsum.common.button.yes') + "</label><input id = \""+rYesId+"\" type=\"radio\" name=\""+data.parameter[i].name__attr+ "\" value=\"Yes\">&nbsp;&nbsp;&nbsp;&nbsp;<label>" + localizer.getString('hpsum.common.button.no') + "</label><input id = \""+rNoId+"\" type=\"radio\" name=\""+data.parameter[i].name__attr+"\" value=\"No\" checked>";
								}
							}
							else if(!isMultiValueField && maxLen < 26)
							{
								//input type text
								//check for password field
								if(data.parameter[i].requirements.input_requirements.password_field.value__attr == "yes")
								{
									valueField = "<input type=\"password\" value=\"" + data.parameter[i].output.value__attr + "\">";							
									//password field
								}
								else
								{
									valueField = "<input type=\"text\" value=\"" + data.parameter[i].output.value__attr + "\">";
								}						
							}
							else if(!isMultiValueField && maxLen > 24)
							{
								//text area
								//check for password field
								if(data.parameter[i].requirements.input_requirements.password_field.value__attr == "yes")
								{
									valueField = "<input type=\"password\" value=\" size=\"" +maxLen+ "\"" + data.parameter[i].output.value__attr + "\">";
									//password field
								}
								else
								{
									valueField = "<textarea rows=\"4\" cols=\"50\">" + data.parameter[i].output.value__attr + "<\/textarea>";
								}
							}
							else if(isMultiValueField)
							{
								if(valuesArray.length > 1)
								{
									//Combo box
									var j, comboField = "<select value=\"" + data.parameter[i].output.value__attr + "\">" ;
									for(j=0;j<valuesArray.length;j++)
									{
										if(valuesArray[j]==data.parameter[i].output.value__attr)
										{
											comboField = comboField + "<option selected>" + valuesArray[j] + "</option>";
										}
										else
										{
											comboField = comboField + "<option>" + valuesArray[j] + "</option>";
										}
									}
									valueField = comboField + "</select>";
								}
							}
							//Add the row to config table
							$('#hpsum-component-config-param tr:last').after('<tr><td>' + data.parameter[i].user_prompt + '</td><td id="'+tdid+'">'+valueField+'</td><td>' + data.parameter[i].name__attr + '</td></tr>');
						}
					
						//Handle dependencies
						var tdid, temp = {};
						for(i=0;i<data.parameter.length;i++)
						{
							if(data.parameter[i].depends)
							{
								if($.trim(data.parameter[i].depends.dependent.name__attr) != "")
								{
									// disable the td of dependent param
									$('#' + $.trim(data.parameter[i].name__attr)).find(':input').prop("disabled", true);
									
									// add onclick event param to enable/disable the dependent param
									var values = data.parameter[i]["default"].value__attr;
									var inputType, srcElem;
									
									//If the field on which other field depends is a radio button
									if(!(values.indexOf(';')>0)&& (($.trim(data.parameter[i].requirements.input_requirements.required_format)).toLowerCase() == "y" || ($.trim(data.parameter[i].requirements.input_requirements.required_format)).toLowerCase() == "n"))
									{
										tdid = $.trim(data.parameter[i].depends.dependent.name__attr) + data.parameter[i].depends.dependent.value__attr.toLowerCase();
										inputType="radio";
									}
									else if(!(values.indexOf(';')>0))
									{
										tdid = $.trim(data.parameter[i].depends.dependent.name__attr);
										inputType="text";
									}
									else
									{
										tdid = $.trim(data.parameter[i].depends.dependent.name__attr);
										inputType="combo";
									}
									
									//Maintaining dictionary of params and dependent params
									temp[tdid] = $.trim(data.parameter[i].name__attr);
									
									if(inputType == "radio")
									{
										$("#"+ tdid).live('change',function(e){
										srcElem = getSrcElem(browserType, e);
										$('#' + temp[srcElem.id]).find(':input').prop("disabled", false);
										});
										
										//This logic holds good when dependent params are radio buttons (Most likely in configurable component)
										if(data.parameter[i].depends.dependent.value__attr.toLowerCase() == "y")
										{
											tdid = $.trim(data.parameter[i].depends.dependent.name__attr) + "n";
											if(!temp[tdid])
											{
												temp[tdid] = $.trim(data.parameter[i].name__attr);
											}
											$("#"+ tdid).live('change',function(e){
											srcElem = getSrcElem(browserType, e);
											$('#' + temp[srcElem.id]).find(':input').prop("disabled", true);
											});
										}
										else if(data.parameter[i].depends.dependent.value__attr.toLowerCase() == "n")
										{
											tdid = $.trim(data.parameter[i].depends.dependent.name__attr) + "y";
											if(!temp[tdid])
											{
												temp[tdid] = $.trim(data.parameter[i].name__attr);
											}
											$("#"+ tdid).live('change',function(e){
											srcElem = getSrcElem(browserType, e);
											$('#' + temp[srcElem.id]).find(':input').prop("disabled", false);
											});
										}
									}
									else if(inputType=="combo")
									{
										var depValue = data.parameter[i].depends.dependent.value__attr.toLowerCase();
										var defaultVal = data.parameter[i].output.value__attr;
										$("#"+ tdid).live('change',function(e){
										srcElem = getSrcElem(browserType, e);
										if(srcElem.value.toLowerCase() == depValue)
										{
											$('#' + temp[e.currentTarget.id]).find(':input').prop("disabled", false);
										}
										else
										{
											$('#' + temp[e.currentTarget.id]).find(':input').prop("disabled", true);
										}
										});
									}
									else
									{
										//According to dependency the enabling/disabling of dependent param has to be made
										if($('#' + $.trim(data.parameter[i].depends.dependent.name__attr)).html != '')
										{
											$('#' + $.trim(data.parameter[i].name__attr)).find(':input').prop("disabled", false);
										}
										
										$("#"+ tdid).live('change',function(e){
										srcElem = getSrcElem(browserType, e);
										if(srcElem.value.toLowerCase() != "")
										{
											$('#' + temp[e.currentTarget.id]).find(':input').prop("disabled", false);
										}
										else
										{
											$('#' + temp[e.currentTarget.id]).find(':input').prop("disabled", true);
										}
										});
									}
								}
							}
						}
					}
				}
				else
				{
					var errorInfo = "Configure Information Unavailable";
					onComponentDataError(errorInfo);
				}
            }
			function saveConfig(item, data, compdata)
			{
				//build the saveconfig hapi request
				var outData,k=0,strJSON, saveRequired = true;
				outData = data;
				var  elem = this;
				if(!data.parameter.length)
				{
					if(elem.form[0].type == "radio")
					{	
						if(elem.form[0].checked == true){
							strJSON = "{\"param\":{\"value__attr\":\"" + elem.form[0].value + "\", \"name__attr\":\"" + data.parameter.name__attr +"\"}}";
						}
						else {
							strJSON = "{\"param\":{\"value__attr\":\"" + elem.form[1].value + "\", \"name__attr\":\"" + data.parameter.name__attr +"\"}}";
						}
						outData = {hapi:{component_id:compdata.hapi.component_id,config_file_data:strJSON }};
					}
					else
					{
						elem.form[0].value = elem.form[0].value.replace(/\\/g, '\\\\');
						strJSON = "{\"param\":{\"value__attr\":\"" + elem.form[0].value + "\", \"name__attr\":\"" + data.parameter.name__attr +"\"}}";
						outData = {hapi:{component_id:compdata.hapi.component_id,config_file_data:strJSON }};
					}							
				}
				else
				{
					var keys = new Array();
					var values = new Array();
					var savedParamValues = {};
					var formInputCount = 0;
					while(k<data.parameter.length)
					{
						
						if(data.parameter[k].requirements.input_requirements.user_visible.value__attr == "no")
						{
							k++;
							continue;
						}
						else 
						{								
							if(!(elem.form[formInputCount].type == "radio"))
							{
								if((outData.parameter[k].requirements.required_for_installation.value__attr.toLowerCase() == "yes" || outData.parameter[k].requirements.required_for_installation.value__attr.toLowerCase() == "y") && (!elem.form[formInputCount].value || elem.form[formInputCount].value == ""))
								{
									$('<p style="color: red">'+localizer.getString('hpsum.common.fieldRequired')+'</p>').appendTo($('#'+outData.parameter[k].name__attr));
									return false;
								}
								values[formInputCount]=elem.form[formInputCount].value;
								values[formInputCount] = values[formInputCount].replace(/\\/g, '\\\\');
								keys[formInputCount]=outData.parameter[k].name__attr;
								savedParamValues[outData.parameter[k].name__attr]=outData.parameter[k].output.value__attr;
								formInputCount++;
								k++;
							}
							else
							{
								while(elem.form[formInputCount].type == "radio")
								{
									if(elem.form[formInputCount].checked == true)
									{
										values[formInputCount]=elem.form[formInputCount].value;
										keys[formInputCount]=outData.parameter[k].name__attr;
										savedParamValues[outData.parameter[k].name__attr]=outData.parameter[k].output.value__attr;
										k++;
									}
									formInputCount++;
								}
							}
						}
					}
					var strObj = "{\"param\":[";
					saveRequired = false;
					for(var i=0; i<keys.length; i++){
						if(keys[i] !== undefined && values[i] !== undefined && savedParamValues[keys[i]].toLowerCase() != values[i].toLowerCase()){						
							strObj = strObj + "{\"value__attr\":\""+values[i]+"\", \"name__attr\":\""+keys[i]+"\"},";
							saveRequired = true;
						}
					}
					if(saveRequired)
					{
						strObj = strObj.substr(0,strObj.length - 1);
						strObj = strObj + "]}";
						outData = {hapi:{component_id:compdata.hapi.component_id,config_file_data:strObj}};
					}
					else//Send atleast one key value pair so that engine marks the component as configured
					{
						for(var i=0; i<keys.length; i++){
							if(keys[i] && values[i]){
								strObj = strObj + "{\"value__attr\":\""+values[i]+"\", \"name__attr\":\""+keys[i]+"\"}]}";
								break;
							}
						}
						outData = {hapi:{component_id:compdata.hapi.component_id,config_file_data:strObj}};
					}
				}

				presenter.saveComponentConfig(item, outData, {
					success : function(compdatareturn) {
						if(compdatareturn.hapi.hcode==0)
						{
							var compId=item.component_id;
 							compId = compId.replace(/(:|\.)/g,'');
 							$('#hpsum-NC-'+compId).hide();
 							$('#hpsum-C-'+compId).show();
							$(CONFIG_DIALOG_MSG).show();
							$("#hpsum-comp-cfg-msg").html(localizer.getString('hpsum.baseline.show.componentConfigSaved'));
							if(export_Config){
								exportConfig.call(this, item.component_id);
								export_Config = false;
							}
							return true;											
						}
						else{
							$('#hpsum-component-config-error').show();
							return false;
						}
					},
					error : function(errorInfo) {
						onComponentDataError(errorInfo);
					}
				});
			}
			
			function onExportLocationChange() {
				$(EXPORT_CONFIG_ERROR).hide();
				$(EXPORT_ERROR_MSG).hide();
				if(instExportConfigBrowse.getLocation() == "")
				{
					instExportConfigBrowse.setPanelText(baselinedetails.baseline_url)
					if(baselinedetails.baseline_isWritable == false)
						{
							$(EXPORT_CONFIG_ERROR).show();
							$(EXPORT_OK_BUTTON).attr('disabled',true);
						}
						else
						{
							$(EXPORT_CONFIG_ERROR).hide();
							$(EXPORT_OK_BUTTON).attr('disabled',false);
						}
				}
				else
					$(EXPORT_OK_BUTTON).attr('disabled',false);
			}
				
			function exportConfig(compId){
				var exportdialog = new DialogView();
				exportdialog.init({contents: exportConfigDialogContents,
					ok: function (elem) {
					},
					cancel: function() {
					}
				});
				
				if(baselinedetails.baseline_isWritable == false)
				{
					$(EXPORT_CONFIG_ERROR).show();
					$(EXPORT_OK_BUTTON).attr('disabled',true);
				}
				else
				{
					$(EXPORT_CONFIG_ERROR).hide();
					$(EXPORT_OK_BUTTON).attr('disabled',false);
				}
				$(EXPORT_ERROR_MSG).hide();
				
	           var options = 	{
									command : 'init',
									panelLabel: "hpsum.baseline.show.folderpath",
									panelLabelStyle: "text-align:left;",
						            panelHelp: "",
						            panelBrowseText: "hpsum.common.browse"
						        };
				$(EXPORT_CONFIG_BROWSE).hpsumBrowse(options);
				instExportConfigBrowse = $(EXPORT_CONFIG_BROWSE).data('plugin_hpsumBrowse');
				
				instExportConfigBrowse.setInputEvent("onchange", onExportLocationChange);
				
				instExportConfigBrowse.setPanelText(baselinedetails.baseline_url);
				
				$(EXPORT_CREDENTIALS_CHKBOX).unbind('click').bind('click', function() {
					if($(EXPORT_CREDENTIALS_CHKBOX).is(':checked'))
						$(EXPORT_WARNING).show();
					else
						$(EXPORT_WARNING).hide();
					$(EXPORT_ERROR_MSG).hide();
				});
				$(EXPORT_OK_BUTTON).unbind('click').bind('click', function() {
					var configFolder = instExportConfigBrowse.getLocation(); 
					if(configFolder == "")
					{
						$(EXPORT_CONFIG_ERROR).show();
					}
					else 
					{
						var configData = {
								hapi: {
									compId : compId,
									location_id : baselinedetails.location_id,
									baseline_id : baselinedetails.baseline_id,
									folderPath : configFolder,
									includeCredentials : $(EXPORT_CREDENTIALS_CHKBOX).is(':checked')
								}
							};
						presenter.exportCompConfig(configData,{
							success : function(data) {
								var message = data.hapi.baselines.baseline[0].components.component.status;
								notifications.show(message, 'ok');
								notificationsView.add({
									status : 'info',
									timestamp : (new Date().toISOString()),
									details: message
								}); 
								$(CONFIG_DIALOG_MSG).show();
								$("#hpsum-comp-cfg-msg").html(message);
								$(EXPORT_CANCEL).trigger('click');
							},
							error : function(data) {
							var message = data.hapi.baselines.baseline[0].components.component.status;
								notifications.show(message, 'error');
								$(EXPORT_ERROR_MSG).show();
								$(EXPORT_ERROR_MSG).text(message);
								$(EXPORT_ERROR_MSG).addClass("hp-error");
							}}
						);
					}
				});
			}
			
			function onImportLocationChange()
			{
				$(IMPORT_CONFIG_ERROR).hide();
				$(IMPORT_ERROR_MSG).hide();
			}

			function importConfig(compId){
				var importdialog = new DialogView();
				importdialog.init({contents: importConfigDialogContents,
					ok: function (elem) {
					},
					cancel: function() {
					}
				});
				$(IMPORT_CONFIG_ERROR).hide();
				$(IMPORT_ERROR_MSG).hide();
				
	           var options = 	{
									command : 'init',
									panelLabel: "hpsum.baseline.show.folderpath",
									panelLabelStyle: "text-align:left;",
						            panelHelp: "",
						            panelBrowseText: "hpsum.common.browse"
						        };
				$(IMPORT_CONFIG_BROWSE).hpsumBrowse(options);
				instImportConfigBrowse = $(IMPORT_CONFIG_BROWSE).data('plugin_hpsumBrowse');
				instImportConfigBrowse.setPanelText(baselinedetails.baseline_url);
				instImportConfigBrowse.setInputEvent('onchange', onImportLocationChange);
				
				$(IMPORT_OK_BUTTON).unbind('click').bind('click', function() {
					var configFolder = instImportConfigBrowse.getLocation(); 
					if(configFolder == "")
					{
						$(IMPORT_CONFIG_ERROR).show();
					}
					else 
					{
						var configData = {
							hapi: {
								compId : compId,
								location_id : baselinedetails.location_id,
								baseline_id : baselinedetails.baseline_id,
								folderPath : configFolder,
							}
						};
						presenter.importCompConfig(configData,{
							success : function(data) {
							var compId=configData.hapi.compId;
								compId = compId.replace(/(:|\.)/g,'');
								$('#hpsum-NC-'+compId).hide();
								$('#hpsum-C-'+compId).show();
								var uri = {location_id: configData.hapi.location_id,
					        			baseline_id: configData.hapi.baseline_id,
					        			component_id: configData.hapi.compId,
						 				filter: "compInfo"
					        			};
								
								presenter.getCompConfDetail(uri, 
								{
									success : function(compdata) {
									onComponentConfigDataSuccess(uri, compdata, browserType);
									var message = data.hapi.baselines.baseline[0].components.component.status;
									notifications.show(message, 'ok');
									notificationsView.add({
										status : 'info',
										timestamp : (new Date().toISOString()),
										details: message
									});
								
								$(CONFIG_DIALOG_MSG).show();
								$("#hpsum-comp-cfg-msg").html(message);
								$(IMPORT_CANCEL).trigger('click');
									},
									error : function(errorInfo) {
									}
								});
							},
							error : function(data) {
								var message = data.hapi.baselines.baseline[0].components.component.status;
								notifications.show(message, 'error');
								$(IMPORT_ERROR_MSG).show();
								$(IMPORT_ERROR_MSG).text(message);
								$(IMPORT_ERROR_MSG).addClass("hp-error");
							}
						});
					}
				});
			}
			
		
			
			function getSrcElem(browserType, e){
				var srcElem;
				if(browserType==1){
				srcElem = e.target;//Firefox
				}
				else{
				srcElem = e.srcElement;//Chrome and IE
				}
				return srcElem;
			}
            function onComponentDataError(errorInfo) {
            }

            function onItemError(errorMessage) {
            }
            
            function onSelectionChange(selection) {
                //urlFragment.replaceHrefUris(HEADER + ', ' + PANEL_SELECTOR, selection.uris);
				urlFragment.replaceHrefUris(HEADER,
                    selection.uris, selection.multiSelectId);
                if ($(HEADER).hasClass('hp-show-init')) {
                    $(HEADER).removeClass('hp-show-init');
                } else {
                    $(HEADER).addClass('hp-show-changing');
                    //$(ACTIONS).addClass('hp-disabled');
                }
            }
			function createCustomUriChange(selection) {
               	urlFragment.replaceHrefUris(ADD_BASELINE_CREATECUSTOM_DIALOG,
                    selection.uris, selection.multiSelectId);
            }
            
           /* function onChange() {            	
            	var selection = $(SCHEDULE_TYPE).hpSelect('get');
            	$('#rec-every-for-schedule').text = selection;            	
            }
            */
            function onItemDeleteSuccess(item_name) {
                //notifications.show("Deleted " + item_name);
                deleteInProgress = false;
                
                var locations = indexService.getLocations();
				if(locations.length == 1) {
					var html = '<li data-id="all" class="hp-selected">' + localizer.getString("hpsum.common.all") + '</li>';
					$('#locations', PAGE).html(html);
                }
                
                deleteInfoDialog.dialog("close");
                deleteInProgress = false;
            }

            /**
             * @private
             */
            function onItemDeleteError(data) {
               notifications.show(errorMessage);
                // real product code should also ensure hp-details-notify
                // is populated via item state
                deleteInProgress = false;
			}

            /**
             * @private
             */
            function onDeleteItem(ev) {
			$('#hpsum-baseline-delete-title-message').show();								
			$(DELETE_IN_PROGRESS_SPAN).hide();
			if($(DELETE_ACTION).hasClass("hp-disabled")) 
				{
                    ev.preventDefault();
                    return;
                }
			$(DELETE_BASELINE_NODES_TABLE).dataTable().fnClearTable();
			$('#hpsum-delete-baseline-nodes-span').show ();
				canbedeleted = false;
				var text, textMessage, noofnodes;
				if (! deleteInProgress) {
                    deleteInProgress = true;
					presenter.getAssociatedNodes(baselineItem, {
                        		success : function(data) {
									var tableNodes = [];
									var l_nodelist = data.hapi.nodes.node;
									noofnodes = l_nodelist.length;
									if (data.hapi.nodes.actively_using_nodes == 0) {
										canbedeleted = true;
									}
									else {
										canbedeleted = false;
									}
									for (var idx = 0; idx < noofnodes; ++idx) {
									tableNodes.push({
									nodeurl: '<a id="hpsum-delete-baseline-node-click" href="#/node' + '/show/r' + l_nodelist[idx].node_uri + '/getdata">' + l_nodelist[idx].node_name + '</a>',
									type : l_nodelist[idx].type,
									status : l_nodelist[idx].node_status
								});
								
								}
								deleteInfoDialog.dialog({
								modal : true,
								dialogClass : 'hp-simple-dialog',
								position : "center",
								draggable : false,
								resizable : false,
								width : 700	
							});
								$(DELETE_BASELINE_NODES_TABLE).dataTable().fnAddData(tableNodes);
								$(DELETE_BUTTON_NAME).removeAttr("disabled");
								$(CLOSE_BUTTON_NAME).removeAttr("disabled");
								if (canbedeleted == true) {
									$('#hpsum-baseline-delete-ok').show();
									if (noofnodes != 0) {
										text = localizer.getString("hpsum.baseline.remove.baseline") + baselineItem.baseline_url + localizer.getString("hpsum.baseline.remove.association") + noofnodes + localizer.getString("hpsum.baseline.remove.nodes") + localizer.getString("hpsum.baseline.remove.continueDel");
										textMessage = localizer.getString("hpsum.baseline.remove.deleteMessage");
									}
									else	{
										text = localizer.getString("hpsum.baseline.remove.delWarningNoNode");
										textMessage = "";
										$('#hpsum-delete-baseline-nodes-span').hide ();
									}
									$(DELETE_TITLE).text (text);
									$('#hpsum-baseline-delete-title-message').text (textMessage);
									deleteInfoDialog.dialog("open");
								}
								else {
										$('#hpsum-baseline-delete-ok').hide();
										text = localizer.getString("hpsum.baseline.remove.baseline") +baselineItem.baseline_url + localizer.getString("hpsum.baseline.remove.currentlyAssign") +noofnodes + localizer.getString("hpsum.baseline.remove.assignNodes");
										textMessage = localizer.getString("hpsum.baseline.remove.delWarning") + data.hapi.nodes.actively_using_nodes + localizer.getString("hpsum.baseline.remove.activelyUse");
										$(DELETE_TITLE).text (text);
										$('#hpsum-baseline-delete-title-message').text (textMessage);
										deleteInfoDialog.dialog("open");
									}
								},
								
                       			 error : function(data) {
								 }
                    			});				
                }
				deleteInProgress = false;
			}
               //eleteInProgress = false;
              //ev.preventDefault();
            //}


            /**
             * @private
             */
            function onAbortItem(ev) {
				if($(ABORT_ACTION).hasClass("hp-disabled")) 
				{
                    ev.preventDefault();
                    return;
                }
            	
				if (! abortInProgress) {
                   abortInProgress = true;
                    
                   var contents = $(abortConfirmHtml);
                   localizer.localizeDom(contents);
                    $(ABORT_TITLE, contents).text(localizer.getString('hpsum.common.abortMessage', [presenter.selectionLabel()]));
                        
                    var dialogView = new DialogView();
                    dialogView.init({contents: contents,
                        ok: function () {
                                abortBaselineItem = baselineItem;
								presenter.abortBaseline(baselineItem, {
									success : onItemAbortSuccess,
									error : onItemAbortError
								});
                        },
                        cancel: function () {
                            abortInProgress = false;
                        }
                    });
                }
                ev.preventDefault();
			}

			function onItemAbortSuccess(item_name) {
                

                notificationsView.clear();
                notificationsView.add({
									status : 'running',
									//summary : "Abort is successful",
									summary : "Abort is accepted and is in progress..",
									timestamp : (new Date().toISOString()),
									changing : true
							}); 
				showAbortWait();
            }

            function onItemAbortError(data) {
               //notifications.show(errorMessage);
                // real product code should also ensure hp-details-notify
                // is populated via item state
                 notificationsView.clear();
                notificationsView.add({
									status : 'running',
									summary : "Abort is unsuccessful",
									timestamp : (new Date().toISOString()),
									changing : true
							});
				//abort failure	message should also be added to "notifications"
				//because "notificationsView" will always shows the current progress
				//When abort fails, user may not be able to see failure message in "notificationsView"
                notifications.add({
                                summary: data.hapi.hmessage,
								sourceName: data.hapi.baseline_url,
                                status: 'error'
                            });
                abortInProgress = false;
			}

			function showAbortWait() {
					
					if (!abortWaitDialog) {
						abortWaitDialog = $(SPLASH_DIALOG);
						abortWaitDialog.dialog({
							modal : true,
							dialogClass : 'hp-simple-dialog',
							position : "center",
							draggable : false,
							resizable : false,
							width : 260,
							height : 180
						});
					}
					
					$(SPLASH_SPINNER).show();
					
					abortWaitDialog.dialog('open');
					var abortItem = 	{
	                					location_id: abortBaselineItem.location_id,
					        			baseline_id: abortBaselineItem.baseline_id
					        		};
					var aborttimer = setInterval(function () {
            		presenter.getBaselineStatus(abortItem, {
                				success : function(data) {
                    				if(data.hapi.baseline_state === "abort_completed") {                    					
                    					clearInterval(aborttimer);
										abortInProgress = false;										
										closeAbortWait();
                    				}
                    		 	},
                    			error : function(errorInfo) {
                        			abortInProgress = false;
									onBaselineStatusError(errorInfo);	
									clearInterval(aborttimer);
                    			}
                			});
                }, 3000);				
				}

			function closeAbortWait() {
				$(SPLASH_SPINNER).hide();
				
				if (abortWaitDialog) {
					abortWaitDialog.dialog('destroy');
					abortWaitDialog = null;
				}
				
				if (aborttimer)
				{
					clearInterval(aborttimer);
					aborttimer = null;
				}
				hashManager.replaceHash('/baseline/show');
			}

            function changeLocation(location) {
                if (location.length > ROUTE_PREFIX.length) {
                    $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
                } else {
                    $(PANELS).hpStackedPanels('setFirstPanel');
                }
            }
			
			function onAddBaseline() {
		
				var contents = $(addBaselineCreateCustomHtml);
				 localizer.localizeDom(contents);
				 var dialogView = new DialogView();				 
				 dialogView.init({contents: contents,
				        ok: function () {},
                        cancel: function () {
                            return;
                        }
                    });
				 $(DIALOG_CONTAINER).css('top','25%');
				 if(baselineInventoryInProgress)
				 {
					$(CREATE_CUSTOM).addClass('hp-disabled').attr("disabled",true);
				 }
				 $(CREATE_CUSTOM).die('click').live('click' ,function(){
					   	presenter.on("selectionChange",createCustomUriChange);
						presenter.off("selectionChange", createCustomUriChange);
						});					
						
				 return false;
			};
			
			this.disableOrEnableCreateCustom = function(inventoryInprogress)
			{
				 baselineInventoryInProgress = inventoryInprogress;
				 if(inventoryInprogress)
				 {
					 $(CREATECUSTOM_ACTION).addClass('hp-disabled').removeClass('company-a').attr('style', 'color: rgb(128, 128, 128);');
					 $(CREATECUSTOM_ACTION).unbind('click');
				 }
				 else
				 {
					 $(CREATECUSTOM_ACTION).removeClass('hp-disabled').addClass('company-a');
					 $(CREATECUSTOM_ACTION).bind('click',true);
				 }
				
			};
			this.associateAddBaselineOptionsPopup = function(baselinecount){					
						if(baselinecount>0)
						{
							$(ADD_BASELINE).attr('href','#');
							$(ADD_BASELINE).die('click',onAddBaseline).live('click',onAddBaseline);
						}	
						else{
							$(ADD_BASELINE).attr('href','#/baseline/add');
							$(ADD_BASELINE).die('click',onAddBaseline);	
						}		
			};
            
            /**
             * @public
             */
             
            this.pause = function () {
				timeOut = 0;
            	$(COMPONENT_TABLE).dataTable().fnClearTable();
                presenter.off("selectionChange", onSelectionChange);
                presenter.off("itemChange", onItemChange);
                presenter.off("itemError", onItemError);
				prevBaselineuri = null;
                if(timer)
                	clearInterval(timer);
            };
            
            this.resume = function () {
				timeOut = 0;
				notificationsView.clear();
				$(ABORT_ACTION).addClass('hp-disabled');
				$(REVALIDATEALL_BUTTON).hide();
				$(DELETE_BUTTON_NAME).removeAttr("disabled");
				$(CLOSE_BUTTON_NAME).removeAttr("disabled");
				$('#hpsum-delete-baseline-nodes-span').show ();
				$(CONFIG_DIALOG_MSG).hide();
				$(BASELINE_WARNING_IMG).hide();
                presenter.on("selectionChange", onSelectionChange);
                presenter.on("itemChange", onItemChange);
                presenter.on("itemError", onItemError);
				$(REVALIDATEALL_BUTTON).attr('tooltip', localizer.getString('hpsum.baseline.show.revalidateHover')).hpTooltip();
            };
            
            this.init = function() {
			
            	$(SCHEDULE_DATE_AND_TIME).datetimepicker({ dateFormat: "yy-mm-dd"});
            	scheduleDialogContents = $(SCHEDULE_DIALOG).detach().show();
            	deleteDialogContents = $(DELETE_DIALOG).detach().show();

                detailsShowView.init();
                $('.hp-details-actions').hpDropMenu();
                notificationsView.init($(VIEW), '#/baseline/show/alerts');
                
                $(PANELS).hpStackedPanels({
                    panelSelector : PANEL_SELECTOR
                });
                
                $(ABORT_ACTION).addClass('hp-disabled');
                $(DELETE_ACTION).bind('click', onDeleteItem);
                $(ABORT_ACTION).bind('click', onAbortItem);
                $(DELETE_BUTTON_NAME).removeAttr("disabled");
				$(CLOSE_BUTTON_NAME).removeAttr("disabled");
                $(DELETE_IN_PROGRESS_SPAN).hide();
				$(REVALIDATEALL_BUTTON).hide();
                $(COMPONENT_TABLE + ' tbody td').click( function () {
				    // Get the position of the current data from the node
				    var aPos = $(COMPONENT_TABLE).dataTable().fnGetPosition( this );
				     
				    // Get the data array for this row
				    var aData = $(COMPONENT_TABLE).dataTable().fnGetData( aPos[0] );
				     
				    
				});
                
                //Sample data added here to show contents section in the Details pane
                /*
                var data = [{component_file_name: "1", package_name: "HP System Management Home page for Windows", component_version: "6.10.002"},
				    {component_file_name: "2", package_name: "Headless Server Registry update for Windows", component_version: "4.2.021"}];
				*/
				var compId;    
				var oTab = $(COMPONENT_TABLE).dataTable({
					oLanguage: {
					    sEmptyTable: localizer.getString("hpsum.baseline.show.loadOrInvInProgress"),
					    sSearch: localizer.getString('hpsum.common.search')
							   },
				    bPaginate : false,
				    bProcessing : true,
				    bFilter : true,
				    bSort : true,
				    bAutoWidth : false,
				    bInfo : false,
				    bRetrieve : true,
				    bDestroy : true,
				    aoColumns : [				        
                        {mDataProp: 'component_file_name',
                fnRender: function (oObj) {
                    return '<a href="javascript:void(0);" class="company-a">'+ oObj.aData.component_file_name + '</a>';
                }},

				        {mDataProp: 'package_name'},
				        {
				            mDataProp: 'product_typeInString',
				            fnRender: function (oObj) {
				                switch(oObj.aData.product_typeInString.toUpperCase()){
                                case 'FIRMWARE':
                                return localizer.getString("hpsum.common.firmware");
                                 case 'DRIVER':
                                return localizer.getString("hpsum.common.driver");
                                 case 'PCI':
                                return localizer.getString("hpsum.common.pci");
                                 case 'UTILITY':
                                return localizer.getString("hpsum.common.utility");
                                 case 'SOFTWARE':
                                return localizer.getString("hpsum.common.software");
                                default:
                                return oObj.aData.product_typeInString;
                                }
				            }
				        },
				        {
				            mDataProp: 'criticality',
				            fnRender: function (oObj) {
                             switch(oObj.aData.criticality.toUpperCase()){
                                case 'OPTIONAL':
                                return localizer.getString("hpsum.common.optional");
                                 case 'RECOMMENDED':
                                return localizer.getString("hpsum.common.recommended");
                                 case 'CRITICAL':
                                return localizer.getString("hpsum.common.critical");
                                 case 'UNKNOWN':
                                return localizer.getString("hpsum.common.status.unknown");                            
                                default:
                                return oObj.aData.criticality;
                                }				              
				            }
				        },
				        {mDataProp: 'component_version'},
						
						{mDataProp: 'reboot_details', sDefaultContent: "",
						fnRender: function (oObj) {
							compId = oObj.aData.component_id;
							compId = compId.replace(/(:|\.)/g,'');
							if(oObj.aData.reboot_details.length == ""){
								if(oObj.aData.reboot_required == REBOOT_DEFAULT_YES){
									return '<div id="hpsum-'+ compId + '" align="center" class="">' + localizer.getString("hpsum.common.reboot_details.value.required") +'</div>';
								}
								else if(oObj.aData.reboot_required == REBOOT_DEFAULT_NO){
									return '<div id="hpsum-'+ compId + '" align="center" class="">' + localizer.getString("hpsum.common.reboot_required.value.no") +'</div>';
								}
							}
							else
							{
								for(var reb = 0; reb < oObj.aData.reboot_details.length; reb++)
								{
									var reb_value = oObj.aData.reboot_details[reb].value;
									switch (reb_value) {
										case REBOOT_REQ_DETAILS_REQUIRED:
											return  '<div id="hpsum-'+ compId + '" align="center" class=""><div>'+ localizer.getString("hpsum.common.reboot_details.value.required") +'</div></div>'; break;
										case REBOOT_REQ_DETAILS_OPTIONAL:
											return '<div id="hpsum-'+ compId + '" align="center" class="">' + localizer.getString("hpsum.common.reboot_details.value.optional") +'</div>'; break;
										case REBOOT_REQ_DETAILS_ENVIRONMENTDEPENDENT:
											return '<div id="hpsum-'+ compId + '" align="center" class="">' + localizer.getString("hpsum.common.reboot_details.value.environmentdependent") +'</div>'; break;
										case REBOOT_REQ_DETAILS_YES:
											return '<div id="hpsum-'+ compId + '" align="center" class="">' + localizer.getString("hpsum.common.reboot_details.value.required") +'</div>'; break;
										default:
											return '<div id="hpsum-'+ compId + '" align="center" class="">' + localizer.getString("hpsum.common.reboot_details.value.no") +'</div>'; break;
									}
								}
							}
 						}},
						
						{mDataProp: 'config_required', sDefaultContent: "",
                        fnRender: function (oObj) {
						if(oObj.aData.config_required == true) {
						compId = oObj.aData.component_id;
						compId = compId.replace(/(:|\.)/g,'');
							if(oObj.aData.is_configured == false)
							{
							    return '<a id="hpsum-NC-' + compId + '" style="white-space:nowrap" href="javascript:void(0);" class="company-a">' + localizer.getString('hpsum.baseline.show.needConfig') + '</a><a id="hpsum-C-' + compId + '" href="javascript:void(0);" class="company-a" style="display: none; white-space:nowrap">' + localizer.getString('hpsum.baseline.addBaseline.configured') + '</a>';
							}
							else
							{
								return '<a id="hpsum-C-'+compId+'" href="javascript:void(0);" style="white-space:nowrap" class="company-a">' + localizer.getString('hpsum.baseline.addBaseline.configured') +'</a>';
							}
						}
							return '<div align="center" class=""></div>'; },
                        sWidth: 15}],
				    	aaSorting: [[ 0, "asc" ]],
				    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
				        return nRow;
				    }
				    });
				 
				 
				var oMissingTab = $(MISSINGCOMPONENT_TABLE).dataTable({
					oLanguage: {
					    sEmptyTable: localizer.getString("hpsum.baseline.show.loadOrInvInProgress"),
					    sSearch: localizer.getString('hpsum.common.search')
							   },
				    bPaginate : false,
				    bProcessing : true,
				    bFilter : true,
				    bSort : true,
				    bAutoWidth : false,
				    bInfo : false,
				    bRetrieve : true,
				    bDestroy : true,
				    aoColumns : [	
						{mDataProp: 'component_file_name',
						fnRender: function (oObj) {
							if(oObj.aData.type.match(/component_sigfile_missing|component_signature_invalid/i))
							{	
								return '<a href="javascript:void(0);" class="company-a">'+ oObj.aData.component_file_name + '</a>';							
							}
							else
							{
								return oObj.aData.component_file_name;	
							}
						}},
						{mDataProp: 'status',
						fnRender: function (oObj) {
						return oObj.aData.status;
					}, sWidth: '180px'},
						
                        

				        {mDataProp: 'package_name', sDefaultContent:'NA'},
				        {mDataProp: 'product_typeInString', sDefaultContent:'NA'},
				        {mDataProp: 'criticality', sDefaultContent:'NA'},
				        {mDataProp: 'component_version', sDefaultContent:'NA'},
						{mDataProp: 'reboot_required', sDefaultContent:'NA'},
						{mDataProp: 'config_required', sDefaultContent: "",
                        fnRender: function (oObj) {
						if(oObj.aData.config_required == true && oObj.aData.showConfigLink ==true) {
						compId = oObj.aData.component_id;
						compId = compId.replace(/(:|\.)/g,'');
							if(oObj.aData.is_configured == false)
							{
							    return '<a id="hpsum-NC-' + compId + '" style="white-space:nowrap" href="javascript:void(0);" class="company-a">' + localizer.getString('hpsum.baseline.show.needConfig') + '</a><a id="hpsum-C-' + compId + '" href="javascript:void(0);" class="company-a" style="display: none; white-space:nowrap">' + localizer.getString('hpsum.baseline.addBaseline.configured') + '</a>';
							}
							else
							{
								return '<a id="hpsum-C-'+compId+'" href="javascript:void(0);" style="white-space:nowrap" class="company-a">' + localizer.getString('hpsum.baseline.addBaseline.configured') +'</a>';
							}
						}
							return '<div align="center" class=""></div>'; },
                        sWidth: 15},
						{mDataProp: 'type', "bVisible": false}],
				    	aaSorting: [[ 0, "asc" ]],
						fnCreatedRow:function(nRow, aData, iDataIndex){
                               if(!aData.type.match(/component_sigfile_missing|component_signature_invalid/i))
                                   nRow.className += ' hp-disabled ' ;
                                },
				    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
				        return nRow;
				    }
				    });
				
				 
				$(COMPONENT_TABLE + ' tbody tr').first().addClass('hp-selected');
				
				componentDialogContents = $(COMPONENT_DIALOG).detach().show();
				componentConfigDialogContents = $(COMPONENT_CONFIG_DIALOG).detach().show();
				exportConfigDialogContents = $(EXPORT_CONFIG_DIALOG).detach().show();
				importConfigDialogContents = $(IMPORT_CONFIG_DIALOG).detach().show();
			    	importConfirmDialogContents = $(IMPORT_CONFIRM_DIALOG).detach().show();

			    router.watch('baseline show section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
				//var dummyNodeData = [];
				deleteInfoDialog = $(DELETE_DIALOG_ERROR);
				revalidateInfoDialog =$(REVALIDATE_DIALOG_ERROR);
				abortInfoDialog = $(ABORT_DIALOG);

				$(DELETE_BASELINE_NODES_TABLE).dataTable({
				oLanguage : {
				    sEmptyTable: localizer.getString("hpsum.group.noMoreNodesAvailable"),
				    sSearch: localizer.getString('hpsum.common.search')
						},
				bPaginate : false,
				sScrollY: "250px",
				bFilter : true,
				bInfo : false,
				bAutoWidth : false,
				bRetrieve : true,
				//aaData : dummyNodeData,
				aoColumns : [{
					mDataProp : 'nodeurl'
				}, {
					mDataProp : 'type'
				}, {
					mDataProp : 'status'
				}],
				aaSorting : [[1, "asc"]],
				bScrollCollapse : true
				});
				
				$(REVALIDATE_BASELINE_NODES_TABLE).dataTable({
				oLanguage : {
				    sEmptyTable: localizer.getString("hpsum.group.noMoreNodesAvailable"),
				    sSearch: localizer.getString('hpsum.common.search')
						},
				bPaginate : false,
				sScrollY: "250px",
				bFilter : true,
				bInfo : false,
				bAutoWidth : false,
				bRetrieve : true,
				//aaData : dummyNodeData,
				aoColumns : [{
					mDataProp : 'nodeurl'
				}, {
					mDataProp : 'type'
				}, {
					mDataProp : 'status'
				}],
				aaSorting : [[1, "asc"]],
				bScrollCollapse : true
				});
				
				$('#hpsum-delete-baseline-node-click').live('click', function(ev) {
					deleteInfoDialog.dialog("close");
					$(DELETE_BASELINE_NODES_TABLE).dataTable().fnClearTable();
				});
                $('#hpsum-revalidate-baseline-node-click').live('click', function(ev) {
					revalidateInfoDialog.dialog("close");
					$(REVALIDATE_BASELINE_NODES_TABLE).dataTable().fnClearTable();
				});
				$('#hpsum-baseline-delete-ok').live('click', function(ev) {
					//deleteInfoDialog.dialog("close");
					$(DELETE_TITLE).text('');
					$('#hpsum-baseline-delete-title-message').hide();									
					$(DELETE_IN_PROGRESS_SPAN).show();
					$(DELETE_BUTTON_NAME).attr("disabled","disabled");
					$(CLOSE_BUTTON_NAME).attr("disabled","disabled");
					$('#hpsum-delete-baseline-nodes-span').hide ();
										
					presenter.removeBaseline(baselineItem, {
                                    success : onItemDeleteSuccess,
                                    error : onItemDeleteError
                                });
				});
				$('#hpsum-baseline-revalidate-ok').live('click', function(ev) {
					revalidateInfoDialog.dialog("close");
					$(REVALIDATE_BASELINE_NODES_TABLE).dataTable().fnClearTable();
					revalbaseline();
				});
				$('#hpsum-baseline-delete-cancel').live('click', function(ev) {
					deleteInfoDialog.dialog("close");
					$(DELETE_BASELINE_NODES_TABLE).dataTable().fnClearTable();
				});
				$('#hpsum-baseline-revalidate-cancel').live('click', function(ev) {
					revalidateInfoDialog.dialog("close");
					$(REVALIDATE_BASELINE_NODES_TABLE).dataTable().fnClearTable();
					revalidateInProgress=false;
				});
				this.resume();
				
				
            };
			
			this.getCompData=function()
			{
				var tabledata=jQuery.makeArray( compData );
				return tabledata;
            };
            
        }

        return new BaselineShowView();
    }());
    
    return BaselineShowView;
});
