define(['hpsum/presenter/baseline/BaselinePresenter',
		'hp/core/EventDispatcher',
		'hp/core/Localizer',
		'text!hpsumpages/baseline/retry_confirm.html',
		'hp/view/DialogView',
		'hp/core/Router',
		'lib/jquery.selectBox',
		'jquery', 
		'hp/lib/jquery.hpStatus',
		'lib/jquery.dataTables',
		'hp/lib/jquery.hpCollapsible',
		'hp/lib/jquery.hpToggle'], 
function(presenter,EventDispatcher, localizer,retryConfirmHtml,DialogView,router) {"use strict";
	(function($) {
		// Create the defaults once
  		var pluginName = "hpsumAddBaselineICMToken",
        defaults = {
            nodeItem: null
        };
		
		var HP_PASSPORT_TOKEN='#hpsum-baseline-ICM_hp-passport-token-input',
			HP_PASSPORT_TOKEN_WARNING='#hpsum-baseline-ICM_hpsum-baseline-token-warning',
			HP_PASSPORT_TOKEN_VALID='#hpsum-baseline-ICM_hpsum-baseline-token-valid',
			MISSINGCOMPONENT_TABLE='#hpsum-baseline-ICM_hpsum-missingcomponents-table',
			MISSINGCOMPONENTS='#hpsum-baseline-ICM_hpsum-retry-table',
			SELECT = '#hpsum-baseline-ICM_select-all-components',
            DESELECT = '#hpsum-baseline-ICM_deselect-all-components';
			
		var icmtoken;
		
		
		// The actual plugin constructor
		function Plugin( element, options ) {
			this.element = element;

			// jQuery has an extend method which merges the contents of two or
			// more objects, storing the result in the first object. The first object
			// is generally empty as we don't want to alter the default options for
			// future instances of the plugin
			this.options = $.extend( {}, defaults, options );
			this.dispatcher = new EventDispatcher();
			this._defaults = defaults;
			this._name = pluginName;

			this.init();
		}

		Plugin.prototype = {
			init: function() {
				$(this.element).addClass('hpsumAddBaselineICMToken');
				if(this.options.command =='init')
					this.calculate(this.element, this.options);
			},
			recalculate: function() {
				// if(this.options.nodeItem == undefined){
					// window.console.error("recalculate before init is not allowed");
					// return;
				// }
				this.calculate(this.element,this.options);
			},
			calculate: function(el, options) {
				var plugin =this;
			},
			onPopulateError : function(el){
				el.text("GetUpdatelist failed for this node");
			},
			destroy: function(el){
					$(this.element).removeClass('hpsumAddBaselineICMToken');
					$.removeData(this.element, "plugin_" + pluginName);
			},
			
			/*
			* Method to render the credential details
			*/
			addICMToken : function(data)
			{
				presenter.getAttributes({success:function(data){
									if(data.hapi.icm_token_id!="no_token_id")
									{
										$(HP_PASSPORT_TOKEN).val(data.hapi.icm_token_id);
										icmtoken=data.hapi.icm_token_id;
									}
								},
								error:function()
								{alert("error")}});
									
				var idPrepender = '';
				if(this.element.id != "" && this.element.id != null)
					idPrepender = this.element.id + "_";
					$(this.element).html(
					'<label id="ICM-label">'+localizer.getString('hpsum.baseline.add.HPPassportIntellectualCapitalManagementSingleSignIn')+'</label>'+
					
                        '<fieldset>'+
                          
                            '<ol>'+
							 
                                '<li class="hp-form-item">'+
									'<label id="ICM-Validate" style="text-align:left;"><b> '+localizer.getString('hpsum.baseline.add.HPPassportTokenValidation') +'</b></label><p></p>'+
									'<label class="hp-stacked-panel">'+localizer.getString('hpsum.baseline.add.HPPassportTokenValidationStr1') + '<a href = "http://www.hp.com/go/hpsc-entitlement-token" target="_blank">' + localizer.getString('hpsum.baseline.add.HPPassportICMTokenURL') +' </a>' + localizer.getString('hpsum.baseline.add.HPPassportTokenValidationStr2') +'</label>' + '<br><br>'+
                                    '<label id=">'+idPrepender+'hp-passport-entitlement-token" style="text-align:left;width:50%;"><b><div>'+localizer.getString('hpsum.baseline.add.HPEntitlementPassportToken')+'</div></b></label>'+
                                    '<input id="'+idPrepender+'hp-passport-token-input" size="40"/>'+ 
									'<br><br>'+
									'<label class="hp-available">' +
									 localizer.getString('hpsum.baseline.add.HPPassportTokenValidationStr3') +'<br><br>'+ 
									 '<a href = "http://www.hp.com/go/hpsc-entitlement-token" target="_blank"> - '+ localizer.getString('hpsum.baseline.add.HPPassportICMTokenLoginURL') +'</a>'+'<br><br>'+ 
									 '<a href = "http://h20564.www2.hpe.com/portal/site/hpsc/template.PAGE/public/kb/docDisplay/?docId=c04055475" target="_blank"> - '+ localizer.getString('hpsum.baseline.add.HPPassportICMTokenSupportCenterHelpURL') + '</a>'+ '<br><br>'+ 
									 '<a href = "http://h20565.www2.hpe.com/portal/site/hpsc/template.PAGE/public/kb/docDisplay/?docId=emr_na-c04044353" target="_blank"> - ' + localizer.getString('hpsum.baseline.add.HPPassportICMTokenFirmwareAccessHelpURL') + ' </a></label>'+
									
                                 '</li>'+
                            '</ol>'+
                        '</fieldset>'+
						'<div id="'+idPrepender+'hpsum-baseline-token-warning" class="hp-stacked-panel" style="display :none;padding-left:30px;padding-right:30px;">'+
							'<div style="background-color:lightyellow">'+
								'<img src="/img/hp-piano/status-warning.png">&nbsp;&nbsp;'+
								'<label class="hp-available">'+localizer.getString('hpsum.baseline.add.HPPassportTokenWarning')+'</label>'+
							'</div>'+
						'</div>'+
						'<div id="'+idPrepender+'hpsum-baseline-token-valid" class="hp-stacked-panel" style="display :none;padding-left:30px;padding-right:30px;">'+
							'<div style="background-color:lightyellow">'+
								'<label class="hp-available">'+localizer.getString('hpsum.baseline.add.HPPassportTokenValid')+'</label>'+
							'</div>'+
						'</div>'
					);		
			},
			/*
			* Method to hide ICM token validation message.
			*/
			
			hideValidationMessage	: function()
			{
				$(HP_PASSPORT_TOKEN_VALID).hide();
			},
			/*
			* Method to add the missing component table.
			*/
			
			addMissingDataTable	: function(data)
			{
				var idPrepender = this.element.id + "_";
				$(this.element).append( 
					'<li id="'+idPrepender+'hpsum-node-retry-baselines" class="hp-stacked-panel">'+
						'<div>'+
							'<fieldset>'+
								'<ol>'+
									'<div class="hp-collapsible" id="'+idPrepender+'hpsum-baseline-collapsible">'+
										'<label>'+localizer.getString('hpsum.baseline.show.missingcomponents')+'</label>'+	
										'<div>'+
											'<fieldset>'+
												'<ol>'+
													'<p>'+
														'<input id="'+idPrepender+'select-all-components" class="hp-button hp-primary" type="button" value="'+localizer.getString('hpsum.group.selectAll')+'"/>'+'&nbsp&nbsp'+
														'<input id="'+idPrepender+'deselect-all-components" class="hp-button hp-primary" type="button" value="'+localizer.getString('hpsum.group.deselectAll')+'"/>'+
													'</p>'+
													'<li class="hp-form-item">'+
														'<div id="'+idPrepender+'hpsum-retry-table">'+
														'</div>'+																									
													'</li>'+
												'</ol>'+
											'</fieldset>'+
										'</div>'+
									'</div>'+
								'</ol>'+
							'</fieldset>'+
						'</div>'+
					'</li>'
				);	
				this.populatemissingcomponent(data,MISSINGCOMPONENTS,idPrepender);
				
			},
			
			/*
			* Method to check if ICM token is changed.
			*/
			
			isTokenChanged	: function()
			{
				if(icmtoken!=$(HP_PASSPORT_TOKEN).val())
					return true;
				else
					return false;
			},
			
			/*
			* Method to check if ICM token is valid. 
			*/
			isTokenValid :function(item)
			{
				if(!item)
				{
					$(HP_PASSPORT_TOKEN_WARNING).show();
				}
				else
				{
					$(HP_PASSPORT_TOKEN_VALID).show();
				}
				
			},
			
			/*
			* Method to create and populate MissingComponentTable. 
			*/
			populatemissingcomponent : function(data,id,idPrepender){
			$(id).append('<table class="hp-selectable" id="'+idPrepender+'hpsum-missingcomponents-table"><thead><tr><td><b>'+
								localizer.getString("hpsum.oneTouchUpdate.selectComponents") + '</b></td><td><b>' + 
								localizer.getString("hpsum.baseline.show.component") + '</b></td><td><b>' + 
								localizer.getString("hpsum.baseline.show.name") + '</b></td><td><b>' +
								localizer.getString("hpsum.baseline.show.type") + '</b></td><td><b>' +
								localizer.getString("hpsum.baseline.show.criticality") + '</b></td><td><b>' + 
								localizer.getString("hpsum.baseline.version") + '</b></td><td><b>' + 
								localizer.getString("hpsum.common.rebootRequired") + '</b></td>'+
								'<td></td><td></td><td></td><td></td></tr></thead></table>');
			this.initMissingComponentTable(MISSINGCOMPONENT_TABLE,data);
			
			},
			initMissingComponentTable : function(tableid,data) {
			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 : 'select'},
						{mDataProp: 'component'},
						/*fnRender: function (oObj) {
								return oObj.aData.component_file_name;
						}},*/
				        {mDataProp: 'package_name'},
				        {mDataProp: 'product_typeInString'},
				        {mDataProp: 'criticality'},
				        {mDataProp: 'component_version'},
						{mDataProp: 'reboot_required'},
						],
				    	aaSorting: [[ 0, "asc" ]],
				    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
				        return nRow;
				    }
				    });
					
					var toggleId = 0;
					var oTab = $(MISSINGCOMPONENT_TABLE).dataTable();
						for(var i=0;i<data.length;i++)
						{
							var item = [{
							select: '<input id="toggle-' + toggleId + '" class="hp-toggle" type="checkbox" checked/>',
							component:data[i].component_file_name,
							package_name : data[i].package_name,
							product_typeInString : data[i].product_typeInString,
							criticality: data[i].criticality,
							component_version: data[i].component_version,
						    reboot_required : data[i].reboot_required            				
							}];
							oTab.fnAddData(item);
            			$('#toggle-' + toggleId).hpToggle({
									unchecked : localizer.getString("hpsum.oneTouchUpdate.select"),
									checked : localizer.getString("hpsum.oneTouchUpdate.selected")
								});
						toggleId++;
						
						}
						$(MISSINGCOMPONENT_TABLE + " tbody tr").addClass('hp-selected');
						$(SELECT).attr('disabled', true);
						$(DESELECT).attr('disabled', false);
						$(MISSINGCOMPONENT_TABLE + " tbody tr").click( function( e ) {
							var data = oTab.fnGetData( this );
							var selectid = data.select.split('"'); 
							selectid ='#'+ selectid[1];
							if($(this).hasClass('hp-selected'))
							{
									$(this).removeClass('hp-selected');
									$(SELECT).attr('disabled', false);
									$(selectid).removeAttr('checked'); 
									$(selectid).trigger('change');
							}
							else
							{
									$(this).addClass('hp-selected');
									$(DESELECT).attr('disabled', false); 
									$(selectid).prop('checked', true); 
									$(selectid).trigger('change'); 
							}
							var selectedRows = $(MISSINGCOMPONENT_TABLE + ' tbody tr.hp-selected');
							if(selectedRows.length>0)
							{
								$(DESELECT).attr('disabled', false);
								$('#hpsum-baselines-retry').attr('disabled', false);
							}
							else
							{
								$(DESELECT).attr('disabled', true);
								$(SELECT).attr('disabled', false);
								$('#hpsum-baselines-retry').attr('disabled', true);
							}
							var deselectedRows = $(MISSINGCOMPONENT_TABLE + ' tbody tr:not(.hp-selected)');
							if(deselectedRows.length>0)
								$(SELECT).attr('disabled', false);
							else
							{
								$(SELECT).attr('disabled', true);
								$(DESELECT).attr('disabled', false);
							}
					    });

		},
		
		getSelectedComponents : function (baseline){
			var selectedRows = $(MISSINGCOMPONENT_TABLE + ' tbody tr.hp-selected');
			var components=[];
			var retryall;
			var oTab = $(MISSINGCOMPONENT_TABLE).dataTable();
			for(var tmp=0; tmp < selectedRows.length; tmp++){
				var compData = oTab.fnGetData(selectedRows[tmp].rowIndex-1);
				var comp={component : compData.component};
				components.push(comp);
			}
			var deselectedRows=$(MISSINGCOMPONENT_TABLE + ' tbody tr:not(.hp-selected)');
			if(selectedRows.length >1 && deselectedRows.length==0)
				retryall=true;	
			else
				retryall=false;
			
			var input = {
            		hapi: {
						validate_token_id : true,
            			icm_token_id : $(HP_PASSPORT_TOKEN).val(),
            			comp_list : components,
						retryall: retryall,
						force_retry:false
            		}            		
            	};
			
			var handlers={success:function(data){
									if(data.hapi.hcode==3022)
									{
										var contents = $(retryConfirmHtml);
										$('#hpsum-retry-download',contents).html(
										'<label id="ICM-Validate" style="text-align:left;">'+localizer.getString('hpsum.baseline.add.HPPassportTokenValidation') +'</label>' + '<br></br>' +
										'<label >'+ localizer.getString('hpsum.baseline.show.ICMtokenInvalid') + '</label>'+'<br></br>' +
										'<label>' + '<a href = "http://www.hp.com/go/hpsc-entitlement-token" target="_blank"> - ' + localizer.getString('hpsum.baseline.add.HPPassportICMTokenLoginURL') +'</a>'+'<br><br>'+ 
										'<a href = "http://h20564.www2.hpe.com/portal/site/hpsc/template.PAGE/public/kb/docDisplay/?docId=c04055475" target="_blank"> - '+ localizer.getString('hpsum.baseline.add.HPPassportICMTokenSupportCenterHelpURL') + '</a>'+ '<br><br>'+ 
										'<a href = "http://h20565.www2.hpe.com/portal/site/hpsc/template.PAGE/public/kb/docDisplay/?docId=emr_na-c04044353" target="_blank"> - '+ localizer.getString('hpsum.baseline.add.HPPassportICMTokenFirmwareAccessHelpURL') + '</a></label>' 
										);
										
										$('#hpsum-retry-ok',contents).html(localizer.getString('hpsum.common.button.yes'));
										$('#hpsum-retry-cancel',contents).html(localizer.getString('hpsum.common.button.no'));
										var dialogView = new DialogView();
										dialogView.init({contents: contents,
											ok: function () {
											var input = {
											hapi: {
												validate_token_id : true,
												icm_token_id : $(HP_PASSPORT_TOKEN).val(),
												comp_list : components,
												retryall: retryall,
												force_retry:true
												}            		
											};
											presenter.retryPFW(input, baseline,handlers);
										},
										cancel: function () {}
										});
									}
									else if(data.hapi.hcode==0)
									{
										router.go('/baseline/show');
									}
								},
								error:function(){}
							};
			presenter.retryPFW(input, baseline,handlers);		
		}
		
		};
		
	// A really lightweight plugin wrapper around the constructor,
		// preventing against multiple instantiations
		$.fn[pluginName] = function ( options ) {
			var instance;
			if ( typeof options === 'string')
			{
				if(options.match(/init/i) ) { 
					return this.each(function () {
						if (!$.data(this, "plugin_" + pluginName)) {
							$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
						}
					});
				}
			}
			var argument,args;
			if (typeof options === 'string'){
				argument = options;
				args = Array.prototype.slice.call( arguments, 1 );
			}
			else{
				argument = options.command;
				args = options.args;
			}
			// call method
			//var args = Array.prototype.slice.call( arguments, 1 );
			this.each(function() {
				instance = $.data( this, "plugin_" + pluginName );
				if ( !instance ) {
					if (window.console) {
						window.console.error( "cannot call methods on hpsumAddNodeDetails prior to initialization; " +
							"attempted to call method '" + argument + "'" );
					}
					return;
				}
				if ( !$.isFunction( instance[argument] ) || argument.charAt(0) === "_" ) {
					if (window.console) {
						window.console.error( "no such method '" + argument + "' for hpsumAddNodeDetails instance" );
					}
					return;
				}
				// apply method
				instance[ argument ].call( instance, args );
			});  
		};
	}(jQuery));
});
	

