/** * * Copyright (c) 2013 OCR Services Inc * Author(s) Jinesh Gopinathan, George Anil John */ var smartHintsLabels; var CURRENT_MODULE; $(document).ready(function(){ $(document).keypress(function(event){ var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode == '13'){ var textareabox = $("textarea"); var selectbox = $("select"); var hyperlink = $("a"); if ($('.modal-backdrop').length == 0){ $(this).find(".form-content").find(".primary-btn:first:enabled").each(function(index){ if (textareabox.is(':focus') || selectbox.is(':focus') || hyperlink.is(':focus')){ return false; }else{ $(this).trigger('click').change(); return false; } }); }else if($('.modal-backdrop').length > 0){ $(document).find(".modal-dialog").find(".recordFromPopup:first, .popupSearchButton,.popupSearchButtonUserProf").each(function(index){ if (textareabox.is(':focus') || selectbox.is(':focus') || hyperlink.is(':focus')){ return false; }else if ($(this).hasClass('recordFromPopup') && $('#resultDIV').css('display') == 'block'){ $(this).trigger('click').change(); return false; }else if ($(this).hasClass('popupSearchButton') && $('#searchDIV').css('display') == 'block'){ $(this).trigger('click').change(); return false; }else if ($(this).hasClass('popupSearchButtonUserProf') && $('#searchDIV').css('display') == 'block'){ $(this).trigger('click').change(); return false; } }); } } }); }); if (!jQuery) {throw new TypeError("jQuery is required.");}; ;(function ($, window, document, undefined) { 'use strict'; var smartHintsLabelsHrd = { "countryName": "Country Name", "isoCode": "ISO Code", "customCode": "Custom Code", "specialProgramName": "Special Program Name", "specialProgramIndicator": "Special Program Indicator", "officeTitle": "office Title", "code": "Code", "description": "Description", "name": "name", "warehouseCode": "warehouseCode" }; if(typeof smartHintsLbls !== "undefined" && smartHintsLbls){ smartHintsLabels = smartHintsLbls; }else{ smartHintsLabels = smartHintsLabelsHrd; } var DEFUALT_COUNTRY_CODE = ''; var countrySmartFieldData = null; var countryJson = null; var uomSmartFieldData = null; var maxExportExcelSize = null; var maxExportExcelErrMsg = null; var filteredCountriesSmartData = null; var US_DATE_FORMAT = 'mm/dd/yy'; var US_DATE_FORMAT_PLACEHOLDER = 'MM/DD/YYYY'; var GRID_US_DATE_FORMAT = 'm/d/Y'; // put module name on which US-DF is needed. var modules = ['LES','CRS','ELAIN','FTZ','CIT','TDEA','DRS','TRNG','PCS','GTC','NRC','OFAC']; var moduleName = $('#moduleName'); var enableUDF = true; if(moduleName && moduleName.length > 0){ moduleName = $(moduleName).val(); } /* PRJ-645: FLEX FIELDS FILE SELECTORS */ var SmartFieldDataRTF = null; var filteredSmartDataRTF = null; /* Subtask#4392 Date format globalization: Defining global variables to globalize dates of GRID, Date Picker etc. */ var userDateFormat = US_DATE_FORMAT; var placeHolderDateFormat = US_DATE_FORMAT_PLACEHOLDER; var gridDateFormat = GRID_US_DATE_FORMAT; var dateFormats = $('#userDateFormat').val(); var countryGroupSmartFieldData = null; var commonLoadText = null; if(dateFormats){ var formats = JSON.parse(dateFormats); placeHolderDateFormat = formats.defaultDateFormat.toUpperCase(); userDateFormat = formats.defaultJSDateFormat; gridDateFormat = formats.defaultGridDateFormat; } /* Process request */ var ProcessRequest = { name : 'OCR-JS', version : '1.0.0', defaults: { role: '', url: '', dismiss: '', source: '', target: '', before: null, complete: null, //Call back functions error: null, data: null, processData: true, avoidModalOnFormProcess: true, avoidPopupOverPopup: false, contentType: 'application/x-www-form-urlencoded; charset=UTF-8', asyncProcessing:true, }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend({}, this.defaults, options); this._build(); return this; }, _build: function(){ this.fromData(); this.process(); }, fromData: function(){ //PRJ-3084(SUBTASK-4487) Number format by Mukesh Singh /*if($.numberFormat){ $.numberFormat.setUnformattedNumber(); }*/ var self = this.$element; if(this.options.role == ''){ this.options.role = self.data('ocr-role'); if(!this.options.role){ this.options.role = 'ajax-link'; } } if(this.options.role == 'native-form'){ this.options.role = 'ajax-form'; } if(this.options.role == 'native-link'){ this.options.role = 'ajax-link'; } if(this.options.url == ''){ this.options.url = self.data('ocr-url'); if(!this.options.url){ var link = self.attr('href'); if(link && link != '#'){ this.options.url = link; } else { link = self.attr('action'); if(link && link != '#'){ this.options.url = link; } } } } /* Added by Anil Jaglan to set 'data-ocr-refresh' attribute in options array */ this.options.refresh = self.data('ocr-refresh'); /* manipulating urls if required : Rakesh Arora*/ this.options.url = $.manipulateUrlForCountrycodes({url: this.options.url}); if(this.options.source == ''){ this.options.source = self.data('ocr-source'); } if(this.options.target == ''){ this.options.target = self.data('ocr-target'); } if(this.options.dismiss == ''){ this.options.dismiss = self.data('ocr-dismiss'); } if(!this.options.url || this.options.url == ''){ throw new Error('The link is invalid. '+ this.options.url); } /*if (self.data('ocr-avoidpopupoverpopup') != '') { this.options.avoidPopupOverPopup = self.data('ocr-avoidpopupoverpopup'); }*/ if (self.data('avoidpopupoverpopup') == '') { this.options.avoidPopupOverPopup = self.data('ocr-avoidpopupoverpopup'); } }, process: function() { if(this.options.role == 'frame-link'){ this.iframe(); } else if(this.options.role == 'tab-link'){ this.showLoader(); this.loadTabContent(); } else { this.showLoader(); this.xhrRequest(this.serializeData()); } }, iframe: function(){ if($.hasValue(this.options.url)){ $('#content-cont').html('').addClass('hidden'); $('.footer-bar').addClass('hidden'); $('#frame-cont').removeClass('hidden'); $('#frame-cont iframe').css('display','block').trigger('resize').attr("src", this.options.url); } }, showLoader: function(){ var self = this.$element; this.$backdrop && this.$backdrop.remove(); this.$backdrop = $('
').insertAfter(document.body); /* make ajax call to get the loading text data */ if(!commonLoadText){ $.ajax({ url : "/vrsportal/getLoadingText.ocr", dataType : "json", cache: false, async: false, success : function(data) { commonLoadText = data.loadingText; } }); } $(".loader-cont .loader-info").html(' '); $(".loader-cont").removeClass('hidden'); if (this.options.role == 'modal-form') { $(self).closest('.modal-loader').removeClass('hidden'); } return this; }, serializeData: function(){ var self = this.$element; var tagType = null; var data = this.options.data; if(this.options.source != null && $.hasValue(this.options.source)){ self = $(this.options.source); } tagType = self.prop("tagName"); /* If data is provided, then don't fetch the data from the form */ if(tagType == 'FORM' && !data){ $.each(self, function(i, value) { var $tempObj = $(value); /*PRJ-75:TextArea having ignoreTrim cssclass to be ignored from trim */ $tempObj.find('input:text, textarea:not(.ignoreTrim)').each(function(){ $(this).val($.trim($(this).val())); }); }); data = self.serialize(); if(data != null){ //replace CRLF with LF data=data.replace(/%0D%0A/g,'%0A'); } } return data; }, /*PRJ-3084(SUBTASK-4487) Number format by Mukesh Singh * Further Enhanced the number format framework. */ manipulateNumberFields: function(data){ var decimalFields = $('.decimal-formatter'); var nonDecimalFields = $('.nondecimal-formatter'); if(data && $.numberFormat && typeof data != 'object'){ if(decimalFields.length > 0 || nonDecimalFields.length > 0){ var dataArrs = []; var dataArr = data.split('&'); $.each(dataArr, function(index, val){ var valArr = val.split('='); var dataValuesArr = [valArr[0], valArr[1]]; dataArrs.push(dataValuesArr); }); if(decimalFields.length > 0){ $.each(decimalFields, function(index, $obj){ if($($obj).val()){ var unformatted_val = $.numberFormat.getUnformattedNumber({number: $($obj).val()}); $.each(dataArrs, function(indx, val){ if(val && $($obj).attr('name') == val[0]){ dataArrs[indx] = [val[0], unformatted_val]; } }); } }); } if(nonDecimalFields.length > 0){ $.each(nonDecimalFields, function(index, $obj){ if($($obj).val()){ var unformatted_val = $.numberFormat.getUnformattedNumber({number: $($obj).val(), isDecimal: false}); $.each(dataArrs, function(indx, val){ if(val && $($obj).attr('name') == val[0]){ dataArrs[indx] = [val[0], unformatted_val]; } }); } }); } data = ''; var i = 0; $.each(dataArrs, function(index, val){ if(i == dataArrs.length-1){ data += val[0]+'='+val[1]; }else{ data += val[0]+'='+val[1]+'&'; } i++; }); } } return data; }, setEnableUDF:function(response){ var enableUDF = true; try{ var enableUDFVal = $(response).find('[name="enableUDF"]').val(); if(moduleName){ if(modules.join(',').indexOf(moduleName)> -1){//Used for minimal user date format required in any module enableUDF = false; if(enableUDFVal == 'Y'){//Put Y in hidden field value if UDF needed enableUDF = true; } }else {//Used for minimal US date format required in any module if(enableUDFVal == 'N'){//Put N in hidden field value if US-DF needed enableUDF = false; } } } }catch(e){} this.enableUDF = enableUDF; }, xhrRequest: function(data) { var that = this; data = this.manipulateNumberFields(data); $.ajax({ context: document.body, data: data, dataType: 'html', type: 'POST', processData: that.options.processData, contentType: that.options.contentType, url: this.options.url, timeout: 300000, async:that.options.asyncProcessing, success: function(response) { that.setEnableUDF(response); if($.isFunction(that.options.complete)){ that.options.complete.call(that, response); } else { try{ that.loadResponse(response); } catch(e){ that.showErrors(e,"success"); } } that.removeLoader(); that.initMultiCountry(); that.initMultiCountryCode(); that.initializeSmartHints(); that.initializeScreen(); /* disable the online help for now - Rakesh */ that.fieldHelpContent(); /* initialize online help, if there is a requirement */ try{ var initOnlineHelp = window["initOnlineHelp"]; if(typeof initOnlineHelp === 'function'){ var $targetContainer = null; if(that.options.role.indexOf('modal') < 0){ /* not a modal */ $targetContainer = $('#content-cont'); }else{ /* its modal */ $targetContainer = that.$element.closest('.ocr-modal-cont').find('.modal'); } var returnObj; initOnlineHelp.call(returnObj, that.options.url, $targetContainer); } }catch(e){ console.log(e.message); } /* calling for initializing external smarthints */ var externalSmartHint = window["initializeHintsOnReady"]; if(typeof externalSmartHint === 'function'){ externalSmartHint.call(); } }, error: function(jqXHR, textStatus, errorThrown) { if(textStatus ==="timeout") { that.timeOut(); that.showErrors(errorThrown,"timeout"); } else { that.removeLoader(); that.showErrors(errorThrown,"error",jqXHR.status); } } }); }, showErrors : function(errorThrown,type,status){ var errors =[]; var message = ""; if(type=="error"){ if(status=="0"){ message="Server encountered an error. Please try again."; }else{ message=" HTTP Status "+status+" - The server encountered an internal error and was unable to complete your request. Please provide the log under Tools -> Server Logs -> tomcat-ocr.log."; } }else if(type=="timeout"){ message="Request has timed out. If applicable, please narrow the search criteria and try again. Otherwise, please contact your system administrator."; } else { message="Unable to process the request due to error in script"; } errors.push({msg:message}); if(this.options.role.indexOf('modal') != -1){ var self = this.$element; var tagType = self.prop("tagName"); var modalCont = null; if(tagType == 'FORM' && this.options.avoidModalOnFormProcess){ modalCont = self.closest('.ocr-modal-cont'); } else { modalCont = self.closest('.ocr-modal-base').find('.ocr-modal-cont:first'); if(modalCont.length < 1){ modalCont = self.closest('#content-cont').find('.ocr-modal-cont:first'); if(modalCont.length < 1){ modalCont = self.closest('body').find('.ocr-modal-cont:last'); } } } if(modalCont.find('.modal').hasClass('in')){ if(modalCont.find('.ocr-error').length > 0){ $(modalCont.find('form')).processMsg({errors:errors}); }else{ alert(message); } }else{ $(this).processMsg({errors:errors}); } }else{ $(this).processMsg({errors:errors}); } console.error(errorThrown); }, loadResponse: function(response){ var self = this.$element; var that = this; var contCont = $('#content-cont'); var frameCont = $('#frame-cont'); if(this.options.role.indexOf('modal') < 0){ if(!frameCont.hasClass('hidden')){ $('#frame-cont iframe').css('display','hidden').attr("src", "about:blank"); frameCont.addClass('hidden'); } if(contCont.hasClass('hidden')){ contCont.removeClass('hidden'); $('.footer-bar').removeClass('hidden'); } contCont.empty().html(response).processMsg().trigger('resize'); $('#lastUsedLink_').val(this.options.url); this.afterResponseLoad(); }else { var tagType = self.prop("tagName"); var modalCont = null; var modalObj = null; var isHidden = true; if(tagType == 'FORM' && this.options.avoidModalOnFormProcess){ modalCont = self.closest('.ocr-modal-cont'); } else { modalCont = self.closest('.ocr-modal-base').find('.ocr-modal-cont:first'); if(modalCont.length < 1){ modalCont = self.closest('#content-cont').find('.ocr-modal-cont:first'); if(modalCont.length < 1){ modalCont = self.closest('body').find('.ocr-modal-cont:last'); } } } if(this.options.dismiss == 'close'){ this.options.clickedCancel = true; modalCont.find('.modal').modal('hide'); }else { /* TODO: need to review this code block: popup on popup POC work */ modalCont.find("#gridPopup").jqGrid("GridUnload"); if(!modalCont.find('.modal').is(":hidden") && !this.options.avoidPopupOverPopup){ try{ if($(".archivedPopups").length == 0 || $(".archivedPopups:last").html().length > 0) $("#content-cont").append(""); /* backup the form state into json */ var formbackup = modalCont.find('.modal').closest(".ocr-modal-cont form").jsonify(); $(".archivedPopups:last").html(modalCont.find('.modal').closest(".ocr-modal-cont").html()); /* restore the form state from its json data */ $(".archivedPopups:last form").loadJSON(formbackup); modalCont.find('.modal .modal-content').addClass("backedUp"); }catch(ex){} } /* End: popup on popup POC changes */ modalObj = modalCont.find('.modal:first'); if(modalObj.length > 0 && modalObj.css('display') == 'block'){ isHidden = false; } if(isHidden){ modalCont.empty().html(response).processMsg().find('.modal:first').modal({backdrop: 'static'}) .initializeDatePickers({jqueryDateFormat:{datePickerFormat: userDateFormat, placeHolderFormat: placeHolderDateFormat}, enableUDF:that.enableUDF}) .ocrSmartHints(); } else { modalCont.find('.modal').modal('hide'); if($('html').hasClass('lt-ie9')||$('html').hasClass('lt-ie10')){//IE8,IE9 fix modalCont.empty().html(response).processMsg().find('.modal:first').modal({backdrop: 'static'}) .initializeDatePickers({jqueryDateFormat:{datePickerFormat: userDateFormat, placeHolderFormat: placeHolderDateFormat}, enableUDF:that.enableUDF}).ocrSmartHints(); } else { modalCont.find('.modal').on('hidden.bs.modal', function (){ modalCont.empty().html(response).processMsg().find('.modal:first').modal({backdrop: 'static'}) .initializeDatePickers({jqueryDateFormat:{datePickerFormat: userDateFormat, placeHolderFormat: placeHolderDateFormat}, enableUDF:that.enableUDF}).ocrSmartHints();; }); } } } } }, afterResponseLoad: function(){ if(this.options.role.indexOf('modal') < 0){ /* Used to remove double spaces from the page heading */ var heading = $('.page-heading h3').length == 0 ? $('.page-heading').contents() : $('.page-heading h3').contents(); if(heading != undefined && heading[0] != undefined && heading[0].nodeValue != undefined){ heading[0].nodeValue = $.trim(heading[0].nodeValue.replace(/\s(\s+)/g, ' ')); } if($('#scrollTarget_').length != 0 && $('#scrollTarget_').val() != ""){ var target = $($('#scrollTarget_').val()); $('html, body').animate({ scrollTop: target.offset().top }, 'slow'); } else { $("#go-top").trigger("click"); } } }, removeLoader: function(){ $(".loader-cont").addClass('hidden'); this.$backdrop && this.$backdrop.remove(); this.$backdrop = null; }, fieldHelpContent:function(){ var globalUserRole=$("input:hidden[name=globalUserType]").val(); var self = this; var screenUrl=''; var iconTag = "
"; var $targetContainer = null; var fullScreenUrl=self.options.url; if(self.options.role.indexOf('modal') < 0){ /* not a modal */ $targetContainer = $('#content-cont'); }else{ /* its modal */ $targetContainer = self.$element.closest('.ocr-modal-cont').find('.modal'); } var $targetContainerVar=$targetContainer; screenUrl=fullScreenUrl.substring(0,fullScreenUrl.indexOf('.')); $targetContainer.find(".form-control").each(function(){ var $formElement = $(this); var $helpIcon = $(iconTag); $targetContainer.find(".form-control").closest('div').css('position','relative'); $formElement.after($helpIcon); //Temporary fix for date picker Help Icon alignment. if($formElement.hasClass("ocr-date")){ $helpIcon.children().css('right','0px !important'); } $helpIcon.on('click', function(){ var fName=$helpIcon.parent().find(':input').attr('name'); var newUrl = '/user/openFieldConfigurationPopup.ocr?screenUrl='+screenUrl+'&fieldName='+fName; $(this).processRequest({ url: newUrl, role: 'modal-link', });; }); }); self.setupfieldHelpContent(screenUrl,$targetContainerVar,globalUserRole); $targetContainer.find(".form-control").each(function(){ var $formElement = $(this); if(globalUserRole!='CORP'){ if($formElement.parent().find('a').hasClass('helpIcon')){ $formElement.parent().find('a').remove(); }else{ $formElement.parent().find('a').off('click'); } }else{ if($formElement.parent().find('a').hasClass('helpIcon')){ $formElement.parent().find('a').removeAttr('data-tooltip'); } } }); }, setupfieldHelpContent: function(screenUrl,$targetContainerVar,globalUserRole){ var newUrl = '/user/setupfieldHelpContent.ocr?screenUrl='+screenUrl; $.ajax({ }); }, timeOut: function(){ this.removeLoader(); }, initializeSmartHints: function(){ $(document).ocrSmartHints({targetURL:this.options.url}); }, initMultiCountry: function(){ this.$element.initMultiCountry(); }, initMultiCountryCode: function(){ this.$element.initMultiCountryCode(); }, getJqueryDateFormat: function(dateFormat){ var dateFormat = {datePickerFormat: userDateFormat, placeHolderFormat: placeHolderDateFormat}; /*if(dateFormat == 'mm/dd/yyyy'){ dateFormat.datePickerFormat = 'mm/dd/yy'; dateFormat.placeHolderFormat = 'MM/DD/YYYY'; }else{ dateFormat.datePickerFormat = 'mm/dd/yy'; dateFormat.placeHolderFormat = 'MM/DD/YYYY'; }*/ return dateFormat; }, initializeScreen: function(){ var self = this; $(document).initializeDatePickers({jqueryDateFormat: self.getJqueryDateFormat('dd/M/yy'), enableUDF:self.enableUDF}); self.loadFlagFields(); }, loadFlagFields: function(){ var self = this; /* todo: need to init the flag fields plugin here */ $("[data-ocr-type='flagField']:not(.flag-field)").ocrFlagFields({}); }, loadTabContent: function() { var tab = this.options.target + ' .col-xs-12:first'; var targetContainer = $(tab); var that = this; $(".tab-menu .popover-content li a").removeClass('active'); $(this.$element).addClass('active'); /* added support for refresh the tab on demand, * also added support for confirmed refreshing a tab */ if (!this.options.refresh && $.trim(targetContainer.html()).length > 0 ) { $('.tab-content').removeClass('active'); targetContainer.parent().addClass('active').trigger('resize'); //targetContainer.addClass('active').trigger('resize'); if($.isFunction(that.options.complete)){ that.options.complete.call(that, null); } /* Monu: This will resize the grids present in the tab */ var grid; if (grid = $('.ui-jqgrid-btable:visible')) { grid.each(function(index) { var gridId = $(this).attr('id'); var gridParentWidth = $('#gbox_' + gridId).parent().width(); $('#' + gridId).setGridWidth(gridParentWidth); }); } this.removeLoader(); } else { $('.tab-content').removeClass('active'); $.ajax({ context: document.body, dataType: 'html', type: 'POST', url: this.options.url, timeout: 9000, async: that.options.asyncProcessing, success: function(response) { that.setEnableUDF(response); if($.isFunction(that.options.complete)){ that.options.complete.call(that, response); } //$('.tab-content').removeClass('active'); targetContainer.empty().html(response).processMsg(); /* Adding active URL as a marker for which url, this div is loaded, so that if the url changes, we need to reload the rab */ targetContainer.parent().addClass('active').trigger('resize'); that.removeLoader(); that.initMultiCountry(); that.initMultiCountryCode(); that.initializeSmartHints(); that.initializeScreen(); }, error: function(jqXHR, textStatus, errorThrown) { if(textStatus ==="timeout") { that.timeOut(); } else { throw new Error(errorThrown); } } }); } } }; /* Dhermi: Fix for Date picker modal popup on chrome and mozilla browsers, requested by Rocky * It was broken on these browsers because browsers compatibilities for the date pickers * */ $.fn.modal.Constructor.prototype.enforceFocus = function() {}; /* Process Error and Java Script Messages. */ var ProcessMsg = { name : 'OCR-JS', version : '1.0.0', defaults: { errors : [], warnings : [], info: [] }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend({}, this.defaults, options); this._build(); return this; }, _build: function(){ this.checkTagsPresent(); this.showMsg(); }, checkTagsPresent: function(){ var self = this.$element; var options = this.options; var baseCont = null; var hasAlert = false; if(self.closest('.ocr-modal-cont') .length < 1){ baseCont = $('#content-cont'); } else { baseCont = self.closest('.ocr-modal-cont'); } if(baseCont == null){ baseCont = self; } this.$parentContainer = baseCont; baseCont.find('.form-control').removeClass("form-error"); baseCont.find('.form-control').removeClass("form-warning"); if($.hasValue(options.errors) && options.errors.length > 0){ var $errorTag = baseCont.find('.ocr-error:first'); if($errorTag.find('.alert-danger').length < 1){ $errorTag.find('.col-xs-12').append('
'+ '×

Error

'); } if($errorTag.find('.alert-danger ul').length < 1){ $errorTag.find('.alert-danger').append(''); } $errorTag.find('.alert ul li').remove(); $.each(options.errors, function(i, value) { var errorMsg = value.msg; baseCont.find(value.element).addClass('form-error'); if($.hasValue(errorMsg)){ $errorTag.find('.alert-danger ul').append( '
  • '+errorMsg+'
  • '); } }); hasAlert=true; } if($.hasValue(options.warnings) && options.warnings.length > 0){ var $warnTag = baseCont.find('.ocr-warning:first'); if($warnTag.find('.alert').length < 1){ $warnTag.find('.col-xs-12').append('
    '+ '×

    Warning

    '); } if($warnTag.find('.alert ul').length < 1){ $warnTag.find('.alert').append(''); } $warnTag.find('.alert ul li').remove(); $.each(options.warnings, function(i, value) { var warMsg = value.msg; baseCont.find(value.element).addClass('form-warning'); if($.hasValue(warMsg)){ $warnTag.find('.alert ul').append( '
  • '+warMsg+'
  • '); } }); hasAlert=true; } if($.hasValue(options.info) && options.info.length > 0){ var $infoTag = baseCont.find('.ocr-info:first'); if($infoTag.find('.alert').length < 1){ $infoTag.find('.col-xs-12').append('
    '+ '×

    Information

    '); } if($infoTag.find('.alert ul').length < 1){ $infoTag.find('.alert').append(''); } $infoTag.find('.alert ul li').remove(); $.each(options.info, function(i, value) { var infoMsg = value.msg; if($.hasValue(infoMsg)){ $infoTag.find('.alert ul').append( '
  • '+infoMsg+'
  • '); } }); hasAlert=true; } if(hasAlert){ $("#go-top").trigger("click"); } }, showMsg: function(){ var baseCont = this.$parentContainer; if($.trim(baseCont.find('.ocr-error:first .alert-danger ul').text()).length > 0){ baseCont.find('.ocr-error:first').removeClass('hidden'); } else { baseCont.find('.ocr-error:first').addClass('hidden'); } if($.trim(baseCont.find('.ocr-warning:first .alert ul').text()).length > 0){ baseCont.find('.ocr-warning:first').removeClass('hidden'); } else { baseCont.find('.ocr-warning:first').addClass('hidden'); } if($.trim(baseCont.find('.ocr-info:first .alert ul').text()).length > 0){ baseCont.find('.ocr-info:first').removeClass('hidden'); } else { baseCont.find('.ocr-info:first').addClass('hidden'); } } }; var stateDataArray = []; var ocrSmartHints = { name : 'OCR-JS', version : '1.0.0', defaults: { targetURL: '', }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend(true, {}, this.defaults, options); this._build(); return this; }, _build: function(){ this.setupAutoCompleter(); /* this will create custom widget */ /* TODO: this method call can be removed in future */ this.setupSmartCountry(); /* This will automatically setup the country populator configuration, at places we have not configured yet */ this.initializeCountryHints(); /* this will do complete initialization of the country hints */ this.populateCountryNameForCode(); /* adding handler to populate country name if the country code is prefilled */ this.initializeUOMHints(); /* initialize smart hints for the UOM */ this.setupSmartCountryCode(); /* this will do complete initialization of the country Code hints */ this.initializeCountryCodeHints(); /* this will do complete initialization of the country Code hints */ this.setupStateCodeHints(); /* mark the smart hint as initialized */ $("input[data-ocr-model~=countryHints]").addClass("smart-hint"); $("input[data-ocr-model~=countryCodeHints]").addClass("smart-hint"); $("input[data-ocr-model~=uomHints]").addClass("smart-hint"); }, setupAutoCompleter: function(){ /* create custom widget */ $.widget('custom.ocrSmartAutoPopulate', $.ui.autocomplete, { _create: function() { this._super(); this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" ); }, _renderMenu: function(ul, items) { var self = this, thead; if (this.options.showHeader) { var mainDiv = $('
    ').addClass('ui-autocomplete-category'); var table = $('
    '); var headerRow = $(""); $.each(this.options.columns, function(index, item) { headerRow.append('' + item.name + ''); }); table.append(headerRow); mainDiv.append(table); ul.append(mainDiv); } $.each(items, function(index, item) { self._renderItem(ul, item, table); }); }, _renderItem: function(ul, item, table) { var t = '', result = ''; $.each(this.options.columns, function(index, column) { t += ''; }); t += '
    ' + (item.value[column.valueField]?item.value[column.valueField]:"") + '
    '; result = $('
  • ').data('ui-autocomplete-item', item).append('' + t + '
    ').appendTo(ul); return result; } }); }, setupSmartCountry: function(){ var urlStr = new String(this.options.targetURL); if(urlStr.indexOf("/dpss") >= 0 || urlStr.indexOf("/user") >= 0 || urlStr.indexOf("/common") >= 0 || urlStr.indexOf("/ftz") >= 0 ){ var countryPopupUrl = 'countryPopUpNew.ocr'; var anchors = $("a[href*='"+countryPopupUrl+"']"); for(var i=0; i= 0 || urlStr.indexOf("/user") >= 0 || urlStr.indexOf("/common") >= 0 || urlStr.indexOf("/ftz") >= 0 ){ var countryPopupUrl = 'countryPopUpNew.ocr'; var anchors = $("a[href*='"+countryPopupUrl+"']"); for(var i=0; i 1) { attrMap[attributes[0]] = attributes[1]; } } return attrMap; }, applySmartClassMap: function(element, fieldClassMap, fieldModelMap){ var attrMap = this.findURLAttributeMap(element); var el; var fieldWithName; for (var prop in fieldModelMap) { fieldWithName = attrMap[prop]; if(fieldWithName){ fieldWithName = fieldWithName.replace("\.","\\."); el = element.closest('form').find("[name="+fieldWithName+"]"); if(el){ /* populate class attributes for the field */ if(fieldClassMap[prop] && fieldClassMap[prop].length > 0){ if(!el.hasClass(fieldClassMap[prop].split(" ")[0])) el.addClass(fieldClassMap[prop]); else break; } /* populate data-ocr-model for the fields */ if(!el.attr('data-ocr-model') || (el.attr('data-ocr-model').indexOf(fieldModelMap[prop].split(" ")[0]) < 0)) el.attr('data-ocr-model', fieldModelMap[prop]); } } } }, initializeCountryHints: function(){ var self = this; /* fetch data from global variable, if it has data */ if(countrySmartFieldData && countrySmartFieldData != null){ self.setupCountrySmartData(countrySmartFieldData); }else{ /* make ajax call to get the country hint data */ $.ajax({ url : "/vrsportal/getCountryNameHints.ocr?addGroupCountries=Y", dataType : "json", cache: false, async: false, success : function(data) { countrySmartFieldData = data; self.setupCountrySmartData(data); /* setup smart hint data for the country */ } }); } /* this will initialize the onchange listeners on country name, so that the country code can be cleared */ self.clearCountryCodeOnChange(); }, initializeCountryCodeHints: function(){ var self = this; /* fetch data from global variable, if it has data */ if(countrySmartFieldData && countrySmartFieldData != null){ self.setupCountryCodeSmartData(countrySmartFieldData); }else{ /* make ajax call to get the country hint data */ $.ajax({ url : "/vrsportal/getCountryNameHints.ocr", dataType : "json", cache: false, async: false, success : function(data) { countrySmartFieldData = data; self.setupCountryCodeSmartData(data); /* setup smart hint data for the country */ } }); } /* this will initialize the onchange listeners on country name, so that the country code can be cleared */ //self.clearCountryCodeOnChange(); }, setupCountrySmartData: function(data){ var self = this; var countryHintsData = $.map( data, function( item ) { return { label: item.expCode+ ", " + item.value +"( "+ item.code+")", value: item }; }); /* issue#260: trigger the change event, when field value is changed */ $("input[data-ocr-model~=countryHints]:not(.smart-hint)").on('input', function(){ $(this).trigger('change'); self.removeStateHint(this); }); $("input[data-ocr-model~=countryHints]:not(.smart-hint)").ocrSmartAutoPopulate( { showHeader: true, columns: [{name: smartHintsLabels.countryName, width: '150px', valueField: 'value'}, {name: smartHintsLabels.isoCode, width: '75px',valueField: 'code'}, {name: smartHintsLabels.customCode, width: '100px',valueField: 'scCode'} ], minLength: 0, position: { my: "left top", at: "left bottom", collision: "flip" }, //source : countryHintsData, source: function(req, response) { var re = $.ui.autocomplete.escapeRegex(req.term); var matcher = new RegExp( "^" + re, "i" ); /* get the list of filtered countries */ filteredCountriesSmartData = self.applyExportCountryFilter($(this.element), countryHintsData); /* get the list of filtered countries for dosType */ filteredCountriesSmartData = self.applyValidDosCountryFilter($(this.element), filteredCountriesSmartData); /* add country group options */ filteredCountriesSmartData = self.applyCountryGroupFilter($(this.element), filteredCountriesSmartData); var result = $.grep(filteredCountriesSmartData, function(item){ var filteredData = matcher.test(item.value.value); if(!filteredData || filteredData.length == 0){ filteredData = matcher.test(item.value.code); } if(!filteredData || filteredData.length == 0){ filteredData = matcher.test(item.value.scCode); } return filteredData; }); response(result); }, focus : function(event, ui) { $('#autoCompleterDIV').removeClass('ui-menu-item'); return false; }, select : function(event, ui) { /* issue#260: trigger the change event, when field value is changed */ $(this).val(ui.item.value.value).trigger('change'); self.populateCountryDataFromSelection(this, ui.item.value); $(this).blur(); self.initializeStateHint(this, ui.item.value); return false; } }); // Overrides the default autocomplete filter function to search only from the beginning of the string $.ui.autocomplete.filter = function (array, term) { var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i"); return $.grep(array, function (value) { return matcher.test(value.label || value.value || value); }); }; /* adding country validation */ $("input[data-ocr-model~=countryHints]:not(.smart-hint)").on("focusout", function(e){ /* fix for the issue on IE8 - if focus goes to the smart field, it shouldn't validate */ if($(":focus").closest(".ui-autocomplete").length == 0 ){ var countryName = $(this).val().toUpperCase(); if(countryName && countryName != ''){ /* Manish Dass: as suggested, we don't need country validation check */ if(filteredCountriesSmartData && filteredCountriesSmartData.length > 0){ for(var i = 0; i < filteredCountriesSmartData.length; i++){ if(filteredCountriesSmartData[i].value.value.toUpperCase() == countryName){ $(this).val(filteredCountriesSmartData[i].value.value); self.populateCountryDataFromSelection(this, filteredCountriesSmartData[i].value); break; }else{//Issue#2538 : validating invalid country name. $(this).val(''); } } }else if(countryName && countrySmartFieldData){ for(var i = 0; i < countrySmartFieldData.length; i++){ if(countrySmartFieldData[i].value.toUpperCase() == countryName){ $(this).val(countrySmartFieldData[i].value); self.populateCountryDataFromSelection(this, countrySmartFieldData[i]); break; }else{//Issue#2538 : validating invalid country name. $(this).val(''); } } } } } //self.initializeStateHint(this, {'code':'null','scCode':''}); }); /* trigger the auto completer on focus */ $("input[data-ocr-model~=countryHints]:not(.smart-hint)").on("focus", function(e){ $(this).ocrSmartAutoPopulate('search', $(this).val()); }); }, setupCountryCodeSmartData :function(data){ var self = this; var countryCodeHintsData = $.map( data, function( item ) { return { label: item.expCode+ ", " + item.code +"( "+ item.value+")", value: item }; }); /* issue#260: trigger the change event, when field value is changed */ $("input[data-ocr-model~=countryCodeHints]:not(.smart-hint)").on('input', function(){ $(this).trigger('change'); }); $("input[data-ocr-model~=countryCodeHints]:not(.smart-hint)").ocrSmartAutoPopulate( { showHeader: true, columns: [{name: smartHintsLabels.countryName, width: '150px', valueField: 'value'}, {name: smartHintsLabels.code, width: '75px',valueField: 'code'} ], minLength: 0, position: { my: "left top", at: "left bottom", collision: "flip" }, //source : countryHintsData, source: function(req, response) { var re = $.ui.autocomplete.escapeRegex(req.term); var matcher = new RegExp( "^" + re, "i" ); /* get the list of filtered countries */ filteredCountriesSmartData = self.applyExportCountryFilter($(this.element), countryCodeHintsData); /* get the list of filtered countries for dosType */ filteredCountriesSmartData = self.applyValidDosCountryFilter($(this.element), filteredCountriesSmartData); var result = $.grep(filteredCountriesSmartData, function(item){return matcher.test(item.value.code); }); response(result); }, focus : function(event, ui) { $('#autoCompleterDIV').removeClass('ui-menu-item'); return false; }, select : function(event, ui) { /* issue#260: trigger the change event, when field value is changed */ //$(this).val(ui.item.value.code).trigger('change'); $(this).val(ui.item.value.code).trigger('change').trigger('blur'); self.populateCountryDataFromSelection(this, ui.item.value); return false; } }); // Overrides the default autocomplete filter function to search only from the beginning of the string $.ui.autocomplete.filter = function (array, term) { var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i"); return $.grep(array, function (value) { return matcher.test(value.label || value.code || value); }); }; /* adding country validation */ $("input[data-ocr-model~=countryCodeHints]:not(.smart-hint)").on("focusout", function(e){ /* fix for the issue on IE8 - if focus goes to the smart field, it shouldn't validate */ if($(":focus").closest(".ui-autocomplete").length == 0 ){ var countryCode = $(this).val().toUpperCase(); if(countryCode && countryCode != ''){ var validationSuccess = false; if(filteredCountriesSmartData && filteredCountriesSmartData.length > 0){ for(var i = 0; i < filteredCountriesSmartData.length; i++){ if(filteredCountriesSmartData[i].value.code.toUpperCase() == countryCode){ $(this).val(filteredCountriesSmartData[i].value.code); self.populateCountryDataFromSelection(this, filteredCountriesSmartData[i].value); validationSuccess = true; break; }else{//Issue#2538 : validating invalid country name. $(this).val(''); } } }else if(countryCode && countrySmartFieldData){ for(var i = 0; i < countrySmartFieldData.length; i++){ if(countrySmartFieldData[i].value.toUpperCase() == countryCode){ $(this).val(countrySmartFieldData[i].value); self.populateCountryDataFromSelection(this, countrySmartFieldData[i]); validationSuccess = true; break; }else{//Issue#2538 : validating invalid country name. $(this).val(''); } } } if(!validationSuccess){ alert("Please enter a valid country Code."); $(this).val(''); $(this).focus(); } } } }); /* trigger the auto completer on focus */ $("input[data-ocr-model~=countryCodeHints]:not(.smart-hint)").on("focus", function(e){ $(this).ocrSmartAutoPopulate('search', $(this).val()); }); }, clearCountryCodeOnChange: function(){ var self = this; $("input[data-ocr-model~=countryHints]:not(.smart-hint)").on('change input', function(event) { self.populateCountryDataFromSelection(this, {'code':'','scCode':''}); self.populateStateDataFromCountrySelection(this, {'stateCode':'','stateName':''}); self.removeStateHint(this); //console.log("value:"+$(this).val()+": # type:"+event.type+": # char :"+event.char+": # data:"+event.data); }); }, populateCountryDataFromSelection: function(element, countryData){ var propertyName = this.findPropertyNameForElement(element,'intelliCountry'); if(propertyName && propertyName != ''){ /* setting the country code */ //var codeElements = $("input[data-ocr-model~="+propertyName+"-country]"); var codeElements = this.searchClosestElementByModel(element, propertyName+'-country'); /* set the code */ if(codeElements) $(codeElements).val(countryData.code).trigger('change'); var codeElements = $("input[data-ocr-model~="+propertyName+"-countryScCode]");//$("."+propertyName+"-countryScCode"); /* set the code */ if(codeElements.length > 0) $(codeElements[0]).val(countryData.scCode).trigger('change'); } }, populateStateDataFromCountrySelection: function(element, stateData){ var propertyId = this.findPropertyIdForElement(element,'intelliCountry'); if(propertyId && propertyId != ''){ var codeElements = this.searchClosestElementByModel(element, 'intelliState-'+propertyId+'-stateCode'); /* set the code */ if(codeElements) $(codeElements).val(stateData.stateCode); var nameElements = this.searchClosestElementByModel(element, 'intelliState-'+propertyId+'-stateName'); /* set the name */ if(nameElements) $(nameElements).val(stateData.stateName); } }, populateCountryNameForCode: function(){ var hintElements = $("input[data-ocr-model~=countryHints]"); var hintElement = null; var propertyName = null; var codeElement = null; var countryCode = null; for(var i=0; i 0){ element = elements[0]; break; } } return element; }, findPropertyNameForElement: function(thisObject, dataType){ thisObject = $(thisObject); var propertyName = null; var className = thisObject.attr('data-ocr-model'); if(className){ var classNames = className.split(' '); var elementClass = null; for(var i = 0; i < classNames.length; i++){ if(classNames[i].match('^'+dataType)){ //if(classNames[i].match("^intelliCountry")){ elementClass = classNames[i]; break; } } if(elementClass){ var parts = elementClass.split('-'); if(parts && parts.length > 1){ propertyName = parts[0]+"-"+parts[1]; } } } return propertyName; }, applyExportCountryFilter: function($element, countryHintsData){ var self = this; var propertyGroupName = self.findPropertyNameForElement($element, 'intelliCountry'); var exportCountryElement = self.searchClosestElementByModel($element, propertyGroupName+'-exportCountry'); var filteredCountries = null; if(exportCountryElement){ filteredCountries = self.filterExportCountry(countryHintsData, $(exportCountryElement).val()); } /* set the filtered countries as all countries if nothing is found after filtering */ if(!filteredCountries || filteredCountries.length == 0) filteredCountries = countryHintsData; return filteredCountries; }, filterExportCountry: function(data, filterCountry){ var filteredCountries = []; if(filterCountry && filterCountry != '' && data){ for(var i = 0; i < data.length; i++){ if(data[i].value.exportCountry && data[i].value.exportCountry.indexOf(filterCountry) >= 0){ filteredCountries.push(data[i]); } } } return filteredCountries; }, applyValidDosCountryFilter: function($element, countryHintsData){ var self = this; var propertyGroupName = self.findPropertyNameForElement($element, 'intelliCountry'); var validDosCheckElement = self.searchClosestElementByModel($element, propertyGroupName+'-hasValidDOSCode'); var filteredCountries = null; if(validDosCheckElement){ filteredCountries = self.filterValidDosCountry(countryHintsData, $(validDosCheckElement).val()); } /* set the filtered countries as all countries if nothing is found after filtering */ if(!filteredCountries || filteredCountries.length == 0) filteredCountries = countryHintsData; return filteredCountries; }, filterValidDosCountry: function(data, filterCountry){ var filteredCountries = []; if(filterCountry && filterCountry == 'Y' && data){ for(var i = 0; i < data.length; i++){ if(data[i].value.dosCode && data[i].value.dosCode != ''){ filteredCountries.push(data[i]); } } } return filteredCountries; }, applyCountryGroupFilter: function($element, countryHintsData){ var self = this; var propertyGroupName = self.findPropertyNameForElement($element, 'intelliCountry'); var addCountryGroups = self.searchClosestElementByModel($element, propertyGroupName+'-addCountryGroups'); var filteredCountries = null; filteredCountries = self.filterCountryGroupValues(countryHintsData, (addCountryGroups?$(addCountryGroups).val():null)); /* set the filtered countries as all countries if nothing is found after filtering */ if(!filteredCountries || filteredCountries.length == 0) filteredCountries = countryHintsData; return filteredCountries; }, filterCountryGroupValues: function(data, addCountryGroupVal){ var filteredCountries = []; if(!addCountryGroupVal){ /* pick the group country data */ for(var i = 0; i < data.length; i++){ if(!data[i].value.groupCountry){ filteredCountries.push(data[i]); } } }else{ filteredCountries = data; } return filteredCountries; }, initializeUOMHints: function(){ var self = this; /* fetch data from global variable, if it has data */ if(uomSmartFieldData && uomSmartFieldData != null){ self.setupUOMSmartHints(uomSmartFieldData); }else{ /* make ajax call to get the country hint data */ $.ajax({ url : "/common/getUomHintsData.ocr?searchFields=unitCode&resultFields=unitCode~unitDesc", dataType : "json", cache: false, async: false, success : function(data) { uomSmartFieldData = data; self.setupUOMSmartHints(data); /* setup smart hint data for the country */ } }); } }, setupUOMSmartHints: function(data){ var self = this; var uomHintsData = $.map( data, function( item ) { return { label: item.unitCode+"( "+ item.unitDesc+")", value: item }; }); $("input[data-ocr-model~=uomHints]:not(.smart-hint)").ocrSmartAutoPopulate( { showHeader: true, columns: [{name: 'Code', width: '75px', valueField: 'unitCode'}, {name: 'Description', width: '150px',valueField: 'unitDesc'} ], minLength: 0, position: { my: "left top", at: "left bottom", collision: "flip" }, source: function(req, response) { var countryCode = null; /* setting the country code */ var propertyName = self.findPropertyNameForElement($(this.element),'intelliUom'); if(propertyName){ var countryCodeElement = self.searchClosestElementByModel($(this.element), propertyName+'-countryCode'); if(propertyName && countryCodeElement){ countryCode = $(countryCodeElement).val(); } } /* check if country code specified */ if(countryCode){ var url = "/common/getUomHintsData.ocr?searchStr="+req.term+"&searchFields=unitCode&resultFields=unitCode~unitDesc"; url = url+"&countryCode="+countryCode; $.ajax({ url : url, dataType : "json", cache: false, async: false, success : function(data) { response( $.map( data, function( item ) { return { label: item.unitCode, value: item } })); }, error: function(){ alert("error occurred"); } }); }else{ var re = $.ui.autocomplete.escapeRegex(req.term); var matcher = new RegExp( "^" + re, "i" ); var result = $.grep(uomHintsData, function(item){return matcher.test(item.value.unitCode); }); response(result); } }, focus : function(event, ui) { return false; }, select : function(event, ui) { $(this).val(ui.item.value.unitCode); $(this).trigger('change'); return false; } }); /* trigger the auto completer on focus */ $("input[data-ocr-model~=uomHints]:not(.smart-hint)").on("focus", function(e){ $(this).ocrSmartAutoPopulate('search', $(this).val()); }); }, removeStateHint: function(element){ var stateElements = this.searchClosestElementByModel(element, 'stateHints'); //$(stateElements).unbind('ocrSmartAutoPopulate'); var propertyId = this.findPropertyIdForElement(stateElements,'intelliState'); var propertyName = "intelliState-" + propertyId; this.removeStateSmartData('', propertyName); }, removeStateSmartData: function(data, propertyName){ var self = this; var countryHintsData = $.map( data, function( item ) { return { label: item.expCode+ ", " + item.stateName +"( "+ item.stateCode+")", value: item }; }); $("input[data-ocr-model~=StateHints]").on('input', function(){ $(this).trigger('change'); }); $("input[data-ocr-model^="+propertyName+"-state][data-ocr-model~=stateHints]").ocrSmartAutoPopulate( { showHeader: true, columns: [{name: 'Name', width: '150px', valueField: 'stateName'}, {name: 'Code', width: '75px',valueField: 'stateCode'} ], minLength: 0, position: { my: "left top", at: "left bottom", collision: "flip" }, source : function( request, response){ var re = $.ui.autocomplete.escapeRegex(request.term); var matcher = new RegExp( "^" + re, "i" ); var result = $.grep(countryHintsData, function(item){ if(matcher.test(item.value.stateName)) return matcher.test(item.value.stateName); if(matcher.test(item.value.stateCode)) return matcher.test(item.value.stateCode); else return ""; }); response(result); }, focus : function(event, ui) { return false; }, select : function(event, ui) { /* issue#260: trigger the change event, when field value is changed */ self.populateStateDataFromSelection(this, ui.item.value); $(this).blur(); return false; } }); }, initializeStateHint: function(element, countryData){ var propertyId = this.findPropertyIdForElement(element,'intelliCountry'); var propertyName = "intelliState-" + propertyId; if(propertyName && propertyName != ''){ //setting the country code //var codeElements = $("input[data-ocr-model~="+propertyName+"-country]"); var stateElements = this.searchClosestElementByModel(element, 'stateHints'); //set the code if(stateElements){ var self = this; if(stateDataArray[countryData.code]){ var data = stateDataArray[countryData.code]; self.setupStateSmartData(data, propertyName); /* setup smart hint data for the State */ }else{ /* make ajax call to get the state data */ $.ajax({ url : "/vrsportal/getStateNameHints.ocr?cCode="+countryData.code, dataType : "json", cache: false, async: false, success : function(data) { stateDataArray[countryData.code] = data; self.setupStateSmartData(data, propertyName); /* setup smart hint data for the State */ } }); } } } /* this will initialize the onchange listeners on state name, so that the state code can be cleared */ //self.clearStateCodeOnChange(); var stateElements = this.searchClosestElementByModel(element, 'stateHints'); $(stateElements).addClass("state-hint"); }, setupStateSmartData: function(data, propertyName){ var self = this; var countryHintsData = $.map( data, function( item ) { return { label: item.expCode+ ", " + item.stateName +"( "+ item.stateCode+")", value: item }; }); $("input[data-ocr-model^="+propertyName+"-state][data-ocr-model~=stateHints]").ocrSmartAutoPopulate( { showHeader: true, columns: [{name: smartHintsLabels.name, width: '150px', valueField: 'stateName'}, {name: smartHintsLabels.code, width: '75px',valueField: 'stateCode'} ], minLength: 0, position: { my: "left top", at: "left bottom", collision: "flip" }, source : function( request, response){ var re = $.ui.autocomplete.escapeRegex(request.term); var matcher = new RegExp( "^" + re, "i" ); var result = $.grep(countryHintsData, function(item){ if(matcher.test(item.value.stateName)) return matcher.test(item.value.stateName); if(matcher.test(item.value.stateCode)) return matcher.test(item.value.stateCode); else return ""; }); response(result); }, focus : function(event, ui) { return false; }, change: function (event, ui) { var source = $(this).val(); source=source.replace(")",""); var found = $('.ui-autocomplete li').text().search(source); if(found < 0) { $(this).val(''); self.populateStateDataFromSelection(this, {'stateCode':''}); } }, select : function(event, ui) { /* issue#260: trigger the change event, when field value is changed */ self.populateStateDataFromSelection(this, ui.item.value); $(this).blur(); return false; } }); /* trigger the auto completer on focus */ $("input[data-ocr-model^="+propertyName+"-state][data-ocr-model~=stateHints]:not(.state-hint)").on("focus", function(e){ $(this).ocrSmartAutoPopulate('search', $(this).val()); }); $("input[data-ocr-model^="+propertyName+"-state][data-ocr-model~=stateHints]").off('input').on('input', function(){ //console.log('aaa'); }); }, clearStateCodeOnChange: function(){ var self = this; $("input[data-ocr-model~=stateHints]").on('change input', function(event) { var propertyId = this.findPropertyIdForElement(element,'intelliState'); var propertyName = "intelliState-" + propertyId; var codeElements = self.searchClosestElementByModel(this, propertyName+'-stateCode'); $(codeElements).val(''); self.populateStateDataFromSelection(this, {'stateCode':''}); //console.log("value:"+$(this).val()+": # type:"+event.type+": # char :"+event.char+": # data:"+event.data); }); }, populateStateDataFromSelection: function(element, countryData){ var propertyId = this.findPropertyIdForElement(element,'intelliState'); var propertyName = "intelliState-" + propertyId; if(propertyName && propertyName != ''){ /* setting the country code */ //var codeElements = $("input[data-ocr-model~="+propertyName+"-country]"); var nameElements = this.searchClosestElementByModel(element, propertyName+'-stateName'); /* set the code */ if(nameElements) $(nameElements).val(countryData.stateName); var codeElements = this.searchClosestElementByModel(element, propertyName+'-stateCode'); /* set the code */ if(codeElements) $(codeElements).val(countryData.stateCode); } }, setupStateCodeHints: function(){ var that = this; /* trigger the auto completer on focus */ $("input[data-ocr-model~=stateHints]:not(.state-hint)").on("focus", function(e){ $(this).ocrSmartAutoPopulate('search', $(this).val()); }); $("input[data-ocr-model~=stateHints]").on("keyup", function(e){ if($(this).val().length==2){ var code = e.keyCode; if(code == 38 || code == 40) { //up down arrow keycode return; } var propertyId = that.findPropertyIdForElement(this,'intelliState'); //var countryElements = that.searchClosestElementByModel(this, 'countryHints'); var countryElements=$('input[data-ocr-model~=intelliCountry-'+propertyId+'-countryName'); var elements = null; var self = this; if(!$(countryElements).val()){ /* make ajax call to get the state data */ $.ajax({ url : "/vrsportal/getStateNameHints.ocr", dataType : "json", type: "POST", contentType: 'application/x-www-form-urlencoded; charset=UTF-8', cache: false, data:{ stateName:$(this).val() }, async: false, success : function(data) { var countryHintsData = $.map( data, function( item ) { return { label: item.expCode+ ", " + item.stateName +"( "+ item.stateCode+")", value: item }; }); $("input[data-ocr-model^=intelliState-"+propertyId+"-state][data-ocr-model~=stateHints]").ocrSmartAutoPopulate( { showHeader: true, columns: [{name: 'State Name', width: '150px', valueField: 'stateName'}, {name: 'State Code', width: '75px',valueField: 'stateCode'}, {name: 'Country Name', width: '150px', valueField: 'countryName'}, {name: 'Country Code', width: '100px',valueField: 'countryCode'} ], minLength: 0, position: { my: "left top", at: "left bottom", collision: "flip" }, source : function( request, response){ var re = $.ui.autocomplete.escapeRegex(request.term); var matcher = new RegExp( "^" + re, "i" ); var result = $.grep(countryHintsData, function(item){ if(matcher.test(item.value.stateName)) return matcher.test(item.value.stateName); if(matcher.test(item.value.stateCode)) return matcher.test(item.value.stateCode); else return ""; }); response(result); }, focus : function(event, ui) { return false; }, change: function (event, ui) { var source = $(this).val(); source=source.replace(")",""); var found = $('.ui-autocomplete li').text().search(source); if(found < 0) { that.populateStateDataFromSelection(this, {'stateCode':'','stateName':''}); that.removeStateHint(self); } }, select : function(event, ui) { if(propertyId && propertyId != ''){ var stateNameElement = that.searchClosestElementByModel(this, 'intelliState-'+propertyId+'-stateName'); if(stateNameElement) $(stateNameElement).val(ui.item.value.stateName); var stateCodeElement = that.searchClosestElementByModel(this, 'intelliState-'+propertyId+'-stateCode'); if(stateCodeElement) $(stateCodeElement).val(ui.item.value.stateCode); var countryCodeElement = that.searchClosestElementByModel(this, 'intelliCountry-'+propertyId+'-country'); if(countryCodeElement) $(countryCodeElement).val(ui.item.value.countryCode); var countryNameElement = that.searchClosestElementByModel(this, 'intelliCountry-'+propertyId+'-countryName'); if(countryNameElement) $(countryNameElement).val(ui.item.value.countryName); } //self.populateStateDataFromSelection(this, ui.item.value); $(this).blur(); return false; } }); } }); $("input[data-ocr-model^=intelliState-"+propertyId+"-state][data-ocr-model~=stateHints]").off('input').on('input', function(event) { var propertyId = that.findPropertyIdForElement(self,'intelliState'); var countryNameElement = $('input[data-ocr-model~=intelliCountry-'+propertyId+'-countryName]'); if(countryNameElement) $(countryNameElement).val(''); var countryCodeElement = $('input[data-ocr-model~=intelliCountry-'+propertyId+'-country]'); if(countryCodeElement) $(countryCodeElement).val(''); }); /* validate state smart hint */ $(self).addClass("state-hint"); $(self).trigger('focus'); } }if($(this).val().length<2){ var propertyId = that.findPropertyIdForElement(this,'intelliState'); var countryNameElement = that.searchClosestElementByModel(this, "intelliCountry-" + propertyId + "-countryName"); if(countryNameElement && !$(countryNameElement).val()){ that.removeStateHint(this); } } }); // onload state hint initialization $("input[data-ocr-model~=countryHints]").each(function() { var propertyName = that.findPropertyNameForElement(this,'intelliCountry'); var codeElement = that.searchClosestElementByModel(this, propertyName+'-country'); if(codeElement){ var countryCode = $(codeElement).val(); if(countryCode){ that.initializeStateHint(this, {'code':countryCode,'scCode':''}); } } var self = $(this); $(codeElement).on('change', function(){ var countryCode = $(codeElement).val(); if(countryCode){ that.initializeStateHint(self, {'code':countryCode,'scCode':''}); } }); }); }, findPropertyIdForElement: function(thisObject, dataType){ thisObject = $(thisObject); var propertyName = null; var className = thisObject.attr('data-ocr-model'); if(className){ var classNames = className.split(' '); var elementClass = null; for(var i = 0; i < classNames.length; i++){ if(classNames[i].match('^'+dataType)){ //if(classNames[i].match("^intelliCountry")){ elementClass = classNames[i]; break; } } if(elementClass){ var parts = elementClass.split('-'); if(parts && parts.length > 1){ propertyName = parts[1]; } } } return propertyName; }, }; var initializeDatePickers = { name : 'OCR-JS', version : '1.0.0', defaults: { targetURL: '', jqueryDateFormat:{datePickerFormat: userDateFormat, placeHolderFormat: placeHolderDateFormat}, enableUDF:true }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend(true, {}, this.defaults, options); this._build(); return this; }, _build: function(){ this.initialize(this.options.jqueryDateFormat); }, initialize: function(jqueryDateFormat){ /*var dateFormat = $("#systemDateFormat").val(); if(!dateFormat || dateFormat == ''){ dateFormat = 'mm/dd/yyyy'; } */ var newDateFormat = jqueryDateFormat.datePickerFormat; var newPlaceHolder = jqueryDateFormat.placeHolderFormat; if(!this.options.enableUDF){ newDateFormat = US_DATE_FORMAT; newPlaceHolder = US_DATE_FORMAT_PLACEHOLDER; } /* remove datepicker if already configured */ $( ".ocr-date" ).removeClass('hasDatepicker'); /* initialize date picker */ $( ".ocr-date" ).datepicker({ dateFormat: newDateFormat, changeMonth: true, changeYear: true, showButtonPanel:true, closeText:'Clear', /* Rakesh-Manish: Fix:EASE-4691 -Today button issue fixed */ onChangeMonthYear: function(){ var input = this; setTimeout(function(){ var clearButton = $(input ).datepicker( "widget" ).find( ".ui-datepicker-close" ); clearButton.unbind("click").bind("click",function(){$.datepicker._clearDate( input );}); var todayButton = $(input ).datepicker( "widget" ).find( ".ui-datepicker-current" ); todayButton.unbind("click").bind("click",function(e){ e.preventDefault(); e.stopPropagation(); $(input).datepicker('hide'); $(input).datepicker('setDate', new Date()); }); },1); }, beforeShow: function( input ) { /* Rakesh-Manish: Fix:EASE-4691 -Today button issue fixed */ setTimeout(function(){ var clearButton = $(input ).datepicker( "widget" ).find( ".ui-datepicker-close" ); clearButton.unbind("click").bind("click",function(){$.datepicker._clearDate( input );}); var todayButton = $(input ).datepicker( "widget" ).find( ".ui-datepicker-current" ); todayButton.unbind("click").bind("click",function(e){ e.preventDefault(); e.stopPropagation(); $(input).datepicker('hide'); $(input).datepicker('setDate', new Date()); }); },1); }, yearRange: '1901:+50'}); /* set the placeholder to show the date format */ if(! $( ".ocr-date" ).val()){ $( ".ocr-date" ).attr("placeholder", newPlaceHolder); } /* TODO: following lines can be moved to css file later */ /* mark the field as readonly */ $( ".ocr-date" ).attr("readonly",true); /* instead of showing the default readonly cursor, show the default cursor as suggested */ $( ".ocr-date" ).css("cursor",'pointer'); /* hide the calendar icon from all the places */ $( ".fa-calendar" ).parent("span").hide(); } }; /* Customized JqGrid for OCR */ var OcrGrid = { name : 'OCR-JS', version : '1.0.0', defaults: { ocrConfig: { gridUrl: '', pagerId: '', recordsPerPage: '', totalRecords: '', loadPage: '1', navGrid: false, search: false, sort: false, columnChooser: false, columnChooserTitle: '', saveBtText: '', exportToExcel: false, exportToExcelTitle: '', clientSidePagination: false, onComplete:null, pagination:true, autoReload:false, autoReloadInterval:5000, modal:false, hideOnEmpty:false }, jqConfig: {} }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend(true, {}, this.defaults, options); this._build(); return this; }, _build: function(){ this.configGrid(); this.loadGrid(); }, prepareJQConfig: function(jqConfig){//Preparing and modefying jqConfig to globalize date columns in GRID result var colModel = jqConfig.colModel; //To enable/disable UDF var enableUDF = true; if(modules.join(',').indexOf(moduleName)> -1){ enableUDF = false; if (this.options.ocrConfig.enableUDF) { enableUDF = true; } }else{ enableUDF = this.options.ocrConfig.enableUDF; if (enableUDF || typeof enableUDF == 'undefined') { enableUDF = true; } } if (enableUDF) { $.each(colModel, function(index, value) { if (value.formatter && value.formatter == 'date') { value['formatoptions'] = {newformat : gridDateFormat}; } }); } return jqConfig; }, configGrid: function() { var self = this.$element; var ocrConfig = this.options.ocrConfig; var jqConfig = this.prepareJQConfig(this.options.jqConfig); /* manipulate the url as required :Rakesh Arora */ ocrConfig.gridUrl = $.manipulateUrlForCountrycodes({url: ocrConfig.gridUrl}); var jqOptions = { datatype: "json", height: 'auto', pager: ocrConfig.pagerId, rowNum:parseInt(ocrConfig.recordsPerPage), url: ocrConfig.gridUrl, initialWidth:'', autowidth: true, hidegrid: false, rownumbers: true, rownumWidth:40, viewrecords: true, hoverrows:false, rowList:[10,20,30,40,50,100,250,500], viewsortcols:[true,'vertical',true], cmTemplate: {title: false, search:ocrConfig.search, sortable:ocrConfig.sort, searchoptions:{sopt: ['cn','eq']}}, jsonReader : { root: "gridUtil.gridModel", page: "gridUtil.page", total: "gridUtil.total", records: "gridUtil.records" }, gridview:true, forceFit:true, toppager: true, postData: {'fr_':$('#fr_').val()}, mtype: "POST", ignoreCase:true, gridComplete:function(){ var gridWidth=self.jqGrid("getGridParam","width"); self.jqGrid("setGridWidth",gridWidth); if(ocrConfig.clientSidePagination && ocrConfig.hideOnEmpty){ var gridRecords=self.jqGrid('getGridParam','records'); if(gridRecords > 0){ var element=self.closest('[class^="col-xs-"]'); if(element.hasClass('hidden')){ element.removeClass('hidden'); } gridWidth=element.width(); self.jqGrid("setGridWidth",gridWidth); $(ocrConfig.pagerId+"_left").removeAttr("style"); } else { self.closest('[class^="col-xs-"]').addClass('hidden'); } } $(window).trigger('resize'); $('#alertmod_'+this.id).remove(); if(ocrConfig.onComplete != null){ ocrConfig.onComplete(); } if(!ocrConfig.multiselect){ $('tr.jqgrow').on('dblclick', function(){ $(this).closest('form:visible').find('.recordFromPopup:first:visible').trigger('click').change(); }); } }, loadError:function (xhr, status,error){ alert(status); }, onPaging:function (){ var postData=self.jqGrid('getGridParam','postData'); var postDataVar=postData; if(postDataVar.hasOwnProperty("postDataStr")){ delete postDataVar.postDataStr; } var postDataStrVar=JSON.stringify(postDataVar); self.jqGrid('setGridParam',{postData:{postDataStr:postDataStrVar}}); }, beforeRequest:function (){ if(ocrConfig.pagination){ if(ocrConfig.clientSidePagination){ self.jqGrid('setGridParam', { beforeRequest:function (){ var pageNum=self.jqGrid('getGridParam','page'); var lastpage=self.jqGrid('getGridParam','lastpage'); if(pageNum > lastpage){ pageNum=lastpage; self.jqGrid('setGridParam',{datatype:'json',page:pageNum}); } } }); }else{ //logic to reset the load page to '1' if loadPage > last page var chunkSize=self.jqGrid('getGridParam','rowNum'); var resultSize=ocrConfig.totalRecords; var total=0; if (resultSize > 0 && chunkSize > 0) { total =Math.ceil( resultSize / chunkSize); } else { total = 0; } if(ocrConfig.loadPage > total){ ocrConfig.loadPage=1; } var loadPostData; var rowNumVar; if(!ocrConfig.postDataStr ||(ocrConfig.postDataStr && ocrConfig.postDataStr=="")){ loadPostData={ "page": ocrConfig.loadPage,"records":ocrConfig.totalRecords}; rowNumVar=parseInt(ocrConfig.recordsPerPage); }else{ loadPostData= $.parseJSON((ocrConfig.postDataStr).replace(/"/g,'"')); rowNumVar=parseInt(loadPostData.rows); ocrConfig.recordsPerPage=loadPostData.rows; } self.jqGrid('setGridParam', { beforeRequest:function (){ var postData=self.jqGrid('getGridParam','postData'); var postDataVar=postData; if(postDataVar.hasOwnProperty("postDataStr")){ delete postDataVar.postDataStr; } var postDataStrVar=JSON.stringify(postDataVar); self.jqGrid('setGridParam',{postData:{postDataStr:postDataStrVar}}); //logic to reset pageNum to lastpage if pageNum > lastpage var pageNum=self.jqGrid('getGridParam','page'); var lastpage=self.jqGrid('getGridParam','lastpage'); if(lastpage >0 && pageNum > lastpage){ pageNum=lastpage; self.jqGrid('setGridParam',{page:pageNum}).trigger('reloadGrid'); } }, postData: loadPostData, rowNum:rowNumVar }); } } }, beforeSelectRow:function(rowid, e) { if(jqConfig.multiselect){ var cbox = $("tr#" + rowid + ".jqgrow > td > input.cbox:checked"); var checked=false; if(cbox.length==1){ checked=true; } var index=0; var containFlag=false; var tempList= self.jqGrid('getGridParam', "selarrrow"); $.each( tempList, function(i,element){ if(element==rowid){ index=i; containFlag=true; return false; } }); if(containFlag && !checked){ tempList.splice(index,1); self.jqGrid('setGridParam', { selarrrow :tempList }); }else if(!containFlag && checked){ tempList.push(rowid); self.jqGrid('setGridParam', { selarrrow :tempList }); } return false; }else{ return true; } } }; if(ocrConfig.postDataStr && ocrConfig.postDataStr!=""){ var loadPostData= $.parseJSON((ocrConfig.postDataStr).replace(/"/g,'"')); var persistGridStateOptions = { rowNum:parseInt(loadPostData.rows) }; jqOptions = $.extend(jqOptions, persistGridStateOptions); } if(!ocrConfig.pagination){ var noPaginationOptions = { rowNum:ocrConfig.totalRecords, rowList:[], pgbuttons: false, pgtext:null, viewrecords:false }; jqOptions = $.extend(jqOptions, noPaginationOptions); } if(ocrConfig.clientSidePagination){ var clientPageOptions = { loadonce:true, jsonReader : { root: "gridUtil.gridModel", repeatitems:false } }; jqOptions = $.extend(jqOptions, clientPageOptions); if(ocrConfig.hideOnEmpty){ this.$element.parent().addClass('hidden'); } } if(ocrConfig.modal){ var gWidth=0; if(self.parents(".modal").hasClass('modal-medium')){ gWidth=670; }else if(self.parents(".modal").hasClass('modal-small')){ gWidth=540; }else if(self.parents(".modal").hasClass('modal-large')){ gWidth=960; } var modalOptions = { autowidth:false, width:gWidth }; jqOptions = $.extend(jqOptions, modalOptions); } if (typeof jqOptions == 'object') { jqOptions = $.extend(jqOptions, jqConfig); } this.options.jqOptions = jqOptions; }, loadGrid: function() { var self = this.$element; var ocrConfig = this.options.ocrConfig; var jqOptions = this.options.jqOptions; self.jqGrid(jqOptions); if(ocrConfig.autoReload){ setInterval(function(){self.trigger('reloadGrid');},ocrConfig.autoReloadInterval); } if(ocrConfig.navGrid){ var showGridSearch=false; if(ocrConfig.search){ showGridSearch=true; } self.jqGrid( 'navGrid', ocrConfig.pagerId, { search:showGridSearch, edit:false, add:false, del:false, cloneToTop:true, beforeRefresh: function() { if(ocrConfig.clientSidePagination){ //enable refresh for client side pagination self.jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid'); } //clearing the search/sort/rows criteria on refresh self.jqGrid('setGridParam',{sortname:''}); var postDataVar=self.jqGrid('getGridParam','postData'); if(ocrConfig.search){ var clearFilter = { searchField:'', searchOper:'', searchString:'', filters:'', _search:false }; postDataVar = $.extend(postDataVar, clearFilter); } self.jqGrid('setGridParam',{postData:postDataVar,rowNum:parseInt(ocrConfig.recordsPerPage)}); $(ocrConfig.pagerId+'_center').find('.ui-pg-selbox').val(ocrConfig.recordsPerPage); if(toppager){ $('#'+self.attr('id')+'_toppager_center').find('.ui-pg-selbox').val(ocrConfig.recordsPerPage); } } }, {}, {}, {}, { closeOnEscape: true, closeAfterSearch: true, closeAfterReset:true, multipleSearch:false }, {} ); } var toppager= self.jqGrid('getGridParam', "toppager"); if(ocrConfig.columnChooser){ self.jqGrid('navButtonAdd', ocrConfig.pagerId,{ caption:'', buttonicon: "ui-icon-calculator", title: ocrConfig.columnChooserTitle, id:'jq_chooser_'+self.attr('id'), onClickButton: function () { self.jqGrid('columnChooser', { dlog_opts : function(opts) { var buttons = {}; opts.bSubmit=ocrConfig.saveBtText; buttons[opts.bSubmit] = function() { var gridWidth=self.jqGrid("getGridParam","width"); self.jqGrid('setGridParam', { initialWidth :gridWidth }); var sLen= $(this).find("ul.selected").children('li.ui-state-default').length; if(sLen<=0){ alert("There should be atleast one Column."); opts.cleanup(true); return false; } opts.apply_perm(); opts.cleanup(false); }; buttons[opts.bCancel] = function() { opts.cleanup(true); }; return $.extend(true, { "buttons": buttons, "close": function() { opts.cleanup(true); }, "modal" : opts.modal || false, "resizable": opts.resizable || true, "width": opts.width+20 }, opts.dialog_opts || {}); }, done: function(perm) { var gridWidth=self.jqGrid("getGridParam","initialWidth"); self.jqGrid("setGridWidth",gridWidth); if (perm) { this.jqGrid("remapColumns", perm, true); } } }); }}); if(toppager){ self.jqGrid('navButtonAdd', toppager,{ caption:'', buttonicon: "ui-icon-calculator", title: ocrConfig.columnChooserTitle, id:'jq_chooser_top'+self.attr('id'), onClickButton: function () { self.jqGrid('columnChooser', { dlog_opts : function(opts) { var buttons = {}; opts.bSubmit=ocrConfig.saveBtText; buttons[opts.bSubmit] = function() { var gridWidth=self.jqGrid("getGridParam","width"); self.jqGrid('setGridParam', { initialWidth :gridWidth }); var sLen= $(this).find("ul.selected").children('li.ui-state-default').length; if(sLen<=0){ alert("There should be atleast one Column."); opts.cleanup(true); return false; } opts.apply_perm(); opts.cleanup(false); }; buttons[opts.bCancel] = function() { opts.cleanup(true); }; return $.extend(true, { "buttons": buttons, "close": function() { opts.cleanup(true); }, "modal" : opts.modal || false, "resizable": opts.resizable || true, "width": opts.width+20 }, opts.dialog_opts || {}); }, done: function(perm) { var gridWidth=self.jqGrid("getGridParam","initialWidth"); self.jqGrid("setGridWidth",gridWidth); if (perm) { this.jqGrid("remapColumns", perm, true); } } }); }}); } } if(ocrConfig.exportToExcel){ self.jqGrid('navButtonAdd', ocrConfig.pagerId,{ caption:'', buttonicon:"ui-icon-document", title:ocrConfig.exportToExcelTitle, id:'jq_excel_'+self.attr('id'), onClickButton : function () { var records = self.jqGrid().getGridParam("records"); if(maxExportExcelSize && records > maxExportExcelSize){ var errors =[]; errors.push({msg:maxExportExcelErrMsg}); $(this).processMsg({errors:errors}); }else{ var postData = self.jqGrid('getGridParam','postData'); var str='&'; $.each(postData, function(i,item){ str+=i+"="+item+"&"; }); var url=ocrConfig.gridUrl; if(url.indexOf("?") != -1){ url+='&export=excel'+str+'&records='+records; }else{ url+='?export=excel'+str+'&records='+records; } /* #6084: forwarding the HTML response for excel format parsing */ $(this).processRequest({ url: url, complete: function(response){ /* #8613 - CJ - System throws HTTP 500 error when users try to export results from any search result or report screen to excel format */ $.ajax_xls_download('/common/downloadExcelFileFormat.ocr', escape(response), 'htmlContent'); } }); } } } ); if(toppager){ self.jqGrid('navButtonAdd', toppager,{ caption:'', buttonicon:"ui-icon-document", title:ocrConfig.exportToExcelTitle, id:'jq_excel_top'+self.attr('id'), onClickButton : function () { var records = self.jqGrid().getGridParam("records"); if(maxExportExcelSize && records > maxExportExcelSize){ var errors =[]; errors.push({msg:maxExportExcelErrMsg}); $(this).processMsg({errors:errors}); }else{ var postData = self.jqGrid('getGridParam','postData'); var str='&'; $.each(postData, function(i,item){ str+=i+"="+item+"&"; }); var url=ocrConfig.gridUrl; if(url.indexOf("?") != -1){ url+='&export=excel'+str+'&records='+records; }else{ url+='?export=excel'+str+'&records='+records; } /* #6084: forwarding the HTML response for excel format parsing */ $(this).processRequest({ url: url, complete: function(response){ /* #8613 - CJ - System throws HTTP 500 error when users try to export results from any search result or report screen to excel format */ $.ajax_xls_download('/common/downloadExcelFileFormat.ocr', escape(response), 'htmlContent'); } }); } } } ); } } } }; // Modal Popup Class Starts //PRJ-49_OCR_FTZ-001 added new popup var ModularPopup = { name: 'OCR-Inc', version: '1.0.0', defaults: { url: '', /* URL for the results screen */ popupResultsGridParams: '', /* Name of the column names in the grids */ popupResultsGridOptions: '', /* Grid column model settings */ queryParams: '', /* Query param */ recordsPerPage: '', /* records per page setting */ directResult: false, allowMultiSelect: false, validateSearchForm: null, preApplyingSelectionCallback: null, /* callback function to confirm the selection */ postSelectionCallback: null, /* callback function to inform the parent about the selection completion */ isApplyAppend: false, appendDelimiter: ',', noChangeEventTrigger: null, /* to controll callback function on change event trigering*/ isCustomDelimiter: false, enableUDF:true, removeDuplicate: false, retainSearchedData:false, retainElements:null }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend({}, this.defaults, options); this._setup(); this.removeLoader(); return this; }, removeLoader: function(){ $(".loader-cont").addClass('hidden'); this.$backdrop && this.$backdrop.remove(); this.$backdrop = null; }, /* This will initialise the listeners on the elements and other setup related tasks */ _setup: function(){ var self = this; /* cancel button in the Popup */ $(".cancelPopup").click(function(){ self.options.clickedCancel = true; $('#ocrModal').modal('hide'); }); $(".close").click(function(){ self.options.clickedCancel = true; var archieveCont = $(".archivedPopups:last").html(); if(archieveCont && archieveCont.length > 0){ $(".archivedPopups").remove(); } }); /* TODO: need to review this code block: popup on popup POC work */ $('#ocrModal').on('hidden.bs.modal', function (e) { if(!self.options.avoidPopupOverPopup && self.options.clickedCancel){ try{ //PRJ-50 remove backdrop on popup over popup. $(".loader-backdrop").remove(); if($(".archivedPopups:last").length > 0 && $(".archivedPopups:last").html() != '' && !$('#ocrModal .modal-content').hasClass("backedUp")){ /* backup the form data */ var formbackup = $(".archivedPopups:last form").jsonify(); $('#ocrModal').closest(".ocr-modal-cont").html($(".archivedPopups:last").html()); $(".archivedPopups:last").html(''); $(".archivedPopups:last").remove(); /* restore the form data */ $('#ocrModal').closest(".ocr-modal-cont form").loadJSON(formbackup); $('#ocrModal').modal({backdrop: 'static'}); $("#ocrModal input[data-ocr-model~=countryHints]").removeClass("smart-hint"); $("#ocrModal input[data-ocr-model~=countryCodeHints]").removeClass("smart-hint"); $("#ocrModal input[data-ocr-model~=uomHints]").removeClass("smart-hint"); $('#ocrModal').closest(".ocr-modal-cont form").ocrSmartHints({targetURL: "/itts/abc.ocr"}); /* initialize the date picker */ $('#ocrModal').closest(".ocr-modal-cont").initializeDatePickers({jqueryDateFormat:{datePickerFormat:userDateFormat, placeHolderFormat: placeHolderDateFormat},enableUDF:self.options.enableUDF}); /* if flag Field use in popup over popup reinitialize*/ var flagField = $('#ocrModal').find("[data-ocr-type='flagField']"); var ocrFlagField = $(flagField).parent().find('.ocr-flag-field'); if(ocrFlagField.length > 0) $(ocrFlagField).remove(); $(flagField).removeClass('flag-field').ocrFlagFields({}); e.preventDefault(); e.stopPropagation(); } }catch(ex){} } }); /* End: popup on popup POC changes */ $(".recordFromPopup").click(function(){ self.options.clickedCancel = true; var rowData = null; var rowDataArr = []; var list = $("#gridPopup"); if(self.options.allowMultiSelect){ var selrows = list.jqGrid('getGridParam','selarrrow'); if(selrows && selrows.length > 0){ //alert(selr); for(var i = 0; i < selrows.length; i++){ rowData = list.getRowData(selrows[i]); rowDataArr.push(rowData); } } }else{ var selr = jQuery('#gridPopup').jqGrid('getGridParam','selrow'); if(selr){ //alert(selr); var selectedRow = list.getGridParam("selrow"); rowData = list.getRowData(selectedRow); rowDataArr.push(rowData); } } if($.isFunction(self.options.preApplyingSelectionCallback)){ var proceedForward = self.options.preApplyingSelectionCallback.call(self, rowDataArr); if(proceedForward == false){ return false; } } if(rowDataArr.length > 0){ self.setQueryParamValues(rowDataArr); $('#ocrModal').modal('hide'); }else{ alert("No selected row"); } if($.isFunction(self.options.postSelectionCallback)){ self.options.postSelectionCallback.call(self, rowDataArr); } return false; }); /* action for the popup search from search button */ $(".popupSearchButton").on('click', function(event){ var isValid = true; var validateForm = false; var flag; var ldap; if(self.options.validateSearchForm){ isValid = self.options.validateSearchForm(); } event.preventDefault(); if(!isValid) return; //console.log("this:"+$(this).size()); //console.log("this prent :"+$(this).parents('form').size()); var formData = $(this).parents('form').serialize(); var userFirstname = $('[name="userProfile.userFirstname"]').val(); var userLastname = $('[name="userProfile.userLastname"]').val(); var userEmail = $('[name="userProfile.emailId"]').val(); if(userFirstname =="" && userLastname=="" && userEmail==""){ validateForm = true; } if(document.forms[1].searchBy!=null) { flag = $("input[name='searchBy']:checked").val(); } if($('[name="ldap"]')!=null){ ldap = $('[name="ldap"]').val(); } //var url = self.options.url; var url = $.manipulateUrlForCountrycodes({url:self.options.url}); if(validateForm && flag=='N' && ldap=='Y') { return; } //console.log("url :"+url); //alert("form Data :"+formData+":"+JSON.stringify(formData)); $.ajax({ url: url, data: formData, cache: false, async: false, success: function(res){ var resultCount = 1; try{ if(flag=='N' && ldap=='Y') { checkLdapResult(res);//Issue #7302 } res = $.parseJSON(res); //console.log(JSON.stringify(res)); //console.log("result is here :"+res["size"]); resultCount = res["size"]; }catch(e){} if(resultCount == '0') self.toggleSearch(false, true); else self.toggleSearch(false); /* This will toggle the search and results div */ }, error:function(){ alert("error");} }); self.initializeResultGrid(); /* this will initialise the results grid */ }); /* action for the popup search from search button */ $(".popupSearchButtonUserProf").on('click', function(event){ var isValid = true; var validateForm = false; var flag; var ldap; if(self.options.validateSearchForm){ isValid = self.options.validateSearchForm(); } event.preventDefault(); if(!isValid) return; //console.log("this:"+$(this).size()); //console.log("this prent :"+$(this).parents('form').size()); var formData = $(this).parents('form').serialize(); var userFirstname = $('#userFirstname').val(); var userLastname = $('#userLastname').val(); var userEmail = $('#emailId').val(); var userEmployeeId = $('#userEmployeeId').val(); if(userFirstname =="" && userLastname=="" && userEmail=="" && userEmployeeId==""){ validateForm = true; } if(document.forms[1].searchBy!=null) { flag = $("input[name='searchBy']:checked").val(); } if($('[name="ldap"]')!=null){ ldap = $('[name="ldap"]').val(); } var url = self.options.url; if(validateForm && flag=='N' && ldap=='Y') { return; } //console.log("url :"+url); //alert("form Data :"+formData+":"+JSON.stringify(formData)); $.ajax({ url: url, data: formData, cache: false, async: false, success: function(res){ var resultCount = 1; try{ if(flag=='N' && ldap=='Y') { checkLdapResult(res);//Issue #7302 } res = $.parseJSON(res); //console.log(JSON.stringify(res)); //console.log("result is here :"+res["size"]); resultCount = res["size"]; }catch(e){} if(resultCount == '0') self.toggleSearch(false, true); else self.toggleSearch(false); /* This will toggle the search and results div */ }, error:function(){ alert("error");} }); self.initializeResultGrid(); /* this will initialise the results grid */ }); /* action for the new search event */ $("button:reset,.newSearchPopup").on('click', function(e){ /* prevent the default action on these buttons */ e.preventDefault(); /* clear the form */ var searchedData = self.prepareSearchedData(); $(this).parents('form').trigger("reset"); /*hack for reseting values when value is selected from Popup*/ $(this).parents('form').find('input:text:not([value=""])').each(function(idx){ //To avoid reseting the disabled and readonly fields. if(!($(this).prop('readonly') == true || $(this).prop('disabled') == true)){ $(this).val(''); } }); /* Remove All errors and hightlighted fields with red box while clicking on New Search button */ $(this).parents('form').find('.ocr-error').addClass('hidden'); $(this).parents('form').find('.form-error').removeClass('form-error'); if(searchedData){ $.each(searchedData, function(k, v){ $(k).val(v); }); } self.toggleSearch(true); }); if(self.options.directResult){ self.initializeResultGrid(); } /* if flag Field use in popup over popup*/ $("[data-ocr-type='flagField']:not(.flag-field)").ocrFlagFields({}); }, prepareSearchedData:function(){ var data = {}; var elements = this.options.retainElements; if(this.options.retainSearchedData && elements){ if(elements == 'all'){ //Needs to impliment in future requirements }else{ $.each(elements, function(i, e){ data[e] = $(e).val(); }); } } return data; }, /* Initialize grid function, this will render the grid if not already rendered */ initializeResultGrid: function(){ if(this.options.allowMultiSelect){ this.options.popupResultsGridOptions["multiselect"] = true; this.options.popupResultsGridOptions["beforeSelectRow"] = function (rowid, e) { if (e.target.nodeName.toUpperCase() === "A" && $(e.target).prev("input").hasClass("cbox")) { $(e.target).prev("input").click(); } return true; }; this.options.popupResultsGridOptions["onSelectRow"]= function (rowid, state) { var $a = $("#jqg_" + $.jgrid.jqID(this.id + "_" + rowid)).next("a"); if (state) { $a.addClass("checked"); } else { $a.removeClass("checked"); } }; } /* unload the grid if it is already rendered */ if($("#gbox_gridPopup").length > 0){ $('#gridPopup').jqGrid("GridUnload"); } /* load the grid */ $('#gridPopup').ocrGrid({ ocrConfig: this.options.popupResultsGridParams, jqConfig: this.options.popupResultsGridOptions }); }, /* This will set the query params for the search popup*/ setQueryParamValues: function(rowData){ //alert("url "+url); var paramAttributeArray = this.options.queryParams.split("&"); var formName = ""; var length = paramAttributeArray.length; //alert(length); for(var counter=0; counter 0){ $tag.find("a").remove(); val = $tag.html(); } }catch(e){ console.log(e); } if(retValue){ retValue += this.options.appendDelimiter+" "+val; }else{ retValue = val; } } return retValue; }, getCommaSepAttrValue: function(jsonArr, attr){ var val; var retValue = null; for(var i = 0; i < jsonArr.length; i ++){ val = jsonArr[i][attr]; /* Issue #773: getCommaSepAttrValue * Following code is a hack to ignore lync and skype tags while populating data from the popup -Rakesh Arora*/ try{ var $tag = $($.parseHTML(val)); if($tag.find('a').length > 0){ $tag.find("a").remove(); val = $tag.html(); } }catch(e){ console.log(e); } if(retValue){ retValue += ", "+val; }else{ retValue = val; } } return retValue; }, // validate populated value in field and ignore value if douplicated in field validateCommaSepAttrValue: function(obj){ var fieldVal = obj.val(); var valArray = fieldVal.split(','); $.each(valArray, function (id, val) { valArray[id] = $.trim(val); }); var result = []; $.each(valArray, function(i, val) { if ($.inArray(val, result) == -1) { result.push(val); } }); obj.val(result.join(", ")); }, /* toggle between the search form and results grid screen, if show = true, render search form else results grid */ toggleSearch: function(show, noData){ if(show){ $("#searchDIV").show(); $("#resultDIV").hide(); }else{ $("#searchDIV").hide(); $("#resultDIV").show(); } if(!show && noData){ var noDataElement = '
    ' +'×

    Information!

    ' +'
    • No Record Found.
    '; /* if grid is not loaded hide the grid */ $('#gridPopup').hide(); $('#gridPopup').parent().hide(); /* if grid is loaded hide the grid elements */ $("#gbox_gridPopup").hide(); $('#gbox_gridPopup').parent().hide(); if($("#noData").length == 0 && $('#gbox_gridPopup').parent().length > 0){ $('#gbox_gridPopup').parent().parent().append(noDataElement); } if($("#noData").length == 0 && $('#gridPopup').parent().length > 0){ $('#gridPopup').parent().parent().append(noDataElement); } /* show the no data label*/ while($("#resultDIV").find("#noData").hasClass('hidden')){ $("#resultDIV").find("#noData").removeClass('hidden'); console.log("removed"); } console.log("data :"+$("#resultDIV").find("#noData").hasClass('hidden')); //$("#noData").removeClass('hidden'); }else{ /* show the grid */ $('#gbox_gridPopup').show(); $('#gbox_gridPopup').parent().show(); /* hide the no data label*/ $("#noData").addClass('hidden'); } } }; // Modal Popup Class Ends /* Function to get selected values from a grid */ $.fn.gridMultiSelect = function ( options ) { options = $.extend({}, $.fn.gridMultiSelect.options, options ); var checkedValues = ''; this.each(function () { var $elem = $(this); if(options.columns==null ||(options.columns).length==0){ alert("Incorrect Configuration[columns missing]"); return; } var columns=options.columns; var multifield=false; if(columns.length>1){ multifield=true; } var multiselect=$elem.jqGrid ('getGridParam', 'multiselect'); var concatVal=''; if(multiselect && !multifield){ var selRowIds = $elem.jqGrid ('getGridParam', 'selarrrow'); if(selRowIds==null || selRowIds==""){ return; } $.each(selRowIds, function(i,rowId){ var rowValue = $elem.jqGrid ('getRowData', rowId); var column=columns[0]; var celValue=rowValue[column]; if(options.fetchAsArray){ if(concatVal==''){ concatVal=options.params[0]+"="+celValue; }else{ concatVal+="&"+options.params[0]+"="+celValue; } }else{ if(concatVal==''){ concatVal=celValue; }else{ concatVal+=options.rowseperator+celValue; } } }); }else if(!multiselect){ var selRowId = $elem.jqGrid ('getGridParam', 'selrow'); if(selRowId==null){ return; } var rowValue = $elem.jqGrid ('getRowData', selRowId); $.each(columns, function(i,column){ if(options.fetchAsArray){ if(concatVal==''){ concatVal=options.params[i]+"="+rowValue[column]; }else{ concatVal+="&"+options.params[i]+"="+rowValue[column]; } }else{ if(concatVal==''){ concatVal=rowValue[column]; }else{ concatVal+=options.fieldseperator+rowValue[column]; } } }); }else if(multifield && multiselect){ var concatField=''; var concatRow=''; var selRowIds = $elem.jqGrid ('getGridParam', 'selarrrow'); if(selRowIds==null || selRowIds==""){ return; } $.each(selRowIds, function(i,rowId){ var rowValue = $elem.jqGrid ('getRowData', rowId); $.each(columns, function(i,column){ if(options.fetchAsArray){ if(concatField==''){ concatField=options.params[i]+"="+rowValue[column]; }else{ concatField+="&"+options.params[i]+"="+rowValue[column]; } }else{ if(concatField==''){ concatField=rowValue[column]; }else{ concatField+=options.fieldseperator+rowValue[column]; } } }); if(!options.fetchAsArray){ if(concatRow==''){ concatRow=concatField; }else{ concatRow+=options.rowseperator+concatField; } concatField=''; }else{ concatRow=concatField; } }); concatVal=concatRow; } checkedValues=concatVal; }); //logic to populate values to parent window if(options.populatefield){ var fieldList = new Array(); var paramArray = (options.querystr).split('&'); if(paramArray.length < 2) return; var form = paramArray[0].substring(paramArray[0].indexOf('=')+1); $.each(paramArray.slice(1), function(i,item){ fieldList.push(item.substring(item.indexOf('=')+1)); }); if(checkedValues !=""){ var keyValue = checkedValues.split(options.fieldseperator); if (keyValue.length != (fieldList.length)) { alert("field# does not match with value#."); return; } $.each(fieldList, function(i,fieldListItem){ if(fieldListItem != ""){ var formIndex=form.substring(form.indexOf('[')+1, form.indexOf(']')); var formObj=$('form')[formIndex]; if (keyValue[i] != "") { $(formObj).find('[name="'+fieldListItem+'"]').val(keyValue[i]); }else { $(formObj).find('[name="'+fieldListItem+'"]').val(""); } } }); $("#ocrModal").modal('hide'); }else{ return ; } }else{ return checkedValues; } }; $.fn.gridMultiSelect.options = { grid: null, columns: [], params: [], rowseperator: ',', fieldseperator: '~', fetchAsArray:false, populatefield:false, querystr:'' }; /* Get User names based on sbu */ var GetUserList = { name : 'OCR-JS', version : '1.0.0', defaults: { target: '', type :'0' }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend({}, this.defaults, options); this._build(); return this; }, _build: function(){ this.getUsers(); }, getUsers: function() { var self = this.$element; var options = this.options; if($.hasValue(options.target)){ var target = $(options.target); var data = 'selectedSbu='+self.val()+'&selectType='+options.type; target.html(''); $.ajax({ context: document.body, data: data, dataType: 'html', type: 'POST', url: '/user/resultUserList.ocr', success: function(response) { target.append(response); } }); } } }; var ChangeActiveSbu = { name : 'OCR-JS', version : '1.0.0', defaults: { }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend({}, this.defaults, options); this._build(); return this; }, _build: function(){ this.dropDown(); }, dropDown: function() { var self = this.$element; var sbuCode = self.data('ocr-value'); if($.hasValue(sbuCode)){ var data = 'sbuCode='+sbuCode; $.ajax({ context: document.body, data: data, dataType: 'html', type: 'POST', url: '/user/updateSbuFromDropDown.ocr', success: function(response) { var object = $.parseJSON(response); if(object.sbuLicensedCountry != "") $('.sbu-list > a').html(object.sbuCode + " - " + object.sbuLicensedCountry); else $('.sbu-list > a').html(object.sbuCode); //if(object.sbuCountryChangeFlag=='Y'){ var url = window.location.href; // Returns full URL var lastIndex = url.lastIndexOf("?m="); if(lastIndex >= 1){ url = url.substring(0,lastIndex); } /* change the url to remove the previous redirects */ lastIndex = url.lastIndexOf("redirect="); if(lastIndex >= 1){ url = url.substring(0,lastIndex-1); } window.history.replaceState("string", "", url); /* #5093: page doesn't reload when sbu is changed */ location.reload(); //$(location).attr('href',url); //} } }); } } }; var getMaxExportExcelSize = { name : 'OCR-JS', version : '1.0.0', defaults: { }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend({}, this.defaults, options); this.maxResultSize(); return this; }, maxResultSize: function() { } }; var initMultiCountry = { name : 'OCR-JS', version : '1.0.0', init: function(options, element){ var $targetElement = $(".ocr-multiCountry:not(.hasMultiCountry)"); $targetElement.tagsInput({ defaultText: 'Add Country', height: 'auto', width: 'auto', delimiter:'~', 'removeWithBackspace' : false, onAddTag:function(value){//Issue#2538 : validating invalid country name. var spans = $targetElement.next().find('span'); var found = false; if(filteredCountriesSmartData && filteredCountriesSmartData.length > 0){ for(var i = 0; i < filteredCountriesSmartData.length; i++){ if(filteredCountriesSmartData[i].value.value.toUpperCase() == value){ found = true; break; } } } if(!found){ $(spans[spans.length-2]).remove(); var textAreaText = $targetElement.val(); if(textAreaText){ $targetElement.val($targetElement.text()); } } } }); $targetElement.parent().find(".tagsinput").find("input:text").attr("data-ocr-model","countryHints intelliCountry-0-countryName"); $targetElement.addClass("hasMultiCountry"); } }; /*Multi Country Code*/ var initMultiCountryCode = { name : 'OCR-JS', version : '1.0.0', init: function(options, element){ var $targetElement = $(".ocr-multiCountryCode:not(.hasMultiCountryCode)"); $targetElement.tagsInput({ defaultText: 'CountryCode', height: 'auto', width: 'auto', 'removeWithBackspace' : false, }); $targetElement.parent().find(".tagsinput").find("input:text").attr("data-ocr-model"," countryCodeHints intelliCountry-0-country "); $targetElement.addClass("hasMultiCountryCode"); } }; /* PRJ-645: Custom field(s) componetes starts*/ //For file smart hint. var ocrSmartHintsFileTypeRecords = { name : 'OCR-JS', version : '1.0.0', defaults: { targetURL: '', }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend(true, {}, this.defaults, options); this._build(); return this; }, _build: function(){ this.setupAutoCompleter(); /* this will create custom widget */ this.initializeRTFHints(); /* this will do complete initialization of the record type group hints (RTF = record type group)*/ }, setupAutoCompleter: function(){ /* create custom widget */ $.widget('custom.ocrSmartAutoPopulateRTF', $.ui.autocomplete, { _renderMenu: function(ul, items) { var self = this, thead; if (this.options.showHeader) { var mainDiv = $('
    '); var table = $('
    '); var headerRow = $(""); $.each(this.options.columns, function(index, item) { headerRow.append('' + item.name + ''); }); table.append(headerRow); mainDiv.append(table); ul.append(mainDiv); } $.each(items, function(index, item) { self._renderItem(ul, item, table); }); }, _renderItem: function(ul, item, table) { var t = '', result = ''; $.each(this.options.columns, function(index, column) { t += ''; }); t += '
    ' + (item.value[column.valueField]?item.value[column.valueField]:"") + '
    '; result = $('
  • ').data('ui-autocomplete-item', item).append('' + t + '
    ').appendTo(ul); return result; } }); }, initializeRTFHints: function(){ var self = this; /* fetch data from global variable, if it has data */ if(SmartFieldDataRTF && SmartFieldDataRTF != null){ self.setupRTFSmartData(SmartFieldDataRTF); }else{ /* make ajax call to get the record type group hint data */ $.ajax({ url : "/user/fileTypeRecords.ocr", dataType : "json", cache: false, async: false, success : function(data) { SmartFieldDataRTF = data; self.setupRTFSmartData(data); /* setup smart hint data for the record type group */ } }); } }, setupRTFSmartData: function(data){ var self = this; var rtHintsData = $.map( data, function( item ) { return { label: item.value+ ", " + item.value +"( "+ item.code+")", value: item }; }); /* trigger the change event, when field value is changed */ $("input[data-ocr-model~=fileTypeRecordsHint]").on('input', function(){ $(this).trigger('change'); }); $("input[data-ocr-model~=fileTypeRecordsHint]").ocrSmartAutoPopulateRTF( { showHeader: true, columns: [{name: 'Record Type', width: '150px', valueField: 'value'}, ], minLength: 0, position: { my: "left top", at: "left bottom", collision: "flip" }, source: function(req, response) { var re = $.ui.autocomplete.escapeRegex(req.term); var matcher = new RegExp( "^" + re, "i" ); filteredSmartDataRTF = rtHintsData; var result = $.grep(filteredSmartDataRTF, function(item){return matcher.test(item.value.value); }); response(result); }, focus : function(event, ui) { $('#autoCompleterDIVRTF').removeClass('ui-menu-item'); return false; }, select : function(event, ui) { /* issue#260: trigger the change event, when field value is changed */ $(this).val(ui.item.value.value).trigger('change'); return false; } }); /* add hint validations below */ $("input[data-ocr-model~=fileTypeRecordsHint]").on("focusout", function(e){ /* fix for the issue on IE8 - if focus goes to the smart field, it shouldn't validate */ if($(":focus").closest(".ui-autocomplete").length == 0 ){ var recordName = $(this).val().toUpperCase(); if(recordName && recordName != ''){ var validationSuccess = false; if(filteredSmartDataRTF && filteredSmartDataRTF.length > 0){ for(var i = 0; i < filteredSmartDataRTF.length; i++){ if(filteredSmartDataRTF[i].value.value.toUpperCase() == recordName){ validationSuccess = true; break; } } } if(!validationSuccess){ $(this).val(''); $(this).trigger('change'); $(this).focusout(); alert("Please enter a valid record type"); } } } }); /* trigger the auto completer on focus */ $("input[data-ocr-model~=fileTypeRecordsHint]").on("focus", function(e){ $(this).ocrSmartAutoPopulateRTF('search', $(this).val()); }); }, }; /* for creating search fields */ var ocrCreateSearchFlexFields = { name : 'OCR-JS', version : '1.0.0', defaults: { targetURL: '', recordType: '', tabName: '', groupName: '', enableUDF:true }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend(true, {}, this.defaults, options); this._build(); return this; }, _build: function(){ this.loadCustomFieldsOnSearch(); }, loadCustomFieldsOnSearch: function(){ var that = this; that.showLoader(); $.ajax({ type: "POST", url:'/common/getCustomFieldsForSearchPages.ocr?recordType=' + this.options.recordType, data: "", dataType: "json", cache: false, success: function(data){ that.createCustomFields(data); that.removeLoader(); /* initialize list fields */ $(".dataType-L").tagsInput({ 'defaultText':'add more' }); }, error: function(data){ $('#customFieldsDIV').hide();//For hiding custom field group, if there is any error to fatch data(custom field data). alert("its error here"); } }); }, createCustomFields: function(jsonArray){ $("#customFieldsDIV").html(""); var tabName = null; var tabId = null; var showTabExp = false; var grpName = null; var grpId = null; for(var i in jsonArray){ var json = jsonArray[i]; //console.log("json.groupName :"+json.tabName); //console.log("json.groupName :"+json.groupName); if(tabId != json.tabId){ showTabExp = true; var htmlTabExp = this.createTab(json.tabName, json.tabId); $("#customFieldsDIV").append(htmlTabExp); } if(grpId != json.groupId){ this.createGroup(json.groupName, json.groupId, json.tabName, json.tabId); } tabName = json.tabName; grpName = json.groupName; tabId = json.tabId; grpId = json.groupId; this.addCustomField(json); } if(!showTabExp){ $('#customFieldsDIV').hide();//For hiding custom field group, if there is no group(custom field data). } /* adding for number fields */ $('.dataType-N').keypress(function(e) { var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/); if (verified) {e.preventDefault();} }); /* initialize date picker */ $(".dataType-D").addClass("ocr-date"); //To enable/disable UDF var newDateFormat = userDateFormat; var newPlaceHolder = placeHolderDateFormat; if(!this.options.enableUDF){ newDateFormat = US_DATE_FORMAT; newPlaceHolder = US_DATE_FORMAT_PLACEHOLDER; } $( ".ocr-date" ).datepicker({ dateFormat: newDateFormat, placeHolderFormat: newPlaceHolder, changeMonth: true, changeYear: true, showButtonPanel:true, closeText:'Clear', beforeShow: function( input ) { setTimeout(function () { /* add clear button on the date picker */ var clearButton = $(input ).datepicker( "widget" ).find( ".ui-datepicker-close" ); clearButton.unbind("click").bind("click",function(){$.datepicker._clearDate( input );}); var todayButton = $(input ).datepicker( "widget" ).find( ".ui-datepicker-current" ); todayButton.unbind("click").bind("click",function(e){ e.preventDefault(); e.stopPropagation(); $(input).datepicker('hide'); $(input).datepicker('setDate', new Date()); }); }, 1 ); }, yearRange: '-50:+50'}); /* set the placeholder to show the date format */ if(! $( ".ocr-date" ).val()){ $( ".ocr-date" ).attr("placeholder", newPlaceHolder); } /* mark the field as readonly */ $( ".ocr-date" ).attr("readonly",true); /* instead of showing the default readonly cursor, show the default cursor as suggested */ $( ".ocr-date" ).css("cursor",'pointer'); }, //Create Tabs Panel createTab: function(tabName, tabId){ var tempTabName = 'TempTabName_' + tabId; var htmlTabExp = '
    '; return htmlTabExp; }, createGroup: function(groupName, groupId, tabName, tabId){ //console.log("creating group:"+groupName); var htmlForGrp = '
    '+groupName+'
    '; var html = htmlForGrp; var tempTabName = 'TempTabName_' + tabId; var divForFields = '#customFields_' + tempTabName; $(divForFields).append(html); }, addCustomField: function(json){ var fieldName = json.fieldName; var description = json.fieldDesc; var fieldId = json.customFieldId; var dataType = json.dataType; if(description == null){ description = ''; } //console.log("creating field:"+fieldName); $(".fieldSet:last").append('
    '); $(".lblField:last").append(fieldName); //To converting type to text on search pages. if(dataType == 'L' || dataType == 'A'){ dataType = 'V'; } if(dataType != 'F' && dataType != 'A'){ $(".inputField:last").append(''); } else if(dataType == 'F'){ $(".inputField:last").append(''); } else if(dataType == 'A'){ $(".inputField:last").append(''); } }, showLoader: function(){ var self = this.$element; this.$backdrop = $('
    ').appendTo(document.body); $(".loader-cont .loader-info").html(' '); $(".loader-cont").removeClass('hidden'); return this; }, removeLoader: function(){ $(".loader-cont").addClass('hidden'); this.$backdrop && this.$backdrop.remove(); this.$backdrop = null; } }; /* for creating custom fields for edit pages*/ var ocrCreateEditPageFlexFields = { name : 'OCR-JS', version : '1.0.0', defaults: { targetURL: '', recordType: '', recordRequestId: '', tabName: '', groupName: '', recordRequestIdFeldName: '', dTabNamePrefix: '', dTabNameSuff: '', idName: '', defaultCodeValue: '', enableUDF:true }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend(true, {}, this.defaults, options); this._build(); return this; }, _build: function(){ this.loadCustomFieldsForEditPage(); }, loadCustomFieldsForEditPage: function(){ var that = this; that.showLoader(); $.ajax({ type: "POST", url:'/common/getCustomFieldsForEditPages.ocr?recordType=' + this.options.recordType +'&recordRequestId=' + this.options.recordRequestId, data: "", dataType: "json", cache: false, async: false, success: function(data){ that.createCustomFieldsForEditPage(data); that.removeLoader(); /* initialize list fields */ $(".dataType-L").tagsInput({ 'defaultText':'add more' }); }, error: function(data){ //$('#customFieldsDIV').hide();//For hiding custom field group, if there is any error to fatch data(custom field data). alert("its error here to show custom fields data.."); } }); }, createCustomFieldsForEditPage: function(jsonArray){ var that = this; var toRepLi = '
  • '; //Following variable will be used for creating "HTML" for tab header. var tabHeaderHtml = '
    '; //Following variable will be used for creating "HTML" for custom tab(s) form(s). var custTabsFormDiv = ''; var tabName = null; var tabId = null; var showTabExp = false; var newTab = false; var grpName = null; var grpId = null; for(var i in jsonArray){ var json = jsonArray[i]; //console.log("json.groupName :"+json.tabName); //console.log("json.groupName :"+json.groupName); if(tabId != json.tabId){ showTabExp = true; var htmlTabExp = this.createTabForEditPage(json.tabName, json.tabId, toRepLi); tabHeaderHtml = tabHeaderHtml.replace(toRepLi, htmlTabExp); custTabsFormDiv = custTabsFormDiv + $('#custTabsFormDiv').html(); $('#custTabsFormDiv').html(''); var htmlTabForm = this.createTabFormForEditPage(json.tabName, json.tabId); $('#custTabsFormDiv').append(htmlTabForm); newTab = true; } if(grpId != json.groupId){ this.createGroupForEditPage(json.groupName, json.groupId, json.tabName, json.tabId, newTab); } newTab = false; tabId = json.tabId; grpId = json.groupId; tabName = json.tabName; grpName = json.groupName; this.addCustomFieldForEditPage(json); } tabHeaderHtml = '' + tabHeaderHtml.replace(toRepLi , ''); custTabsFormDiv = custTabsFormDiv + $('#custTabsFormDiv').html(); $('#custTabsFormDiv').html(''); $('#custTabsFormDiv').hide(''); custTabsFormDiv = '
    ' + custTabsFormDiv + '
    '; if(showTabExp){ var containerHtml = tabHeaderHtml + $('#container').html() + custTabsFormDiv; $('#container').html(); $('#container').html(containerHtml); $( "#tabs" ).tabs(); //For GUI $('.ui-tabs-nav li a').click(function () { $('.ui-tabs-nav li a').removeClass('selected'); $(this).addClass('selected'); }); $('#tabs').addClass('conftab '); $('.conftab .ui-tabs-nav').addClass('ocrTabsList'); $('.ocrTabsList li').addClass('pipe'); //To validate fields data. $(".validate").on("click", function(e){ if(this.id.indexOf('SAVE_BUTTON_') != -1){ var tabId = this.id; tabId = this.id.replace('SAVE_BUTTON_', ''); var formId = '#customDataForm_' + tabId; var isValid = true; var requiredFields = $(formId).find("input:text.required"); for(var i = 0; i < requiredFields.length; i++){ if(!$(requiredFields[i]).val()){ alert("Please fill values in all required fields."); isValid = false; e.preventDefault(); break; } } if(isValid){//For vaidating textarea var requiredFields = $(formId).find("textarea.required"); for(var i = 0; i < requiredFields.length; i++){ if(!$(requiredFields[i]).val()){ alert("Please fill values in all required fields."); isValid = false; e.preventDefault(); break; } } } if(isValid){ that.saveCustomFieldData(formId); } } }); } /* adding for number fields */ $('.dataType-N').keypress(function(e) { var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/); if (verified) {e.preventDefault();} }); //To enable/disable UDF var newDateFormat = userDateFormat; var newPlaceHolder = placeHolderDateFormat; if(!this.options.enableUDF){ newDateFormat = US_DATE_FORMAT; newPlaceHolder = US_DATE_FORMAT_PLACEHOLDER; } /* initialize date picker */ $(".ocr-date").removeClass("hasDatepicker"); $(".ocr-date").addClass("hasDatepicker11"); $(".dataType-D").addClass("ocr-date"); $( ".ocr-date" ).datepicker({ dateFormat: newDateFormat, placeHolderFormat: newPlaceHolder, changeMonth: true, changeYear: true, showButtonPanel:true, closeText:'Clear', beforeShow: function( input ) { setTimeout(function () { /* add clear button on the date picker */ var clearButton = $(input ).datepicker( "widget" ).find( ".ui-datepicker-close" ); clearButton.unbind("click").bind("click",function(){$.datepicker._clearDate( input );}); var todayButton = $(input ).datepicker( "widget" ).find( ".ui-datepicker-current" ); todayButton.unbind("click").bind("click",function(e){ e.preventDefault(); e.stopPropagation(); $(input).datepicker('hide'); $(input).datepicker('setDate', new Date()); }); }, 1 ); }, yearRange: '-50:+50'}); /* set the placeholder to show the date format */ if(! $( ".ocr-date" ).val()){ $( ".ocr-date" ).attr("placeholder", newPlaceHolder); } /* mark the field as readonly */ $( ".ocr-date" ).attr("readonly",true); /* instead of showing the default readonly cursor, show the default cursor as suggested */ $( ".ocr-date" ).css("cursor",'pointer'); //Fixing smart hint issues.. this.$element.ocrSmartHints(); }, //Creating Tabs on tab bar createTabForEditPage: function(tabName, tabId, toRepLi){ var htmlTabExp = '
  • '+ tabName +'
  • ' + toRepLi; return htmlTabExp; }, //Creating form for each tab with differnt form id(on the base of tabId) createTabFormForEditPage: function(tabName, tabId){ var htmlTabForm = '

    Additional Information

    '; return htmlTabForm; }, createGroupForEditPage: function(groupName, groupId, tabName, tabId, newTab){ var panelClassSuff = ''; if(newTab){ panelClassSuff = ' in'; } //console.log("creating group:"+groupName); //var htmlForGrp = '
    '+groupName+'
    '; var tempGroupName = 'Group_' + tabId + '_' + groupId; var htmlForGrp = ''; var html = htmlForGrp; var divForFields = '#customFieldsDIV_' + tabId; $(divForFields).append(html); }, addCustomFieldForEditPage: function(json){ var fieldId = json.customFieldId; var fieldName = json.fieldName; var dataType = json.dataType; var description = json.fieldDesc; var isInActive = false; var isRequired = (json.isRequired == "Y"); var fieldValue = (json.fieldData == 'null')?'':json.fieldData; if(description == null){ description = ''; } var tempGroupName = 'Group_' + json.tabId + '_' + json.groupId; var appendIn = '#customFieldsGroup_' + tempGroupName + ':last'; //console.log("creating field:"+fieldName+":"+fieldValue); $(appendIn).append('
    '); $(".lblField:last").append(fieldName); if(dataType != 'F' && dataType != 'A') $(".inputField:last").append(''); else if(dataType == 'F'){ if(fieldValue == 'true' || fieldValue == 'on') $(".inputField:last").append(''); else $(".inputField:last").append(''); } else if(dataType == 'A'){ $(".inputField:last").append(''); } if(dataType != 'F' && isRequired){ if(dataType == 'A'){ $("textarea:last").addClass("required"); }else{ $("input:text:last").addClass("required"); } $( "div.lblField" ).last().append('*'); } if(isInActive){ $(".inputField:last").addClass("disabled"); $("input:text:last").attr('disabled', 'disabled'); } }, saveCustomFieldData: function(formId){ var that = this; var recordType = that.options.recordType; var idValue = ''; var idFieldName = that.options.recordRequestIdFeldName; idFieldName = '[name="' + idFieldName + '"]'; idValue = $(idFieldName).val(); idValue = $.trim(idValue); if(($(idFieldName).val() == that.options.defaultCodeValue)){ idValue = ''; } var cbs = $(formId).find('input[type="checkbox"]:not(:checked)'); var uncheckedUrl = ''; $.each(cbs, function(index, value){ uncheckedUrl += '&'+$(this).attr('name')+'=off'; }); if(idValue && idValue != ''){ that.showLoader(); console.log("saving the form first "); $.ajax({ type : "POST", url : '/common/saveCustomFieldsInfo.ocr?recordType=' + recordType + '&recordRequestId=' + $.base64.encode(idValue), data : $(formId).serialize()+'&'+uncheckedUrl, cache : false, success : function(data) { that.removeLoader(); //console.log(" starting to autoclassify "); }, error : function(data) { that.removeLoader(); //console.log("its error while saving the form"); } }); }else{ alert('Data is not saved as ' + that.options.idName +' not defined.'); } }, showLoader: function(){ var self = this.$element; this.$backdrop = $('
    ').appendTo(document.body); $(".loader-cont .loader-info").html(' '); $(".loader-cont").removeClass('hidden'); return this; }, removeLoader: function(){ $(".loader-cont").addClass('hidden'); this.$backdrop && this.$backdrop.remove(); this.$backdrop = null; } }; /* for displaying tabs in the application */ var OcrTabs = { name : 'OCR-JS', version : '1.0.0', defaults: { queryStr: '', showNavButtons: false, tabsConfig: {} }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend({}, this.defaults, options); this._build(); return this; }, _build: function(){ this.createTabs(); this.initTabs(); if(this.options.showNavButtons) this.addNavigationButtons(); this.setupNavigation(); }, createTabs: function(){ var innerHTML = '
      '; var tabsConfig = this.options.tabsConfig; var tabConfig = null; for(var i=0; i'+tabConfig.displayName+''; } innerHTML += '
    '; this.$element.append(innerHTML); }, initTabs: function(){ this.$element.tabs({ cache: true, itemOptions: [ { cache: false } ], beforeLoad: function( event, ui ) { ui.jqXHR.error(function() { ui.panel.html("This is an error loading the tab details."); }); } }); /* load the default tab */ var tabsConfig = this.options.tabsConfig; var tabIndex = 0; for(var i=0; i
    '); }, setupNavigation: function(){ var self = this; $(".btnNext").click(function () { self.$element.tabs( "option", "active", $("#tabs").tabs('option', 'active')+1 ); }); $(".btnPrev").click(function () { self.$element.tabs( "option", "active", $("#tabs").tabs('option', 'active')-1 ); }); } }; /* PRJ-645: Custom field(s) componetes ends*/ /* for displaying colored flag fields */ var OcrFlagFields = { name : 'OCR-JS', version : '1.0.0', defaults: { colorOptions: [{color:'black', code: 'BR'}, {color:'red', code: 'RD'}, {color:'yellow', code:'YL'}, {color:'green', code:'GR'}, {color:'blue', code:'BL'}, {color:'orange', code:'OR'}, {color:'purple', code:'PR'}, {color:'pink', code:'PI'}, {color:'brown', code:'BN'}], defaultOption: {color:'black', code: 'BR'}, iconOptions: [{icon:'flag', code:'FL'},{icon:'info', code:'IN'},{icon:'gavel', code:'LE'},{icon:'lock', code:'LO'}, {icon:'check-square', code:'OK'}, {icon:'star', code:'SR'}, {icon:'hand-stop-o', code:'ST'}], iconDefaultOption: {icon:'flag', code: 'FL'}, $flagIcon: null, smallSize: false }, init: function(options, element) { this.$element = $(element); this.$iconElement = this.$element.closest('.form-group').find('[data-ocr-type="flagIcon"]'); this.options = jQuery.extend({}, this.defaults, options); this.options.smallSize = this.$element.data("small-size"); this._build(); return this; }, _build: function(){ this.initFlag(); this.loadFlag(); this.initActions(); }, initFlag: function(){ if(!this.options.$flagIcon){ var $flagIcon = $(''); if(!this.options.smallSize){ $flagIcon.css("font-size","24px"); } this.$element.before($flagIcon); this.$element.addClass("flag-field"); this.options.$flagIcon = $flagIcon; } }, loadFlag: function(){ var flagColorCode = this.$element.val(); var flagset = false; if(flagColorCode){ for(var i=0; i 0){ this.options.$flagIcon.addClass("fa-"+this.options.iconDefaultOption.icon); }*/ if(flagIconCode){ /* remove the icon class */ /*for(var i=0; i
    '); this.$element.find("table.jqplot-table-legend").replaceWith(legendDiv); $(legendDiv).html(legends); //$(legendDiv).style(''); this.$element.find("tr.jqplot-table-legend").addClass("jqplot-table-legend-label"); this.$element.find("tr.jqplot-table-legend").addClass("jqplot-seriesToggle"); this.$element.find(".jqplot-seriesToggle").css("cursor","pointer"); this.$element.find(".jqplot-seriesToggle").on('click', function(e){ var idx = $(this).index(); if(self.backupData && self.backupData[idx] == null){ self.backupData[idx] = self.data[idx][1]; self.data[idx][1] = 0; }else{ self.data[idx][1] = self.backupData[idx]; self.backupData[idx] = null; } //this.plot.destroy(); self.createPlot(self.data); for(var i = 0; i < self.backupData.length; i++){ if(self.backupData[i] != null && self.$element.find(".jqplot-table-legend-label").length >= i){ //$($(".jqplot-table-legend-label:nth-child("+(i+1)+"n)")[0]).css("text-decoration", "line-through"); $(self.$element.find("td.jqplot-table-legend-label").eq(i)).css("text-decoration", "line-through"); } } }); this.$element.find("table.jqplot-table-legend").css("z-index",50000); ///$("#chart1 table.jqplot-table-legend").css("z-index",50000); return plot1; }, }; var OcrGraphs = { name: 'OCR-Inc', version: '1.0.0', defaults: { data: [], xAxisTicks: [], yAxisPrefix: '', seriesDefaults: {rendererOptions: {fillToZero: true}, pointLabels: { show: true }}, seriesInfo: [], animate: true, zoom: false, showTooltip: true, fullscreen: false, xAxisLabel: '', yAxisLabel: '', onClickUrl: '' }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend({}, this.defaults, options); this.elementId = this.$element.attr('id'); this._setup(); return this; }, /* This will initialise the listeners on the elements and other setup related tasks */ _setup: function(){ this.generatePlot(); }, generatePlot: function(){ this.data = this.options.data; this.seriesInfo = this.options.seriesInfo; var seriesInfo = this.seriesInfo; if(seriesInfo){ for(var i=0; i'); var $thead = $('
    '); $thead.appendTo($tableElement); var $tbody = $(''); $tbody.appendTo($tableElement); $.each(dataVar, function(idx, arr){ var $tr = null; if(idx == 0){ $tr = $(''); }else{ $tr = $(''); } $.each(arr, function(index, data){ $tr.append(''); }); if(idx == 0){ $tr.appendTo($thead); }else{ $tr.appendTo($tbody); } }); $tableElement.appendTo(self.$element); }, }; var OcrFileDownload = { name: 'OCR-Inc', version: '1.0.0', defaults: { url: null, data: null }, init: function(options, element) { this.$element = $(element); this.options = jQuery.extend({}, this.defaults, options); this.elementId = this.$element.attr('id'); this._setup(); return this; }, /* This will initialise the listeners on the elements and other setup related tasks */ _setup: function(){ /* manipulate the url as required :Rakesh Arora */ this.options.url = $.manipulateUrlForCountrycodes({url: this.options.url}); var self = this; $.fileDownload(self.options.url, { data: self.options.data }); }, }; /* Add created plugins */ $.plugin('processMsg', ProcessMsg); $.plugin('processRequest', ProcessRequest); $.plugin('ocrGrid', OcrGrid); $.plugin('getUserList', GetUserList); $.plugin('changeActiveSbu', ChangeActiveSbu); /* Add plugins for Modular Popup */ // PRJ-49_OCR_FTZ-001 added new popup $.plugin('modularPopup',ModularPopup); $.plugin('ocrSmartHints', ocrSmartHints); $.plugin('getMaxExportExcelSize', getMaxExportExcelSize); $.plugin('initMultiCountry', initMultiCountry); $.plugin('initMultiCountryCode', initMultiCountryCode); $.plugin('initializeDatePickers', initializeDatePickers); $.plugin('ocrTabs',OcrTabs); $.plugin('ocrFlagFields',OcrFlagFields); /* PRJ-645: Adding created plugins for flex field(s) components*/ $.plugin('ocrSmartHintsFileTypeRecords', ocrSmartHintsFileTypeRecords); $.plugin('ocrCreateSearchFlexFields', ocrCreateSearchFlexFields); $.plugin('ocrCreateEditPageFlexFields', ocrCreateEditPageFlexFields); /* added the graphs support */ $.plugin('ocrPieGraphs', OcrPieGraphs); $.plugin('ocrGraphs', OcrGraphs); $.plugin('ocrSimpleTableGraph', OcrSimpleTableGraph); $.plugin('ocrFileDownload', OcrFileDownload); /* Register events for request processing */ $(document).on('click.processRequest.api', '[data-ocr-role="menu-link"], [data-ocr-role="ajax-link"], [data-ocr-role="modal-link"], [data-ocr-role="frame-link"], [data-ocr-role="tab-link"]', function(e){ $(this).blur(); $(this).processRequest(); e.preventDefault(); return false; }); $(document).on('submit.processRequest.api', '[data-ocr-role="ajax-form"], [data-ocr-role="modal-form"]', function(e){ $(this).processRequest(); e.preventDefault(); return false; }); $(document).on('submit.processRequest.api', '[data-ocr-role="native-form"]', function(e){ e.preventDefault(); return false; }); $(document).on('click.changeActiveSbu.api', '[data-ocr-role="sbu-select"]', function(e){ $(this).changeActiveSbu(); e.preventDefault(); return false; }); $(document).ready(function(){ $(document).getMaxExportExcelSize(); var ie = (function(){ var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '', all[0] ); return v > 4 ? v : undef; }()); if(ie == '8') $("html").addClass("lt-ie9"); if(ie == '9') $("html").addClass("lt-ie10"); var userAgent = navigator.userAgent; if(userAgent != null && userAgent.indexOf("MSIE 10.0") > -1){ $("html").addClass("ie10"); } /** collaps plus and minus icon*****************/ $('.slidingDiv').find('.show_hide').addClass("shChild"); $(".slidingDiv").hide(); $('.show_hide').click(function( e ){ var that = this; var children = $(this).closest('li').closest('li:not(.open)').find('.shChild').length; if(children){ if(children > 0){ if($(this).hasClass('shChild')){ toggleMenu(that); }else{ closeMenu(that); toggleMenu(that); } } }else{ closeMenu(that); toggleMenu(that); } }); var closeMenu = function (that){ if($(that).closest('li').find('.fa-minus-square').length == 0){ $('.fa-minus-square').closest('li').find('.slidingDiv').hide(300); $('.menu-width').find(".fa-minus-square").removeClass("fa-minus-square").addClass("fa-plus-square"); } }; var toggleMenu = function (that){ $(that).next(".slidingDiv").slideToggle(); if($(that).find(".fa-plus-square").length > 0) $(that).find(".fa-plus-square").removeClass("fa-plus-square").addClass("fa-minus-square"); else if($(that).find(".fa-minus-square").length > 0) $(that).find(".fa-minus-square").removeClass("fa-minus-square").addClass("fa-plus-square"); }; /* fix for rendering the icons correctly */ setTimeout(function(){ $.makeIe8FontCompatibile(); },20); }); /***************************** Menu Filter Start*****************/ $('.box').keyup(function(){ var valThis = $(this).val().toLowerCase(); var noresult = 0; if(valThis == ""){ //$('.navList > li').show(); $(this).closest('ul.navList').find('li').show(); $(this).parent().find(".fa-minus-square").trigger('click'); noresult = 1; $('.no-results-found').remove(); } else { var $tobeOpened = null; $(this).closest('ul.navList').find('li').each(function(){ var text = $(this).text().toLowerCase(); var match = text.indexOf(valThis); if (match >= 0) { $(this).show(); if($(this).closest('ul').closest('div').closest('li').find(".fa-plus-square:first").length > 0 && $tobeOpened == null) $tobeOpened = $(this).closest('ul').closest('div').closest('li').find(".fa-plus-square:first"); } else { $(this).hide(); } }); if($tobeOpened){ //alert("here its found"); $tobeOpened.trigger('click'); }else{ //alert("here not found"); } }; //if (noresult == 0) { // $(".navList").append('
  • No results found.
  • '); // } }); $(".show_hide").click(function() { var childs = $(this).closest('ul.dropdown-menu').find('.show_hide'); if(childs.index(this) >= childs.length -1){ $(".dropdown-menu").animate({ scrollTop: 520 }, "slow"); }else{ } return false; }); $(".moveUp").click(function() { var childs = $(this).closest('ul.dropdown-menu').find('.show_hide'); $(".dropdown-menu").animate({ scrollTop: 620 }, "slow"); }); /* * Misc. Plugins. */ /* Go to top function */ var goTop = function(){ var $goTop = $('#go-top'); var showMinHeight = 150; var duration = 300; var easing = 'swing'; $goTop.click(function() { $('html, body').stop().animate({ scrollTop : 0 }, duration, easing); }); $(window).scroll(function() { var sd = $(window).scrollTop(); if (sd > showMinHeight) { $goTop.fadeIn(); } else { $goTop.fadeOut(); } }); }; /* Function to calculate the empty area */ var windowResize = function(){ var contCont = $('#content-cont'); var frameCont = $('#frame-cont'); var pxToAdd = null; if(!contCont.hasClass('hidden') && frameCont.hasClass('hidden')){ if ($('.bottom-empty-row').css('min-height') != '30px'){ $('.bottom-empty-row').css('min-height','30px'); } var windowHeight = $(window).height(); contCont.css('min-height','0'); var contentHeight = $('header').outerHeight(true)+$('#content-cont').outerHeight(true)+$('footer').outerHeight(true)-25; if (contentHeight < windowHeight) { pxToAdd = windowHeight-contentHeight; $('.bottom-empty-row').css('min-height',pxToAdd+'px'); } } else if(contCont.hasClass('hidden') && !frameCont.hasClass('hidden')){ var windowHeight = $(window).height(); if (windowHeight > 500) { var frameHeight = windowHeight - ($('header').outerHeight(true) + $('footer').outerHeight(true) - 20); $('#frame-cont iframe').css('height',frameHeight+'px'); } } else if(contCont.hasClass('hidden') && frameCont.hasClass('hidden')) { var windowHeight = $(window).height(); var contentHeight = $('header').outerHeight(true) || 0 + $('footer').outerHeight(true) || 0; if (contentHeight < windowHeight) { pxToAdd = windowHeight-contentHeight; contCont.css('min-height',pxToAdd+'px'); if(contCont.hasClass('hidden')){ contCont.removeClass('hidden'); } } } }; $(window).resize(function() { windowResize(); }); $(window).load(function() { windowResize(); goTop(); }); /* Function to check null values */ $.hasValue = $.fn.hasValue = function (value) { var returnVal = true; if (value == null || value == undefined){ returnVal = false; } else { if(typeof value == 'string' && $.trim(value).length < 1){ returnVal = false; } } return returnVal; }; /* Add Favorite Menus */ $('#addFavorite').click(function() { if(!$('#content-cont').hasClass('hidden')){ var url = $('#lastUsedLink_').val(); var pageHeading = $('.page-heading').html(); var module = $('#module_').val(); if($('#canAddToFav_').val() == 'true'){ if($.hasValue(url) && url != '#'){ url = 'addFavourite.ocr?favUrl='+url+'&urlTitle='+pageHeading+'&module='+module; $(this).processRequest({ url: url, role: 'modal-link' }); } } else { alert('The selected page can\'t be as favorite.'); } } else if(!$('#frame-cont').hasClass('hidden')){ var module = $('#module_').val(); var url = $('#frame-cont iframe').prop('src'); var title = $('#frame-cont iframe').contents().find('title').html(); if ((/search/i).test(title)) { if($.hasValue(url) && url != '#'){ url = 'addFavourite.ocr?favUrl='+url+'&urlTitle='+title+'&module='+module; $(this).processRequest({ url: url, role: 'modal-link' }); } } else { alert('The selected page can\'t be as favorite.'); } } return false; }); /* Set Module Default Page */ $('#setDefaultPage').click(function() { if(!$('#content-cont').hasClass('hidden')){ var module = $('#module_').val(); var url = $('#lastUsedLink_').val(); var pageHeading = $('.page-heading').html(); if($('#canAddToFav_').val() == 'true'){ if($.hasValue(url) && url != '#'){ url = 'addAsDefaultPage.ocr?pageUrl='+url+'&urlTitle='+pageHeading+'&module='+module; $(this).processRequest({ url: url, role: 'modal-link' }); } } else { alert('The selected page can\'t be added as module default.'); } }else if(!$('#frame-cont').hasClass('hidden')){ var module = $('#module_').val(); var url = $('#frame-cont iframe').prop('src'); var title = $('#frame-cont iframe').contents().find('title').html(); if ((/search/i).test(title)) { if($.hasValue(url) && url != '#'){ url = 'addAsDefaultPage.ocr?pageUrl='+url+'&urlTitle='+title+'&module='+module; $(this).processRequest({ url: url, role: 'modal-link' }); } } else { alert('The selected page can\'t be added as module default.'); } } return false; }); /* Function to open a popup window */ $.fn.popupWindow = function ( options ) { options = $.extend( {}, $.fn.popupWindow.options, options ); return this.each(function () { window.open(options.url, '', 'toolbar=0,scrollbars=1,location=0,status=1,menubars=0,resizable=1,width='+options.width+',height='+options.height+',top=10,left=25').focus(); }); }; $.fn.popupWindow.options = { url: '', windowName: 'helpwindow', width: 750, height: 700 }; /* Function to validate 'beginDate' and 'endDate' date fields */ $.fn.validateDateRange = function (options) { options = $.extend({}, $.fn.validateDateRange.options, options); var isValid=false; var format=userDateFormat; if(options.enableUDF == false){ format = US_DATE_FORMAT; } if($(options.endDate).val() != null && $(options.endDate).val() != ""){ if($(options.beginDate).val() != null && $(options.beginDate).val() != ""){ var beginDate = $.datepicker.parseDate(format, $(options.beginDate).val()); var endDate = $.datepicker.parseDate(format, $(options.endDate).val()); if (beginDate <= endDate) { isValid=true; } } }else{ isValid=true; } return isValid; }; $.fn.validateDateRange.options = { beginDate: '', endDate: '', }; /* TODO: need to review this method code: popup on popup POC work */ $.fn.jsonify = function(options) { var settings = $.extend({ stringify : false }, options); var json = {}; $.each(this.serializeArray(), function() { if (json[this.name]) { if (!json[this.name].push) json[this.name] = [json[this.name]]; json[this.name].push(this.value || ''); } else json[this.name] = this.value || ''; }); if(settings.stringify) return JSON.stringify(json); else return json; }; /* End: popup on popup POC work */ /* Open module help links */ $(document).on('click.popup.api', '[data-ocr-role="pop750x700"], [data-ocr-role="pop510x450"], [data-ocr-role="pop490x280"]', function(e){ var width = 750; var height = 700; var windowName = 'helpwindow'; if ($(this).data('ocr-role') == 'pop510x450'){ windowName = 'whoAmI'; width = 510; height = 450; } if ($(this).data('ocr-role') == 'pop510x450'){ windowName = 'aboutEase'; width = 490; height = 280; } $(this).popupWindow({ url: $(this).prop('href'), windowName: windowName, width: width, height: height }); e.preventDefault(); return false; }); /* Mark alerts as read */ $('#mark-alert-viewed').click(function() { $.ajax({ context: document.body, dataType: 'html', type: 'POST', url: '/user/markAlerts.ocr', success: function(response) { $('.alerts .badge').addClass('hidden'); } }); return false; }); /* Disable context menu for modal links */ $(document).on('contextmenu', function(e) { if ($(e.target).is("[data-ocr-role='modal-link']") || $(e.target).is("[data-toggle='modal']")){ return false; } }); /* Override the jquery Ajax */ $.ajax = (function(ajax){ return function(option){ var basePage = $('#fr_').val(); var data = option.data; if(data == undefined || data == null || data ==''){ data = 'fr_='+basePage; } else if(jQuery.type(data) == 'string'){ data += '&fr_='+basePage; } option.data = data; return ajax.apply(this, arguments); }; })($.ajax); /* EASE-4622 Function to display the font icons in ie8 on initial load */ $.makeIe8FontCompatibile = function(){ if($("html").hasClass("lt-ie9")){ var head = document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; style.styleSheet.cssText = ':before,:after{content:none !important'; head.appendChild(style); setTimeout(function(){ head.removeChild(style); }, 0); } }; /* $(".slidingDiv").hide(); $(".show_hide").click(function(){ if ($('.slidingDiv').is(':visible')) { $(".slidingDiv").slideUp(500); //$(".fa").addClass("fa-plus-square"); } $(this).next(".slidingDiv").slideDown(500); $('.fa').removeClass("fa-plus-square").addClass("fa-minus-square"); if($('.menu-width').find(".fa-minus-square").length > 0) $('.menu-width').find(".fa-minus-square").removeClass("fa-minus-square").addClass("fa-plus-square"); }); */ /* EASE-4584 Function to print content inside a div */ $.printContent = function(content){ var win = window.open('','_blank'); win.document.open(); win.document.write('OCR Services, Inc. | Export & Import Global Trade Compliance Software Solutions'); win.document.write(''); win.document.write(''); win.document.write(content.html()); win.document.write('function PrintPage() { window.print(); window.close(); } window.onload = PrintPage;'); win.document.write(''); win.document.close(); win.focus(); }; //PRJ-84 Added feature for unloading the MultiCountry $.unloadMultiCountry = function ($element){ var id = $element.attr('id'); $("#"+id+"_tagsinput").remove(); $("#"+id).removeClass('hasMultiCountry').show(); }; /* Function to open a popup window */ $.manipulateUrlForCountrycodes = function ( options ) { options = $.extend( {}, $.manipulateUrlForCountrycodes.options, options ); if(options.url && $("#activeSbuLicensedCountry").val() && $("#activeSbuLicensedCountry").val() != 'US' && (options.url.indexOf('/itts/')>=0 || options.url.indexOf('/ead/')>=0 || options.url.indexOf('/gead/')>=0 || options.url.indexOf('/gaes/')>=0)){ var parts = options.url.split("?"); var queryPart = null; if(parts.length > 1) queryPart = parts[1]; var tempUrl = parts[0]; tempUrl = tempUrl.replace("/ead/","/gead/"); //alert("original url :"+temp); parts = tempUrl.split("\/"); tempUrl = ""; for(var i=0;i < (parts.length -1);i++ ){ tempUrl += parts[i]+"/"; } tempUrl+= "global/"; if($("#activeSbuCountryGroup").val()){ //append only if the country group code doesn't exist in the url if(tempUrl.indexOf("/"+$("#activeSbuCountryGroup").val().toLowerCase()+"/") < 0) tempUrl+= $("#activeSbuCountryGroup").val().toLowerCase()+"/"; } //append only if the country code doesn't exist in the url if(tempUrl.indexOf("/"+$("#activeSbuLicensedCountry").val().toLowerCase()+"/") < 0) tempUrl+= $("#activeSbuLicensedCountry").val().toLowerCase()+"/"; tempUrl += parts[parts.length -1] ; if(queryPart) options.url = tempUrl+'?'+queryPart; else options.url = tempUrl; } return options.url; }; $.manipulateUrlForCountrycodes.options = { url: '' }; $.getCountryNameForCode = function(countryCode){ if(!countryJson){ countryJson = {}; if(countrySmartFieldData){ for(var j = 0; j < countrySmartFieldData.length; j++){ countryJson[countrySmartFieldData[j].code]= countrySmartFieldData[j].value; } } } return countryJson[countryCode]; }; /* This method will change the sbu, and redirect to the given url, only if the active sbu is different than the selSbu */ $.changeSbuAndRedirect = function(selSbu, modId, pageTo, redirectUrl){ var sbuText = $(".sbu-list").find("a:first").text(); sbuText = $.trim(sbuText); var texts = sbuText.split(" - "); var activeSbu = $.trim(texts[0]); var currentSbuCountry = $.trim(texts[1]); if(selSbu == ""){ alert("Please Select SBU"); return false; } var selSbuCountry = $.getCountryForSbu(selSbu); if(selSbuCountry != currentSbuCountry){ alert("Active SBU will be changed to "+selSbu+"."); $.ajax({ context: document.body, data: "", async: false, cache: true, dataType: 'html', type: 'POST', url: '/user/updateSbuFromDropDown.ocr?sbuCode='+$.base64.encode(selSbu), success: function(response) { var object = $.parseJSON(response); if(object.sbuLicensedCountry != "") $('.sbu-list > a').html(object.sbuCode + " - " + object.sbuLicensedCountry); else $('.sbu-list > a').html(object.sbuCode); var url = window.location.href; // Returns full URL /* remove the previously redirected URL */ var lastIndex = url.lastIndexOf("redirect="); if(lastIndex >= 1){ url = url.substring(0,lastIndex-1); } lastIndex = url.lastIndexOf("?m="); if(lastIndex >= 1){ url = url.substring(0,lastIndex); } /* remove the # from url */ lastIndex = url.lastIndexOf("#"); if(lastIndex >= 1){ url = url.substring(0,lastIndex); } lastIndex = url.lastIndexOf("?continue"); if(lastIndex >= 1){ url = url.substring(0,lastIndex); } redirectUrl = $.base64.encode(redirectUrl); if(url.indexOf("?") != -1 ){ url=url+"&redirect="+ $.base64.encode("Y")+"&pageTo="+$.base64.encode(pageTo)+"&modId="+$.base64.encode(modId)+"&redirectUrl="+redirectUrl; }else{ url=url+"?redirect="+ $.base64.encode("Y")+"&pageTo="+$.base64.encode(pageTo)+"&modId="+$.base64.encode(modId)+"&redirectUrl="+redirectUrl; } window.history.replaceState("string", "", url); location.reload(); } }); }else{ $(document.forms[0]).processRequest({url: redirectUrl, role: 'ajax-link'}); } } /**This method will change the sbu as per the selected country. Only active and assigned sbu will be populated in the dropdown. * Params details are as under: * selectedCountryCode : Country code selected by the user. * selSbuCode : Sbu dropdown object. * activeSbuCountryCode : Active Sbu country code. * activeSbuCount : Number of AciveSbu against the Active Sbu country. * fromWhere : This parameter is to identify the screen from which this method has been called. */ $.fetchActiveSbuForCountry = function(selectedCountryCode, selSbuCode, activeSbuCountryCode,activeSbuCount,fromWhere,module){ var sbuText = $(".sbu-list").find("a:first").text(); sbuText = $.trim(sbuText); var texts = sbuText.split(" - "); var activeSbu = $.trim(texts[0]); if(selectedCountryCode == null || selectedCountryCode == ''){ selSbuCode.html($("
    '+data+'