// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (BaselineValidateView)
 * This is a view class for Validate Baseline menu option.
 */
define(['hpsum/presenter/baseline/BaselinePresenter',
	'hp/core/Router',
    'hp/core/Notifications',
	'hp/core/HelpMenu',
    'hp/core/Localizer',
    'hp/view/DialogView',
    'hp/view/FormStateView',
    'hp/model/Session',
    'text!hpsumpages/common/confirm_dialog.html',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'lib/jquery.selectBox',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpToggle',
	'hp/lib/jquery.hpSearchCombo',
	'hpsum/common/jquery.hpsumBrowse',
	'lib/jquery-ui-timepicker-addon',
	'hp/lib/jquery.hpStatus'],
function(presenter, router, notifications, helpMenu, localizer, DialogView, FormStateView, session, dialogContent) { "use strict";

    var BaselineValidateView = (function() {
      
        var FORM = '#hpsum-baselines-validate-form',
        	SELECTED_BL = '#hpsum-validate-selected-baseline',
        	SELECTED_BL_XML = '#hpsum-vbl-xml',
			CANCEL = '#hpsum-validate-baselines-close',
			COMPONENTS_TABLE = '#baseline-validate-table',
            VALIDATION_TYPE = '#hpsum-validate-baseline-against',
            LOCATION_TYPE = '#hpsum-vbl-location-type',
            PROXY_OPTIONS = '#hpsum-vbl-proxy-options',
            CSM_VERSION = '#hpsum-csm-version',
            SPP_PATH = '#hpsum-vbl-spp-location-path',
            BROWSE_MATRIX_LOCATION_ERROR = '#hpsum-vbl-invalid-location-error',
            INFO_DIALOG = '#hpsum-info-dialog',
            VALIDATE  = '#hp-validate-baseline',
            TOTAL_SUMMARY = '#hpsum-vbl-total-summary',
            MISSING_SUMMARY = '#hpsum-vbl-missing-summary',
            SPLASH_DIALOG = '#hpsum-validate-wait-dialog',
            SPLASH_SPINNER = '#hpsum-validate-spinner',
            RETRIEVE_MATRIX_BUTTON = '#hpsum-baselines-getmatrix',
            MATRIX_LOCATION_BROWSE_PANEL = "#hpsum-matrix-ftp-browse";
            
        /**
         * Constructor
         */
        function BaselineValidateView() {
            
            var oTableComponents;
            var proxyOptionValue;
            var browseDialogContents;
            var infoDialog;
            var baselineItem;
            var nodeTable = null;
            var formStateView = new FormStateView();
            var waitDialog;
            var instMatrixLocBrowse;

            function onItemChange(item) {
            	baselineItem = item;
                if (item && item.hasOwnProperty("hapi")) {
                    $(SELECTED_BL).html(item.hapi.baseline_name + " " + item.hapi.baseline_version);
					if(item.hapi.baseline_url.match("/"))
                     $(SELECTED_BL_XML).html(item.hapi.baseline_url + "/" + item.hapi.baseline_id + ".xml");
                    else
                     $(SELECTED_BL_XML).html(item.hapi.baseline_url + "\\" + item.hapi.baseline_id + ".xml");
                }
            }

            function onValidate(){
                if($(VALIDATION_TYPE).val() === 'bundle'){
                    validateAgainstBundle();
                    $(VALIDATE).attr("disabled",true);
                }
                if($(VALIDATION_TYPE).val() === 'CSM'){
                    validateAgainstCSM();
                    $(VALIDATE).attr("disabled",true);
                }
            }

            function validateAgainstBundle(){
            	var msg = localizer.getString('hpsum.baseline.validate.validationInProgress');
            	showSaveWait(msg);
            	var URI;
            	URI = baselineItem.hapi.baseline_uri + "/validatebundleinventory";
            	presenter.startBundleValidation(URI,{
                        success : onValidationSuccess,
                        error : onValidationError
                    });
            }
            
            function onValidationSuccess(data){
            	closeSaveWait();
                var msg;
            	
            	if(data.hapi.hcode === 0)
            		msg = 'ok';
            	else{
                    msg = 'error';
                    if($(VALIDATION_TYPE).val() === 'bundle') {
                    	$('#hpsum-vbl-summary').show();                    	
                    }
                    if ($(VALIDATION_TYPE).val() === 'CSM') {
                    	$('#hpsum-vbl-summary').hide();
                    }
                    $('#hpsum-vbl-components').show();
                    
                    var summarystr = '<label style="position:absolute;">' + data.hapi.total_no_of_component + localizer.getString('hpsum.baseline.validate.totalSummary') + ', ' + data.hapi.total_no_of_missing_component + localizer.getString('hpsum.baseline.validate.missingSummary') + '</label>';
	                if(data.hapi.total_no_of_missing_component > 0) {
	                	$(MISSING_SUMMARY).html('<div class="hp-status"><div class="hp-status-value hp-status-error"><span class="hp-value">error</span></div>' + summarystr + '</div>');
	                }
	                else
	                	$(MISSING_SUMMARY).html('<div class="hp-status"><div class="hp-status-value hp-status-ok"><span class="hp-value">ok</span></div>' + summarystr) + '</div>';
                    
                    $(MISSING_SUMMARY).show();
                    instMatrixLocBrowse.setPanelLabel(localizer.getString('hpsum.baseline.validate.csmPath'));
                    initComponentsTable();
                    populateComponentsTable(data);
                }
                     
               	formStateView.setMessage({
                    summary: data.hapi.hmessage,
                    status: msg,
                    details: ""});

                $(VALIDATE).attr("disabled", true);
            }
            
            function onValidationError(){
                closeSaveWait();
            	formStateView.setMessage({
                                summary: localizer.getString("hpsum.baseline.custom.validationErrorMsg"),
                                status: 'error',
                                details: ""});
            }

            function validateAgainstCSM(){
            	var msg = localizer.getString('hpsum.baseline.validate.validationInProgress');
            	showSaveWait(msg);
            	var URI;
            	URI = baselineItem.hapi.baseline_uri + "/validatereciepefile";
            	var selectedIndex = $('#hpsum-csm-version')[0].selectedIndex;
            	var selectedVersion = $('#hpsum-csm-version')[0][selectedIndex].text;             	
            	var input = {
            		hapi: {
            			csm_version : selectedVersion
            		}            		
            	};
				formStateView.reset();
            	presenter.validateReciepeFile(URI, input, {
                        success : onCSMValidationSuccess,
                        error : onCSMValidationError
                    });

            }

	    function onCSMValidationSuccess(data) {            	
            	closeSaveWait();
            	var msg;
            	
            	if(data.hapi.hcode === 0) {
            		msg = 'ok';            		
            	} else {
            		msg = 'error';            		
            	}
                
                $('#hpsum-vbl-summary').show();
                $('#hpsum-vbl-components').show();
                
                var summarystr = '<label style="position:absolute;">' + data.hapi.total_no_of_component + localizer.getString('hpsum.baseline.validate.totalSummary') + ', ' + data.hapi.total_no_of_missing_component + localizer.getString('hpsum.baseline.validate.missingSummary') + '</label>';
                if(data.hapi.total_no_of_missing_component > 0) {
                	$(MISSING_SUMMARY).html('<div class="hp-status"><div class="hp-status-value hp-status-error"><span class="hp-value">error</span></div>' + summarystr + '</div>');
                }
                else
                	$(MISSING_SUMMARY).html('<div class="hp-status"><div class="hp-status-value hp-status-ok"><span class="hp-value">ok</span></div>' + summarystr) + '</div>';
                    	
                $(MISSING_SUMMARY).show();
                instMatrixLocBrowse.setPanelLabel(localizer.getString('hpsum.baseline.validate.csmPath'));
                initComponentsTable();
                populateComponentsTable(data);
               	formStateView.setMessage({
                    summary: data.hapi.hmessage,
                    status: msg,
                    details: ""});
            }
            
            function onCSMValidationError(data) {            	
            	closeSaveWait();
            }
			

            //Initialize install components table to add all the missing components
            function initComponentsTable() {
                
                  nodeTable = $(COMPONENTS_TABLE).dataTable({
                        oLanguage: {
                            sEmptyTable: localizer.getString('hpsum.node.noItemsFound'),
                            sSearch: localizer.getString('hpsum.common.search')
                               },
                    bScrollCollapse: true,
                    bPaginate : false,
                    bProcessing : true,
                    bFilter : true,
                    bSort : true,
                    bAutoWidth : true,
                    bInfo : false,
                    bRetrieve : true,
                    bDestroy : true,
                        aoColumns : [                            
                            {mDataProp: 'component_id'},
                            {mDataProp: 'package_name'},
                            {mDataProp: 'component_version'},
                            {mDataProp: 'found'}],
                    aaSorting: [],
                    });
                nodeTable.fnClearTable();
            }

            function populateComponentsTable(data){

                nodeTable = $(COMPONENTS_TABLE).dataTable();
                nodeTable.fnClearTable();
                nodeTable.fnAddData(data.hapi.missing_comp_list.component);
                nodeTable.fnAddData(data.hapi.available_components.component);
            }
            
            function setValidationType(){
                if($(VALIDATION_TYPE).val() == 'bundle'){
                    $('#hpsum-FTP-CSM-msg').hide();
                    $('#hpsum-validate-csm-location-type').hide();
                    $('#hpsum-validate-csm-local').hide();
                    $('#hpsum-validate-csm-version').hide();
                    $('#hpsum-validate-csm-ftp').hide();
                    $('#hpsum-matrix-from-ftp').hide();
                    $(VALIDATE).attr("disabled", false);
                    $('#hpsum-vbl-summary').hide();
                    $('#hpsum-vbl-components').hide();
                    formStateView.reset();
                    $(RETRIEVE_MATRIX_BUTTON).hide();
                }
                else if($(VALIDATION_TYPE).val() == 'CSM'){
                    $('#hpsum-validate-csm-location-type').show();
                    //$('#hpsum-validate-csm-local').show();
                    $('#hpsum-validate-csm-local').hide();
                    $('#hpsum-validate-csm-version').hide();
                    $('#hpsum-matrix-from-ftp').show();
                    $('#hpsum-vbl-summary').hide();
                    $('#hpsum-vbl-components').hide();
                    $(LOCATION_TYPE).selectBox('value','local');
                    instMatrixLocBrowse.setLocationType('local');
                    setLocationType();
                    formStateView.reset();
                }                 
            }

            function setLocationType(){
                $('#hpsum-FTP-CSM-msg').hide();
                if($(LOCATION_TYPE).val() == 'local'){
                    $('#hpsum-vbl-summary').hide();
                    $('#hpsum-vbl-components').hide();
                    $('#hpsum-validate-csm-local').hide();
                    $('#hpsum-validate-csm-version').hide();
                    $('#hpsum-validate-csm-ftp').hide();
                    $('#hpsum-matrix-from-ftp').show();
                    $(PROXY_OPTIONS).hide();
                    if(instMatrixLocBrowse) {
                    	instMatrixLocBrowse.setPanelText("");
                    	instMatrixLocBrowse.setPanelLabel(localizer.getString('hpsum.baseline.validate.csmPath'));
                    	instMatrixLocBrowse.setLocationType('local');
                    	instMatrixLocBrowse.setBrowseOptions({bshowXml: true, bshowFile: false, bShowHPSUMFiles: false, bShowEmptyFolder: false, bCreateDirectory: false});
                    }
                    $(RETRIEVE_MATRIX_BUTTON).css( "display", "none" );
                    $(RETRIEVE_MATRIX_BUTTON).off('click',retrieveReciepeFile);
                    $(VALIDATE).attr("disabled", false);
                    formStateView.reset();
                }
                else if($(LOCATION_TYPE).val() == 'FTP'){
                        $('#hpsum-FTP-CSM-msg').show();
                        $('#hpsum-validate-csm-local').hide();
                        $('#hpsum-validate-csm-version').hide();
                        $('#hpsum-validate-csm-ftp').hide();
                        $('#hpsum-vbl-summary').hide();
                        $('#hpsum-vbl-components').hide();
                        
                        $(VALIDATE).attr("disabled", true);
                        $(RETRIEVE_MATRIX_BUTTON).hide();
                        $(".hpsum-proxy").attr("disabled", true);
                        $('#hpsum-matrix-from-ftp').hide();
                        formStateView.reset();
                    }             
            }

            function onProxyOptionsChange(msg) 
            {
                var value = $(PROXY_OPTIONS).val();
                if(value == "No" || msg == "No"){
                    $('#hpsum-vbl-proxy-usehp-item').hide();
                    $('#hpsum-vbl-proxy-usescript-item').hide();
                    proxyOptionValue = "No";
                }
                else if(value == "Server"){
                    $('#hpsum-vbl-proxy-usehp-item').show();
                    $('#hpsum-vbl-proxy-usescript-item').hide();
                    $('#hpsum-vbl-proxy-url').attr("disabled",false);
                    $('#hpsum-vbl-proxy-port').attr("disabled",false);
                    $('#hpsum-vbl-proxy-username').attr("disabled",false);
                    $('#hpsum-vbl-proxy-password').attr("disabled",false);
                    proxyOptionValue = "Server";
                }
                else if (value == "Script"){
                    $('#hpsum-vbl-proxy-usehp-item').hide();
                    $('#hpsum-vbl-proxy-usescript-item').show();
                    $('#hpsum-vbl-proxy-script').attr("disabled",false);
                    $('#hpsum-vbl-proxyscript-username').attr("disabled",false);
                    $('#hpsum-vbl-proxyscript-password').attr("disabled",false);
                    proxyOptionValue = "Script";
                }
				$(RETRIEVE_MATRIX_BUTTON).attr("disabled", false);
            }

            /**
             * * 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 showSaveWait(msg) {					
					
					if (!waitDialog) {
						waitDialog = $(SPLASH_DIALOG);
						waitDialog.dialog({
							modal : true,
							dialogClass : 'hp-simple-dialog',
							position : "center",
							draggable : false,
							resizable : false,
							width : 260,
							height : 180
						});
					}						                   

					$('#hpsum-bs-validate-wait-message', waitDialog).html(msg);
					$(SPLASH_SPINNER).show();
					msg='';
					waitDialog.dialog('open');
				}

				function closeSaveWait() {
					$(SPLASH_SPINNER).hide();
					if (waitDialog) {
						waitDialog.dialog('close');
					}
				}
            
            /**
             * * Saves the given local matrix xml file and wait for the engine to response
             * * Till engine response page will be blocked. 
             */
            function saveLocalMatrixFile(matrixXmlFile) {
            	var msg = localizer.getString('hpsum.baseline.validate.saveInProgress');
            	showSaveWait(msg);
            	            	
            	var input = {
            		hapi: {
            			uri : matrixXmlFile            			
            		}            		
            	};
            	
            	presenter.saveReciepeFile(input, 
            		{
                        success : onItemSaveSuccess,
                        error : onItemSaveError
                    });            	
            }
            
            
            function onItemSaveSuccess(data) {
            	
            	closeSaveWait();
            	var msg;
            	
            	if(data.hapi.hcode === 0) {
            		msg = 'ok';
            		$('#hpsum-validate-csm-local').show();
                    $('#hpsum-validate-csm-version').show();
            		var versions = data.hapi.available_versions.matrix_version;
            		var length = versions.length;
					var maxwidth = 0;
					var versiondata ="";
					var canvas = document.createElement('canvas');
					var ctx = canvas.getContext("2d");
					ctx.font = "13px Arial bold";
            		for(var i = 0; i < length; ++i) {
            			var ver = versions[i].version;
            			var baseline = versions[i].associated_bundle_name;
            			versiondata += '<option value="' + baseline + '_' + i + '">' + ver + '</option>';
						var width = ctx.measureText(ver).width;	
						if(maxwidth < width)
							maxwidth = width;
            		}
					var selectdata = '<select id=hpsum-csm-version class= hp-select' + ' style="width:' + maxwidth + 'px;">';
					selectdata += versiondata;
            		selectdata += '</select>';
            		$('#hpsum-csm-selectbox').html(selectdata);
			$(CSM_VERSION).selectBox({autoWidth: false});
            		var selectvalue = $('#hpsum-csm-version').val();
					selectvalue = selectvalue.substr(0,selectvalue.lastIndexOf('_'));
            		$('#hpsum-starting-bl-used-value').text(selectvalue);	
            		$('#hpsum-csm-version').change(function(){
            			var selectvalue = $('#hpsum-csm-version').val();
						selectvalue = selectvalue.substr(0,selectvalue.lastIndexOf('_'));
            			$('#hpsum-starting-bl-used-value').text(selectvalue);
                        $(VALIDATE).attr("disabled", false);
                        if(nodeTable != null)
                            nodeTable.fnClearTable();
                        formStateView.reset();
                        $(MISSING_SUMMARY).hide();
            		});
            	} else {
            		msg = 'error';
            		$('#hpsum-validate-csm-local').hide();
                    $('#hpsum-validate-csm-version').hide();
            	}
                     
               	formStateView.setMessage({
                    summary: data.hapi.hmessage,
                    status: msg,
                    details: ""});
            	
            }
            
            function onItemSaveError(data) {
            	closeSaveWait();
            }
            
            function getProxyJsonObject(){
                var proxy_settings;
                if((proxyOptionValue == "No") || (proxyOptionValue == undefined))
                    proxy_settings ='';
                else if(proxyOptionValue == "Server"){
                    proxy_settings = {
                        proxy_username: $('#hpsum-vbl-proxy-username').val(),
                        proxy_password: $('#hpsum-vbl-proxy-password').val(),
                        proxy_ftp_port: $('#hpsum-vbl-proxy-port').val(),
                        proxy_url: $('#hpsum-vbl-proxy-url').val(),
                        use_proxy_script:false
                    };
                }
                else if(proxyOptionValue == "Script"){
                    proxy_settings = {
                        proxy_username: $('#hpsum-vbl-proxyscript-username').val(),
                        proxy_password: $('#hpsum-vbl-proxyscript-password').val(),
                        use_proxy_script: true,
                        proxy_script: $('#hpsum-vbl-proxy-script').val()
                    };
                }
                return proxy_settings;
            }

            function retrieveReciepeFile() {
                var input = {
                    hapi: {
                        working_location : instMatrixLocBrowse.getLocation(), //$(MATRIX_PATH).val(),
                        proxy_settings: getProxyJsonObject()
                    }
                };
                
                presenter.getPFWReciepefile(input, {
                    success:function(data){
                        closeSaveWait();
                        $(".hpsum-proxy").attr("disabled", true);
                        $('#hpsum-proxy-options').selectBox('disable');

                        var msg;
                        
                        if(data.hapi.hcode === 0) {
                            msg = 'ok';
                            var xmlFile = instMatrixLocBrowse.getLocation() + "/MatrixConfig.xml"; //$(MATRIX_PATH).val() + "/MatrixConfig.xml";
                            saveLocalMatrixFile(xmlFile);
                            $(VALIDATE).attr("disabled", false);
							$(RETRIEVE_MATRIX_BUTTON).attr("disabled", true);
                        }
                        else{
                            msg = 'error';
                        }
                             
                        formStateView.setMessage({
                            summary: data.hapi.hmessage,
                            status: msg,
                            details: ""});
                    },
                    error:function(message) {
                        closeSaveWait();
                    }
                });

                showSaveWait(localizer.getString('hpsum.baseline.validate.retrieveInProgress'));
            }

            function setRetrieveButtonState(){
                if($(LOCATION_TYPE).val() == 'FTP'){
                       if(instMatrixLocBrowse.getLocation() == '')
                            $(RETRIEVE_MATRIX_BUTTON).attr("disabled", true);
                        else
                            $(RETRIEVE_MATRIX_BUTTON).attr("disabled", false);
                      }
            }

            function onPathEdit() {
                $(BROWSE_MATRIX_LOCATION_ERROR).hide();
                instMatrixLocBrowse.removeInputClass("hp-error");
                instMatrixLocBrowse.setInputEvent('offkeyup', onPathEdit);
            }

            function onHandleInvalidPath(hapi) {
                if (hapi.hcode == 5) {
                    $(BROWSE_MATRIX_LOCATION_ERROR).text(localizer.getString('hpsum.baseline.add.inValidLocation'));
                    instMatrixLocBrowse.addInputClass("hp-error");
                    $(BROWSE_MATRIX_LOCATION_ERROR).show();
                    instMatrixLocBrowse.setInputEvent('onkeyup', onPathEdit);
                    instMatrixLocBrowse.triggerDialogEvent('clickcancel');
                    $(VALIDATE).attr("disabled", true);
                } else {
                    $(BROWSE_MATRIX_LOCATION_ERROR).hide();
                    instMatrixLocBrowse.removeInputClass("hp-error");
                    instMatrixLocBrowse.setInputEvent('offkeyup', onPathEdit);
                }
            }

            function reset() {
                setValidationType();
                //'#hpsum-validate-csm-location-type').hide();
                //'#hpsum-validate-csm-ftp').hide();
                //'#hpsum-validate-csm-local').hide();
                $('#hpsum-vbl-proxy-usehp-item').hide();
                $('#hpsum-vbl-proxy-usescript-item').hide();
                $('#hpsum-vbl-summary').hide();
                $('#hpsum-vbl-components').hide();
                $('#PROXY_OPTIONS').selectBox('value', 'No');
                if(instMatrixLocBrowse)
                	instMatrixLocBrowse.setPanelText("");
                $(SELECTED_BL).html("");
                $(SELECTED_BL_XML).html("");
                $(VALIDATE).attr("disabled", false);
                $(PROXY_OPTIONS).hide();
                formStateView.reset();
            }
            
            function onSelectNode(nodeval, nodetype) {
            	var str = instMatrixLocBrowse.getLocation(); 
                var xmlname = nodeval;
                
                var loc_type = $(LOCATION_TYPE).val();
                if (loc_type != 'FTP'){
                    if (xmlname.match(".xml$") && !(str.match(".xml$"))) {
            			var xmlFileSelected=str + "/" + xmlname;                    			
            			instMatrixLocBrowse.setPanelText(xmlFileSelected);
            			instMatrixLocBrowse.triggerInputEvent('change');
            			instMatrixLocBrowse.removeDialogAttr('ok', "disabled");
					}
                }                    
                else
                {
                    instMatrixLocBrowse.removeDialogAttr('ok', "disabled");
                }
                
                formStateView.reset();
           	}
           	
           	function onBrowseDone(){
           		if($(LOCATION_TYPE).val() == 'local') {
                    $(VALIDATE).attr("disabled", false);
                    var path = instMatrixLocBrowse.getLocation();
                    path = path.replace("_C_", ":");
               		if ( navigator.appVersion.indexOf("Win") != -1 )
					{
						var repSlash1 = path.split('/').join('\\');
						path = repSlash1;		
					}                            
					instMatrixLocBrowse.setPanelText(path);
                    var xmlFile = instMatrixLocBrowse.getLocation();
               		saveLocalMatrixFile(xmlFile);
               	} else {
               		var currVal = instMatrixLocBrowse.getSelectedItem();
               		instMatrixLocBrowse.setPanelText(currVal);
               		var path = instMatrixLocBrowse.getLocation();
               		path = path.replace("_C_", ":");
               		if ( navigator.appVersion.indexOf("Win") != -1 )
					{
						var repSlash1 = path.split('/').join('\\');
						path = repSlash1;		
					}
					instMatrixLocBrowse.setPanelText(path);
					instMatrixLocBrowse.triggerInputEvent('change');
                }
           	}
           	
           	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" && mfg != "HPE") {
								// Remove the CloudSystem Matrix from validate options
								$('#hpsum-validate-baseline-against option[value="CSM"]').remove();
								$('#hpsum-validate-baseline-against').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);
			}
            
          	/**
             * @public
             */
            this.resume = function () {
                $(VALIDATION_TYPE).selectBox('value','bundle');
                $(LOCATION_TYPE).selectBox('value','local');
                instMatrixLocBrowse.setLocationType('local');
                setLocationType();
                $(PROXY_OPTIONS).selectBox('value', "No");                
                $(RETRIEVE_MATRIX_BUTTON).attr("disabled", false);
                $(RETRIEVE_MATRIX_BUTTON).css( "display", "none" );
                if(instMatrixLocBrowse)
                	instMatrixLocBrowse.setInputAttr("disabled", false);
                reset();
                presenter.on("itemChange", onItemChange);
            };
            
            this.pause = function () {
                presenter.off("itemChange", onItemChange);
            };
            
            /**
             * @public
             * Initialization funtion for the object
             * All the controls actions are initialized in this function.
             */
            this.init = function() {
            	
            	var options = 	{
									command : 'init',
									panelLabel: "hpsum.baseline.validate.csmPath",
									panelLabelStyle: "",
						            panelHelp: "",
						            panelBrowseText: "hpsum.common.browse",
						            bshowXml: true,
						            onSelectNode: onSelectNode,
						            onHandleInvalidPath: onHandleInvalidPath,
						            onInvalidPackageSelection: onInvalidPackageSelection,
						            onBrowseDone: onBrowseDone
								};
				
				updateUserInterfaceForOEM();
				
				$(MATRIX_LOCATION_BROWSE_PANEL).hpsumBrowse(options);
				
				instMatrixLocBrowse = $(MATRIX_LOCATION_BROWSE_PANEL).data('plugin_hpsumBrowse');
				
                $('#hpsum-vbl-title').text(localizer.getString("hpsum.baseline.validate.csmTitle"));
                $(VALIDATION_TYPE).selectBox({autoWidth: false});
                $(LOCATION_TYPE).selectBox({autoWidth: false});
                $(PROXY_OPTIONS).selectBox({autoWidth: false});
                $(CSM_VERSION).selectBox({autoWidth: false});
                $(VALIDATION_TYPE).change(setValidationType);
                $(LOCATION_TYPE).change(setLocationType);
                $(PROXY_OPTIONS).change(onProxyOptionsChange);
                $(VALIDATE).attr("disabled", false);
                $(RETRIEVE_MATRIX_BUTTON).css( "display", "none" );
		$('#hpsum-validate-baseline-matrixhelp').attr('tooltip', localizer.getString('hpsum.baseline.validate.locationTypehelp')).hpTooltip();
		$('#hpsum-validate-baseline-typehelp').attr('tooltip', localizer.getString('hpsum.baseline.validate.validationTypehelp')).hpTooltip();
		$('#hpsum-validate-baseline-proxyhelp').attr('tooltip', localizer.getString('hpsum.baseline.add.proxyOptionshelp')).hpTooltip();
                				
				$(VALIDATE).on('click',function(){
                    onValidate();
                });

                formStateView.reset();
                formStateView.init({form: FORM, routePattern: "" + '.*', autoTrack: true});
				$("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 = $(VALIDATE).attr('disabled');
						if(isDisabled === undefined)
						{
							$(VALIDATE).trigger('click');
						}
                        event.preventDefault();
                      }
                });
                this.resume();
            };
        }

        return BaselineValidateView;
    }());
    
    return new BaselineValidateView();
});