gerd
11/8/2016 - 1:59 PM

LN.js

/**
 * @author Balaji Ranjan</a>
 */
/**
 * This class loads all the components and registers them
 * Binds and invokes ready method on load completion
 * @class LN 
 * 
 */
var fnKeys =[9,13,16,17,18,19,20,27,33,34,35,36,37,38,39,40,45,91,92,93,112,113,114,115,116,117,118,119,120,121,122,123,144,145];
var LN = {
    ajaxErrMesg : 'An error occurred with your request. Please try again',
    THRESHOLD_LIMIT : 250,
    ppmContextPath : '/ppm',
    phmContextPath : '/phm2',
	data  : {
		GLOBAL_RETRY_COUNT:5		
	},
    // Pass the component and the component handler method
    registerComponent : function(component) {
        // Checking if the component is an instance of component
        if (!(component instanceof lexisnexis.component.Component)) {
            debug("Only components that extend from lexisnexis.component.Component can be registered");
            return;
        }
        $(this).bind("loadComponent", jQuery.proxy(component.ready, component));
    },
    onComponentsLoaded : function(object, componentsLoadedHandler) {
        $(this).bind("componentsLoaded",
                jQuery.proxy(componentsLoadedHandler, object));
    },
   /**
    * Ready method called when document.ready happens 
    * @method ready
    **/
    ready : function() {
     try {	
        if (!this.currentPageObject) {
            this.currentPageObject = new lexisnexis.page.Page();
        }
        // Load the page
        this.currentPageObject.onLoad();
        
     // this is to send unique transaction id for each page load
    	LN.TRANSACTION_ID=this.getPage().getTransactionID();
    	
        // Triggers the components to be loaded
        $(this).trigger("loadComponent");
        // After page and components have been loaded
        $(this).trigger("componentsLoaded");
        
        //INITRELEAS-506
        $('input').focus(function(){
        	$(this).data('placeholder',$(this).attr('placeholder'))
            $(this).attr('placeholder','');
        });
        $('input').blur(function(){
           $(this).attr('placeholder',$(this).data('placeholder'));
        });
        
     } catch(err) {
    	 LN.debug("ERROR: Unable to initialize Page"+err);
     }   
    },
    /**
     * Displays the loading dialog blocking the page UI for all components to load
     * @method openLoadingDialog
     */
    openLoadingDialog:function() {
    	var cs=this;
    	if(!(cs.data.message)) {
    		cs.data.message= "<img title='Processing...' src='"+LN.getContextPath()+"/resources/default/images/ajax-loader-big.gif'/>";
    	}
    	$.blockUI.defaults.css = {};
    	$.blockUI({  css: {
    		   padding: 0,
               margin: 0,
               top: '50%',
               left: '50%',
               textAlign: 'center',
               cursor: 'wait',
               color:'#000000',
               backgroundColor:'#F0F8FF',
               baseZ:2000
    		}, 
            message: cs.data.message  }
    	); 
    },
    /**
     * Returns the current page object 
     * @method getPage
     **/
    getPage : function() {
        return this.currentPageObject;
    },
    /**
     * Blocks the dialog.
     * @method openWaitingDialog
     * @param message
     * @param title
     *            (optional)
     * @param showWaitingImage
     *            (optional)
     * @param height
     *            (optional)
     * @param width
     *            (optional)
     */
    openWaitingDialog : function(message, title, showWaitingImage, height,
            width) {
        var dialogHtml = '<div class="waiting-dialog"';
        if (title) {
            dialogHtml = dialogHtml + ' title="' + title + '">';
        }
        if (showWaitingImage === 'true') {
            dialogHtml = dialogHtml
                    + '<div class="image-container">&nbsp;</div>';
        }
        dialogHtml = dialogHtml + '<div class="message-container"><p>'
                + message + '</p></div></div>';
        $('body:first').append(dialogHtml);
        // Set height and width defaults if passed in values are empty
        if (height === null || height === '') {
            height = 'auto';
        }
        if (width === null || width === '') {
            width = 300;
        }
        $(".waiting-dialog").dialog({
            modal : true,
            height : height,
            width : width,
            open : function(event, ui) {
            },
            closeOnEscape : false,
            draggable : false,
            buttons : {},
            resizable : false,
            dialogClass : "loadingScreenWindow"
        });
    },
    /**
     * This method opens a dialog and is used to open a help modal dialog
     * @method openDialog
     * @param message
     * @param title
     * @param height
     * @param width
     * @param modal
     * @param thisDialogClass
     * @param anchor
     */
    openDialog : function(message, title, height, width, modal,
            thisDialogClass, anchor) {
        dlg.simpleDialog(message, title, height, width, modal, thisDialogClass,
                anchor);
    },
    /**
     * Formats numbers to add commas
     * @method addCommas
     * @param nStr
     * @returns string
     */
    addCommas : function(nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    },
    /**
     * Retrieves a param from url query based on passed in name
     *
     * @param name
     *            of param to look for
     * @return value of param or '' if it doesnt find it
     */
    getQueryAttr : function(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results === null) {
            return '';
        } else {
            return results[1];
        }
    },
    /**
     * Get query string by name copied from
     * http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
     */
    getParameterByName : function(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results === null) {
            return "";
        } else {
            return decodeURIComponent(results[1].replace(/\+/g, " "));
        }
    },
    /**
     *  Browser safe debug statement Copied from
     * http://www.onelineofcode.net/code/safeconsolelogging
     * @method debug 
     * @param obj
     * @param label
     *            Optional, displays the debug with a label line before it
     */
    debug : function(/* object */obj, /* String */label) {
        // When the site goes to production, we should disable this on prod or
        // add in some secured parameter for log messages
        if (window.console) {
            if (label) {
                console.log(label);
            }
            console.log(obj);
        }
    },
    /**
     * Method to get the url parameter from the URL
     * @method getUrlParameter
     * @param sParam
     * @returns string
     */
    getUrlParameter : function(sParam) {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++) {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam) {
                LN.debug(sParam, "paramName");
                LN.debug(sParameterName[1], "paramValue");
                return sParameterName[1];
            }
        }
    },
    /**
     * @method secondsToTime
     * @param secs
     * @returns object
     */
    secondsToTime : function(secs) {
        var hours = Math.floor(secs / (60 * 60));
        var divisor_for_minutes = secs % (60 * 60);
        var minutes = Math.floor(divisor_for_minutes / 60);
        var divisor_for_seconds = divisor_for_minutes % 60;
        var seconds = Math.ceil(divisor_for_seconds);
        var obj = {
            "h" : hours,
            "m" : minutes,
            "s" : seconds
        };
        return obj;
    },
    /**
     * @method isDate
     * @param dateStr
     * @returns {Boolean}
     */
    isDate : function(dateStr) {
        var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
        var matchArray = dateStr.match(datePat); // is the format ok?
        if (matchArray === null) {
            return false;
        }
        month = matchArray[1]; // p@rse date into variables
        day = matchArray[3];
        year = matchArray[5];
        if (month < 1 || month > 12) { // check month range
            return false;
        }
        if (day < 1 || day > 31) {
            return false;
        }
        if ((month === 4 || month === 6 || month === 9 || month === 11)
                && day === 31) {
            return false;
        }
        if (month === 2) { // check for february 29th
            var isleap = (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0));
            if (day > 29 || (day === 29 && !isleap)) {
                return false;
            }
        }
        return true; // date is valid
    },
    /**
     * @method validateDate
     * @param dateFormat
     * @param strDate
     * @returns
     */
    validateDate : function(dateFormat, strDate) {
        if (dateFormat !== "mm/dd/yyyy") {
            var dates = strDate.split("/");
            var year = dates[2];
            var month = dates[1];
            var day = dates[0];
            strDate = month + "/" + day + "/" + year;
        }
        if (this.isDate(strDate)) {
            var strDates = strDate.split("/");
            var date = new Date();
            date.setFullYear(strDates[2], strDates[0] - 1, strDates[1]);
            return date;
        }
        return null;
    },
    /**
     * @method deepCopy
     * @param object
     * @returns
     */
    deepCopy : function(object) {
        return jQuery.extend(true, {}, object);
    },
    /**
     * @method validateForm
     * @param formId
     * @param componentId
     * @param errorType
     * @param errMesg
     * @returns
     */
    validateForm : function(formId, componentId, errorType, errMesg) {
        var validator = $("#" + formId)
                .validate(
                        {
                            highlight : function(input) {
                                $(input).addClass("ui-state-error");
                            },
                            unhighlight : function(input) {
                                $(input).removeClass("ui-state-error");
                                $(input).parents('.addressValue').parents(
                                        ".formField").removeClass(
                                        "ui-state-error");
                            },
                            errorElement : "span",
                            wrapper : 'div',
                            errorClass : "fieldError",
                            errorPlacement : function(error, element) {
                                var errorIcon = '<span class="ui-icon ui-icon-circle-arrow-n inline-error-icon"/>';
                                error.prepend(errorIcon).appendTo(
                                        element.parent());
                                error.addClass('ui-state-error');
                            },
                            invalidHandler : function(form, validator) {
                                var errors = validator.numberOfInvalids();
                                if (errors) {
                                    LN.getPage().clearAllComponentMessages(
                                            componentId);
                                    LN.getPage().displayStatusMessage(
                                            componentId, formId.toUpperCase(),
                                            errorType, errMesg);
                                }
                            }
                        });
        return validator;
    },
    /**
     * function to set the context path of the application
     * @method - Global method to set the context path to be used in all javascript
     * @param ctxPath
     */
    setContextPath : function(ctxPath) {
        var cs = this;
        cs.contextPath = ctxPath;
    },
    /**
     * Returns the context path of the application (e.g. /phm)
     * @method getContextPath
     * @returns  string
     */
    getContextPath : function() {
        var cs = this;
        return cs.contextPath;
    },
    getAppContextPath : function(context) {
        var cs = this;
        return window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '')+'/'+context;
    },
    // pagelevel help
    setUpHelp : function(hlpId){
    	$(hlpId).click(function(event) {
    		event.preventDefault();
    		window.open(LN.getHelpPath(), "popuphelpWindow",
            "width=800,height=600,scrollbars=yes,menubar=no,location=no,top=200,left=400,resizable=1"); 
        });
    },
    // container level help
    loadContainerHelp : function(){
    	// note: HelpPath and click function for container help is set in controlling JS pages. ie... measurecompliance.js
		event.preventDefault();
		window.open(LN.getHelpPath(), "popuphelpWindow",
        "width=800,height=600,scrollbars=yes,menubar=no,location=no,top=200,left=400,resizable=1"); 
    },
    /**
     * Function to set the help path for the application
     * @param helpPath
     */
    setHelpPath : function(baseHelpPath, helpPath) {
    	var cs = this;
    	cs.baseHelpPath = baseHelpPath;
    	cs.helpPath = helpPath;
    },
    /**
     * Function to return the help path
     * @returns the help path location
     */
    getHelpPath : function() {
    	var cs = this;
    	return cs.contextPath + cs.baseHelpPath + window.location.search + cs.helpPath;
    },
    /**
     * Function to get help messages from HelpMessageController
     * @method getHelpMessageAjax
     */
    getHelpMessageAjax :function(helpMsgkey) {
    	LN.debug("******* Inside LN.getHelpMessageAjax ******* "+helpMsgkey);
    	//Flag if ajax is already running and don't call
    	var cs=this;
        if(cs.data.isInAjaxCall) {
      	  return;
        }
    	var helpMessage = $.ajax({
    		'url'	: LN.getContextPath()+"/getHelpMessages",
    		'method' : 'GET',
    	    'datatype' : "json",
    	    'async' : false,
    	    'contentType' : "application/json; charset=utf-8",
    	    'data' : { 
    	        'key' : helpMsgkey
    	    },        	    
    	    'success' : function(result) {
    	    	cs.data.isInAjaxCall=false;
    	    }, 
    		'error' : function(result) {
    			cs.data.isInAjaxCall=false;
    		},
    	    'beforeSend': function() {
            	cs.data.isInAjaxCall=true;
    	    },
    	    'complete' : function() {
                cs.data.isInAjaxCall=false;
    	    }
    	});
    	LN.debug("******* Inside LN.getHelpMessageAjax : End *******$"+JSON.stringify(helpMessage)+"$");
    	
    	if(helpMessage.status != 200){
    		return "Error Getting help message";
    	}
    	if(helpMessage.responseText == ""){
    		return "Help message not yet defined";
    	}
    	return helpMessage.responseText;
    },
    /**
     * Method to post the ajax query in addition to showing the ajax indicator
     * on target div
     * @method ajaxPostJSON
     * @param targetDiv -
     *            the parentDiv into which the data will be loaded
     * @param url -
     *            the AJAX URL to be invoked
     * @param arrParams -
     *            pass an array of parameters
     * @param funcCallBack -
     *            the call back method which will be called on success of the
     *            ajax
     * @returns
     */
    ajaxPostJSON : function(targetDiv, url, dataVal, funcCallBack, callBackScope) {
        // Iterate over the params and add to the data
        $.ajax({
            'url' : url,
            'contentType' : 'application/json',
            'dataType' : 'json',
            'method' : 'post',
            // This parameter will override the global
            'global' : false,
            'beforeSend' : function(xhr) {
                // hide all the children and display background
            	xhr.setRequestHeader('X-TransactionID', LN.TRANSACTION_ID);
                LN.showAjaxIndicator(targetDiv);
            },
            'data' : dataVal,
            'success' : function(data, textStatus, jqXHR) {
                funcCallBack(callBackScope, data, textStatus);
            },
            'error' : function(jqXHR, textStatus, errorThrown) {
                LN.showError(targetDiv);
            },
            'complete' : function(jqXHR, textStatus) {
                // Show all the children when either a success or an error.
                LN.hideAjaxIndicator(targetDiv);
                if (callBackScope != null && callBackScope.callbackComplete != null && typeof(callBackScope.callbackComplete) == 'function'){
                	callBackScope.callbackComplete(jqXHR, textStatus);
                }
            }
        });
    },
    /**
     * Shows opaque ajax indicator
     * @method showOpaqueAjaxIndicator
     * @param targetDiv
     */
    showOpaqueAjaxIndicator : function(targetDiv) {
        /*US 252 - Defect Fix for the transparency occurrence while filters are applied after page scroll*/
        $(targetDiv).children().css("visibility", "hidden");
    	$(targetDiv).css('background', 'url("'+LN.getContextPath()+'/resources/default/images/ajax-loader.gif") no-repeat center center');
    },
    /**
     * @method hideOpaqueAjaxIndicator
     * @param targetDiv
     */
    hideOpaqueAjaxIndicator : function(targetDiv) {
        /*US 252 - Defect Fix for the transparency occurrence while filters are applied after page scroll*/
        $(targetDiv).css('background', '');
        $(targetDiv).children().css("visibility", "visible");
    },
    /**
     * @method showAjaxIndicator
     * @param targetDiv
     */
    showAjaxIndicator : function(targetDiv) {
        $(targetDiv).children().css("visibility", "hidden");
        $(targetDiv).css('background', 'url("'+LN.getContextPath()+'/resources/default/images/ajax-loader-big.gif") no-repeat center center');
    },
    /**
     * @method hideAjaxIndicator
     * @param targetDiv
     */
    hideAjaxIndicator : function(targetDiv) {
        $(targetDiv).css('background', '');
        $(targetDiv).children().css("visibility", "visible");
    },
    //Check if function keys are pressed to avoid further processing Starts
    isFnKeyPressed : function(e) {
 		var code = (e.keyCode || e.which);
 		if(fnKeys.indexOf(code)!=-1) {
 			return false;
 	    } else {
 	    	return true;
 	    }
    },
    /**
     * shows error message in the div
     * @method showError
     * @param targetDiv
     */
    showError : function(targetDiv) {
        $(targetDiv).css('background', 'none');
        $(targetDiv).html(
                '<div style="align:center">' + LN.ajaxErrMesg + '</div>');
    },
    /**
     * function to register for the data set change
     * The method does:
     * 1. Updates the patient count
     * 2. Sends an event
     */
    registerDataSetChange : function() {
        var cs = this;
        $('#dataSet').on(
                'change',
                function() {
                    var dataVal=JSON.stringify({'dataSet': $('#dataSet').val()});
                    LN.ajaxPostJSON($('#ln_viewPopulationText'), 'getPatientsCount', dataVal, cs.dataSetChangeCallBack, cs);
                });
    },
    dataSetChangeCallBack : function(cs) {
        LN.getPage().pushEvent(EVENT_TYPES.ON_DATASET_CHANGE);
    },
    callWebServiceWithRetry : function(cs,funcCallBack) {
       		try {
       			setTimeout(function() {
       				funcCallBack(cs);
       			}, 3000);
       		} catch(err) {
       			LN.debug("error occured..retrying");
       			setTimeout(function() {
       				funcCallBack(cs);
       			}, 3000);
       		}
       } , 
    //To ignore Special Charactes  
    containsSpecialCharacters : function(text) {
           var pattern = new RegExp(/[*<>{}()+=\~\`&%\!\^#!:;\'\"\@\[\]\/\\\?\|]/);
           if (pattern.test(text)) {
                  return true;
           }
           return false;
    },
    //To allow only Numbers
    isNumberKey : function (evt){
       var charCode = (evt.which) ? evt.which : evt.keyCode;
       if (charCode != 46 && charCode > 31 
         && (charCode < 48 || charCode > 57))
          return false;

       return true;
    },
    
    getSAMLAssertion: function(cs,successCallbackFn,contextPath){
    	var urlStr = LN.getContextPath() + '/getsamlassertion';
    	$.ajax({
    		url: urlStr,
    		method: 'GET',
    		cache : false,
    		success: function(samlString){	
    			successCallbackFn(cs,samlString);
    		}, error: function(err){
    			LN.debug('error occurred getting SAML assertion '+err);
    			successCallbackFn(cs,'');  
    		}
    	});
    }
    
    
       //End of function logRenderTime
    
};
$(document).ready(function() {
    //setting a global timeout for hte ajax calls
    $.ajaxSetup({
        //Time in milliseconds
        timeout: 240000
    });
    try {
        console.log("loading components");
    } catch (e) {
        window.status=e;
    }
    LN.ready();
    //Unblock the UI on ajax error
    $(document).ajaxError(function(err){
    	LN.debug("ajax error is : "+err);
    	LN.isAjaxError=true;
    	$.unblockUI();
      });
    
    
});



/**
 * unblock the UI after everything is loaded
 */