// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (BaselineAddView)
 * This is a view class for Baseline Add menu option.
 */
define(['hpsum/presenter/baseline/BaselinePresenter',
    'hp/core/Notifications',
    'hp/view/DialogView',
    'hp/view/FormStateView',
    'hp/model/Session',
    'hp/core/Localizer',
    'hp/core/Router',
    'text!hpsumpages/baseline/retry_confirm.html',
    'text!hpPages/core/header_help.html',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'lib/jquery.selectBox',
    'lib/jquery.dataTables',
    'lib/jquery-ui-timepicker-addon',
    'lib/jquery.dateFormat',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpToggle',
    'lib/jquery.cookie',
	'hpsum/view/baseline/jquery.hpsumAddBaselineICMToken',
	'hpsum/common/jquery.hpsumBrowse'
    ],
function(presenter, notifications, DialogView, FormStateView, session, localizer, router, retryConfirmHtml, headerHelpHtml) { "use strict";

    var BaselineAddView = (function() {
      
        var ADD = '#hpsum-baselines-add',
            CANCEL = '#hpsum-baselines-add-close',
            RESET = "#hpsum-baselines-reset",
            NAME = '#hpsum-baselines-name',
	    PATH_DETAILS = '#hpsum-path-details',
            PATH = '#hpsum-location-path',
            LOCATION_TYPE = '#hpsum-baseline-location-type',
            URI_PATH = '#hpsum-baseline-uri-path',
            USERNAME = '#hpsum-baseline-credential-username',
            PASSWORD = '#hpsum-baseline-credential-password',
	    BROWSE_LOCATION_ERROR = '#hpsum-invalid-location-error',
            
			BROWSE_TEXT = '#hpsum-baseline-add-browse-text',
			INPUT_BROWSE_TEXT = '#hpsum-baseline-add-browse-hpsumBrowse-input-text',
			INPUT_BROWSE_BUTTON= '#hpsum-baseline-add-browse-hpsumBrowse-browse-button',
            WEB_BUNDLES_LIST = '#hpsum-pfw-bundles',
            WEB_BUNDLES_PANEL ='#hpsum-baseline-bundles-list',
            RETRIEVELIST_BUTTON = '#hpsum-baselines-getList',
            
            INFO_DIALOG = '#hpsum-info-dialog',
            ROUTE_PREFIX = '/baseline/add',
            PANEL_SELECTOR = "#hpsum-baseline-add-panel-selector",
            PANELS = '#hpsum-baseline-add-panels',
            URI_DETAILS = '#hpsum-uri-details',
			BASELINE_CREDS = '#hpsum-baseline-add-credentials',
			ENTER_CRED = '#hpsum-baseline-cred-details',
            BASELINE_LABEL = '#hpsum-baseline-location-lable-path',
            PROXY_SETTINGS = '#hpsum-baseline-proxy-settings',
	    SCHEDULE_DETAILS = '#hpsum-baseline-schedule-information',
	    FORM = '#hpsum-baselines-add-form',
	    
            SPLASH_DIALOG = '#hpsum-add-wait-dialog',
			SPLASH_SPINNER = '#hpsum-add-spinner',
			HTTP_SETTINGS = '#hpsum-baseline-http-settings',
			HTTP_URL = '#hpsum-http-url',
			HTTP_ERROR = '#hpsum-invalid-httpurl-error',
            USERNAME_ERR ='#hpsum-baseline-username-err',
			PASSWORD_ERR ='#hpsum-baseline-password-err',
			HP_PASSPORT_ICM='#hpsum-baseline-ICM',
			HP_PASSPORT_TOKEN='#hpsum-baseline-ICM_hp-passport-token-input',
			COLLAPSE_OSFILTER = '#hpsum-os-filter-options',
			WINDOWS_CHKBOX = '#chkbox-os-windows',
			LINUX_CHKBOX = '#chkbox-os-linux',
			HPUX_CHKBOX = '#chkbox-os-hpux',
			VMWARE_CHKBOX = '#chkbox-os-vmware',
			ADD_BROWSE_PANEL = "#hpsum-baseline-add-browse",
			BASELINE_INV_ERR_INPROGRESS = "#hpsum-baseline-inventory-error-inprogress",
			BASELINE_ADD_LOC = "#hpsum-baseline-add-location";
			
        /**
         * Constructor
         */
        function BaselineAddView() {
          
            var addInProgress = false;
            var browseDialogContents;
            var infoDialog;
            var proxyOptionValue;
            var locationType = 'local';
            var addWaitDialog;
	    	var iserror = false;
	    	var FOLDER_NOT_EMPTY_ERROR = 3017;
	    	var INCORRECT_PARAM = 5;
			var ADD_BASELINE_ERROR = 3001;
	    	var instAddLocBrowse;
	    	var formStateView = new FormStateView();
           	function onPathEdit() {
				$(BROWSE_LOCATION_ERROR).hide();
				
				instAddLocBrowse.removeInputClass("hp-error");
                instAddLocBrowse.setInputEvent('offkeyup', onPathEdit);
			}

			function handleInvalidPath(hapi) {
				if (hapi.hcode == 5) {
					$(BROWSE_LOCATION_ERROR).text(localizer.getString('hpsum.baseline.add.inValidLocation'));
					$(BROWSE_LOCATION_ERROR).show();
					
					instAddLocBrowse.addInputClass("hp-error");
                	instAddLocBrowse.setInputEvent('onkeyup', onPathEdit);
				    $(ADD).attr("disabled", true);
				    $(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
				    $(INPUT_BROWSE_BUTTON).attr("disabled", false);
				} else {
				    $(BROWSE_LOCATION_ERROR).hide();
				    instAddLocBrowse.removeInputClass("hp-error");
                	instAddLocBrowse.setInputEvent('offkeyup', onPathEdit);
				}
			}

            function reset() {
                $(NAME).val("");
				$('#hpsum-FTP-info-msg').hide();
				$(BASELINE_ADD_LOC).show();
                $(LOCATION_TYPE).selectBox('value','local');
                instAddLocBrowse.setLocationType('local');
                instAddLocBrowse.setBrowseOptions({bshowXml: false, bshowFile: false, bShowHPSUMFiles: false, bShowEmptyFolder: false, bCreateDirectory: false});
		        $('#hpsum-invalid-location-error-nonempty').html(" ");
                $(NAME).focus();
                
                instAddLocBrowse.setPanelText("");
                $(HTTP_URL).val("");
                $(HTTP_ERROR).hide();
                $(HTTP_URL).removeClass("hp-error");
                var firstOption = $('#hpsum-baseline-location-type option:first');
				firstOption.attr('selected', true);
				$(PATH_DETAILS).show();
                $(URI_DETAILS).hide();
				$(BASELINE_CREDS).hide();
				$('#hpsum-baseline-uri-path').val("");
				$('#hpsum-baseline-credential-username').val("");
				$('#hpsum-baseline-credential-password').val("");
				$('#hpsum-baseline-username-err').hide();
				$('#hpsum-baseline-password-err').hide();
                $(PROXY_SETTINGS).hide();
				$(HP_PASSPORT_ICM).hide();
                $(RETRIEVELIST_BUTTON).css( "display", "none" );
				$(HTTP_SETTINGS).hide();
				$(BROWSE_LOCATION_ERROR).hide();
                addInProgress = false;
                $(ADD).attr("disabled", true);
                $(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
				$(INPUT_BROWSE_TEXT).removeClass('hp-tooltipped').removeAttr('tooltip data-tooltip');
                $(INPUT_BROWSE_BUTTON).attr("disabled", false);
                $('#hpsum-baseline-proxy-hp').val("");
                $('#hpsum-baseline-proxy-url').val("");
                $('#hpsum-baseline-proxy-port').val("");
                $('#hpsum-baseline-proxy-username').val("");
                $('#hpsum-baseline-proxy-password').val("");
                $('#hpsum-baseline-proxy-username').val("");
                $('#hpsum-baseline-proxy-password').val("");
				$('#hpsum-baseline-proxy-script').val("");
				$('#hpsum-baseline-proxyscript-username').val("");
				$('#hpsum-baseline-proxyscript-password').val("");				
		onProxyOptionsChange("No");
		$('#hpsum-proxy-options').selectBox('value', 'No');
                 $(WEB_BUNDLES_PANEL).hide();
                 $(".hpsum-proxy").attr("disabled", false);
		 $('#hpsum-proxy-options').selectBox('enable');

            	formStateView.reset();
				$(USERNAME_ERR).hide();
				$(PASSWORD_ERR).hide();
				credentialsOptions('one');
				$(WINDOWS_CHKBOX).attr('checked',false);
				$(LINUX_CHKBOX).attr('checked',false); 
				$(HPUX_CHKBOX).attr('checked',false); 
				$(VMWARE_CHKBOX).attr('checked',false);
				$(BASELINE_INV_ERR_INPROGRESS).html("");
            }
            
            function resetCancel() {
                reset();
            }
            
         
			function onItemAddSuccess(item) {
					resetCancel();
					addInProgress = false;
					closeAddWait();
					$(CANCEL).trigger('click');					
			}

            /**
             * @private
             */
            function onItemAddError(errorItem) {
				var errorMessage = errorItem;
				if(errorItem.hcode) {
					errorMessage = errorItem.hmessage;
					if(errorItem.hcode == FOLDER_NOT_EMPTY_ERROR || (errorItem.hcode == INCORRECT_PARAM)
						|| (errorItem.hcode === ADD_BASELINE_ERROR))
					{
						$(BASELINE_INV_ERR_INPROGRESS).html(errorMessage);
					}
						closeAddWait();
						iserror=true;
						$(WEB_BUNDLES_PANEL).hide();
						addInProgress = false;
						$(ADD).attr("disabled",true);
						$(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
						$(INPUT_BROWSE_BUTTON).attr("disabled", false);
						return;
				}
				else if(errorMessage.indexOf("#") != -1) {
					var error = errorMessage.split("#");
					var notif = {
						summary:error[0],
						sourceName: error[1],
						status: 'error'
						};
					notifications.add(notif, true);
				} else
					notifications.show(errorMessage, 'error');
                addInProgress = false;
                resetCancel();
                closeAddWait();
                $(CANCEL).trigger('click');
            }


				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.baseline.add.addInProgress');
					$('#hpsum-bs-wait-message', addWaitDialog).html(msg);
					$(SPLASH_SPINNER).show();
					msg='';
					addWaitDialog.dialog('open');
				}

				function closeAddWait() {
					$(SPLASH_SPINNER).hide();
					if (addWaitDialog) {
						addWaitDialog.dialog('close');
					}
				}
			

				
            /**
             * @private
             * Call presenter's addItem() to add a new baseline item into Indexservice
             */
            function onAddItem() {
            	$(ADD).attr("disabled", true);
				$(BASELINE_INV_ERR_INPROGRESS).html("");
            	showAddWait();
            	var uriPath;
				var filter_os = "";
				var isPFWwithICM = true;
            	
                if(! addInProgress) {
                    addInProgress = true;
                    if($(LOCATION_TYPE).val() == 'FTP'){
                    	var icm_token ="no_token_id";
                       var selectedRow = $('#hpsum-pfw-bundles-table tbody tr.hp-selected');
            			var data = $('#hpsum-pfw-bundles-table').dataTable().fnGetData(selectedRow[0]._DT_RowIndex);
						var index = data.url.search(/ftp:\/\//i);
						var length = data.url.length;
						var inst = $('#hpsum-baseline-ICM').data('plugin_hpsumAddBaselineICMToken');
						var tokenChanged = inst.isTokenChanged();
						if(index != -1)
							uriPath = data.url.substr(index+6, length );
						else
							uriPath = data.url;

						if($(HP_PASSPORT_TOKEN).val())
							icm_token=$(HP_PASSPORT_TOKEN).val();
						if(tokenChanged)
						{
							isPFWwithICM = false;
							doICM_setAttribute(icm_token,uriPath);
						}

            			}
            		else if($(LOCATION_TYPE).val() == 'HTTP'){
                        if(instAddLocBrowse.getLocation() == "") {
                            $(BROWSE_LOCATION_ERROR).show();
                            $(BROWSE_LOCATION_ERROR).text(localizer.getString('hpsum.baseline.add.inValidLocation'));
                            $(ADD).attr("disabled",true);
                            $(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
                            $(INPUT_BROWSE_BUTTON).attr("disabled", false);
                            return;
                        }
						
						if ($(WINDOWS_CHKBOX).is(':checked'))
							filter_os = "Windows,";
							
						if ($(LINUX_CHKBOX).is(':checked'))
							filter_os += "Linux,";
							
						if ($(HPUX_CHKBOX).is(':checked'))
							filter_os += "Hpux,";
							
						if ($(VMWARE_CHKBOX).is(':checked'))
							filter_os += "VMware";
							
                        var HTTP_URL_STRING = $(HTTP_URL).val();
                        var TOKEN_ARRAY = HTTP_URL_STRING.split('/');
                        var lastToken = TOKEN_ARRAY.pop();  // .pop() removes and returns the last item of the array
 
            			if((($(HTTP_URL).val().indexOf(localizer.getString('hpsum.baseline.add.httpPrefix')) === 0) || ($(HTTP_URL).val().indexOf(localizer.getString('hpsum.baseline.add.httpsPrefix')) === 0)))
            				uriPath = $(HTTP_URL).val();
            			else
            			{
            				closeAddWait();
            				$(HTTP_ERROR).show();
            				$(HTTP_URL).focus();
            				$(HTTP_URL).addClass("hp-error");
            				$(ADD).attr("disabled",true);
            				$(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
            				$(INPUT_BROWSE_BUTTON).attr("disabled", false);
            				addInProgress = false;
            				return;
            			}
            		}
					else if($(LOCATION_TYPE).val() == 'UNC')
					{
						var usecurrcreds = false;
						if($('input[name="hpsum-baseline-credential"]:checked').val() == 'one')
						{
							usecurrcreds = true;
						}
						else 
						{
							if(!validate_credentials()) {
								closeAddWait();
								addInProgress = false;
								return;
							}
						}
						uriPath = $(URI_PATH).val();
					}
            		else{
            			uriPath = $(URI_PATH).val();
            		}        
            		if(isPFWwithICM){
            		    call_addcmd(uriPath,usecurrcreds,filter_os);
            		}
	                else{
	                	addInProgress = false;
	                	closeAddWait();
	                }
                    //$(CANCEL).trigger('click');
                }

                //return false;
            }
			
			function validate_credentials() {
				var success;
				if($(USERNAME).val() == ''){
					$(USERNAME).addClass("hp-error");
					$(USERNAME_ERR).show();
					$(USERNAME).bind('keyup', function(){
						$(USERNAME_ERR).hide();
						$(USERNAME).removeClass('hp-error');
						});
						success = false;
				}
				if($(PASSWORD).val() == ''){
					$(PASSWORD).addClass("hp-error");
					$(PASSWORD_ERR).show();
					$(PASSWORD).bind('keyup', function(){
						$(PASSWORD_ERR).hide();
						$(PASSWORD).removeClass('hp-error');
					});
					success = false;
				}
				if( success == false)
					return false;
				else
					return true;
			}

			function call_addcmd(uri_path,use_curr_creds,filter_os) {
				presenter.addItem({
                	category: 'baseline',
                	name: 'Service Pack for Proliant ' + (new Date()).getTime(), //adds a dummy baseline name for now
                    locationType: $(LOCATION_TYPE).val(),
					location: instAddLocBrowse.getLocation(), //$(PATH).val(),
                    uripath: uri_path,
                    username : $(USERNAME).val(),
                    password : $(PASSWORD).val(),
                    proxy_settings: getProxyJsonObject(),
                    uri: '/baseline/item-' + (new Date()).getTime(), 
                    status: 'ok',
					usecurrcreds : use_curr_creds,
					filter_os : filter_os,
                    attributes: {version:'2012.10.31', size:'1.5 GB'}}, {
                    success : onItemAddSuccess,
                    error : onItemAddError
                });
			}

			function doICM_setAttribute(icm_token_id, uri_Path) {
				var input = {
								hapi: {
									icm_token_id : icm_token_id
									}            		
								};
				presenter.setAttributes(input,{success:function(data){
									var options = {
										command : 'isTokenValid',
										args : data.hapi.validated_icm_token_id
									};
									$("#hpsum-baseline-ICM").hpsumAddBaselineICMToken(options);
									var inst = $('#hpsum-baseline-ICM').data('plugin_hpsumAddBaselineICMToken');
									inst.hideValidationMessage();
									if (options.args == false)
									{
										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://www.hp.com/go/hpsc-entitlement-token-help" target="_blank"> - '+ localizer.getString('hpsum.baseline.add.HPPassportICMTokenSupportCenterHelpURL') + '</a>'+ '<br><br>'+ 
										'<a href = "http://h20565.www2.hp.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 () {											
											showAddWait();
											addInProgress = true;
											call_addcmd(uri_Path,"","");
										},
										cancel: function () {
											$(ADD).attr("disabled", false);
										}
										});
									}
									else
									{
										addInProgress = true;
										showAddWait();
										call_addcmd(uri_Path,"","");
									}
								},
								error:function()
								{}});
			}
            /**
             * * Show information dialog to user such as selecting a valid baseline before proceed.
             */
            function showInfoDialog()
            {
            	if (!infoDialog) {
                    infoDialog =  $(INFO_DIALOG);
                    infoDialog.dialog({
                        modal : true,
                        dialogClass: 'hp-simple-dialog',
                        position : "center",
                        draggable : false,
                        resizable : false
                    });
                    $('button', infoDialog).on('click', function () {
                        infoDialog.dialog('close');
                    });
                }
                infoDialog.dialog('open');
            }
            
            
       
            function onProxyOptionsChange(msg) 
            {
            	 var value = $('#hpsum-proxy-options').val();
		 $(WEB_BUNDLES_LIST).html('');
		 $(WEB_BUNDLES_PANEL).hide();
		 formStateView.reset();
            	 if(value == "No" || msg == "No"){
            	 	 $('#hpsum-proxy-usehp-item').hide();
               		 $('#hpsum-proxy-usescript-item').hide();
               		 proxyOptionValue = "No";
            	 }
            	 else if(value == "Server"){
            	 	 $('#hpsum-proxy-usehp-item').show();
                	 $('#hpsum-proxy-usescript-item').hide();
                	 proxyOptionValue = "Server";
					 
					 // reset the proxy server values
					 $('#hpsum-baseline-proxy-url').val("");
					 $('#hpsum-baseline-proxy-port').val("");
					 $('#hpsum-baseline-proxy-username').val("");
					 $('#hpsum-baseline-proxy-password').val("");						 
            	 }
            	 else if (value == "Script"){
            	 	$('#hpsum-proxy-usehp-item').hide();
                	$('#hpsum-proxy-usescript-item').show();
                	proxyOptionValue = "Script";
					
					// reset the proxy script values
					$('#hpsum-baseline-proxy-script').val("");
					$('#hpsum-baseline-proxyscript-username').val("");
					$('#hpsum-baseline-proxyscript-password').val("");					
            	 }
            }
            
            function changeLocation(location) {
                	
              if (location.length > ROUTE_PREFIX.length) {
                   $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
               	} else {
                   $(PANELS).hpStackedPanels('setFirstPanel');
                }
            }
            
           	function initBundlesTable(tableid){
				return $(tableid).dataTable({
				  		oLanguage: {
				  		    sEmptyTable: localizer.getString('hpsum.node.noItemsFound'),
				  		    sSearch: localizer.getString('hpsum.common.search')
							   },
				    bPaginate : false,
				    bProcessing : true,
				    bFilter : false,
				    bSort : false,
				    bAutoWidth : false,
				    bInfo : false,
				    bRetrieve : false,
				    bDestroy : true,
				    	aoColumns : [
				        	{mDataProp: 'name'},
				        	{mDataProp: 'version'},
				        	{mDataProp : 'url',
							"bVisible" : false
							}
				        ],
				    aaSorting: [[ 0, "asc" ]],
				    });
			}
			
            
            function showBundlesTable(data){
            	var berror = false;

            	closeAddWait();
            	$(WEB_BUNDLES_LIST).empty();
            	formStateView.reset();
            	if(typeof data === 'string')
            	{
            		$(WEB_BUNDLES_PANEL).hide();
			berror = true;
            		$(ADD).attr("disabled", true);
            		$(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
            		$(INPUT_BROWSE_BUTTON).attr("disabled", false);
            	}
            	if(berror)
				{
								
					formStateView.setMessage({
				summary: localizer.getString('hpsum.baseline.add.invalidDirectoryPath'),
                                status: 'error',
                                changing: false,
                                details: data});
                                
					return;
            	}
            	if(data.length < 1){
            		$(WEB_BUNDLES_LIST).append('No bundles available');
            		$(ADD).attr("disabled", true);
            		$(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style','width:450px;');
            		$(INPUT_BROWSE_BUTTON).attr("disabled", false);
            		return;
            	}
            		
            	$(WEB_BUNDLES_LIST).append('<table class="hp-selectable" id="hpsum-pfw-bundles-table"><thead><tr><td><b>' + 
								localizer.getString("hpsum.common.name") + '</b></td><td><b>' + 
								localizer.getString("hpsum.common.version") + '</b></td><td></td></tr></thead></table>');
				
							
				var bundleTable = initBundlesTable('#hpsum-pfw-bundles-table');
				for( var i=0; i<data.length; i++){
					var compItem = [{
								'name' : data[i].name.name_en,
								'version' : data[i].version,
								'url':  data[i].url.url__value
							}];
					bundleTable.fnAddData(compItem);
				}
				$("#hpsum-pfw-bundles-table tbody tr").click(function(e) {
						var srcElem;
									//Check if firefox or (chrome and IE)
						if (e.srcElement) {
										srcElem = e.srcElement;
											//Chrome and IE
									} else {
										srcElem = e.target;
										//Firefox
									
									}
						$(".hp-selected").each(function(){
						$(this).removeClass("hp-selected");});
						$(this).addClass("hp-selected");
						
				});
            	$('#hpsum-pfw-bundles-table tbody tr').first().addClass('hp-selected');	
            	$(ADD).attr("disabled", false);
            	$(INPUT_BROWSE_TEXT).attr("disabled", true).attr('style', 'width:450px;color:grey;');
            	$(INPUT_BROWSE_BUTTON).attr("disabled", true);
            	$(RETRIEVELIST_BUTTON).attr("disabled", true);
            	$(RETRIEVELIST_BUTTON).off('click',retrieveListofBundles);
            }
            

            function getProxyJsonObject(){
            	var proxy_settings;
            	if((proxyOptionValue == "No") || (proxyOptionValue == undefined))
            		proxy_settings ='';
            	else if(proxyOptionValue == "Server"){
            		proxy_settings = {
            			proxy_username: $('#hpsum-baseline-proxy-username').val(),
            			proxy_password: $('#hpsum-baseline-proxy-password').val(),
            			proxy_ftp_port: $('#hpsum-baseline-proxy-port').val(),
            			proxy_url: $('#hpsum-baseline-proxy-url').val(),
            			use_proxy_script:false
            		};
            	}
            	else if(proxyOptionValue == "Script"){
            		proxy_settings = {
            			proxy_username: $('#hpsum-baseline-proxyscript-username').val(),
            			proxy_password: $('#hpsum-baseline-proxyscript-password').val(),
            			use_proxy_script: true,
            			proxy_script: $('#hpsum-baseline-proxy-script').val()
            		};
            	}
            	return proxy_settings;
            }
                      
            function retrieveListofBundles() {
				$(BASELINE_INV_ERR_INPROGRESS).html("");
            	 $('> li:visible' , PANELS).last().css("padding-bottom", "0px");			
				var inst = $('#hpsum-baseline-ICM').data('plugin_hpsumAddBaselineICMToken');
				var validate = inst.isTokenChanged();
				if($(HP_PASSPORT_TOKEN).val())
					var icm_token=$(HP_PASSPORT_TOKEN).val();
				else
					var icm_token="no_token_id";						
            	var input = {
            		hapi: {
            			working_location : instAddLocBrowse.getLocation(), 
            			proxy_settings: getProxyJsonObject(),
						icm_token_id: icm_token,
						validate_token_id : validate
            		}
            		
            	};
            	
            	presenter.getListofPFWBundles(input, {success:function(data,valid){				   
				   var options = {
										command : 'isTokenValid',
										args : valid
									};
									$("#hpsum-baseline-ICM").hpsumAddBaselineICMToken(options);
            		$(WEB_BUNDLES_PANEL).show();
                    $(PANELS).hpStackedPanels("reset");
            		showBundlesTable(data);
            		
            		$(".hpsum-proxy").attr("disabled", true);
			$('#hpsum-proxy-options').selectBox('disable');
            	},error:function(message) {
            		closeAddWait();
            		$(WEB_BUNDLES_PANEL).show();
                    $(PANELS).hpStackedPanels("reset");
            		showBundlesTable(message);
            	}});
            	showAddWait(localizer.getString('hpsum.baseline.add.retrieveInProgress'));
            }
            function setRetrieveButtonState(){
            	if($(LOCATION_TYPE).val() == 'FTP'){
                       
                       if(instAddLocBrowse.getLocation() == "")
                     	   			$(RETRIEVELIST_BUTTON).attr("disabled", true);
                       				else{
                       				$(RETRIEVELIST_BUTTON).attr("disabled", false);
						if(iserror == true)
						{
						$(RETRIEVELIST_BUTTON).on('click',retrieveListofBundles);
						}
						}
									
                      }
            	
            }
            
            function onLocalPathInput(){
            	if($(LOCATION_TYPE).val() == 'local'){
            		$('#hpsum-invalid-location-error-nonempty').html("");
            		if(instAddLocBrowse.getLocation().length > 0) {
            			$(ADD).attr("disabled", false);
            		}
            		else {
            			$(ADD).attr("disabled", true);	
            			$(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
            			$(INPUT_BROWSE_BUTTON).attr("disabled", false);
            		}
            	}
				else if ($(LOCATION_TYPE).val() == 'HTTP'){
					HandleAddButtonForHTTP();
				}
            }
            
            function setLocationType(){
            	formStateView.reset();
            	$('#hpsum-invalid-location-error-nonempty').html("");
            	$(INPUT_BROWSE_TEXT).val('');
            	 $(BROWSE_TEXT).text(localizer.getString('hpsum.baseline.add.browseText'));
				 $(BASELINE_INV_ERR_INPROGRESS).html("");
				  $('#hpsum-FTP-info-msg').hide();
            	 locationType = $(LOCATION_TYPE).val();
                    if (locationType == 'local') {
                    	$(HTTP_ERROR).hide();
                        $(BASELINE_LABEL).html(localizer.getString('hpsum.baseline.add.enterDirectory'));
                        $(PATH_DETAILS).show();
                        $(URI_DETAILS).hide();
                        $(BASELINE_ADD_LOC).show();
						$(BASELINE_CREDS).hide();
                        $(RETRIEVELIST_BUTTON).css( "display", "none" );
                        $(RETRIEVELIST_BUTTON).off('click',retrieveListofBundles);
                        $(WEB_BUNDLES_PANEL).hide();
                        $(RETRIEVELIST_BUTTON).hide();
                        instAddLocBrowse.setPanelText('');
                        instAddLocBrowse.setLocationType('local');
			instAddLocBrowse.setBrowseOptions({bshowXml: false, bshowFile: false, bShowHPSUMFiles: false, bShowEmptyFolder: false, bCreateDirectory: false});
                        instAddLocBrowse.setInputEvent('oninput', onLocalPathInput);
            		$(PROXY_SETTINGS).hide();
                        $(ADD).attr("disabled", true);
                        $(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
                        $(INPUT_BROWSE_BUTTON).attr("disabled", false);
                        $(HTTP_SETTINGS).hide();
						$(HP_PASSPORT_ICM).hide();
                    }
                    else if (locationType == 'UNC') {
                    	$(BROWSE_TEXT).text(localizer.getString('hpsum.baseline.add.browseUNCText'));
                        $(PATH_DETAILS).hide();
                        $(HTTP_ERROR).hide();
                        $(URI_DETAILS).show();
                        $(BASELINE_ADD_LOC).show();
						$(BASELINE_CREDS).show();
                        $(PROXY_SETTINGS).hide();
                        $(WEB_BUNDLES_PANEL).hide();
                        $(RETRIEVELIST_BUTTON).css( "display", "none" );
                        $(RETRIEVELIST_BUTTON).off('click',retrieveListofBundles);
                        $(ADD).attr("disabled", true);
                        $(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
                        $(INPUT_BROWSE_BUTTON).attr("disabled", false);
                        $(HTTP_SETTINGS).hide();
						$(HP_PASSPORT_ICM).hide();
						instAddLocBrowse.setLocationType('unc');
			instAddLocBrowse.setBrowseOptions({bshowXml: false, bshowFile: false, bShowHPSUMFiles: false, bShowEmptyFolder: false, bCreateDirectory: false});
                    }
                    else if (locationType == 'FTP'){
                        $(PATH_DETAILS).hide();
                        $(HTTP_ERROR).hide();
                        $(URI_DETAILS).hide();
						$(BASELINE_CREDS).hide();
                        $(PROXY_SETTINGS).hide();
						$(HP_PASSPORT_ICM).hide();
                        $(RETRIEVELIST_BUTTON).hide();
                        $(BASELINE_ADD_LOC).hide();
						
						
						
                    	
                        $(WEB_BUNDLES_LIST).html('');
                        $('#hpsum-FTP-info-msg').show();
                       
					
						
						$(HTTP_SETTINGS).hide();
                    }
                    else if (locationType == 'HTTP'){
                        $(BROWSE_TEXT).text(localizer.getString('hpsum.baseline.add.browseHTTPText'));
						$(URI_DETAILS).hide();
						$(BASELINE_CREDS).hide();
	                    $(PROXY_SETTINGS).hide();
						$(HP_PASSPORT_ICM).hide();
	                    $(RETRIEVELIST_BUTTON).hide();
						$(BROWSE_LOCATION_ERROR).html("");
                        $(HTTP_URL).removeClass("hp-error");
	                    $(BASELINE_LABEL).html(localizer.getString('hpsum.baseline.add.enterWorkingDirectory'));
						$(PATH_DETAILS).show();
						$(BASELINE_ADD_LOC).show();
						$(HTTP_SETTINGS).show();
	                    $(HTTP_URL).val("");	
						instAddLocBrowse.setInputEvent('oninput', onLocalPathInput);
	                    $(ADD).attr("disabled", true);
 			    $(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
                    	    $(INPUT_BROWSE_BUTTON).attr("disabled", false);	
	                	instAddLocBrowse.setLocationType('http');
				instAddLocBrowse.setBrowseOptions({bshowXml: false, bshowFile: false, bShowHPSUMFiles: false, bShowEmptyFolder: true, bCreateDirectory: true});
                }
                }

            function credentialsOptions(value){
          		if(value.target)
            		value = value.target.value;
            	if(value == "one"){
					$('#hpsum-baseline-credential-current').attr('checked',true);
            		$(ENTER_CRED).hide();
            	}
            	if(value == "two"){
            		$(ENTER_CRED).show();
            		$(USERNAME).removeClass("hp-error");
            		$(PASSWORD).removeClass("hp-error");
            	}
            		
            }
			
			function HandleAddButtonForHTTP()
			{
				$(BROWSE_LOCATION_ERROR).html("");
				if(instAddLocBrowse.getLocation().length > 0 && $(HTTP_URL).val().trim() != "") {
					$(ADD).attr("disabled", false);					
				}
				else {
					$(ADD).attr("disabled", true);
					$(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
                    			$(INPUT_BROWSE_BUTTON).attr("disabled", false);	
				}
			}
            
            function onBrowseDone(){
            	if($(LOCATION_TYPE).val() == 'local')
            	{
                    $(ADD).attr("disabled", false);					
				}
				else if($(LOCATION_TYPE).val() == 'HTTP'){
					HandleAddButtonForHTTP();
				}
				
            }
            
            function onInvalidPackageSelection(){
            	showInfoDialog();	
            }

 			function updateUserInterfaceForOEM()
			{
				var sessionDataHandlers = {
					success : function(data) {
						// if hcode is 0 then session is alive and set session cookies
						if(data.hapi.hcode == 0) {
							var mfg = data.hapi.manufacturer;
							if (mfg != "HP") {
								// Remove the 'Download from hp.com' from the select box
								//$('#hpsum-baseline-location-type option[value="FTP"]').remove();
								$(LOCATION_TYPE).selectBox('reset');
							}
						}
						else
						{
							// if session is expired or any other error, then goto login page
							session.eraseAll();
							document.location.href = "/#/login";
						}
					},
					error : function(jqXHR) {
						// getsessiondata failed, so goto login page
						session.eraseAll();
						document.location.href = "/#/login";
					}
				};

				//get session data and set user and login details for the session
				session.getSessionData(sessionDataHandlers);
			}
			function handleAddButton(uripath, type)
			{
				if(uripath=="" || type=="") 
				{
					$(ADD).attr("disabled", true);
					
				}
				else 
				{ 
					$(ADD).attr("disabled", false);
				}
			}
			/**
	         * @public
	         */
            this.resume = function () {
            	router.watch('baseline add section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
                $(WEB_BUNDLES_PANEL).hide();
                $(LOCATION_TYPE).selectBox('value','local');
                instAddLocBrowse.setLocationType('local');
				instAddLocBrowse.setBrowseOptions({bshowXml: false, bshowFile: false, bShowHPSUMFiles: false, bShowEmptyFolder: false, bCreateDirectory: false});
				$(BROWSE_TEXT).text(localizer.getString('hpsum.baseline.add.browseText'));
                $(RETRIEVELIST_BUTTON).attr("disabled", false);
                $(RETRIEVELIST_BUTTON).css( "display", "none" );
				$('input[name="hpsum-baseline-credential"]').click(credentialsOptions);
            	reset();
            };
            
            this.pause = function () {
            };
            
            /**
             * @public
             * Initialization funtion for the object
             * All the controls actions are initialized in this function.
             */
            this.init = function() {
       
				updateUserInterfaceForOEM();

				$("#hpsum-baseline-ICM").hpsumAddBaselineICMToken('init');
                
				$('input[name="hpsum-baseline-credential"]').click(credentialsOptions);
				
		$(CANCEL).live('click', function() {
		$('#hpsum-invalid-location-error-nonempty').html(" "); 
			router.go('/baseline/show/');						
		});

                $(PANELS).hpStackedPanels({
                    panelSelector : PANEL_SELECTOR
                });
                
                $(LOCATION_TYPE).selectBox({autoWidth: false});
                $(RETRIEVELIST_BUTTON).css( "display", "none" );

                var listItem = $('.hp-details-header-controls', $(FORM).parent());

                // put help in header
                if ($('.hp-details-header-controls', $(FORM).parent()).length === 0) {
                    var headerHelp = $(headerHelpHtml);
                    localizer.localizeDom(headerHelp);
                    $('.hp-details-header', $(FORM).parent()).append(headerHelp);
                }
				$(ADD).live('click', function(ev) {
				iserror=false;
                   	onAddItem.call(this);
                   	ev.preventDefault();
               	});

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

                formStateView.init({form: FORM,
                    	routePattern: ROUTE_PREFIX + '.*',
                    	autoTrack: false});
                
               	var options = 	{
									command : 'init',
									panelLabel: "hpsum.baseline.add.enterDirectory",
									panelLabelStyle: "text-align:left;",
						            panelHelp: "",
						            panelBrowseText: "hpsum.common.browse",
						            onBrowseDone: onBrowseDone,
						            onInvalidPackageSelection: onInvalidPackageSelection
								};
				$(ADD_BROWSE_PANEL).hpsumBrowse(options);
				
				instAddLocBrowse = $(ADD_BROWSE_PANEL).data('plugin_hpsumBrowse');
				instAddLocBrowse.setInputEvent('oninput', onLocalPathInput);
				reset();
				
                $(LOCATION_TYPE).change(setLocationType);
				$(COLLAPSE_OSFILTER).attr('tooltip', localizer.getString('hpsum.baseline.add.osFilterOpt')).hpTooltip();
                $(COLLAPSE_OSFILTER).hpCollapsible();
				
                $(URI_PATH).on('input', function(){
 			if($(URI_PATH).val()=="")
 			{
        			$(ADD).attr("disabled", true);
        			$(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style', 'width:450px;');
        			$(INPUT_BROWSE_BUTTON).attr("disabled", false);
 		 	}
    			else 
    			{ 
    				$(ADD).attr("disabled", false);
    				$(INPUT_BROWSE_TEXT).attr("disabled", true).attr('style', 'width:450px;color:grey;');
    				$(INPUT_BROWSE_BUTTON).attr("disabled", true);
    			}
 				});
				$(USERNAME).bind('keyup', function(){
					handleAddButton($(URI_PATH).val(), $(USERNAME).val());
 				});
				$(PASSWORD).bind('keyup', function(){
					handleAddButton($(URI_PATH).val(),  $(PASSWORD).val());
 				});
				$("input").bind("keypress", function(event) {
                    var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
                    if (keycode == 13) { // keycode for enter key
						var isDisabled = $(ADD).attr('disabled');
						if(isDisabled === undefined)
						{
							$(ADD).trigger('click');
						}
                        event.preventDefault();
                      }
                    });
				
                $(HTTP_URL).on('input', function(){
                	$(HTTP_ERROR).hide();
            		$(HTTP_URL).removeClass("hp-error");
                	if($(HTTP_URL).val() == "" || instAddLocBrowse.getLocation() == "")	{	//$(PATH).val() == ""){
                        if(instAddLocBrowse.getLocation() == "")
                        {
                            $(BROWSE_LOCATION_ERROR).show();
                            $(BROWSE_LOCATION_ERROR).text(localizer.getString('hpsum.baseline.add.inValidLocation'));
                        }
                		$(ADD).attr("disabled", true);
                		$(INPUT_BROWSE_TEXT).attr("disabled", false).attr('style','width:450px;');
                		$(INPUT_BROWSE_BUTTON).attr("disabled", false);
                    }
                	else
                	{
                		$(ADD).attr("disabled", false);                		
                	}
                });

                $('#hpsum-proxy-usehp-item').hide();
                $('#hpsum-proxy-usescript-item').hide();
                //$('input:radio[name=hpsum-baseline-proxy-opt]').click(onProxyOptionChange);

		// Linux to windows UNC path for add baseline not supported
		if ((navigator.appVersion.indexOf("X11") != -1) || (navigator.appVersion.indexOf("Linux") != -1)) {
                        $('#hpsum-baseline-location-type option[value="UNC"]').remove();
                        $(LOCATION_TYPE).selectBox('reset');
                }

                this.resume();
            };
        }

        return BaselineAddView;
    }());
    
    return new BaselineAddView();
});
