Utils.js 28.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

19
define(['require', 'utils/Globals', 'pnotify', 'utils/Messages', 'utils/Enums', 'pnotify.buttons', 'pnotify.confirm'], function(require, Globals, pnotify, Messages, Enums) {
20 21 22
    'use strict';

    var Utils = {};
23
    var prevNetworkErrorTime = 0;
24 25 26 27 28 29 30 31 32 33 34 35

    Utils.escapeHtml = function(string) {
        var entityMap = {
            "&": "&",
            "<": "&lt;",
            ">": "&gt;",
            '"': '&quot;',
            "'": '&#39;',
            "/": '&#x2F;'
        };
        return String(string).replace(/[&<>"'\/]/g, function(s) {
            return entityMap[s];
36
        });
37
    }
38 39 40

    Utils.generatePopover = function(options) {
        if (options.el) {
41
            var defaultObj = {
42 43
                placement: 'auto bottom',
                html: true,
44
                animation: false,
45 46 47 48 49 50
                container: 'body'
            };
            if (options.viewFixedPopover || options.contentClass) {
                defaultObj.template = '<div class="popover ' + (options.viewFixedPopover ? 'fixed-popover' : '') + ' fade bottom"><div class="arrow"></div><h3 class="popover-title"></h3><div class="' + (options.contentClass ? options.contentClass : '') + ' popover-content"></div></div>';
            }
            return options.el.popover(_.extend(defaultObj, options.popoverOptions));
51 52 53 54 55 56 57 58 59 60 61 62 63
        }
    }

    Utils.getNumberSuffix = function(options) {
        if (options && options.number) {
            var n = options.number,
                s = ["th", "st", "nd", "rd"],
                v = n % 100,
                suffix = (s[(v - 20) % 10] || s[v] || s[0]);
            return n + (options.sup ? '<sup>' + suffix + '</sup>' : suffix);
        }
    }

64 65 66 67 68 69 70 71 72 73 74 75
    Utils.generateUUID = function() {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now(); //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    };
76 77 78
    Utils.getBaseUrl = function(url) {
        return url.replace(/\/[\w-]+.(jsp|html)|\/+$/ig, '');
    };
79
    Utils.getEntityIconPath = function(options) {
80 81 82 83
        var entityData = options && options.entityData,
            serviceType,
            status,
            typeName,
84
            iconBasePath = Utils.getBaseUrl(window.location.pathname) + Globals.entityImgPath;
85 86
        if (entityData) {
            typeName = entityData.typeName;
87 88 89 90
            serviceType = entityData && entityData.serviceType;
            status = entityData && entityData.status;
        }

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        function getImgPath(imageName) {
            return iconBasePath + (Enums.entityStateReadOnly[status] ? "disabled/" + imageName : imageName);
        }

        function getDefaultImgPath() {
            if (entityData.isProcess) {
                if (Enums.entityStateReadOnly[status]) {
                    return iconBasePath + 'disabled/process.png';
                } else {
                    return iconBasePath + 'process.png';
                }
            } else {
                if (Enums.entityStateReadOnly[status]) {
                    return iconBasePath + 'disabled/table.png';
                } else {
                    return iconBasePath + 'table.png';
                }
            }
        }

111 112
        if (entityData) {
            if (options.errorUrl) {
113 114
                var isErrorInTypeName = (options.errorUrl && options.errorUrl.match("entity-icon/" + typeName + ".png|disabled/" + typeName + ".png") ? true : false);
                if (serviceType && isErrorInTypeName) {
115
                    var imageName = serviceType + ".png";
116
                    return getImgPath(imageName);
117
                } else {
118
                    return getDefaultImgPath();
119
                }
120
            } else if (entityData.typeName) {
121
                var imageName = entityData.typeName + ".png";
122 123 124
                return getImgPath(imageName);
            } else {
                return getDefaultImgPath();
125 126 127 128
            }
        }
    }

129
    pnotify.prototype.options.styling = "fontawesome";
130
    var notify = function(options) {
131 132 133 134 135 136 137 138 139 140 141 142 143
        return new pnotify(_.extend({
            icon: true,
            hide: true,
            delay: 3000,
            remove: true,
            buttons: {
                classes: {
                    closer: 'fa fa-times',
                    pin_up: 'fa fa-pause',
                    pin_down: 'fa fa-play'
                }
            }
        }, options));
144
    }
145
    Utils.notifyInfo = function(options) {
146 147
        notify({
            type: "info",
148
            text: (options.html ? options.content : _.escape(options.content)) || "Info message."
149 150
        });
    };
151

152
    Utils.notifyWarn = function(options) {
153 154
        notify({
            type: "notice",
155
            text: (options.html ? options.content : _.escape(options.content)) || "Info message."
156 157 158 159
        });
    };

    Utils.notifyError = function(options) {
160
        notify({
161
            type: "error",
162
            text: (options.html ? options.content : _.escape(options.content)) || "Error occurred."
163 164 165 166
        });
    };

    Utils.notifySuccess = function(options) {
167
        notify({
168
            type: "success",
169
            text: (options.html ? options.content : _.escape(options.content)) || "Error occurred."
170 171
        });
    };
172 173

    Utils.notifyConfirm = function(options) {
174 175 176
        var modal = {};
        if (options && options.modal) {
            var myStack = { "dir1": "down", "dir2": "right", "push": "top", 'modal': true };
177
            modal['addclass'] = 'stack-modal ' + (options.modalClass ? modalClass : 'width-500');
178 179
            modal['stack'] = myStack;
        }
180 181 182 183
        notify(_.extend({
            title: 'Confirmation',
            hide: false,
            confirm: {
184 185
                confirm: true,
                buttons: [{
186
                        text: options.cancelText || 'Cancel',
187 188 189 190 191 192 193
                        addClass: 'btn-action btn-md',
                        click: function(notice) {
                            options.cancel(notice);
                            notice.remove();
                        }
                    },
                    {
194
                        text: options.okText || 'Ok',
195 196 197 198 199 200 201
                        addClass: 'btn-atlas btn-md',
                        click: function(notice) {
                            options.ok(notice);
                            notice.remove();
                        }
                    }
                ]
202 203 204 205 206 207 208 209
            },
            buttons: {
                closer: false,
                sticker: false
            },
            history: {
                history: false
            }
210 211

        }, modal, options)).get().on('pnotify.confirm', function() {
212 213 214 215 216 217 218 219 220
            if (options.ok) {
                options.ok();
            }
        }).on('pnotify.cancel', function() {
            if (options.cancel) {
                options.cancel();
            }
        });
    }
221
    Utils.defaultErrorHandler = function(model, error) {
222 223 224 225 226 227 228 229
        if (error && error.status) {
            if (error.status == 401) {
                window.location = 'login.jsp'
            } else if (error.status == 419) {
                window.location = 'login.jsp'
            } else if (error.status == 403) {
                var message = "You are not authorized";
                if (error.statusText) {
230 231 232 233 234 235
                    try {
                        message = JSON.parse(error.statusText).AuthorizationError;
                    } catch (err) {}
                    Utils.notifyError({
                        content: message
                    });
236 237 238 239 240 241 242 243 244 245
                }
            } else if (error.status == "0" && error.statusText != "abort") {
                var diffTime = (new Date().getTime() - prevNetworkErrorTime);
                if (diffTime > 3000) {
                    prevNetworkErrorTime = new Date().getTime();
                    Utils.notifyError({
                        content: "Network Connection Failure : " +
                            "It seems you are not connected to the internet. Please check your internet connection and try again"
                    });
                }
246
            } else {
247
                Utils.serverErrorHandler(model, error)
248
            }
249 250 251 252 253 254 255
        } else {
            Utils.serverErrorHandler(model, error)
        }
    };
    Utils.serverErrorHandler = function(model, response) {
        var responseJSON = response ? response.responseJSON : response;
        if (response && responseJSON && (responseJSON.errorMessage || responseJSON.message || responseJSON.error)) {
256
            Utils.notifyError({
257 258 259 260 261
                content: responseJSON.errorMessage || responseJSON.message || responseJSON.error
            });
        } else {
            Utils.notifyError({
                content: Messages.defaultErrorMessage
262
            });
263
        }
264 265
    };
    Utils.cookie = {
266
        setValue: function(cname, cvalue) {
267
            document.cookie = cname + "=" + cvalue + "; ";
268
        },
269
        getValue: function(findString) {
270 271 272 273 274 275 276 277 278 279
            var search = findString + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1);
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
280 281 282 283 284 285 286 287 288 289
        }
    };
    Utils.localStorage = function() {
        this.setValue = function() {
            localStorage.setItem(arguments[0], arguments[1]);
        }
        this.getValue = function(key, value) {
            var keyValue = localStorage.getItem(key);
            if ((!keyValue || keyValue == "undefined") && (value != undefined)) {
                return this.setLocalStorage(key, value);
290
            } else {
291 292 293 294 295 296
                if (keyValue === "" || keyValue === "undefined" || keyValue === "null") {
                    return null;
                } else {
                    return keyValue;
                }

297 298
            }
        }
299 300 301 302 303 304 305 306 307
        this.removeValue = function() {
            localStorage.removeItem(arguments[0]);
        }
        if (typeof(Storage) === "undefined") {
            _.extend(this, Utils.cookie);
            console.log('Sorry! No Web Storage support');
        }
    }
    Utils.localStorage = new Utils.localStorage();
308 309 310 311

    Utils.setUrl = function(options) {
        if (options) {
            if (options.mergeBrowserUrl) {
312 313
                var param = Utils.getUrlState.getQueryParams();
                if (param) {
314
                    options.urlParams = $.extend(param, options.urlParams);
315 316 317
                }
            }
            if (options.urlParams) {
318
                var urlParams = "?";
319
                _.each(options.urlParams, function(value, key, obj) {
320
                    if (value) {
321
                        value = encodeURIComponent(String(value));
322 323
                        urlParams += key + "=" + value + "&";
                    }
324 325 326 327
                });
                urlParams = urlParams.slice(0, -1);
                options.url += urlParams;
            }
328
            if (options.updateTabState) {
329 330 331 332 333 334 335
                var urlUpdate = {
                    stateChanged: true
                };
                if (Utils.getUrlState.isTagTab(options.url)) {
                    urlUpdate['tagUrl'] = options.url;
                } else if (Utils.getUrlState.isSearchTab(options.url)) {
                    urlUpdate['searchUrl'] = options.url;
336 337
                } else if (Utils.getUrlState.isGlossaryTab(options.url)) {
                    urlUpdate['glossaryUrl'] = options.url;
338 339
                }
                $.extend(Globals.saveApplicationState.tabState, urlUpdate);
340
            }
341 342
            Backbone.history.navigate(options.url, { trigger: options.trigger != undefined ? options.trigger : true });
        }
343
    };
344 345

    Utils.getUrlState = {
346
        getQueryUrl: function(url) {
347
            var hashValue = window.location.hash;
348 349 350
            if (url) {
                hashValue = url;
            }
351 352 353 354 355 356 357
            return {
                firstValue: hashValue.split('/')[1],
                hash: hashValue,
                queyParams: hashValue.split("?"),
                lastValue: hashValue.split('/')[hashValue.split('/').length - 1]
            }
        },
358 359 360 361 362 363
        checkTabUrl: function(options) {
            var url = options && options.url,
                matchString = options && options.matchString,
                quey = this.getQueryUrl(url);
            return quey.firstValue == matchString || quey.queyParams[0] == "#!/" + matchString;
        },
364
        isInitial: function() {
365
            return this.getQueryUrl().firstValue == undefined;
366
        },
367
        isTagTab: function(url) {
368 369 370 371
            return this.checkTabUrl({
                url: url,
                matchString: "tag"
            });
372
        },
373
        isSearchTab: function(url) {
374 375 376 377
            return this.checkTabUrl({
                url: url,
                matchString: "search"
            });
378
        },
379
        isGlossaryTab: function(url) {
380 381 382 383
            return this.checkTabUrl({
                url: url,
                matchString: "glossary"
            });
384
        },
385
        isDetailPage: function(url) {
386 387 388 389
            return this.checkTabUrl({
                url: url,
                matchString: "detailPage"
            });
390
        },
391 392 393 394 395 396
        getLastValue: function() {
            return this.getQueryUrl().lastValue;
        },
        getFirstValue: function() {
            return this.getQueryUrl().firstValue;
        },
397 398
        getQueryParams: function(url) {
            var qs = this.getQueryUrl(url).queyParams[1];
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
            if (typeof qs == "string") {
                qs = qs.split('+').join(' ');
                var params = {},
                    tokens,
                    re = /[?&]?([^=]+)=([^&]*)/g;
                while (tokens = re.exec(qs)) {
                    params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
                }
                return params;
            }
        },
        getKeyValue: function(key) {
            var paramsObj = this.getQueryParams();
            if (key.length) {
                var values = [];
                _.each(key, function(objKey) {
                    var obj = {};
                    obj[objKey] = paramsObj[objKey]
                    values.push(obj);
                    return values;
                })
            } else {
                return paramsObj[key];
            }
        }
    }
425 426 427 428 429 430 431 432
    Utils.getName = function() {
        return Utils.extractKeyValueFromEntity.apply(this, arguments).name;
    }
    Utils.getNameWithProperties = function() {
        return Utils.extractKeyValueFromEntity.apply(this, arguments);
    }
    Utils.extractKeyValueFromEntity = function() {
        var collectionJSON = arguments[0],
433 434 435 436 437 438 439
            priorityAttribute = arguments[1],
            skipAttribute = arguments[2],
            returnObj = {
                name: '-',
                found: true,
                key: null
            }
440 441
        if (collectionJSON) {
            if (collectionJSON.attributes && collectionJSON.attributes[priorityAttribute]) {
442 443 444
                returnObj.name = _.escape(collectionJSON.attributes[priorityAttribute]);
                returnObj.key = priorityAttribute;
                return returnObj;
445 446
            }
            if (collectionJSON[priorityAttribute]) {
447 448 449
                returnObj.name = _.escape(collectionJSON[priorityAttribute]);
                returnObj.key = priorityAttribute;
                return returnObj;
450 451 452
            }
            if (collectionJSON.attributes) {
                if (collectionJSON.attributes.name) {
453 454 455
                    returnObj.name = _.escape(collectionJSON.attributes.name);
                    returnObj.key = 'name';
                    return returnObj;
456
                }
457 458 459 460 461
                if (collectionJSON.attributes.displayName) {
                    returnObj.name = _.escape(collectionJSON.attributes.displayName);
                    returnObj.key = 'displayName';
                    return returnObj;
                }
462
                if (collectionJSON.attributes.qualifiedName) {
463 464 465
                    returnObj.name = _.escape(collectionJSON.attributes.qualifiedName);
                    returnObj.key = 'qualifiedName';
                    return returnObj;
466
                }
467 468 469 470 471 472 473 474 475 476
                if (collectionJSON.attributes.displayText) {
                    returnObj.name = _.escape(collectionJSON.attributes.displayText);
                    returnObj.key = 'displayText';
                    return returnObj;
                }
                if (collectionJSON.attributes.guid) {
                    returnObj.name = _.escape(collectionJSON.attributes.guid);
                    returnObj.key = 'guid';
                    return returnObj;
                }
477
                if (collectionJSON.attributes.id) {
478 479 480 481 482 483 484
                    if (_.isObject(collectionJSON.attributes.id)) {
                        if (collectionJSON.id.id) {
                            returnObj.name = _.escape(collectionJSON.attributes.id.id);
                        }
                    } else {
                        returnObj.name = _.escape(collectionJSON.attributes.id);
                    }
485 486
                    returnObj.key = 'id';
                    return returnObj;
487 488 489
                }
            }
            if (collectionJSON.name) {
490 491 492
                returnObj.name = _.escape(collectionJSON.name);
                returnObj.key = 'name';
                return returnObj;
493
            }
494 495 496 497 498
            if (collectionJSON.displayName) {
                returnObj.name = _.escape(collectionJSON.displayName);
                returnObj.key = 'displayName';
                return returnObj;
            }
499
            if (collectionJSON.qualifiedName) {
500 501 502
                returnObj.name = _.escape(collectionJSON.qualifiedName);
                returnObj.key = 'qualifiedName';
                return returnObj;
503 504
            }
            if (collectionJSON.displayText) {
505 506 507
                returnObj.name = _.escape(collectionJSON.displayText);
                returnObj.key = 'displayText';
                return returnObj;
508 509
            }
            if (collectionJSON.guid) {
510 511 512
                returnObj.name = _.escape(collectionJSON.guid);
                returnObj.key = 'guid';
                return returnObj;
513 514
            }
            if (collectionJSON.id) {
515 516 517 518 519 520 521
                if (_.isObject(collectionJSON.id)) {
                    if (collectionJSON.id.id) {
                        returnObj.name = _.escape(collectionJSON.id.id);
                    }
                } else {
                    returnObj.name = _.escape(collectionJSON.id);
                }
522 523
                returnObj.key = 'id';
                return returnObj;
524 525
            }
        }
526
        returnObj.found = false;
527 528 529 530 531 532 533 534 535 536
        if (skipAttribute && returnObj.key == skipAttribute) {
            return {
                name: '-',
                found: true,
                key: null
            }
        } else {
            return returnObj;
        }

537
    }
538
    Utils.showTitleLoader = function(loaderEl, titleBoxEl) {
539
        loaderEl.css ? loaderEl.css({
540 541 542 543 544 545
            'display': 'block',
            'position': 'relative',
            'height': '85px',
            'marginTop': '85px',
            'marginLeft': '50%',
            'left': '0%'
546 547
        }) : null;
        titleBoxEl.hide ? titleBoxEl.hide() : null;
548 549
    }
    Utils.hideTitleLoader = function(loaderEl, titleBoxEl) {
550 551
        loaderEl.hide ? loaderEl.hide() : null;
        titleBoxEl.fadeIn ? titleBoxEl.fadeIn() : null;
552
    }
553 554 555
    Utils.findAndMergeRefEntity = function(options) {
        var attributeObject = options.attributeObject,
            referredEntities = options.referredEntities
556
        var mergeObject = function(obj) {
557 558 559 560 561 562 563 564
            if (obj) {
                if (obj.attributes) {
                    Utils.findAndMergeRefEntity(obj.attributes, referredEntities);
                } else if (referredEntities[obj.guid]) {
                    _.extend(obj, referredEntities[obj.guid]);
                }
            }
        }
565 566 567 568 569
        if (attributeObject && referredEntities) {
            _.each(attributeObject, function(obj, key) {
                if (_.isObject(obj)) {
                    if (_.isArray(obj)) {
                        _.each(obj, function(value) {
570
                            mergeObject(value);
571 572
                        });
                    } else {
573
                        mergeObject(obj);
574 575 576 577 578
                    }
                }
            });
        }
    }
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
    Utils.getNestedSuperTypes = function(options) {
        var data = options.data,
            collection = options.collection,
            superTypes = [];

        var getData = function(data, collection) {
            superTypes = superTypes.concat(data.superTypes);

            if (data.superTypes && data.superTypes.length) {
                _.each(data.superTypes, function(superTypeName) {
                    if (collection.fullCollection) {
                        var collectionData = collection.fullCollection.findWhere({ name: superTypeName }).toJSON();
                    } else {
                        var collectionData = collection.findWhere({ name: superTypeName }).toJSON();
                    }
                    return getData(collectionData, collection);
                });
            }
        }
        getData(data, collection);
        return _.uniq(superTypes);
    }
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    Utils.getNestedSuperTypeObj = function(options) {
        var flag = 0,
            data = options.data,
            collection = options.collection;
        if (options.attrMerge) {
            var attributeDefs = [];
        } else {
            var attributeDefs = {};
        }
        var getData = function(data, collection) {
            if (options.attrMerge) {
                attributeDefs = attributeDefs.concat(data.attributeDefs);
            } else {
                if (attributeDefs[data.name]) {
                    if (_.isArray(attributeDefs[data.name])) {
                        attributeDefs[data.name] = attributeDefs[data.name].concat(data.attributeDefs);
                    } else {
                        _.extend(attributeDefs[data.name], data.attributeDefs);
                    }
620

621 622 623 624 625 626 627
                } else {
                    attributeDefs[data.name] = data.attributeDefs;
                }
            }
            if (data.superTypes && data.superTypes.length) {
                _.each(data.superTypes, function(superTypeName) {
                    if (collection.fullCollection) {
628
                        var collectionData = collection.fullCollection.findWhere({ name: superTypeName });
629
                    } else {
630 631 632 633 634 635 636
                        var collectionData = collection.findWhere({ name: superTypeName });
                    }
                    collectionData = collectionData && collectionData.toJSON ? collectionData.toJSON() : collectionData;
                    if (collectionData) {
                        return getData(collectionData, collection);
                    } else {
                        return;
637 638 639 640 641
                    }
                });
            }
        }
        getData(data, collection);
642
        return attributeDefs;
643
    }
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731

    Utils.getProfileTabType = function(profileData, skipData) {
        var parseData = profileData.distributionData;
        if (_.isString(parseData)) {
            parseData = JSON.parse(parseData);
        }
        var createData = function(type) {
            var orderValue = [],
                sort = false;
            if (type === "date") {
                var dateObj = {};
                _.keys(parseData).map(function(key) {
                    var splitValue = key.split(":");
                    if (!dateObj[splitValue[0]]) {
                        dateObj[splitValue[0]] = {
                            value: splitValue[0],
                            monthlyCounts: {},
                            totalCount: 0 // use when count is null
                        }
                    }
                    if (dateObj[splitValue[0]] && splitValue[1] == "count") {
                        dateObj[splitValue[0]].count = parseData[key];
                    }
                    if (dateObj[splitValue[0]] && splitValue[1] !== "count") {
                        dateObj[splitValue[0]].monthlyCounts[splitValue[1]] = parseData[key];
                        if (!dateObj[splitValue[0]].count) {
                            dateObj[splitValue[0]].totalCount += parseData[key]
                        }
                    }
                });
                return _.toArray(dateObj).map(function(obj) {
                    if (!obj.count && obj.totalCount) {
                        obj.count = obj.totalCount
                    }
                    return obj
                });
            } else {
                var data = [];
                if (profileData.distributionKeyOrder) {
                    orderValue = profileData.distributionKeyOrder;
                } else {
                    sort = true;
                    orderValue = _.keys(parseData);
                }
                _.each(orderValue, function(key) {
                    if (parseData[key]) {
                        data.push({
                            value: key,
                            count: parseData[key]
                        });
                    }
                });
                if (sort) {
                    data = _.sortBy(data, function(o) {
                        return o.value.toLowerCase()
                    });
                }
                return data;
            }
        }
        if (profileData && profileData.distributionType) {
            if (profileData.distributionType === "count-frequency") {
                return {
                    type: "string",
                    label: Enums.profileTabType[profileData.distributionType],
                    actualObj: !skipData ? createData("string") : null,
                    xAxisLabel: "FREQUENCY",
                    yAxisLabel: "COUNT"
                }
            } else if (profileData.distributionType === "decile-frequency") {
                return {
                    label: Enums.profileTabType[profileData.distributionType],
                    type: "numeric",
                    xAxisLabel: "DECILE RANGE",
                    actualObj: !skipData ? createData("numeric") : null,
                    yAxisLabel: "FREQUENCY"
                }
            } else if (profileData.distributionType === "annual") {
                return {
                    label: Enums.profileTabType[profileData.distributionType],
                    type: "date",
                    xAxisLabel: "",
                    actualObj: !skipData ? createData("date") : null,
                    yAxisLabel: "COUNT"
                }
            }
        }
    }
732

733 734 735 736
    Utils.isUrl = function(url) {
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
        return regexp.test(url);
    }
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760

    Utils.JSONPrettyPrint = function(obj) {
        var replacer = function(match, pIndent, pKey, pVal, pEnd) {
                var key = '<span class=json-key>';
                var val = '<span class=json-value>';
                var str = '<span class=json-string>';
                var r = pIndent || '';
                if (pKey)
                    r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
                if (pVal)
                    r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
                return r + (pEnd || '');
            },
            jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
        if (obj && _.isObject(obj)) {
            return JSON.stringify(obj, null, 3)
                .replace(/&/g, '&amp;').replace(/\\"/g, '&quot;')
                .replace(/</g, '&lt;').replace(/>/g, '&gt;')
                .replace(jsonLine, replacer);
        } else {
            return {};
        }
    };

761 762 763 764 765 766 767
    $.fn.toggleAttribute = function(attributeName, firstString, secondString) {
        if (this.attr(attributeName) == firstString) {
            this.attr(attributeName, secondString);
        } else {
            this.attr(attributeName, firstString);
        }
    }
768
    return Utils;
769
});