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

define(['hpsum/model/activity/ActivityResource',
    'hpsum/presenter/activity/ActivityPresenter',
    'hp/view/MasterPaneView',
    'hp/core/LinkTargetBuilder',
    'hp/core/Localizer',
    'hpsum/presenter/node/NodePresenter',
    'jquery',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpStatus',
    'hp/lib/jquery.hpTimestamp',
    'lib/jquery.dateFormat',
    'hp/lib/date',
    'hp/lib/jquery.hpDropMenu',
    'hp/lib/jquery.hpSelect',
    'hp/view/DialogView',
    'hp/lib/jquery.hpCollapsible',	
    'hp/lib/jquery.hpProgressBar'],
function(resource, Presenter, MasterPaneView, linkTargetBuilder,  localizer, NodePresenter) { "use strict";

    var ActivityView = (function() {
        var TYPE = 'task';
        var PAGE = '#tour-activity-page';
        var FILTERBAR_CONTROL = PAGE + ' .hp-filterbar-control';
        var CATEGORY_FILTER = '#hp-activity-category-filter';
        var STATE_FILTER = '#hp-activity-state-filter';
        var DATE_FILTER = '#hp-activity-date-filter';
		var SPLASH_DIALOG = '#hpsum-add-activity-dialog';
		var	SPLASH_SPINNER = '#hpsum-add-spinner';
        var DATE_MENU = '#hp-activity-date-menu';
        var DETAILS_TEMPLATE = '#tour-activity-details-template';
        var ACTIVITY_TABLE = '#tour-activities';
        var REFRESH = '#hpsum-activity-refresh';
        var ACTIVITYIDS = {};
		var INSTALL_PROGRESS_UPDATE_TIMER;
        /**
         * Constructor
         */
        function ActivityView() {
          
            var presenter = new Presenter();
			var addWaitDialog;
            var masterPaneView = new MasterPaneView();
            var detailsTemplate = null;
                        
            function appendNote(details, activityNote) {
                var note = $('.hp-comment.hp-template', details).clone();
                note.removeClass('hp-template');
				var date = Date.parseISOString(activityNote.date);
				var formattedDate;
				if (date.isToday()) {
					formattedDate = localizer.getString('hpsum.task.today');
				} else if (date.getFullYear() === (new Date()).getFullYear()) {
					formattedDate = $.format.date(date, 'MMM d');
				} else {
					formattedDate = $.format.date(date, 'M/d/280\ ');
				}
               if(activityNote.text === 'Schedule created') 
			   {
					
				$('.hp-comment-text', note).html('<table><td width=300><div class="hp-collapsible" id="message-collapsible"><label>'+linkTargetBuilder.makeLink(activityNote.text,activityNote.textDetails)+'('+formattedDate + ' ' + $.format.date(Date.parseISOString(activityNote.date),'h:mma') +')</label></div></td><td><label>'+formattedDate+ $.format.date(Date.parseISOString(activityNote.date),'h:mma') +'</label></td></table>');			   
			   
			   }
			   else
			   {
			   $('.hp-comment-text', note).html('<table><td width=300><div class="hp-collapsible" id="message-collapsible"><label>'+activityNote.text + '</label></div></td><td><label>'+formattedDate+ $.format.date(Date.parseISOString(activityNote.date),'h:mma') +'</label></td></table><div class="",id=""><textarea size="80x10" >'+activityNote.textDetails+'</textarea></div>');			   
			   }
			   $('#hp-collapsible').hpCollapsible();
			   note.show();
			   
                $('.hp-comments', details).append(note);                
                $('.hp-comment-delete', note).click(function () {
                    alert("TBD");
                });
            }
            
            function addNote(details, alertUri) {
                var alertNote = {user: 'Sam',
                    text: $('.hp-comment-form-text', details).val(),
                    date: new Date().toISOString()};
                presenter.addNote(alertUri, alertNote);
                appendNote(details, alertNote);
                $('.hp-comment-form-text', details).val('')
            }
            
            function renderDetails(indexResult) {
				
                var details = detailsTemplate.clone();
                
                if (indexResult.hasOwnProperty('notes')) {
                    $.each(indexResult.notes, function (index, activityNote) {
                        appendNote(details, activityNote);
                    });
                }
                
                $('.hp-comment-form-text', details).focus(function () {
                    $('.hp-comment-add', details).fadeIn();
                }).blur(function () {
                    $('.hp-comment-add', details).fadeOut();
                });
                
                $('.hp-comment-form-text', details).bind('keydown', function (ev) {
                    if (13 === ev.keyCode) {
                        addNote(details, indexResult.uri);
                        ev.preventDefault();
                    }
                });
                
                $('.hp-comment-add', details).bind('click', function () {
                    addNote(details, indexResult.uri);
                });
                
                return details;
            }
            
            function onSelectionChange(selection) {
                //$('.hp-header-selection').html((selection.uris ? selection.uris.length : 0) + ' selected');
            }
            
            function onIndexResultsChange(indexResults) {
			// If there are node in deploy progress and if the timer was running then stop it
				if (Object.keys(ACTIVITYIDS).length > 0)
					stopInstallProgressTimer();

				for(var i = 0; i < indexResults.count; i++){
					if(indexResults.members[i].status == 4 || indexResults.members[i].status == 5 || indexResults.members[i].status == 6){
						// Remove item from the hash list if the task id doesn't contains in the latest results
						if(!ACTIVITYIDS.hasOwnProperty(indexResults.members[i].taskid)) {
							 delete ACTIVITYIDS[indexResults.members[i].taskid];
						}
					}
				}

				startInstallProgressTimer();
            }
            
            function selectAll() {
                presenter.selectAll();
            }
            
            function onFilterChange(filter) {
                $(STATE_FILTER).hpSelect('set', presenter.getStateFilter(true));
                $(STATE_FILTER + ' .hp-value').
                    text(presenter.getStateFilterSummary(true));
            }
            
            function onStateFilterChange(ev, values) {
                presenter.setStateFilter(values, true);
            }
            
            function onDateFilterChange(ev, values) {
            }
			
			/*
				The function updates the component log in the GUI
			*/
			function showLog(data, logWindowId, taskid, parent)
			{
				if (!data)
					return;

				var logdata = data;
				if(data.hapi.task.component_log.length > 0) 
					logdata = data.hapi.task.component_log;
				else
					logdata = 'ERROR: Unable to retrieve installation logs at this time.';
					
				updateLogTexArea(logdata, logWindowId, taskid, parent);
			}
			/*
				The function updates the error message when there is an error in the get livelog for selected component
			*/
			function showError(data, logWindowId, taskid, parent)
			{
				if (!data)
					return;

				updateLogTexArea(data, logWindowId, taskid, parent);
			}
			
			/*
				The function updates the component log in the GUI
			*/
			function updateLogTexArea(data, logWindowId, taskid, parent)
			{
				var logwindow = $("#hpsum-component-log", logWindowId).get(0);
				if (!logwindow)
					return;
				
				$(logwindow).text(data.replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
				updateActivityList(taskid, parent);
			}
			/*
				The function updates the activity of livelog GUI to member variable
			*/
			function updateActivityList(taskid, parent){
				
				for (var taskID in ACTIVITYIDS) {
					if (taskID == taskid){
						ACTIVITYIDS[taskID] = $(parent).parent().html();
						break;
					}
				}
			}
			/*
				The function updates the GUI for currently deploying node
			*/
			function showInstallingComponent(status){
				if(status && ACTIVITYIDS)
				{
					if(!ACTIVITYIDS.hasOwnProperty(status.hapi.task.task_id)) 
						return;
					
					if(status.hapi.task.task_status.length == 0)
						return;

					var arrayList = status.hapi.task.task_status.split("|");
					if(arrayList.length > 1)
					{
						var array = [];
						array = $(".hpsum-expandabale");
						var parent;
						var parentval;
						
						for( var i = 0; i < array.length; i++){
							parent = array[i];
							parentval = $(array[i]).data('parent-value');
							parentval = parentval.split("#");
							
							if(parentval[1] == status.hapi.task.task_id)
								break;
						}
						
						if(parent)
						{
							var topLevelMsg = "";
							var taskheading = arrayList[0];
							var task = taskheading.split("@");
							var componentList = "";
							var oldInstallingComp = "";
							
							var oldMessage = $(".hpsum-livelog-window", parent).data("task-message");
							
							// parse installed components
							if(arrayList[1].length > 0)
								componentList = arrayList[1].split(",");
							
							if (oldMessage.length > 1){
								var oldComponentList = oldMessage.split("|");								
								if (oldComponentList.length > 2){
									if (oldComponentList[2].length > 0)
										oldInstallingComp = oldComponentList[2];
								}
								
								if (oldComponentList.length > 1){
									if (oldComponentList[1].length > 0){
										oldComponentList = oldComponentList[1].split(",");
										for(var i = 0; i < oldComponentList.length; i++){
											componentList = jQuery.grep(componentList, function(value) {
											  return value != oldComponentList[i];
											});
										}
									}
								}
							}
								
							if(componentList.length > 0){
								for(var i = 0; i < componentList.length; i ++){
								// Old installing component is in the installed list then do not add to list
									if(oldInstallingComp === componentList[i])
										continue;
									
									topLevelMsg = localizer.getString('hpsum.node.liveLogInstalled') +  componentList[i];
									$('#complist', parent).prepend(getComponentLink(parentval[0] + "#" + componentList[i] + "#" + status.hapi.task.task_id, topLevelMsg));
								}
							}							
							
							// When status changed from installing to install complete then update the status
							if (status.hapi.task.task_criticality == 4){
								$('a:first', parent).text(localizer.getString('hpsum.node.liveLogInprogress') + task[0] + "/" + task[1]);	
							}
							else{
								$('a:first', parent).text(localizer.getString('hpsum.node.liveLogCompleted') + task[0] + "/" + task[1]);
								$(parent).attr('data-parent-value', parentval[0] + '#' + parentval[1] + '#' + status.hapi.task.task_criticality);
							}
							
							
							// parse installing component and check currently installing and old installing component are same or not
							if(arrayList.length > 2 && oldInstallingComp.length > 0 && arrayList[2] != oldInstallingComp){
								topLevelMsg = localizer.getString('hpsum.node.liveLogInstalling') +  arrayList[2];
								$('#complist', parent).prepend(getComponentLink(parentval[0] + "#" + arrayList[2] + "#" + status.hapi.task.task_id, topLevelMsg));
							}

							if (oldInstallingComp.length > 0){
								var cList = $(parent).find("textarea");
								var updateComponentLog;
								for (var i = 0; i < cList.length; i ++) {
									var val = $(cList[i]).parent().data("child-value");
									if (val == parentval[0] + "#" + oldInstallingComp + "#" + status.hapi.task.task_id){
										updateComponentLog = cList[i];
										break;
									}
								}
								
								if (arrayList.length > 2 && arrayList[2] == oldInstallingComp){
									
								}
								else{
									//Old component was installing and become installed so need to update install task to installed 
									//and also update the latest log if its expanded
									topLevelMsg = localizer.getString('hpsum.node.liveLogInstalled') + oldInstallingComp;
									$(updateComponentLog).parent().find("a").text(topLevelMsg);
								}
								
								if ($(updateComponentLog).is(':visible'))
									$(updateComponentLog).text(status.hapi.task.component_log);
							}
							
							var liveLog = $(".hpsum-livelog-window", parent);
							$(liveLog).data("task-message", status.hapi.task.task_status);							
							$(liveLog).attr("data-task-message", status.hapi.task.task_status);
							ACTIVITYIDS[status.hapi.task.task_id] = $(parent).parent().html();
						}
					}
				}
			}
			
			function showInstallingError(status){
			
			}
			
			/*
				The function update the GUI based on user selection
			*/
			function updateProgressTimer(){
				stopInstallProgressTimer();
				var array = [];
				array = $(".hpsum-expandabale");
				
				for( var i = 0; i < array.length; i++){
					var parentval = $(array[i]).data('parent-value');
					parentval = parentval.split("#");
					
					if(!ACTIVITYIDS.hasOwnProperty(parentval[1])) 
						continue;
					
					// Post message only for the currently installing node to get updated task status
					if (parentval[2] == 4){	
						// Get task meesage and check for installing component is expanded or not
						// get id if its expanded get the latest log
						var taskMsg = $('.hpsum-livelog-window', array[i]).get(0);
						taskMsg = $(taskMsg).data('task-message');
						
						var componentName = "";
						if ($('textarea:first', array[i]).is(':visible') && taskMsg.length > 0){
							taskMsg = taskMsg.split("|");
							if (taskMsg.length > 2)
								componentName = (taskMsg[2].length > 0 ? taskMsg[2] : "");
						}
						
						var object;
						if( componentName.length > 0)
							object = { hapi : { task_id : parentval[1], component_name : componentName } };
						else
							object = { hapi : { task_id : parentval[1]} };
						
						NodePresenter.postLiveLogData(parentval[0], object, {
						success: function(data){
							showInstallingComponent(data);
						},
						error: function(data){
							showInstallingError(data);
						}
						});
					}
				}
				startInstallProgressTimer();
			}
			
			/*
				The function shows the dialog box for missing components on click of "Missing Components While Downloading" link present at activity page.
			*/
			function showMissingComponentsDialog(msgToDisplay){
			  var missingComponentInfoDialog=$('#hpsum-activity-missingcomponents-confirm');
						missingComponentInfoDialog.dialog({
								modal : true,
								dialogClass : 'hp-simple-dialog',
								position : "center",
								draggable : false,
								resizable : false,
								width : 700
							});
				msgToDisplay = msgToDisplay.replace(/====>/g,"<br/> ====>");
				$("#hpsum-activity-missingcomponents-title").text (localizer.getString("hpsum.common.missingComponentsInfo"));
            	$('#hpsum-activity-missingcomponents-ok').show();
            	$('#hpsum-activity-missingcomponents-title-message').html (msgToDisplay);
            	missingComponentInfoDialog.dialog("open");
				
				$('#hpsum-activity-missingcomponents-cancel').live('click', function(ev) {
					missingComponentInfoDialog.dialog("close");
				});
			}
			
			/*
				The function starts to update deploy status for the currently deploying node
			*/
			function startInstallProgressTimer()
			{
				// With latest data if there are any nodes deploy in progress then start the timer to refresh the installed or installing components
				if (Object.keys(ACTIVITYIDS).length > 0){
					var startTimer = false;
					var array = [];
					array = $(".hpsum-expandabale");
					
					for( var i = 0; i < array.length; i++){
						var parentval = $(array[i]).data('parent-value');
						parentval = parentval.split("#");
						
						if(!ACTIVITYIDS.hasOwnProperty(parentval[1])) 
							continue;
							
						if (parentval[2] == 4){
							startTimer = true;
							break;
						}
					}
					// If any one node is is deploy progress start the timer to update livelog
					if (startTimer)
						INSTALL_PROGRESS_UPDATE_TIMER = setInterval(function(){updateProgressTimer()},6000);
				}
			}
			/*
				The function stops the timer to update deploy status for the currently deploying node
			*/
			function stopInstallProgressTimer()
			{
				clearInterval(INSTALL_PROGRESS_UPDATE_TIMER);
				INSTALL_PROGRESS_UPDATE_TIMER = null;
			}
			
			/*
			This function show or hide the live log windows
			*/
			function showHideLiveLog(event, logWindowId){
				var expanded =  false;
				// check if we have the display window already created
				var srcElement = getSrcElement(event);
				var parentdiv = $(srcElement).parent().get(0);
				var logwindow = $(logWindowId, parentdiv).get(0);
				if(logwindow &&  $(logwindow).is(":visible") )
				{
				   //Is visible let close it
				   if ( logWindowId == "#hpsum-component-log"){
						$('.hpsum-child-icon',parentdiv).removeClass("hpsum-down-icon");
						$('.hpsum-child-icon',parentdiv).addClass("hpsum-up-icon");
					}
					else {
						$('.hpsum-icon',parentdiv).removeClass("hpsum-down-icon");
						$('.hpsum-icon',parentdiv).addClass("hpsum-up-icon");
					}
					$(logwindow).slideUp();	
					$(logwindow).css("display","none");
				}
				else if(logwindow)
				{
					if ( logWindowId == "#hpsum-component-log"){
						$('.hpsum-child-icon',parentdiv).removeClass("hpsum-up-icon");
						$('.hpsum-child-icon',parentdiv).addClass("hpsum-down-icon");
					}
					else{
						$('.hpsum-icon',parentdiv).removeClass("hpsum-up-icon");
						$('.hpsum-icon',parentdiv).addClass("hpsum-down-icon");
					}
					$(logwindow).css("display","block");
					$(logwindow).slideDown();						
					expanded = true;
				}
				return expanded;
			}
            
            function initFilters() {
              
                $(STATE_FILTER).hpSelect({multiSelect: true}).
                    change(onStateFilterChange);
                
                $('#hp-activity-filter-default').bind('click', function (ev) {
                    presenter.setDefaultFilters(true);
                });
                
                $(DATE_FILTER).hpSelect().change(onDateFilterChange);
                                              
                $('#hp-activity-date-range-from').datepicker();
                $('#hp-activity-date-range-to').datepicker();
            }
            
            function initActions() {
                $('#tour-activity-actions').hpDropMenu();
                
                $('.hp-header-select-all').click(selectAll);
                
                $('#tour-activity-dismiss').click(function () {
                    presenter.dismissSelected();
                });
                
                $('#tour-activity-delete').click(function () {
                    presenter.deleteSelectedItems({});
                });
            }
            
            function initTable() {
                detailsTemplate = $('#tour-activity-details-template').
                    remove().attr('id', '');
                    
                var oTab = $(ACTIVITY_TABLE).dataTable({
				oLanguage : {
					sEmptyTable : localizer.getString("hpsum.common.activitywait")
                },
				bPaginate : false,
				bProcessing : true,
				bFilter : false,
				bSort : true,
				bAutoWidth : false,
				bInfo : false,
				bRetrieve : true,
				bDestroy : true,
				//aaData: data,
				aoColumns : [
                
                            /* expand/collapse
                             {fnRender: function (oObj) {
                                return '<div class="hp-collapser"></div>';
                              },
                              sWidth: 10, sClass: "hp-icon", mDataProp: 'collapse'}, */
                            // status
                            {fnRender: function (oObj) {
							
							$('#hpsum-spinner').hide();
								if(oObj.aData.state.match(localizer.getString("hpsum.baseline.compDownloadingFinished")))
								{
								     var installMessage ="";
								     installMessage = "<div id='hpsum-missingcomponents-parent' data-parent-value=''><a class='missingComponent' data-hpsum= '" + oObj.aData.Message + "'>Missing Components While Downloading</a></div>";
									 oObj.aData.Message=installMessage;
								}
                            	if(oObj.aData.status === 0 )
                                    return '<div class="hp-status"><div class="hp-status-value hp-status-ok"><span class="hp-value">ok</span></div></div></div>';
                                else if(oObj.aData.status === 1 )
                                	return '<div class="hp-status"><div class="hp-status-value hp-status-error"><span class="hp-value">error</span></div></div>';
                                else if(oObj.aData.status === 2 )
                                	return '<div class="hp-status"><div class="hp-status-value hp-status-warning"><span class="hp-value">warning</span></div></div>';
								else if(oObj.aData.status === 3 )
                                	return '<div class="hp-status"><div class="hp-status-value hp-status-unknown"><span class="hp-value">unknown</span></div></div>';
                                else if(oObj.aData.status === 4 || oObj.aData.status === 5 || oObj.aData.status === 6){
									// 4 deploy in-progress
									// 5 deploy done with success
									// 6 deploy done with error
									var message = "";
									for (var taskID in ACTIVITYIDS) {
										if (taskID == oObj.aData.taskid){
											message = ACTIVITYIDS[taskID];
											break;
										}
									}
									
									if (message.length > 0)
										oObj.aData.Message = message;
									else{
										oObj.aData.Message = parseTaskStatus(oObj.aData.Message, oObj.aData.status, oObj.aData.taskid);
										ACTIVITYIDS[oObj.aData.taskid] = oObj.aData.Message;
									}
																		
									if (oObj.aData.status === 4)
										return '<div class="hp-status"><div class="hp-status-value hp-status-changing"><span class="hp-value">deploying</span></div></div>';
									else if (oObj.aData.status === 5)
										return '<div class="hp-status"><div class="hp-status-value hp-status-ok"><span class="hp-value">ok</span></div></div></div>';
									else if (oObj.aData.status === 6)
										return '<div class="hp-status"><div class="hp-status-value hp-status-error"><span class="hp-value">error</span></div></div>';
								}
								else if(oObj.aData.status === 7 || oObj.aData.status === 8){
									//7 Export configuration
									//8 Import configuration  or AutoImport configuartion
									
									oObj.aData.Message = parseConfigStatus(oObj.aData.Message, oObj.aData.status, oObj.aData.taskid);
									return '<div class="hp-status"><div class="hp-status-value hp-status-unknown"><span class="hp-value">unknown</span></div></div>';
								}
                              },
                              sWidth: "2%", sClass: "hp-icon", mDataProp: 'status'},
							 // source
                            {fnRender: function (oObj) {
                                return linkTargetBuilder.makeLink(
                                    oObj.aData.Resource);
                            }, sWidth: "13%",mDataProp: 'Resource'}, 
                           // message
                            {fnRender: function (oObj) {								
                                if (oObj.aData.category === 'alert' || oObj.aData.category === 'task') {
                                    return oObj.aData.Message;
                                }
                            }, sWidth: "13%", mDataProp: 'Message'},
                           // State
                            {fnRender: function (oObj) {								
                                if (oObj.aData.category === 'alert') {
                                    return oObj.aData.state;
                                } else if (oObj.aData.category === 'task') {
                                    return oObj.aData.state;
							    } 
                            }, sWidth: "13%", mDataProp: 'state'},  
                            // progress
                            /*{fnRender: function (oObj) {
                                if (oObj.aData.category === 'task' &&
                                    'finished' !== oObj.aData.state) {
                                    var progress = oObj.aData.progress;
                                    if (! progress) {
                                        progress = 0;
                                    }
                                    return '<span data-percent="' + progress +
                                        '" class="hp-progress hp-condensed">' +
                                    '</span>' + progress + '%';
                                } else {
                                    return '';
                                }
                              },
                              sWidth: 90, mDataProp: 'progress'},*/
                            // date/time
                           {fnRender: function (oObj) {
                                // 2011-12-20T08:48:22.888Z
                                /*var date = Date.parseISOString(oObj.aData.LastUpdate);
                                var formattedDate;
                                if (date.isToday()) {
                                    formattedDate = localizer.getString('hpsum.task.today');
                                } else if (date.getFullYear() === (new Date()).getFullYear()) {
                                    formattedDate = $.format.date(date, 'MMM d');
                                } else {
                                    formattedDate = $.format.date(date, 'M/d/280\
                                    ');
                                }
                                return '<div class="hp-timestamp">' +
                                    formattedDate + ' ' + $.format.date(
                                        Date.parseISOString(oObj.aData.LastUpdate), 'h:mma') +
                                    '</div>';*/
                                   return oObj.aData.LastUpdate;
                              },
                              sWidth: "13%", mDataProp: 'LastUpdate'} 
                          ],
                         
                        aaSorting: [[ 4, "desc" ]],
                        fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                            $('td:eq(1) > div.hp-status', nRow).hpStatus();
                            if (aData.category === 'task' &&
                                'finished' !== aData.state) {
                                $('td:eq(3) span', nRow).hpProgressBar();
                            }
                            return nRow;
                        } 
                    
                });
            }
            
            var refreshClicked = function(event) {
				// Fix for QXCR1001392898
				// Clear task ids which are stored when task satus 4 (deploy in-progress), 5 (deploy done with success), 6 (deploy done with error)
				ACTIVITYIDS = {};
                populateActivity();
                event.preventDefault();
            };
           
            /**
             * @public
             */
            this.pause = function () {
                $(REFRESH).off('click' ,refreshClicked);
            };
            
            this.resume = function () {
                document.title = 'Activity';
                populateActivity();
                $(REFRESH).on('click' ,refreshClicked);
                presenter.resume(true);
            	$('#hpsum-activity-missingcomponents-confirm').hide();
            };
            
			/*
                This function parses task message data to form the link in the format
				Deploying in progress 2/10
					Deploying the package cpxxxx1.exe
					Deploying the package cpxxxx2.exe
            */
			function parseTaskStatus(taskMessage, status, taskid){
				// 2@10@N1localhost@|cp010920.exe,cp016819.exe|cp017871.exe
				var arrayList = taskMessage.split("|");
				var installMessage = "";
				
				if(arrayList.length > 1){
					var nodeid = "";
					var topLevelMsg = "";
					var installComponents = "";
					var componentList = arrayList[0];
					
					if(componentList.length > 2){
						var task = componentList.split("@");
						if (task.length > 2)
						{
							nodeid = task[2];
							if (status === 4)
								topLevelMsg = localizer.getString('hpsum.node.liveLogInprogress') + task[0] + "/" + task[1];
							else if (status === 5 || status === 6)
								topLevelMsg = localizer.getString('hpsum.node.liveLogCompleted') + " " + task[0] + "/" + task[1];

							installMessage = "<div id='hpsum-configuration-parent' data-parent-value='" + nodeid + "#" + taskid + "#" + status + "' class='hpsum-expandabale'><a>" + topLevelMsg + "</a><div class='hpsum-up-icon hpsum-icon'></div>";
							installMessage += "<div class='hpsum-livelog-window' data-task-message='" + taskMessage + "' style=''><br><dl id='complist'>";
						}
					}
					
					// parse installing component
					if(arrayList.length > 2){
						if( arrayList[2].length > 0){
							topLevelMsg = localizer.getString('hpsum.node.liveLogInstalling') +  arrayList[2];
							installComponents += getComponentLink(nodeid + "#" + arrayList[2] + "#" + taskid, topLevelMsg);
						}
					}
					
					// parse insalled components
					if (arrayList[1].length > 0){
						componentList = arrayList[1].split(",");
						if(componentList.length > 0){
							for(var i = 0; i < componentList.length; i ++){
								topLevelMsg = localizer.getString('hpsum.node.liveLogInstalled') +  componentList[i];
								installComponents += getComponentLink(nodeid + "#" + componentList[i] + "#" + taskid, topLevelMsg);
							}
						}
					}
					
					if (installMessage.length > 0){
						installMessage += installComponents;
						installMessage += "</dl></div></div>";
					}
				}
				return installMessage;
			};
			
			
			/*
				The function html content for the component in the install task
			*/
			function getComponentLink(divValue, link){
				return "<dd id='compid'><div id='hpsum-livelog-child' data-child-value='" +  divValue + "'><a id='complink'> " + link + "</a><div class='hpsum-up-icon hpsum-child-icon'></div><textarea id='hpsum-component-log' readonly='readonly' style='width:100%;height:100%;resize:both;min-height:150px;display:none;'></textarea></div></dd>";
			}
			
			function parseConfigStatus(taskMessage, status, taskid)
			{
				// cp010920.exe,cp016819.exe|cp017871.exe
				var arrayList = taskMessage.split("|");
				var installMessage = "";
				
				if(arrayList.length > 1){
					var nodeid = "";
					var topLevelMsg = "";
					var childLevelMsg = "";
					var installComponents = "";
					var componentList = arrayList[0];
					if (status === 7){
						topLevelMsg = "Export component configuration status";
						childLevelMsg = "Export successful list";
					}
					else if (status === 8)
					{
						topLevelMsg = "Import component configuration status";
						childLevelMsg = "Import successful list";
					}
					
					componentList = arrayList[0].split(",");
					if(componentList.length > 0){
					if (status === 7)
					{
						for(var i = 0; i < componentList.length; i ++)
						{
							var tmpList = componentList[i].split("@");
							installComponents += tmpList[0] + " exported successfully to " + tmpList[1] + "\n\n";
						}
					}
					else if (status === 8)
					{
						if (arrayList[0].length > 0)
						{
							installComponents = "Component configuration for " + arrayList[0] + " were imported successfully from " + arrayList[3];
						} else {
							installComponents = "None of components matched while attempting to import configuration from " + arrayList[3]; 
						}
					}						
					}
					if (installComponents.length > 0){
						installMessage = "<div id='hpsum-configuration-parent' data-parent-value='" + taskid + "#" + status + "' class='hpsum-expandabale'>" + topLevelMsg;
						installMessage += "<div id='hpsum-configuration-child1' data-child-value='" + arrayList[0] + "''><a>" + childLevelMsg + "</a><div class='hpsum-up-icon hpsum-icon'></div>";
						installMessage += "<textarea id='hpsum-component-list' readonly='readonly' style='width:100%;height:100%;resize:both;min-height:150px;display:none;'>" + installComponents +"</textarea>";
					}
					$('#hpsum-configuration-child1').die('click').live('click', function (event) {
						showHideComponentList(event, "#hpsum-component-list");
					});
					
					// parse installing component
					if(arrayList.length > 2){
						if( arrayList[1].length > 0){
							if (status === 7)
								childLevelMsg = "Export failure list";
							else if (status === 8)
								childLevelMsg = "Import failure list";
							installComponents = {};
							componentList = arrayList[1].split(",");
							if(componentList.length > 0){
								for(var i = 0; i < componentList.length; i ++){
									var tmpList = componentList[i].split("@");
									if(status === 7)
									{
										installComponents += tmpList[0] + " failed to export " + tmpList[1] + "\n";
									}
									else if(status === 8)
										installComponents += tmpList[0] + " failed to import " + tmpList[1] + "\n";
								}
							}
							if (installComponents.length > 0){
								installMessage += "<div class='hpsum-configuration-child2' data-child-value='" + arrayList[1] + "''><a>" + childLevelMsg + "</a><div class='hpsum-up-icon hpsum-icon'></div>";
								installMessage += "<textarea id='hpsum-component-list' readonly='readonly' style='width:100%;height:100%;resize:both;min-height:150px;display:none;'>" + installComponents +"</textarea>";
							}
							$('#hpsum-configuration-child2').die('click').live('click', function (event) {
								showHideComponentList(event, "#hpsum-component-list");
							});
						}
					}
					
					if(arrayList.length > 2){
						if( arrayList[2].length > 0){
								childLevelMsg = "Extra configurations list";
							installComponents = {};
							componentList = arrayList[2].split(",");
							if(componentList.length > 0){
								installComponents = "Additional configurations found for components not in this baseline: " + arrayList[2];
							}
							if (installComponents.length > 0){
								installMessage += "<div class='hpsum-configuration-child3' data-child-value='" + arrayList[2] + "''><a>" + childLevelMsg + "</a><div class='hpsum-up-icon hpsum-icon'></div>";
								installMessage += "<textarea id='hpsum-component-list' readonly='readonly' style='width:100%;height:100%;resize:both;min-height:150px;display:none;'>" + installComponents +"</textarea>";
							}
							$('#hpsum-configuration-child3').die('click').live('click', function (event) {
								showHideComponentList(event, "#hpsum-component-list");
							});
						}
					}
				}
				return installMessage;
			}
			/*
			This function show or hide the live log windows
			*/
			function showHideComponentList(event, logWindowId){
				var expanded =  false;
				// check if we have the display window already created
				var srcElement = getSrcElement(event);
				var parentdiv = $(srcElement).parent().get(0);
				var logwindow = $(logWindowId, parentdiv).get(0);
				if(logwindow &&  $(logwindow).is(":visible") )
				{
				   //Is visible let close it
				   if ( logWindowId == "#hpsum-component-list"){
						$('.hpsum-child-icon',parentdiv).removeClass("hpsum-down-icon");
						$('.hpsum-child-icon',parentdiv).addClass("hpsum-up-icon");
					}
					else {
						$('.hpsum-icon',parentdiv).removeClass("hpsum-down-icon");
						$('.hpsum-icon',parentdiv).addClass("hpsum-up-icon");
					}
					$(logwindow).slideUp();	
					$(logwindow).css("display","none");
				}
				else if(logwindow)
				{
					if ( logWindowId == "#hpsum-component-list"){
						$('.hpsum-child-icon',parentdiv).removeClass("hpsum-up-icon");
						$('.hpsum-child-icon',parentdiv).addClass("hpsum-down-icon");
					}
					else{
						$('.hpsum-icon',parentdiv).removeClass("hpsum-up-icon");
						$('.hpsum-icon',parentdiv).addClass("hpsum-down-icon");
					}
					$(logwindow).css("display","block");
					$(logwindow).slideDown();						
					expanded = true;
				}
				return expanded;
			}
			/*
				The function returns the source element based on browser type
			*/
			function getSrcElement(event)
			{
				var srcElement;
				//Check if firefox or (chrome and IE)
				if (event.srcElement) 
				{
					//Chrome and IE
					srcElement = event.srcElement;
				} 
				else 
				{
					//Firefox
					srcElement = event.target;
				}
				return srcElement;
			}
			function showAddWait(msg) {
					
					
					if (!addWaitDialog) {
						addWaitDialog = $(SPLASH_DIALOG);
						addWaitDialog.dialog({
							modal : true,
							dialogClass : 'hp-simple-dialog',
							position : "center",
							draggable : false,
							resizable : false,
							width : 260,
							height : 180
						});
					}
					if(msg == undefined)
						msg = localizer.getString('hpsum.common.activitywait');
					$('#hpsum-bs-wait-message', addWaitDialog).html(msg);
					$(SPLASH_SPINNER).show();
					msg='';
					addWaitDialog.dialog('open');
				}

				function closeAddWait() {
					$(SPLASH_SPINNER).hide();
					if (addWaitDialog) {
						addWaitDialog.dialog('close');
					}
				}
			
			function onGetTaskDataSuccess(data){
            	var activitytable = $(ACTIVITY_TABLE).dataTable();
            	
            	if(activitytable) {
            		activitytable.fnClearTable();
					var trs = data.members;
					for(var idx = 0; idx < trs.length; idx++){
						trs[idx].Message = trs[idx].Message.replace(/\n/g, "<br />");
					}
            		activitytable.fnAddData(trs);
            	}
            }
            
            function onGetTaskDataError(data) {
            	
            }
            
			function populateActivity() {
				
				var handlers = {
                        success: function (data) {
                            onGetTaskDataSuccess(data);
                        },
                        error: function (errorInfo) {
                            onGetTaskDataError(data);
                        }
                    };
				
				
           	 	presenter.getTaskData(handlers);
			}
				
            this.init = function() {   
            	
            	initFilters();
                initActions();
                initTable();
				
				if($('#tour-activities tbody tr:nth-child(1) td:nth-child(1)').html() == 'Loading activity ...')
				$('.missingComponent').live('click', function(event) {
				var msgToDisplay = $('.missingComponent').data("hpsum");
				showMissingComponentsDialog(msgToDisplay);
				});
				
                $('#tour-activity-clear').click(function () {
                    presenter.clearSelectedItems();
                });
                $('#tour-activity-delete').click(function () {
                    presenter.deleteSelectedItems();
                });
				
               $('#hpsum-livelog-parent').live('click', function (event) {
					var srcElement = getSrcElement(event);
					if(srcElement.id == 'complink')
						return;
					
                    var isexpanded = showHideLiveLog(event, ".hpsum-livelog-window");
					var temp = $(this).data('parent-value');
                    temp = temp.split("#");
					
					// During deploy install task expanded
					if(temp[2] == 4 && isexpanded){					
						var object = { hapi : { task_id : temp[1]} };
						
						NodePresenter.postLiveLogData(temp[0], object, {
						success: function(data){
							showInstallingComponent(data);
						},
						error: function(data){
							showInstallingError(data);
						}
						});
					}
					
					updateActivityList(temp[1],  $(this));
                });
				
               $('#hpsum-livelog-child').live('click', function (event) {
					var srcElement = getSrcElement(event);
					var isexpanded = showHideLiveLog(event, "#hpsum-component-log");
					
                    // get component id
                    var temp = $(this).data('child-value');
                    temp = temp.split("#");
                    
					var nodeid = temp[0];
		            var parentdiv = $(srcElement).parent().get(0);
					
					// get top parent for selected component
					var topDiv;
					var array = [];
					array = $(".hpsum-expandabale");					
					for( var i = 0; i < array.length; i++){
						var parentval = $(array[i]).data('parent-value');
						parentval = parentval.split("#");
						if (parentval[1] === temp[2]){
							topDiv = array[i];
							break;
						}
					}
					
					updateActivityList(temp[2], topDiv);;

					if(!isexpanded)
						return;
						
					var object = { hapi : { task_id : temp[2], component_name : temp[1] } };
										
					NodePresenter.postLiveLogData(nodeid, object, {
					success: function(data){
						showLog(data, parentdiv, temp[2], topDiv);
					},
					error: function(data){
						showError(data, parentdiv, temp[2], topDiv);
					}
					});
                });
				
                presenter.init();

                $('.hp-collapsible').hpCollapsible();
                this.resume();
            };
        }

        return new ActivityView();
    }());
    
    return ActivityView;
});
