diff --git a/web/pgadmin/about/static/js/about.js b/web/pgadmin/about/static/js/about.js
index c692ae1c..1e72c917 100644
--- a/web/pgadmin/about/static/js/about.js
+++ b/web/pgadmin/about/static/js/about.js
@@ -1,13 +1,13 @@
 define(
   ['jquery', 'alertify', 'sources/pgadmin', 'underscore.string', 'sources/gettext',
-   'sources/url_for'
+    'sources/url_for',
   ],
   function($, alertify, pgAdmin, S, gettext, url_for) {
     pgAdmin = pgAdmin || window.pgAdmin || {};
 
     /* Return back, this has been called more than once */
     if (pgAdmin.About)
-        return;
+      return;
 
     pgAdmin.About = {
       about_show: function() {
@@ -20,14 +20,14 @@ define(
               },
               setup: function() {
                 return {
-                  buttons:[{ text: gettext("OK"), key: 27, className: "btn btn-primary" }],
+                  buttons:[{ text: gettext('OK'), key: 27, className: 'btn btn-primary' }],
                   options: {
                     modal: false,
                     resizable: true,
                     maximizable: true,
                     pinnable: false,
-                    closableByDimmer: false
-                  }
+                    closableByDimmer: false,
+                  },
                 };
               },
               build: function() {
@@ -35,19 +35,18 @@ define(
               },
               prepare:function() {
                 this.setContent(this.message);
-              }
+              },
             };
           });
         }
 
-        var content = '';
         $.get(url_for('about.index'),
             function(data) {
               alertify.aboutDialog(
-                  S(gettext("About %s")).sprintf(pgAdmin.Browser.utils.app_name).value(), data
+                  S(gettext('About %s')).sprintf(pgAdmin.Browser.utils.app_name).value(), data
               ).resizeTo(800, 450);
             });
-      }
+      },
     };
 
     return pgAdmin.About;
diff --git a/web/pgadmin/dashboard/static/js/dashboard.js b/web/pgadmin/dashboard/static/js/dashboard.js
index 0da32f60..6fcef0fb 100644
--- a/web/pgadmin/dashboard/static/js/dashboard.js
+++ b/web/pgadmin/dashboard/static/js/dashboard.js
@@ -1,14 +1,15 @@
 define('pgadmin.dashboard', [
-    'sources/url_for', 'sources/gettext', 'require', 'jquery', 'underscore',
-    'sources/pgadmin', 'backbone', 'backgrid', 'flotr2',
-    'pgadmin.alertifyjs', 'backgrid.filter',
-    'pgadmin.browser', 'bootstrap', 'wcdocker'
-    ],
-function(url_for, gettext, r, $, _, pgAdmin, Backbone, Backgrid, Flotr,
-  alertify) {
-
-  var wcDocker = window.wcDocker,
-  pgBrowser = pgAdmin.Browser;
+  'sources/url_for', 'sources/gettext', 'require', 'jquery', 'underscore',
+  'sources/pgadmin', 'backbone', 'backgrid', 'flotr2',
+  'pgadmin.alertifyjs', 'pgadmin.backform', 'backgrid.filter',
+  'pgadmin.browser', 'bootstrap', 'wcdocker',
+], function(
+  url_for, gettext, r, $, _, pgAdmin, Backbone, Backgrid, Flotr,
+  Alertify, Backform
+) {
+
+  pgAdmin.Browser = pgAdmin.Browser || {};
+  var pgBrowser = pgAdmin.Browser;
 
   /* Return back, this has been called more than once */
   if (pgAdmin.Dashboard)
@@ -24,102 +25,103 @@ function(url_for, gettext, r, $, _, pgAdmin, Backbone, Backgrid, Flotr,
 
   // Custom BackGrid cell, Responsible for cancelling active sessions
   var customDashboardActionCell = Backgrid.Extension.DeleteCell.extend({
-        render: function () {
-          this.$el.empty();
-          var self = this,
-            cell_action = self.column.get('cell_action');
-          // if cancel query button then
-          if (cell_action === 'cancel') {
-            this.$el.html(
-              "<i class='fa fa-stop' data-toggle='tooltip' " +
-              "title='" + gettext('Cancel the active query') +
-              "'></i>"
-            );
-          } else {
-            this.$el.html(
-              "<i class='fa fa-times-circle' data-toggle='tooltip' " +
-              "title='" + gettext('Terminate the session') +
-              "'></i>"
-            );
-          }
-          this.delegateEvents();
-          return this;
-        },
-        deleteRow: function(e) {
-          var self = this,
-            title, txtConfirm, txtSuccess, txtError, action_url,
-            cell_action = self.column.get('cell_action');
-
-          e.preventDefault();
-
-          var canDeleteRow = Backgrid.callByNeed(
-            self.column.get('canDeleteRow'), self.column, self.model
-          );
-          // If we are not allowed to cancel the query, return from here
-          if(!canDeleteRow)
-            return;
-
-          // This will refresh the grid
-          var refresh_grid = function() {
-            if(is_server_dashboard) {
-              $('#btn_server_activity_refresh').click();
-            } else if(is_database_dashboard) {
-              $('#btn_database_activity_refresh').click();
-            }
-          };
-
-          if (cell_action === 'cancel') {
-            title = gettext('Cancel Active Query?');
-            txtConfirm = gettext('Are you sure you wish to cancel the active query?');
-            txtSuccess = gettext('Active query cancelled successfully.')
-            txtError = gettext('An error occurred whilst cancelling the active query.')
-            action_url = cancel_query_url + self.model.get('pid')
-          } else {
-            title = gettext('Terminate Session?');
-            txtConfirm = gettext('Are you sure you wish to terminate the session?');
-            txtSuccess = gettext('Session terminated successfully.')
-            txtError = gettext('An error occurred whilst terminating the active query.')
-            action_url = terminate_session_url + self.model.get('pid')
-          }
+    render: function() {
+      this.$el.empty();
+      var self = this,
+        cell_action = self.column.get('cell_action');
+      // if cancel query button then
+      if (cell_action === 'cancel') {
+        this.$el.html(
+          '<i class=\'fa fa-stop\' data-toggle=\'tooltip\' ' +
+          'title=\'' + gettext('Cancel the active query') +
+          '\'></i>'
+        );
+      } else {
+        this.$el.html(
+          '<i class=\'fa fa-times-circle\' data-toggle=\'tooltip\' ' +
+          'title=\'' + gettext('Terminate the session') +
+          '\'></i>'
+        );
+      }
+      this.delegateEvents();
+      return this;
+    },
+    deleteRow: function(e) {
+      var self = this,
+        title, txtConfirm, txtSuccess, txtError, action_url,
+        cell_action = self.column.get('cell_action');
+
+      e.preventDefault();
+
+      var canDeleteRow = Backgrid.callByNeed(
+        self.column.get('canDeleteRow'), self.column, self.model
+      );
+      // If we are not allowed to cancel the query, return from here
+      if (!canDeleteRow)
+        return;
+
+      // This will refresh the grid
+      var refresh_grid = function() {
+        if (is_server_dashboard) {
+          $('#btn_server_activity_refresh').click();
+        } else if (is_database_dashboard) {
+          $('#btn_database_activity_refresh').click();
+        }
+      };
+
+      if (cell_action === 'cancel') {
+        title = gettext('Cancel Active Query?');
+        txtConfirm = gettext('Are you sure you wish to cancel the active query?');
+        txtSuccess = gettext('Active query cancelled successfully.');
+        txtError = gettext('An error occurred whilst cancelling the active query.');
+        action_url = cancel_query_url + self.model.get('pid');
+      } else {
+        title = gettext('Terminate Session?');
+        txtConfirm = gettext('Are you sure you wish to terminate the session?');
+        txtSuccess = gettext('Session terminated successfully.');
+        txtError = gettext('An error occurred whilst terminating the active query.');
+        action_url = terminate_session_url + self.model.get('pid');
+      }
 
-          alertify.confirm(
-            title,
-            txtConfirm,
-            function(evt) {
-              $.ajax({
-                url: action_url,
-                type:'DELETE',
-                success: function(res) {
-                  if (res == gettext('Success')) {
-                    alertify.success(txtSuccess);
-                    refresh_grid();
-                  } else {
-                    alertify.error(txtError);
-                  }
-                },
-                error: function(xhr, status, error) {
-                  try {
-                    var err = $.parseJSON(xhr.responseText);
-                    if (err.success == 0) {
-                      alertify.error(err.errormsg);
-                    }
-                  } catch (e) {}
+      Alertify.confirm(
+        title, txtConfirm,
+        function() {
+          $.ajax({
+            url: action_url,
+            type: 'DELETE',
+            success: function(res) {
+              if (res == gettext('Success')) {
+                Alertify.success(txtSuccess);
+                refresh_grid();
+              } else {
+                Alertify.error(txtError);
+              }
+            },
+            error: function(xhr) {
+              try {
+                var err = $.parseJSON(xhr.responseText);
+                if (err.success == 0) {
+                  Alertify.error(err.errormsg);
                 }
-              });
+              } catch (e) {
+                console.warn(e.stack || e);
+              }
             },
-            function(evt) {
-              return true;
-            }
-          );
+          });
+        },
+        function() {
+          return true;
         }
+      );
+    },
   });
 
 
   // Subnode Cell, which will display subnode control
   var SessionDetailsCell = Backgrid.Extension.ObjectCell.extend({
-   enterEditMode: function () {
+    enterEditMode: function() {
       // Notify that we are about to enter in edit mode for current cell.
-      this.model.trigger("enteringEditMode", [this]);
+      this.model.trigger('enteringEditMode', [this]);
 
       Backgrid.Cell.prototype.enterEditMode.apply(this, arguments);
       /* Make sure - we listen to the click event */
@@ -128,1159 +130,1204 @@ function(url_for, gettext, r, $, _, pgAdmin, Backbone, Backgrid, Flotr,
 
       if (editable) {
         this.$el.html(
-          "<i class='fa fa-caret-down subnode-edit-in-process'></i>"
-          );
+          '<i class=\'fa fa-caret-down subnode-edit-in-process\'></i>'
+        );
         this.model.trigger(
-          "pg-sub-node:opened", this.model, this
-          );
+          'pg-sub-node:opened', this.model, this
+        );
       }
     },
-    render: function(){
-        this.$el.empty();
-        this.$el.html(
-          "<i class='fa fa-caret-right' data-toggle='tooltip' " +
-          "title='" + gettext('View the active session details') +
-          "'></i>"
-        );
-        this.delegateEvents();
-        if (this.grabFocus)
-          this.$el.focus();
-        return this;
-    }
+    render: function() {
+      this.$el.empty();
+      this.$el.html(
+        '<i class=\'fa fa-caret-right\' data-toggle=\'tooltip\' ' +
+        'title=\'' + gettext('View the active session details') +
+        '\'></i>'
+      );
+      this.delegateEvents();
+      if (this.grabFocus)
+        this.$el.focus();
+      return this;
+    },
   });
 
   // Subnode Model
   var ActiveQueryDetailsModel = Backbone.Model.extend({
     defaults: {
-      version: null /* Postgres version */
+      version: null,
+      /* Postgres version */
     },
     schema: [{
-      id: 'backend_type', label: gettext('Backend type'),
-      type: 'text', editable: true, disabled: true,
+      id: 'backend_type',
+      label: gettext('Backend type'),
+      type: 'text',
+      editable: true,
+      disabled: true,
       group: gettext('Details'),
-      visible: function(m) {
+      visible: function() {
         return this.version >= 100000;
-      }
-    },{
-      id: 'query_start', label: gettext('Query started at'),
-      type: 'text', editable: false, disabled: true,
-      group: gettext('Details')
-    },{
-      id: 'state_change', label: gettext('Last state changed at'),
-      type: 'text', editable: true, disabled: true,
-      group: gettext('Details')
-    },{
-      id: 'query', label: gettext('SQL'),
-      type: 'text', editable: true, disabled: true,
+      },
+    }, {
+      id: 'query_start',
+      label: gettext('Query started at'),
+      type: 'text',
+      editable: false,
+      disabled: true,
+      group: gettext('Details'),
+    }, {
+      id: 'state_change',
+      label: gettext('Last state changed at'),
+      type: 'text',
+      editable: true,
+      disabled: true,
+      group: gettext('Details'),
+    }, {
+      id: 'query',
+      label: gettext('SQL'),
+      type: 'text',
+      editable: true,
+      disabled: true,
       control: Backform.SqlFieldControl,
-      group: gettext('Details')
-    }]
+      group: gettext('Details'),
+    }],
   });
 
   pgAdmin.Dashboard = {
-        init: function() {
-            if (this.initialized)
-                return;
-
-            this.initialized = true;
-
-            // Bind the Dashboard object with the 'object_selected' function
-            var selected = this.object_selected.bind(this);
-            var disconnected = this.object_disconnected.bind(this);
-
-            // Listen for selection of any of object
-            pgBrowser.Events.on('pgadmin-browser:tree:selected', selected);
-
-            // Listen for server disconnected event
-            pgBrowser.Events.on('pgadmin:server:disconnect', disconnected);
-
-            // Load the default welcome dashboard
-            var url = url_for('dashboard.index');
-
-            var dashboardPanel = pgBrowser.panels['dashboard'].panel;
-            if (dashboardPanel) {
-                var div = dashboardPanel.layout().scene().find('.pg-panel-content');
-
-                if (div) {
-                    $.ajax({
-                        url: url,
-                        type: "GET",
-                        dataType: "html",
-                        success: function (data) {
-                            $(div).html(data);
-                        },
-                        error: function (xhr, status) {
-                            $(div).html(
-                                '<div class="alert alert-danger pg-panel-message" role="alert">' + gettext('An error occurred whilst loading the dashboard.') + '</div>'
-                            );
-                        }
-                    });
-
-                    // Cache the current IDs for next time
-                    $(dashboardPanel).data('sid', -1)
-                    $(dashboardPanel).data('did', -1)
-                }
-            }
-        },
-
-        // Handle Server Disconnect
-        object_disconnected: function(obj) {
-            this.object_selected(obj.item, obj.data, pgBrowser.Nodes[obj.data._type]);
-        },
+    init: function() {
+      if (this.initialized)
+        return;
 
-        // Handle treeview clicks
-        object_selected: function(item, itemData, node) {
-            if (itemData && itemData._type && dashboardVisible) {
-                var treeHierarchy = node.getTreeNodeHierarchy(item),
-                    url = url_for('dashboard.index'),
-                    sid = -1, did = -1, b = pgAdmin.Browser,
-                    m = b && b.Nodes[itemData._type];
-
-                cancel_query_url = url_for('dashboard.index') + 'cancel_query/';
-                terminate_session_url = url_for('dashboard.index') + 'terminate_session/';
-
-                // Check if user is super user
-                var server = treeHierarchy['server'];
-                maintenance_database = (server && server.db) || null;
-
-                if(server && server.user && server.user.is_superuser) {
-                  is_super_user = true;
-                } else {
-                  is_super_user = false;
-                  // Set current user
-                  current_user = (server && server.user) ? server.user.name : null;
-                }
+      this.initialized = true;
 
-                if (m && m.dashboard) {
-                    if (_.isFunction(m.dashboard)) {
-                        url = m.dashboard.apply(
-                            item, itemData, node, treeHierarchy
-                        );
-                    } else {
-                        url = m.dashboard;
-                    }
-                } else {
-                    if ('database' in treeHierarchy) {
-                        sid = treeHierarchy.server._id;
-                        did = treeHierarchy.database._id;
-                        is_server_dashboard = false;
-                        is_database_dashboard = true;
-                        url += sid + '/' + did;
-                        cancel_query_url += sid + '/' + did + '/';
-                        terminate_session_url += sid + '/' + did + '/';
-                    } else if ('server' in treeHierarchy) {
-                        sid = treeHierarchy.server._id;
-                        is_server_dashboard = true;
-                        is_database_dashboard = false;
-                        url += sid;
-                        cancel_query_url += sid + '/';
-                        terminate_session_url += sid + '/';
-                    }
-                }
+      // Bind the Dashboard object with the 'object_selected' function
+      var selected = this.object_selected.bind(this);
+      var disconnected = this.object_disconnected.bind(this);
 
-                var dashboardPanel = pgBrowser.panels['dashboard'].panel;
-                if (dashboardPanel) {
-                    var div = dashboardPanel.layout().scene().find(
-                            '.pg-panel-content'
-                        );
-
-                    if (div) {
-                        if (itemData.connected || _.isUndefined(itemData.connected)) {
-                            // Avoid unnecessary reloads
-                            if (url != $(dashboardPanel).data('dashboard_url') ||
-                               (url == $(dashboardPanel).data('dashboard_url') && $(dashboardPanel).data('server_status') == false )) {
-                                // Clear out everything so any existing timers die off
-                                $(div).empty();
-
-                                $.ajax({
-                                    url: url,
-                                    type: "GET",
-                                    dataType: "html",
-                                    success: function (data) {
-                                        $(div).html(data);
-                                    },
-                                    error: function (xhr, status) {
-                                        $(div).html(
-                                            '<div class="alert alert-danger pg-panel-message" role="alert">' + gettext('An error occurred whilst loading the dashboard.') + '</div>'
-                                        );
-                                    }
-                                });
-                                $(dashboardPanel).data('server_status', true);
-                            }
-
-                        }
-                        else {
-                            $(div).empty();
-                            $(div).html(
-                                '<div class="alert alert-info pg-panel-message" role="alert">' + gettext('Please connect to the selected server to view the dashboard.') + '</div>'
-                            );
-                            $(dashboardPanel).data('server_status', false);
-                        }
-                        // Cache the current IDs for next time
-                        $(dashboardPanel).data('dashboard_url', url);
-
-                    }
-                }
-            }
-        },
+      // Listen for selection of any of object
+      pgBrowser.Events.on('pgadmin-browser:tree:selected', selected);
 
-        // Render a chart
-        render_chart: function(container, data, dataset, sid, did, url, options, counter, refresh) {
+      // Listen for server disconnected event
+      pgBrowser.Events.on('pgadmin:server:disconnect', disconnected);
 
-            // Data format:
-            // [
-            //     { data: [[0, y0], [1, y1]...], label: 'Label 1', [options] },
-            //     { data: [[0, y0], [1, y1]...], label: 'Label 2', [options] },
-            //     { data: [[0, y0], [1, y1]...], label: 'Label 3', [options] }
-            // ]
+      // Load the default welcome dashboard
+      var url = url_for('dashboard.index');
 
-            if (!dashboardVisible)
-              return;
+      var dashboardPanel = pgBrowser.panels['dashboard'].panel;
+      if (dashboardPanel) {
+        var div = dashboardPanel.layout().scene().find('.pg-panel-content');
 
-            var y = 0;
-            if (dataset.length == 0) {
-                if (counter == true)
-                {
-                    // Have we stashed initial values?
-                    if (_.isUndefined($(container).data('counter_previous_vals'))) {
-                        $(container).data('counter_previous_vals', data[0])
-                    } else {
-                        // Create the initial data structure
-                        for (var x in data[0]) {
-                            dataset.push({ 'data': [[0, data[0][x] - $(container).data('counter_previous_vals')[x]]], 'label': x });
-                        }
-                    }
-                } else {
-                    // Create the initial data structure
-                    for (var x in data[0]) {
-                        dataset.push({ 'data': [[0, data[0][x]]], 'label': x });
-                    }
-                }
-            } else {
-                for (var x in data[0]) {
-                    // Push new values onto the existing data structure
-                    // If this is a counter stat, we need to subtract the previous value
-                    if (counter == false) {
-                        dataset[y]['data'].unshift([0, data[0][x]]);
-                    } else {
-                        // Store the current value, minus the previous one we stashed.
-                        // It's possible the tab has been reloaded, in which case out previous values are gone
-                        if (_.isUndefined($(container).data('counter_previous_vals')))
-                            return
-
-                        dataset[y]['data'].unshift([0, data[0][x] - $(container).data('counter_previous_vals')[x]]);
-                    }
-
-                    // Reset the time index to get a proper scrolling display
-                    for (var z = 0; z < dataset[y]['data'].length; z++) {
-                        dataset[y]['data'][z][0] = z;
-                    }
-
-                    y++;
-                }
-                $(container).data('counter_previous_vals', data[0])
-            }
+        if (div) {
+          $.ajax({
+            url: url,
+            type: 'GET',
+            dataType: 'html',
+            success: function(data) {
+              $(div).html(data);
+            },
+            error: function() {
+              $(div).html(
+                '<div class="alert alert-danger pg-panel-message" role="alert">' + gettext('An error occurred whilst loading the dashboard.') + '</div>'
+              );
+            },
+          });
 
-             // Remove uneeded elements
-            for (x = 0; x < dataset.length; x++) {
-                // Remove old data points
-                if (dataset[x]['data'].length > 101) {
-                    dataset[x]['data'].pop();
-                }
-            }
+          // Cache the current IDs for next time
+          $(dashboardPanel).data('sid', -1);
+          $(dashboardPanel).data('did', -1);
+        }
+      }
+    },
 
-            // Draw Graph, if the container still exists and has a size
-            var dashboardPanel = pgBrowser.panels['dashboard'].panel;
-            var div = dashboardPanel.layout().scene().find('.pg-panel-content');
-            if ($(div).find(container).length) { // Exists?
-                if (container.clientHeight > 0 && container.clientWidth > 0) { // Not hidden?
-                    Flotr.draw(container, dataset, options);
-                }
-            } else {
-                return;
-            }
+    // Handle Server Disconnect
+    object_disconnected: function(obj) {
+      this.object_selected(obj.item, obj.data, pgBrowser.Nodes[obj.data._type]);
+    },
 
-            // Animate
-            var setTimeoutFunc = function () {
-                var path = url + sid;
-                if (did != -1) {
-                    path += '/' + did;
-                }
-                $.ajax({
-                    url: path,
-                    type: "GET",
-                    dataType: "html",
-                    success: function (resp) {
-                        $(container).removeClass('graph-error')
-                        data = JSON.parse(resp);
-                        pgAdmin.Dashboard.render_chart(container, data, dataset, sid, did, url, options, counter, refresh);
-                    },
-                    error: function (xhr, status, msg) {
-                        var err = $.parseJSON(xhr.responseText),
-                            msg = err.errormsg,
-                            cls;
-                        // If we get a 428, it means the server isn't connected
-                        if (xhr.status == 428) {
-                            if (_.isUndefined(msg) || _.isNull(msg)) {
-                              msg = gettext('Please connect to the selected server to view the graph.');
-                            }
-                            cls = 'info';
-                        } else {
-                            msg = gettext('An error occurred whilst rendering the graph.');
-                            cls = 'danger';
-                        }
-
-                        $(container).addClass('graph-error');
-                        $(container).html(
-                            '<div class="alert alert-' + cls + ' pg-panel-message" role="alert">' + msg + '</div>'
-                        );
-
-                        // Try again...
-                        if (container.clientHeight > 0 && container.clientWidth > 0) {
-                            setTimeout(setTimeoutFunc, refresh * 1000);
-                        }
-                    },
-                });
-            };
+    // Handle treeview clicks
+    object_selected: function(item, itemData, node) {
+      if (itemData && itemData._type && dashboardVisible) {
+        var treeHierarchy = node.getTreeNodeHierarchy(item),
+          url = url_for('dashboard.index'),
+          sid = -1,
+          did = -1,
+          b = pgAdmin.Browser,
+          m = b && b.Nodes[itemData._type];
+
+        cancel_query_url = url_for('dashboard.index') + 'cancel_query/';
+        terminate_session_url = url_for('dashboard.index') + 'terminate_session/';
+
+        // Check if user is super user
+        var server = treeHierarchy['server'];
+        maintenance_database = (server && server.db) || null;
+
+        if (server && server.user && server.user.is_superuser) {
+          is_super_user = true;
+        } else {
+          is_super_user = false;
+          // Set current user
+          current_user = (server && server.user) ? server.user.name : null;
+        }
 
-            setTimeout(setTimeoutFunc, refresh * 1000);
-        },
+        if (m && m.dashboard) {
+          if (_.isFunction(m.dashboard)) {
+            url = m.dashboard.apply(
+              item, itemData, node, treeHierarchy
+            );
+          } else {
+            url = m.dashboard;
+          }
+        } else {
+          if ('database' in treeHierarchy) {
+            sid = treeHierarchy.server._id;
+            did = treeHierarchy.database._id;
+            is_server_dashboard = false;
+            is_database_dashboard = true;
+            url += sid + '/' + did;
+            cancel_query_url += sid + '/' + did + '/';
+            terminate_session_url += sid + '/' + did + '/';
+          } else if ('server' in treeHierarchy) {
+            sid = treeHierarchy.server._id;
+            is_server_dashboard = true;
+            is_database_dashboard = false;
+            url += sid;
+            cancel_query_url += sid + '/';
+            terminate_session_url += sid + '/';
+          }
+        }
 
-        // Handler function to support the "Add Server" link
-        add_new_server: function() {
-            if (pgBrowser && pgBrowser.tree) {
-                var i = pgBrowser.tree.selected().length != 0 ?
-                          pgBrowser.tree.selected() :
-                          pgBrowser.tree.first(null, false),
-                     serverModule = r('pgadmin.node.server'),
-                     itemData = pgBrowser.tree.itemData(i);
-
-                while (itemData && itemData._type != "server_group") {
-                    i = pgBrowser.tree.next(i);
-                    itemData = pgBrowser.tree.itemData(i);
-                }
+        var dashboardPanel = pgBrowser.panels['dashboard'].panel;
+        if (dashboardPanel) {
+          var div = dashboardPanel.layout().scene().find(
+            '.pg-panel-content'
+          );
 
-                if (!itemData) {
-                    return;
-                }
+          if (div) {
+            if (itemData.connected || _.isUndefined(itemData.connected)) {
+              // Avoid unnecessary reloads
+              if (url != $(dashboardPanel).data('dashboard_url') ||
+                (url == $(dashboardPanel).data('dashboard_url') && $(dashboardPanel).data('server_status') == false)) {
+                // Clear out everything so any existing timers die off
+                $(div).empty();
 
-                if (serverModule) {
-                    serverModule.callbacks.show_obj_properties.apply(
-                        serverModule, [{action: 'create'}, i]
+                $.ajax({
+                  url: url,
+                  type: 'GET',
+                  dataType: 'html',
+                  success: function(data) {
+                    $(div).html(data);
+                  },
+                  error: function() {
+                    $(div).html(
+                      '<div class="alert alert-danger pg-panel-message" role="alert">' + gettext('An error occurred whilst loading the dashboard.') + '</div>'
                     );
-                }
-            }
-        },
-
-        // Render a grid
-        render_grid: function(container, sid, did, url, columns) {
-            var Datum = Backbone.Model.extend({});
+                  },
+                });
+                $(dashboardPanel).data('server_status', true);
+              }
 
-            var path = url + sid;
-            if (did != -1) {
-                path += '/' + did;
+            } else {
+              $(div).empty();
+              $(div).html(
+                '<div class="alert alert-info pg-panel-message" role="alert">' + gettext('Please connect to the selected server to view the dashboard.') + '</div>'
+              );
+              $(dashboardPanel).data('server_status', false);
             }
+            // Cache the current IDs for next time
+            $(dashboardPanel).data('dashboard_url', url);
 
-            var Data = Backbone.Collection.extend({
-              model: Datum,
-              url: path,
-              mode: "client"
-            });
-
-            var data = new Data();
-
-            // Set up the grid
-            var grid = new Backgrid.Grid({
-              columns: columns,
-              collection: data,
-              className: "backgrid table-bordered presentation table backgrid-striped"
-            });
-
-            // Render the grid
-            $(container).append(grid.render().el)
+          }
+        }
+      }
+    },
 
-            // Initialize a client-side filter to filter on the client
-            // mode pageable collection's cache.
-            var filter = new Backgrid.Extension.ClientSideFilter({
-              collection: data
+    // Render a chart
+    render_chart: function(
+      container, data, dataset, sid, did, url, options, counter, refresh
+    ) {
+
+      // Data format:
+      // [
+      //     { data: [[0, y0], [1, y1]...], label: 'Label 1', [options] },
+      //     { data: [[0, y0], [1, y1]...], label: 'Label 2', [options] },
+      //     { data: [[0, y0], [1, y1]...], label: 'Label 3', [options] }
+      // ]
+
+      if (!dashboardVisible)
+        return;
+
+      var y = 0,
+        x;
+      if (dataset.length == 0) {
+        if (counter == true) {
+          // Have we stashed initial values?
+          if (_.isUndefined($(container).data('counter_previous_vals'))) {
+            $(container).data('counter_previous_vals', data[0]);
+          } else {
+            // Create the initial data structure
+            for (x in data[0]) {
+              dataset.push({
+                'data': [
+                  [0, data[0][x] - $(container).data('counter_previous_vals')[x]],
+                ],
+                'label': x,
+              });
+            }
+          }
+        } else {
+          // Create the initial data structure
+          for (x in data[0]) {
+            dataset.push({
+              'data': [
+                [0, data[0][x]],
+              ],
+              'label': x,
             });
+          }
+        }
+      } else {
+        for (x in data[0]) {
+          // Push new values onto the existing data structure
+          // If this is a counter stat, we need to subtract the previous value
+          if (counter == false) {
+            dataset[y]['data'].unshift([0, data[0][x]]);
+          } else {
+            // Store the current value, minus the previous one we stashed.
+            // It's possible the tab has been reloaded, in which case out previous values are gone
+            if (_.isUndefined($(container).data('counter_previous_vals')))
+              return;
 
-            // Render the filter
-            $('#' + container.id + '_filter').before(filter.render().el);
-
-            // Add some space to the filter and move it to the right
-            $(filter.el).css({float: "right", margin: "5px", "margin-right": "2px", "margin-top": "3px"});
-
-            // Stash objects for future use
-            $(container).data('data', data);
-            $(container).data('grid', grid);
-            $(container).data('filter', filter);
-        },
-
-        // Render the data in a grid
-        render_grid_data: function(container) {
-            var data = $(container).data('data'),
-                grid = $(container).data('grid'),
-                filter = $(container).data('filter');
+            dataset[y]['data'].unshift([0, data[0][x] - $(container).data('counter_previous_vals')[x]]);
+          }
 
-            if(_.isUndefined(data)){
-              return null;
-            }
+          // Reset the time index to get a proper scrolling display
+          for (var z = 0; z < dataset[y]['data'].length; z++) {
+            dataset[y]['data'][z][0] = z;
+          }
 
-            data.fetch({
-                reset: true,
-                success: function() {
-                    // If we're showing an error, remove it, and replace the grid & filter
-                    if ($(container).hasClass('grid-error')) {
-                        $(container).removeClass('grid-error');
-                        $(container).html(grid.render().el)
-                        $(filter.el).show();
-                    }
-
-                    // Re-apply search criteria
-                    filter.search();
-                },
-                error: function(model, xhr, options) {
-                     var err = $.parseJSON(xhr.responseText),
-                         msg = err.errormsg,
-                         cls;
-                    // If we get a 428, it means the server isn't connected
-                    if (xhr.status == 428) {
-                        if (_.isUndefined(msg) || _.isNull(msg)) {
-                            msg = gettext('Please connect to the selected server to view the table.');
-                        }
-                        cls = 'info';
-                    } else {
-                        msg = gettext('An error occurred whilst rendering the table.');
-                        cls = 'danger';
-                    }
-
-                    // Replace the content with the error, if not already present. Always update the message
-                    if (!$(container).hasClass('grid-error')) {
-                        $(filter.el).hide();
-                        $(container).addClass('grid-error');
-                    }
-
-                    $(container).html(
-                        '<div class="alert alert-' + cls + ' pg-panel-message" role="alert">' + msg + '</div>'
-                    );
+          y++;
+        }
+        $(container).data('counter_previous_vals', data[0]);
+      }
 
-                    // Try again
-                    setTimeout(function() {
-                        pgAdmin.Dashboard.render_grid_data(container, data);
-                    }, 5000)
-                }
-            });
-        },
+      // Remove uneeded elements
+      for (x = 0; x < dataset.length; x++) {
+        // Remove old data points
+        if (dataset[x]['data'].length > 101) {
+          dataset[x]['data'].pop();
+        }
+      }
 
-        // Rock n' roll on the server dashboard
-        init_server_dashboard: function(sid, version, session_stats_refresh, tps_stats_refresh, ti_stats_refresh, to_stats_refresh, bio_stats_refresh) {
-            var div_sessions = $('.dashboard-container').find('#graph-sessions')[0];
-            var div_tps = $('.dashboard-container').find('#graph-tps')[0];
-            var div_ti = $('.dashboard-container').find('#graph-ti')[0];
-            var div_to = $('.dashboard-container').find('#graph-to')[0];
-            var div_bio = $('.dashboard-container').find('#graph-bio')[0];
-            var div_server_activity = $('.dashboard-container').find('#server_activity');
-            var div_server_locks = $('.dashboard-container').find('#server_locks');
-            var div_server_prepared = $('.dashboard-container').find('#server_prepared');
-            var div_server_config = $('.dashboard-container').find('#server_config');
-            var dataset_sessions = [];
-            var data_sessions = [];
-            var dataset_tps = [];
-            var data_tps = [];
-            var dataset_ti = [];
-            var data_ti = [];
-            var dataset_to = [];
-            var data_to = [];
-            var dataset_bio = [];
-            var data_bio = [];
-
-            // Fake DB ID
-            var did = -1;
-
-            var options_line = {
-                  parseFloat: false,
-                  xaxis: {
-                      min: 100,
-                      max: 0,
-                      autoscale: 0
-                  },
-                  yaxis : {
-                      autoscale: 1
-                  },
-                  legend : {
-                      position : 'nw',
-                      backgroundColor : '#D2E8FF'
-                  }
-            }
+      // Draw Graph, if the container still exists and has a size
+      var dashboardPanel = pgBrowser.panels['dashboard'].panel;
+      var div = dashboardPanel.layout().scene().find('.pg-panel-content');
+      if ($(div).find(container).length) { // Exists?
+        if (container.clientHeight > 0 && container.clientWidth > 0) { // Not hidden?
+          Flotr.draw(container, dataset, options);
+        }
+      } else {
+        return;
+      }
 
-            var server_activity_columns = [{
-                name: "pid",
-                label: gettext('PID'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "datname",
-                label: gettext('Database'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "usename",
-                label: gettext('User'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "application_name",
-                label: gettext('Application'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "client_addr",
-                label: gettext('Client'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "backend_start",
-                label: gettext('Backend start'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "state",
-                label: gettext('State'),
-                editable: false,
-                cell: "string"
-            }];
-
-            if (version < 90600) {
-                server_activity_columns = server_activity_columns.concat(
-                [{
-                    name: "waiting",
-                    label: gettext('Waiting?'),
-                    editable: false,
-                    cell: "string"
-                }]);
+      // Animate
+      var setTimeoutFunc = function() {
+        var path = url + sid;
+        if (did != -1) {
+          path += '/' + did;
+        }
+        $.ajax({
+          url: path,
+          type: 'GET',
+          dataType: 'html',
+          success: function(resp) {
+            $(container).removeClass('graph-error');
+            data = JSON.parse(resp);
+            pgAdmin.Dashboard.render_chart(container, data, dataset, sid, did, url, options, counter, refresh);
+          },
+          error: function(xhr) {
+            var err = $.parseJSON(xhr.responseText),
+              msg = err.errormsg,
+              cls;
+            // If we get a 428, it means the server isn't connected
+            if (xhr.status == 428) {
+              if (_.isUndefined(msg) || _.isNull(msg)) {
+                msg = gettext('Please connect to the selected server to view the graph.');
+              }
+              cls = 'info';
             } else {
-                server_activity_columns = server_activity_columns.concat(
-                [{
-                    name: "wait_event",
-                    label: gettext('Wait Event'),
-                    editable: false,
-                    cell: "string"
-                },{
-                    name: "blocking_pids",
-                    label: gettext('Blocking PIDs'),
-                    editable: false,
-                    cell: "string"
-                }]);
+              msg = gettext('An error occurred whilst rendering the graph.');
+              cls = 'danger';
             }
 
-            var newActiveQueryDetailsModel = new ActiveQueryDetailsModel();
-
-            var subNodeFieldsModel = Backform.generateViewSchema(
-              null, newActiveQueryDetailsModel, 'create', null, null, true
-            );
-
-            // Add version to each field
-            _.each(subNodeFieldsModel[0].fields, function(obj) {
-              obj['version'] = version;
-            });
-
-            // Add cancel active query button
-            server_activity_columns.unshift({
-              name: "pg-backform-expand", label: "",
-              cell: SessionDetailsCell,
-              cell_priority: -1,
-              postgres_version: version,
-              schema: subNodeFieldsModel
-            });
-
-            // Add cancel active query button
-            server_activity_columns.unshift({
-              name: "pg-backform-delete", label: "",
-              cell: customDashboardActionCell,
-              cell_action: 'cancel',
-              editable: false, cell_priority: -1,
-              canDeleteRow: pgAdmin.Dashboard.can_take_action,
-              postgres_version: version
-            });
-
-            server_activity_columns.unshift({
-              name: "pg-backform-delete", label: "",
-              cell: customDashboardActionCell,
-              cell_action: 'terminate',
-              editable: false, cell_priority: -1,
-              canDeleteRow: pgAdmin.Dashboard.can_take_action,
-              postgres_version: version
-            });
-
-            var server_locks_columns = [{
-                name: "pid",
-                label: gettext('PID'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "datname",
-                label: gettext('Database'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "locktype",
-                label: gettext('Lock type'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "relation",
-                label: gettext('Target relation'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "page",
-                label: gettext('Page'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "tuple",
-                label: gettext('Tuple'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "virtualxid",
-                label: gettext('vXID (target)'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "transactionid",
-                label: gettext('XID (target)'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "classid",
-                label: gettext('Class'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "objid",
-                label: gettext('Object ID'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "virtualtransaction",
-                label: gettext('vXID (owner)'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "mode",
-                label: gettext('Mode'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "granted",
-                label: gettext('Granted?'),
-                editable: false,
-                cell: "string"
-            }];
-
-            var server_prepared_columns = [{
-                name: "git",
-                label: gettext('Name'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "database",
-                label: gettext('Database'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "Owner",
-                label: gettext('Owner'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "transaction",
-                label: gettext('XID'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "prepared",
-                label: gettext('Prepared at'),
-                editable: false,
-                cell: "string"
-            }];
-
-            var server_config_columns = [{
-                name: "name",
-                label: gettext('Name'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "category",
-                label: gettext('Category'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "setting",
-                label: gettext('Setting'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "unit",
-                label: gettext('Unit'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "short_desc",
-                label: gettext('Description'),
-                editable: false,
-                cell: "string"
-            }];
-
-            // Render the graphs
-            pgAdmin.Dashboard.render_chart(
-              div_sessions, data_sessions, dataset_sessions, sid, did,
-              url_for('dashboard.session_stats'), options_line, false,
-              session_stats_refresh
-            );
-            pgAdmin.Dashboard.render_chart(
-              div_tps, data_tps, dataset_tps, sid, did,
-              url_for('dashboard.tps_stats'), options_line, true,
-              tps_stats_refresh
-            );
-            pgAdmin.Dashboard.render_chart(
-              div_ti, data_ti, dataset_ti, sid, did,
-              url_for('dashboard.ti_stats'), options_line, true,
-              ti_stats_refresh
-            );
-            pgAdmin.Dashboard.render_chart(
-              div_to, data_to, dataset_to, sid, did,
-              url_for('dashboard.to_stats'), options_line, true,
-              to_stats_refresh
-            );
-            pgAdmin.Dashboard.render_chart(
-              div_bio, data_bio, dataset_bio, sid, did,
-              url_for('dashboard.bio_stats'), options_line, true,
-              bio_stats_refresh
+            $(container).addClass('graph-error');
+            $(container).html(
+              '<div class="alert alert-' + cls + ' pg-panel-message" role="alert">' + msg + '</div>'
             );
 
-            // To align subnode controls properly
-            $(div_server_activity).addClass('pg-el-container');
-            $(div_server_activity).attr('el', 'sm');
+            // Try again...
+            if (container.clientHeight > 0 && container.clientWidth > 0) {
+              setTimeout(setTimeoutFunc, refresh * 1000);
+            }
+          },
+        });
+      };
 
-            // Render the tabs, but only get data for the activity tab for now
-            pgAdmin.Dashboard.render_grid(
-              div_server_activity, sid, did,
-              url_for('dashboard.activity'), server_activity_columns
-            );
-            pgAdmin.Dashboard.render_grid(
-              div_server_locks, sid, did, url_for('dashboard.locks'),
-              server_locks_columns
-            );
-            pgAdmin.Dashboard.render_grid(
-              div_server_prepared, sid, did, url_for('dashboard.prepared'),
-              server_prepared_columns
-            );
-            pgAdmin.Dashboard.render_grid(
-              div_server_config, sid, did, url_for('dashboard.config'),
-              server_config_columns
-            );
+      setTimeout(setTimeoutFunc, refresh * 1000);
+    },
 
-            pgAdmin.Dashboard.render_grid_data(div_server_activity);
+    // Handler function to support the "Add Server" link
+    add_new_server: function() {
+      if (pgBrowser && pgBrowser.tree) {
+        var i = pgBrowser.tree.selected().length != 0 ?
+          pgBrowser.tree.selected() :
+          pgBrowser.tree.first(null, false),
+          serverModule = require('pgadmin.node.server'),
+          itemData = pgBrowser.tree.itemData(i);
+
+        while (itemData && itemData._type != 'server_group') {
+          i = pgBrowser.tree.next(i);
+          itemData = pgBrowser.tree.itemData(i);
+        }
 
-            // (Re)render the appropriate tab
-            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
-                switch ($(e.target).attr('aria-controls')) {
-                    case "tab_server_activity":
-                        pgAdmin.Dashboard.render_grid_data(div_server_activity);
-                        break;
+        if (!itemData) {
+          return;
+        }
 
-                    case "tab_server_locks":
-                        pgAdmin.Dashboard.render_grid_data(div_server_locks);
-                        break;
+        if (serverModule) {
+          serverModule.callbacks.show_obj_properties.apply(
+            serverModule, [{
+              action: 'create',
+            }, i]
+          );
+        }
+      }
+    },
 
-                    case "tab_server_prepared":
-                        pgAdmin.Dashboard.render_grid_data(div_server_prepared);
-                        break;
+    // Render a grid
+    render_grid: function(container, sid, did, url, columns) {
+      var Datum = Backbone.Model.extend({});
 
-                    case "tab_server_config":
-                        pgAdmin.Dashboard.render_grid_data(div_server_config);
-                        break;
-                }
-            });
+      var path = url + sid;
+      if (did != -1) {
+        path += '/' + did;
+      }
 
-            // Handle button clicks
-            $("button").click(function(e){
-                switch(this.id) {
-                    case "btn_server_activity_refresh":
-                        pgAdmin.Dashboard.render_grid_data(div_server_activity);
-                        break;
+      var Data = Backbone.Collection.extend({
+        model: Datum,
+        url: path,
+        mode: 'client',
+      });
+
+      var data = new Data();
+
+      // Set up the grid
+      var grid = new Backgrid.Grid({
+        columns: columns,
+        collection: data,
+        className: 'backgrid table-bordered presentation table backgrid-striped',
+      });
+
+      // Render the grid
+      $(container).append(grid.render().el);
+
+      // Initialize a client-side filter to filter on the client
+      // mode pageable collection's cache.
+      var filter = new Backgrid.Extension.ClientSideFilter({
+        collection: data,
+      });
+
+      // Render the filter
+      $('#' + container.id + '_filter').before(filter.render().el);
+
+      // Add some space to the filter and move it to the right
+      $(filter.el).css({
+        float: 'right',
+        margin: '5px',
+        'margin-right': '2px',
+        'margin-top': '3px',
+      });
+
+      // Stash objects for future use
+      $(container).data('data', data);
+      $(container).data('grid', grid);
+      $(container).data('filter', filter);
+    },
 
-                    case "btn_server_locks_refresh":
-                        pgAdmin.Dashboard.render_grid_data(div_server_locks);
-                        break;
+    // Render the data in a grid
+    render_grid_data: function(container) {
+      var data = $(container).data('data'),
+        grid = $(container).data('grid'),
+        filter = $(container).data('filter');
 
-                    case "btn_server_prepared_refresh":
-                        pgAdmin.Dashboard.render_grid_data(div_server_prepared);
-                        break;
+      if (_.isUndefined(data)) {
+        return null;
+      }
 
-                    case "btn_server_config_refresh":
-                        pgAdmin.Dashboard.render_grid_data(div_server_config);
-                        break;
-                }
-            });
+      data.fetch({
+        reset: true,
+        success: function() {
+          // If we're showing an error, remove it, and replace the grid & filter
+          if ($(container).hasClass('grid-error')) {
+            $(container).removeClass('grid-error');
+            $(container).html(grid.render().el);
+            $(filter.el).show();
+          }
 
+          // Re-apply search criteria
+          filter.search();
         },
-
-        // Rock n' roll on the database dashboard
-        init_database_dashboard: function(sid, did, version, session_stats_refresh, tps_stats_refresh, ti_stats_refresh, to_stats_refresh, bio_stats_refresh) {
-            var div_sessions = document.getElementById('graph-sessions');
-            var div_tps = document.getElementById('graph-tps');
-            var div_ti = document.getElementById('graph-ti');
-            var div_to = document.getElementById('graph-to');
-            var div_bio = document.getElementById('graph-bio');
-            var div_database_activity = document.getElementById('database_activity');
-            var div_database_locks = document.getElementById('database_locks');
-            var div_database_prepared = document.getElementById('database_prepared');
-            var dataset_sessions = [];
-            var data_sessions = [];
-            var dataset_tps = [];
-            var data_tps = [];
-            var dataset_ti = [];
-            var data_ti = [];
-            var dataset_to = [];
-            var data_to = [];
-            var dataset_bio = [];
-            var data_bio = [];
-
-            var options_line = {
-                  parseFloat: false,
-                  xaxis: {
-                      min: 100,
-                      max: 0,
-                      autoscale: 0
-                  },
-                  yaxis : {
-                      autoscale: 1
-                  },
-                  legend : {
-                      position : 'nw',
-                      backgroundColor : '#D2E8FF'
-                  }
-            }
-
-            var database_activity_columns = [{
-                name: "pid",
-                label: gettext('PID'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "usename",
-                label: gettext('User'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "application_name",
-                label: gettext('Application'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "client_addr",
-                label: gettext('Client'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "backend_start",
-                label: gettext('Backend start'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "state",
-                label: gettext('State'),
-                editable: false,
-                cell: "string"
-            }];
-
-            if (version < 90600) {
-                database_activity_columns = database_activity_columns.concat(
-                [{
-                    name: "waiting",
-                    label: gettext('Waiting?'),
-                    editable: false,
-                    cell: "string"
-                }]);
-            } else {
-                database_activity_columns = database_activity_columns.concat(
-                [{
-                    name: "wait_event",
-                    label: gettext('Wait Event'),
-                    editable: false,
-                    cell: "string"
-                },{
-                    name: "blocking_pids",
-                    label: gettext('Blocking PIDs'),
-                    editable: false,
-                    cell: "string"
-                }]);
+        error: function(model, xhr) {
+          var err = $.parseJSON(xhr.responseText),
+            msg = err.errormsg,
+            cls;
+          // If we get a 428, it means the server isn't connected
+          if (xhr.status == 428) {
+            if (_.isUndefined(msg) || _.isNull(msg)) {
+              msg = gettext('Please connect to the selected server to view the table.');
             }
+            cls = 'info';
+          } else {
+            msg = gettext('An error occurred whilst rendering the table.');
+            cls = 'danger';
+          }
 
-            var newActiveQueryDetailsModel = new ActiveQueryDetailsModel();
-
-            var subNodeFieldsModel = Backform.generateViewSchema(
-              null, newActiveQueryDetailsModel, 'create', null, null, true
-            );
-
-            // Add version to each field
-            _.each(subNodeFieldsModel[0].fields, function(obj) {
-              obj['version'] = version;
-            });
-
-
-            // Add cancel active query button
-            database_activity_columns.unshift({
-              name: "pg-backform-expand", label: "",
-              cell: SessionDetailsCell,
-              cell_priority: -1,
-              postgres_version: version,
-              schema: subNodeFieldsModel
-            });
-
-            database_activity_columns.unshift({
-              name: "pg-backform-delete", label: "",
-              cell: customDashboardActionCell,
-              cell_action: 'cancel',
-              editable: false, cell_priority: -1,
-              canDeleteRow: pgAdmin.Dashboard.can_take_action,
-              postgres_version: version
-            });
-            database_activity_columns.unshift({
-              name: "pg-backform-delete", label: "",
-              cell: customDashboardActionCell,
-              cell_action: 'terminate',
-              editable: false, cell_priority: -1,
-              canDeleteRow: pgAdmin.Dashboard.can_take_action,
-              postgres_version: version
-            });
-
-            var database_locks_columns = [{
-                name: "pid",
-                label: gettext('PID'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "locktype",
-                label: gettext('Lock type'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "relation",
-                label: gettext('Target relation'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "page",
-                label: gettext('Page'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "tuple",
-                label: gettext('Tuple'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "virtualxid",
-                label: gettext('vXID (target)'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "transactionid",
-                label: gettext('XID (target)'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "classid",
-                label: gettext('Class'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "objid",
-                label: gettext('Object ID'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "virtualtransaction",
-                label: gettext('vXID (owner)'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "mode",
-                label: gettext('Mode'),
-                editable: false,
-                cell: "string"
-            },{
-                name: "granted",
-                label: gettext('Granted?'),
-                editable: false,
-                cell: "string"
-            }];
-
-            var database_prepared_columns = [{
-                name: "git",
-                label: gettext('Name'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "Owner",
-                label: gettext('Owner'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "transaction",
-                label: gettext('XID'),
-                editable: false,
-                cell: "string"
-            }, {
-                name: "prepared",
-                label: gettext('Prepared at'),
-                editable: false,
-                cell: "string"
-            }];
-
-            // Render the graphs
-            pgAdmin.Dashboard.render_chart(
-              div_sessions, data_sessions, dataset_sessions, sid, did,
-              url_for('dashboard.session_stats'), options_line, false,
-              session_stats_refresh
-            );
-            pgAdmin.Dashboard.render_chart(
-              div_tps, data_tps, dataset_tps, sid, did,
-              url_for('dashboard.tps_stats'), options_line, true,
-              tps_stats_refresh
-            );
-            pgAdmin.Dashboard.render_chart(
-              div_ti, data_ti, dataset_ti, sid, did,
-              url_for('dashboard.ti_stats'), options_line, true,
-              ti_stats_refresh
-            );
-            pgAdmin.Dashboard.render_chart(
-              div_to, data_to, dataset_to, sid, did,
-              url_for('dashboard.to_stats'), options_line, true,
-              to_stats_refresh
-            );
-            pgAdmin.Dashboard.render_chart(
-              div_bio, data_bio, dataset_bio, sid, did,
-              url_for('dashboard.bio_stats'), options_line, true,
-              bio_stats_refresh
-            );
-
-            // To align subnode controls properly
-            $(div_database_activity).addClass('pg-el-container');
-            $(div_database_activity).attr('el', 'sm');
-
-            // Render the tabs, but only get data for the activity tab for now
-            pgAdmin.Dashboard.render_grid(
-              div_database_activity, sid, did, url_for('dashboard.activity'),
-              database_activity_columns
-            );
-            pgAdmin.Dashboard.render_grid(
-              div_database_locks, sid, did, url_for('dashboard.locks'),
-              database_locks_columns
-            );
-            pgAdmin.Dashboard.render_grid(
-              div_database_prepared, sid, did, url_for('dashboard.prepared'),
-              database_prepared_columns
-            );
-
-            pgAdmin.Dashboard.render_grid_data(div_database_activity);
-
-            // (Re)render the appropriate tab
-            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
-                switch ($(e.target).attr('aria-controls')) {
-                    case "tab_database_activity":
-                        pgAdmin.Dashboard.render_grid_data(div_database_activity);
-                        break;
+          // Replace the content with the error, if not already present. Always update the message
+          if (!$(container).hasClass('grid-error')) {
+            $(filter.el).hide();
+            $(container).addClass('grid-error');
+          }
 
-                    case "tab_database_locks":
-                        pgAdmin.Dashboard.render_grid_data(div_database_locks);
-                        break;
+          $(container).html(
+            '<div class="alert alert-' + cls + ' pg-panel-message" role="alert">' + msg + '</div>'
+          );
 
-                    case "tab_database_prepared":
-                        pgAdmin.Dashboard.render_grid_data(div_database_prepared);
-                        break;
-                }
-            });
+          // Try again
+          setTimeout(function() {
+            pgAdmin.Dashboard.render_grid_data(container, data);
+          }, 5000);
+        },
+      });
+    },
 
-            // Handle button clicks
-            $("button").click(function(e){
-                switch(this.id) {
-                    case "btn_database_activity_refresh":
-                        pgAdmin.Dashboard.render_grid_data(div_database_activity);
-                        break;
+    // Rock n' roll on the server dashboard
+    init_server_dashboard: function(sid, version, session_stats_refresh, tps_stats_refresh, ti_stats_refresh, to_stats_refresh, bio_stats_refresh) {
+      var div_sessions = $('.dashboard-container').find('#graph-sessions')[0];
+      var div_tps = $('.dashboard-container').find('#graph-tps')[0];
+      var div_ti = $('.dashboard-container').find('#graph-ti')[0];
+      var div_to = $('.dashboard-container').find('#graph-to')[0];
+      var div_bio = $('.dashboard-container').find('#graph-bio')[0];
+      var div_server_activity = $('.dashboard-container').find('#server_activity');
+      var div_server_locks = $('.dashboard-container').find('#server_locks');
+      var div_server_prepared = $('.dashboard-container').find('#server_prepared');
+      var div_server_config = $('.dashboard-container').find('#server_config');
+      var dataset_sessions = [];
+      var data_sessions = [];
+      var dataset_tps = [];
+      var data_tps = [];
+      var dataset_ti = [];
+      var data_ti = [];
+      var dataset_to = [];
+      var data_to = [];
+      var dataset_bio = [];
+      var data_bio = [];
+
+      // Fake DB ID
+      var did = -1;
+
+      var options_line = {
+        parseFloat: false,
+        xaxis: {
+          min: 100,
+          max: 0,
+          autoscale: 0,
+        },
+        yaxis: {
+          autoscale: 1,
+        },
+        legend: {
+          position: 'nw',
+          backgroundColor: '#D2E8FF',
+        },
+      };
+
+      var server_activity_columns = [{
+        name: 'pid',
+        label: gettext('PID'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'datname',
+        label: gettext('Database'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'usename',
+        label: gettext('User'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'application_name',
+        label: gettext('Application'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'client_addr',
+        label: gettext('Client'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'backend_start',
+        label: gettext('Backend start'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'state',
+        label: gettext('State'),
+        editable: false,
+        cell: 'string',
+      }];
+
+      if (version < 90600) {
+        server_activity_columns = server_activity_columns.concat(
+          [{
+            name: 'waiting',
+            label: gettext('Waiting?'),
+            editable: false,
+            cell: 'string',
+          }]);
+      } else {
+        server_activity_columns = server_activity_columns.concat(
+          [{
+            name: 'wait_event',
+            label: gettext('Wait Event'),
+            editable: false,
+            cell: 'string',
+          }, {
+            name: 'blocking_pids',
+            label: gettext('Blocking PIDs'),
+            editable: false,
+            cell: 'string',
+          }]);
+      }
 
-                    case "btn_database_locks_refresh":
-                        pgAdmin.Dashboard.render_grid_data(div_database_locks);
-                        break;
+      var newActiveQueryDetailsModel = new ActiveQueryDetailsModel();
+
+      var subNodeFieldsModel = Backform.generateViewSchema(
+        null, newActiveQueryDetailsModel, 'create', null, null, true
+      );
+
+      // Add version to each field
+      _.each(subNodeFieldsModel[0].fields, function(obj) {
+        obj['version'] = version;
+      });
+
+      // Add cancel active query button
+      server_activity_columns.unshift({
+        name: 'pg-backform-expand',
+        label: '',
+        cell: SessionDetailsCell,
+        cell_priority: -1,
+        postgres_version: version,
+        schema: subNodeFieldsModel,
+      });
+
+      // Add cancel active query button
+      server_activity_columns.unshift({
+        name: 'pg-backform-delete',
+        label: '',
+        cell: customDashboardActionCell,
+        cell_action: 'cancel',
+        editable: false,
+        cell_priority: -1,
+        canDeleteRow: pgAdmin.Dashboard.can_take_action,
+        postgres_version: version,
+      });
+
+      server_activity_columns.unshift({
+        name: 'pg-backform-delete',
+        label: '',
+        cell: customDashboardActionCell,
+        cell_action: 'terminate',
+        editable: false,
+        cell_priority: -1,
+        canDeleteRow: pgAdmin.Dashboard.can_take_action,
+        postgres_version: version,
+      });
+
+      var server_locks_columns = [{
+        name: 'pid',
+        label: gettext('PID'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'datname',
+        label: gettext('Database'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'locktype',
+        label: gettext('Lock type'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'relation',
+        label: gettext('Target relation'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'page',
+        label: gettext('Page'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'tuple',
+        label: gettext('Tuple'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'virtualxid',
+        label: gettext('vXID (target)'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'transactionid',
+        label: gettext('XID (target)'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'classid',
+        label: gettext('Class'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'objid',
+        label: gettext('Object ID'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'virtualtransaction',
+        label: gettext('vXID (owner)'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'mode',
+        label: gettext('Mode'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'granted',
+        label: gettext('Granted?'),
+        editable: false,
+        cell: 'string',
+      }];
+
+      var server_prepared_columns = [{
+        name: 'git',
+        label: gettext('Name'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'database',
+        label: gettext('Database'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'Owner',
+        label: gettext('Owner'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'transaction',
+        label: gettext('XID'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'prepared',
+        label: gettext('Prepared at'),
+        editable: false,
+        cell: 'string',
+      }];
+
+      var server_config_columns = [{
+        name: 'name',
+        label: gettext('Name'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'category',
+        label: gettext('Category'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'setting',
+        label: gettext('Setting'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'unit',
+        label: gettext('Unit'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'short_desc',
+        label: gettext('Description'),
+        editable: false,
+        cell: 'string',
+      }];
+
+      // Render the graphs
+      pgAdmin.Dashboard.render_chart(
+        div_sessions, data_sessions, dataset_sessions, sid, did,
+        url_for('dashboard.session_stats'), options_line, false,
+        session_stats_refresh
+      );
+      pgAdmin.Dashboard.render_chart(
+        div_tps, data_tps, dataset_tps, sid, did,
+        url_for('dashboard.tps_stats'), options_line, true,
+        tps_stats_refresh
+      );
+      pgAdmin.Dashboard.render_chart(
+        div_ti, data_ti, dataset_ti, sid, did,
+        url_for('dashboard.ti_stats'), options_line, true,
+        ti_stats_refresh
+      );
+      pgAdmin.Dashboard.render_chart(
+        div_to, data_to, dataset_to, sid, did,
+        url_for('dashboard.to_stats'), options_line, true,
+        to_stats_refresh
+      );
+      pgAdmin.Dashboard.render_chart(
+        div_bio, data_bio, dataset_bio, sid, did,
+        url_for('dashboard.bio_stats'), options_line, true,
+        bio_stats_refresh
+      );
+
+      // To align subnode controls properly
+      $(div_server_activity).addClass('pg-el-container');
+      $(div_server_activity).attr('el', 'sm');
+
+      // Render the tabs, but only get data for the activity tab for now
+      pgAdmin.Dashboard.render_grid(
+        div_server_activity, sid, did,
+        url_for('dashboard.activity'), server_activity_columns
+      );
+      pgAdmin.Dashboard.render_grid(
+        div_server_locks, sid, did, url_for('dashboard.locks'),
+        server_locks_columns
+      );
+      pgAdmin.Dashboard.render_grid(
+        div_server_prepared, sid, did, url_for('dashboard.prepared'),
+        server_prepared_columns
+      );
+      pgAdmin.Dashboard.render_grid(
+        div_server_config, sid, did, url_for('dashboard.config'),
+        server_config_columns
+      );
+
+      pgAdmin.Dashboard.render_grid_data(div_server_activity);
+
+      // (Re)render the appropriate tab
+      $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
+        switch ($(e.target).attr('aria-controls')) {
+        case 'tab_server_activity':
+          pgAdmin.Dashboard.render_grid_data(div_server_activity);
+          break;
+
+        case 'tab_server_locks':
+          pgAdmin.Dashboard.render_grid_data(div_server_locks);
+          break;
+
+        case 'tab_server_prepared':
+          pgAdmin.Dashboard.render_grid_data(div_server_prepared);
+          break;
+
+        case 'tab_server_config':
+          pgAdmin.Dashboard.render_grid_data(div_server_config);
+          break;
+        }
+      });
+
+      // Handle button clicks
+      $('button').click(function() {
+        switch (this.id) {
+        case 'btn_server_activity_refresh':
+          pgAdmin.Dashboard.render_grid_data(div_server_activity);
+          break;
+
+        case 'btn_server_locks_refresh':
+          pgAdmin.Dashboard.render_grid_data(div_server_locks);
+          break;
+
+        case 'btn_server_prepared_refresh':
+          pgAdmin.Dashboard.render_grid_data(div_server_prepared);
+          break;
+
+        case 'btn_server_config_refresh':
+          pgAdmin.Dashboard.render_grid_data(div_server_config);
+          break;
+        }
+      });
 
-                    case "btn_database_prepared_refresh":
-                        pgAdmin.Dashboard.render_grid_data(div_database_prepared);
-                        break;
-                }
-            });
+    },
 
+    // Rock n' roll on the database dashboard
+    init_database_dashboard: function(sid, did, version, session_stats_refresh, tps_stats_refresh, ti_stats_refresh, to_stats_refresh, bio_stats_refresh) {
+      var div_sessions = document.getElementById('graph-sessions');
+      var div_tps = document.getElementById('graph-tps');
+      var div_ti = document.getElementById('graph-ti');
+      var div_to = document.getElementById('graph-to');
+      var div_bio = document.getElementById('graph-bio');
+      var div_database_activity = document.getElementById('database_activity');
+      var div_database_locks = document.getElementById('database_locks');
+      var div_database_prepared = document.getElementById('database_prepared');
+      var dataset_sessions = [];
+      var data_sessions = [];
+      var dataset_tps = [];
+      var data_tps = [];
+      var dataset_ti = [];
+      var data_ti = [];
+      var dataset_to = [];
+      var data_to = [];
+      var dataset_bio = [];
+      var data_bio = [];
+
+      var options_line = {
+        parseFloat: false,
+        xaxis: {
+          min: 100,
+          max: 0,
+          autoscale: 0,
         },
-        toggleVisibility: function(flag) {
-          dashboardVisible = flag;
+        yaxis: {
+          autoscale: 1,
         },
-        can_take_action: function(m) {
-          // We will validate if user is allowed to cancel the active query
-          // If there is only one active session means it probably our main
-          // connection session
-          var active_sessions = m.collection.where({'state': 'active'}),
-            pg_version = this.get('postgres_version') || null,
-            cell_action = this.get('cell_action') || null,
-            is_cancel_session = cell_action === 'cancel',
-            txtAction = is_cancel_session ? gettext('cancel') : gettext('terminate');
-
-          // With PG10, We have background process showing on dashboard
-          // We will not allow user to cancel them as they will fail with error
-          // anyway, so better usability we will throw our on notification
-
-          // Background processes do not have database field populated
-          if (pg_version && pg_version >= 100000 && !m.get('datname')) {
-            alertify.info(
-              gettext('You cannot ') +
-              txtAction +
-              gettext(' background worker processes.')
-            );
-            return false;
-          // If it is the last active connection on maintenance db then error out
-          } else if (maintenance_database == m.get('datname') &&
-              m.get('state') == 'active' && active_sessions.length == 1) {
-            alertify.error(
-              gettext('You are not allowed to ') +
-              txtAction +
-              gettext(' the main active session.')
-            );
-            return false;
-          } else if(is_cancel_session && m.get('state') == 'idle') {
-            // If this session is already idle then do nothing
-            alertify.info(
-              gettext('The session is already in idle state.')
-            );
-            return false;
-          } else if(is_super_user) {
-            // Super user can do anything
-            return true;
-          } else if (current_user && current_user == m.get('usename')) {
-            // Non-super user can cancel only their active queries
-            return true;
-          } else {
-            // Do not allow to cancel someone else session to non-super user
-            alertify.error(
-              gettext('Superuser privileges are required to ') +
-              txtAction +
-              gettext(' another users query.')
-            );
-            return false;
-          }
+        legend: {
+          position: 'nw',
+          backgroundColor: '#D2E8FF',
+        },
+      };
+
+      var database_activity_columns = [{
+        name: 'pid',
+        label: gettext('PID'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'usename',
+        label: gettext('User'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'application_name',
+        label: gettext('Application'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'client_addr',
+        label: gettext('Client'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'backend_start',
+        label: gettext('Backend start'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'state',
+        label: gettext('State'),
+        editable: false,
+        cell: 'string',
+      }];
+
+      if (version < 90600) {
+        database_activity_columns = database_activity_columns.concat(
+          [{
+            name: 'waiting',
+            label: gettext('Waiting?'),
+            editable: false,
+            cell: 'string',
+          }]);
+      } else {
+        database_activity_columns = database_activity_columns.concat(
+          [{
+            name: 'wait_event',
+            label: gettext('Wait Event'),
+            editable: false,
+            cell: 'string',
+          }, {
+            name: 'blocking_pids',
+            label: gettext('Blocking PIDs'),
+            editable: false,
+            cell: 'string',
+          }]);
+      }
+
+      var newActiveQueryDetailsModel = new ActiveQueryDetailsModel();
+
+      var subNodeFieldsModel = Backform.generateViewSchema(
+        null, newActiveQueryDetailsModel, 'create', null, null, true
+      );
+
+      // Add version to each field
+      _.each(subNodeFieldsModel[0].fields, function(obj) {
+        obj['version'] = version;
+      });
+
+
+      // Add cancel active query button
+      database_activity_columns.unshift({
+        name: 'pg-backform-expand',
+        label: '',
+        cell: SessionDetailsCell,
+        cell_priority: -1,
+        postgres_version: version,
+        schema: subNodeFieldsModel,
+      });
+
+      database_activity_columns.unshift({
+        name: 'pg-backform-delete',
+        label: '',
+        cell: customDashboardActionCell,
+        cell_action: 'cancel',
+        editable: false,
+        cell_priority: -1,
+        canDeleteRow: pgAdmin.Dashboard.can_take_action,
+        postgres_version: version,
+      });
+      database_activity_columns.unshift({
+        name: 'pg-backform-delete',
+        label: '',
+        cell: customDashboardActionCell,
+        cell_action: 'terminate',
+        editable: false,
+        cell_priority: -1,
+        canDeleteRow: pgAdmin.Dashboard.can_take_action,
+        postgres_version: version,
+      });
+
+      var database_locks_columns = [{
+        name: 'pid',
+        label: gettext('PID'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'locktype',
+        label: gettext('Lock type'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'relation',
+        label: gettext('Target relation'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'page',
+        label: gettext('Page'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'tuple',
+        label: gettext('Tuple'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'virtualxid',
+        label: gettext('vXID (target)'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'transactionid',
+        label: gettext('XID (target)'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'classid',
+        label: gettext('Class'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'objid',
+        label: gettext('Object ID'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'virtualtransaction',
+        label: gettext('vXID (owner)'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'mode',
+        label: gettext('Mode'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'granted',
+        label: gettext('Granted?'),
+        editable: false,
+        cell: 'string',
+      }];
+
+      var database_prepared_columns = [{
+        name: 'git',
+        label: gettext('Name'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'Owner',
+        label: gettext('Owner'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'transaction',
+        label: gettext('XID'),
+        editable: false,
+        cell: 'string',
+      }, {
+        name: 'prepared',
+        label: gettext('Prepared at'),
+        editable: false,
+        cell: 'string',
+      }];
+
+      // Render the graphs
+      pgAdmin.Dashboard.render_chart(
+        div_sessions, data_sessions, dataset_sessions, sid, did,
+        url_for('dashboard.session_stats'), options_line, false,
+        session_stats_refresh
+      );
+      pgAdmin.Dashboard.render_chart(
+        div_tps, data_tps, dataset_tps, sid, did,
+        url_for('dashboard.tps_stats'), options_line, true,
+        tps_stats_refresh
+      );
+      pgAdmin.Dashboard.render_chart(
+        div_ti, data_ti, dataset_ti, sid, did,
+        url_for('dashboard.ti_stats'), options_line, true,
+        ti_stats_refresh
+      );
+      pgAdmin.Dashboard.render_chart(
+        div_to, data_to, dataset_to, sid, did,
+        url_for('dashboard.to_stats'), options_line, true,
+        to_stats_refresh
+      );
+      pgAdmin.Dashboard.render_chart(
+        div_bio, data_bio, dataset_bio, sid, did,
+        url_for('dashboard.bio_stats'), options_line, true,
+        bio_stats_refresh
+      );
+
+      // To align subnode controls properly
+      $(div_database_activity).addClass('pg-el-container');
+      $(div_database_activity).attr('el', 'sm');
+
+      // Render the tabs, but only get data for the activity tab for now
+      pgAdmin.Dashboard.render_grid(
+        div_database_activity, sid, did, url_for('dashboard.activity'),
+        database_activity_columns
+      );
+      pgAdmin.Dashboard.render_grid(
+        div_database_locks, sid, did, url_for('dashboard.locks'),
+        database_locks_columns
+      );
+      pgAdmin.Dashboard.render_grid(
+        div_database_prepared, sid, did, url_for('dashboard.prepared'),
+        database_prepared_columns
+      );
+
+      pgAdmin.Dashboard.render_grid_data(div_database_activity);
+
+      // (Re)render the appropriate tab
+      $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
+        switch ($(e.target).attr('aria-controls')) {
+        case 'tab_database_activity':
+          pgAdmin.Dashboard.render_grid_data(div_database_activity);
+          break;
+
+        case 'tab_database_locks':
+          pgAdmin.Dashboard.render_grid_data(div_database_locks);
+          break;
+
+        case 'tab_database_prepared':
+          pgAdmin.Dashboard.render_grid_data(div_database_prepared);
+          break;
         }
+      });
+
+      // Handle button clicks
+      $('button').click(function() {
+        switch (this.id) {
+        case 'btn_database_activity_refresh':
+          pgAdmin.Dashboard.render_grid_data(div_database_activity);
+          break;
+
+        case 'btn_database_locks_refresh':
+          pgAdmin.Dashboard.render_grid_data(div_database_locks);
+          break;
+
+        case 'btn_database_prepared_refresh':
+          pgAdmin.Dashboard.render_grid_data(div_database_prepared);
+          break;
+        }
+      });
+
+    },
+    toggleVisibility: function(flag) {
+      dashboardVisible = flag;
+    },
+    can_take_action: function(m) {
+      // We will validate if user is allowed to cancel the active query
+      // If there is only one active session means it probably our main
+      // connection session
+      var active_sessions = m.collection.where({
+          'state': 'active',
+        }),
+        pg_version = this.get('postgres_version') || null,
+        cell_action = this.get('cell_action') || null,
+        is_cancel_session = cell_action === 'cancel',
+        txtAction = is_cancel_session ? gettext('cancel') : gettext('terminate');
+
+      // With PG10, We have background process showing on dashboard
+      // We will not allow user to cancel them as they will fail with error
+      // anyway, so better usability we will throw our on notification
+
+      // Background processes do not have database field populated
+      if (pg_version && pg_version >= 100000 && !m.get('datname')) {
+        Alertify.info(
+          gettext('You cannot ') +
+          txtAction +
+          gettext(' background worker processes.')
+        );
+        return false;
+        // If it is the last active connection on maintenance db then error out
+      } else if (maintenance_database == m.get('datname') &&
+        m.get('state') == 'active' && active_sessions.length == 1) {
+        Alertify.error(
+          gettext('You are not allowed to ') +
+          txtAction +
+          gettext(' the main active session.')
+        );
+        return false;
+      } else if (is_cancel_session && m.get('state') == 'idle') {
+        // If this session is already idle then do nothing
+        Alertify.info(
+          gettext('The session is already in idle state.')
+        );
+        return false;
+      } else if (is_super_user) {
+        // Super user can do anything
+        return true;
+      } else if (current_user && current_user == m.get('usename')) {
+        // Non-super user can cancel only their active queries
+        return true;
+      } else {
+        // Do not allow to cancel someone else session to non-super user
+        Alertify.error(
+          gettext('Superuser privileges are required to ') +
+          txtAction +
+          gettext(' another users query.')
+        );
+        return false;
+      }
+    },
   };
 
   return pgAdmin.Dashboard;
diff --git a/web/pgadmin/misc/bgprocess/static/js/bgprocess.js b/web/pgadmin/misc/bgprocess/static/js/bgprocess.js
index be4ac152..5e305908 100644
--- a/web/pgadmin/misc/bgprocess/static/js/bgprocess.js
+++ b/web/pgadmin/misc/bgprocess/static/js/bgprocess.js
@@ -1,9 +1,8 @@
 define('misc.bgprocess', [
   'sources/pgadmin', 'sources/gettext', 'sources/url_for', 'underscore',
   'underscore.string', 'jquery', 'pgadmin.browser', 'alertify',
-  'pgadmin.browser.messages'
 ], function(
-  pgAdmin, gettext, url_for, _, S, $, pgBrowser, alertify, pgMessages
+  pgAdmin, gettext, url_for, _, S, $, pgBrowser, Alertify
 ) {
 
   pgBrowser.BackgroundProcessObsorver = pgBrowser.BackgroundProcessObsorver || {};
@@ -12,6 +11,8 @@ define('misc.bgprocess', [
     return pgBrowser.BackgroundProcessObsorver;
   }
 
+  var wcDocker = window.wcDocker;
+
   var BGProcess = function(info, notify) {
     var self = this;
     setTimeout(
@@ -45,7 +46,9 @@ define('misc.bgprocess', [
           notifier: null,
           container: null,
           panel: null,
-          logs: $('<ol></ol>', {class: 'pg-bg-process-logs'})
+          logs: $('<ol></ol>', {
+            class: 'pg-bg-process-logs',
+          }),
         });
 
         if (this.notify) {
@@ -62,7 +65,7 @@ define('misc.bgprocess', [
               if (!process.notifier)
                 process.show.apply(process);
             }
-          )
+          );
         }
         var self = this;
 
@@ -75,29 +78,32 @@ define('misc.bgprocess', [
 
       bgprocess_url: function(type) {
         switch (type) {
-          case 'status':
-            if (this.details && this.out != -1 && this.err != -1) {
-              return url_for(
+        case 'status':
+          if (this.details && this.out != -1 && this.err != -1) {
+            return url_for(
                 'bgprocess.detailed_status', {
                   'pid': this.id,
                   'out': this.out,
-                  'err': this.err
+                  'err': this.err,
                 }
               );
-            }
-            return url_for('bgprocess.status', {'pid': this.id});
-          case 'acknowledge':
-            return url_for('bgprocess.acknowledge', {'pid': this.id});
-          default:
-            return url_for('bgprocess.list');
+          }
+          return url_for('bgprocess.status', {
+            'pid': this.id,
+          });
+        case 'acknowledge':
+          return url_for('bgprocess.acknowledge', {
+            'pid': this.id,
+          });
+        default:
+          return url_for('bgprocess.list');
         }
       },
 
       update: function(data) {
         var self = this,
-            out = [],
-            err = [],
-            idx = 0;
+          out = [],
+          err = [];
 
         if ('stime' in data)
           self.stime = new Date(data.stime);
@@ -131,9 +137,7 @@ define('misc.bgprocess', [
         }
         self.completed = self.completed || (
           'err' in data && 'out' in data && data.err.done && data.out.done
-        ) || (
-          !self.details && !_.isNull(self.exit_code)
-        );
+        ) || (!self.details && !_.isNull(self.exit_code));
 
         var io = 0,
           ie = 0,
@@ -145,7 +149,7 @@ define('misc.bgprocess', [
           };
 
         while (io < out.length && ie < err.length) {
-          if (pgAdmin.natural_sort(out[io][0], err[ie][0]) <= 0){
+          if (pgAdmin.natural_sort(out[io][0], err[ie][0]) <= 0) {
             res.push('<li class="pg-bg-res-out">' + escapeHTML(out[io++][1]) + '</li>');
           } else {
             res.push('<li class="pg-bg-res-err">' + escapeHTML(err[ie++][1]) + '</li>');
@@ -179,7 +183,7 @@ define('misc.bgprocess', [
               self.curr_status = gettext('Successfully completed.');
             } else {
               self.curr_status = S(
-                gettext("Failed (exit code: %s).")
+                gettext('Failed (exit code: %s).')
               ).sprintf(String(self.exit_code)).value();
             }
           }
@@ -198,7 +202,9 @@ define('misc.bgprocess', [
             );
           }
 
-          setTimeout(function() {self.show.apply(self)}, 10);
+          setTimeout(function() {
+            self.show.apply(self);
+          }, 10);
         }
 
         if (!self.completed) {
@@ -219,15 +225,19 @@ define('misc.bgprocess', [
           url: self.bgprocess_url('status'),
           cache: false,
           async: true,
-          contentType: "application/json",
+          contentType: 'application/json',
           success: function(res) {
-            setTimeout(function() { self.update(res); }, 10);
+            setTimeout(function() {
+              self.update(res);
+            }, 10);
           },
           error: function(res) {
             // Try after some time only if job id present
             if (res.status != 410)
-              setTimeout(function() { self.update(res); }, 10000);
-          }
+              setTimeout(function() {
+                self.update(res);
+              }, 10000);
+          },
         });
       },
 
@@ -237,35 +247,40 @@ define('misc.bgprocess', [
         if (self.notify && !self.details) {
           if (!self.notifier) {
             var header = $('<div></div>', {
-                  class: "h5 pg-bg-notify-header"
-                }).append($('<span></span>').text(self.desc)),
-                content = $('<div class="pg-bg-bgprocess row"></div>').append(
-                  header
-                ).append(
-                  $('<div></div>', {class: 'pg-bg-notify-body h6' }).append(
-                    $('<div></div>', {class: 'pg-bg-start col-xs-12' }).append(
-                      $('<div></div>').text(self.stime.toString())
-                    ).append(
-                      $('<div class="pg-bg-etime"></div>')
-                    )
-                  )
-                ),
-                for_details = $('<div></div>', {
-                  class: "col-xs-12 text-center pg-bg-click h6"
+                class: 'h5 pg-bg-notify-header',
+              }).append($('<span></span>').text(self.desc)),
+              content = $('<div class="pg-bg-bgprocess row"></div>').append(
+                header
+              ).append(
+                $('<div></div>', {
+                  class: 'pg-bg-notify-body h6',
                 }).append(
-                  $('<span></span>').text(gettext('Click here for details.'))
-                ).appendTo(content),
-                status = $('<div></div>', {
-                  class: "pg-bg-status col-xs-12 h5 " + ((self.exit_code === 0) ?
-                      'bg-success': (self.exit_code == 1) ?
-                      'bg-failed' : '')
-                }).appendTo(content),
-                close_me = $(
-                  '<div class="bg-close"><i class="fa fa-close"></i></div>'
-                ).appendTo(header);
+                  $('<div></div>', {
+                    class: 'pg-bg-start col-xs-12',
+                  }).append(
+                    $('<div></div>').text(self.stime.toString())
+                  ).append(
+                    $('<div class="pg-bg-etime"></div>')
+                  )
+                )
+              ),
+              for_details = $('<div></div>', {
+                class: 'col-xs-12 text-center pg-bg-click h6',
+              }).append(
+                $('<span></span>').text(gettext('Click here for details.'))
+              ).appendTo(content),
+              close_me = $(
+                '<div class="bg-close"><i class="fa fa-close"></i></div>'
+              ).appendTo(header);
+
+            $('<div></div>', {
+              class: 'pg-bg-status col-xs-12 h5 ' + ((self.exit_code === 0) ?
+                'bg-success' : (self.exit_code == 1) ?
+                'bg-failed' : ''),
+            }).appendTo(content);
 
             self.container = content;
-            self.notifier = alertify.notify(
+            self.notifier = Alertify.notify(
               content.get(0), 'bg-bgprocess', 0, null
             );
 
@@ -281,7 +296,7 @@ define('misc.bgprocess', [
               this.show_detailed_view.apply(this);
             }.bind(self));
 
-            close_me.on('click', function(ev) {
+            close_me.on('click', function() {
               this.notifier.dismiss();
               this.notifier = null;
               this.acknowledge_server.apply(this);
@@ -312,37 +327,37 @@ define('misc.bgprocess', [
 
           if (self.exit_code === 0) {
             $status_bar.addClass('bg-success');
-          } else if (self.exit_code == 1){
+          } else if (self.exit_code == 1) {
             $status_bar.addClass('bg-failed');
           }
         } else {
-          self.show_detailed_view.apply(self)
+          self.show_detailed_view.apply(self);
         }
       },
 
       show_detailed_view: function() {
         var self = this,
-            panel = this.panel,
-            is_new = false;
+          panel = this.panel,
+          is_new = false;
 
         if (!self.panel) {
           is_new = true;
           panel = this.panel =
-              pgBrowser.BackgroundProcessObsorver.create_panel();
+            pgBrowser.BackgroundProcessObsorver.create_panel();
 
           panel.title('Process Watcher - ' + _.escape(self.desc));
           panel.focus();
         }
 
         var container = panel.$container,
-            status_class = (
-              (self.exit_code === 0) ?
-                'bg-bgprocess-success': (self.exit_code == 1) ?
-                  'bg-bgprocess-failed' : ''
-            ),
-            $logs = container.find('.bg-process-watcher'),
-            $header = container.find('.bg-process-details'),
-            $footer = container.find('.bg-process-footer');
+          status_class = (
+            (self.exit_code === 0) ?
+            'bg-bgprocess-success' : (self.exit_code == 1) ?
+            'bg-bgprocess-failed' : ''
+          ),
+          $logs = container.find('.bg-process-watcher'),
+          $header = container.find('.bg-process-details'),
+          $footer = container.find('.bg-process-footer');
 
         if (is_new) {
           // set logs
@@ -413,14 +428,15 @@ define('misc.bgprocess', [
           url: self.bgprocess_url('acknowledge'),
           cache: false,
           async: true,
-          contentType: "application/json",
-          success: function(res) {
+          contentType: 'application/json',
+          success: function() {
             return;
           },
-          error: function(res) {
-          }
+          error: function() {
+            console.warn(arguments);
+          },
         });
-      }
+      },
     });
 
   _.extend(
@@ -449,7 +465,7 @@ define('misc.bgprocess', [
               }, 1000
             );
           }
-        )
+        );
       },
 
       update_process_list: function(recheck) {
@@ -461,9 +477,8 @@ define('misc.bgprocess', [
           url: url_for('bgprocess.list'),
           cache: false,
           async: true,
-          contentType: "application/json",
+          contentType: 'application/json',
           success: function(res) {
-            var cnt = 0;
             if (!res || !_.isArray(res)) {
               return;
             }
@@ -484,9 +499,10 @@ define('misc.bgprocess', [
               );
             }
           },
-          error: function(res) {
+          error: function() {
             // FIXME:: What to do now?
-          }
+            console.warn(arguments);
+          },
         });
       },
 
@@ -498,11 +514,11 @@ define('misc.bgprocess', [
           wcDocker.DOCK.FLOAT,
           null, {
             w: (screen.width < 700 ?
-                screen.width * 0.95 : screen.width * 0.5),
-                h: (screen.height < 500 ?
-                    screen.height * 0.95 : screen.height * 0.5),
-                    x: (screen.width < 700 ? '2%' : '25%'),
-                    y: (screen.height < 500 ? '2%' : '25%')
+              screen.width * 0.95 : screen.width * 0.5),
+            h: (screen.height < 500 ?
+              screen.height * 0.95 : screen.height * 0.5),
+            x: (screen.width < 700 ? '2%' : '25%'),
+            y: (screen.height < 500 ? '2%' : '25%'),
           });
       },
 
@@ -510,40 +526,40 @@ define('misc.bgprocess', [
         var w = pgBrowser.docker,
           panels = w.findPanels('bg_process_watcher');
 
-          if (panels && panels.length >= 1)
-            return;
+        if (panels && panels.length >= 1)
+          return;
 
-          var p = new pgBrowser.Panel({
-                name: 'bg_process_watcher',
-                showTitle: true,
-                isCloseable: true,
-                isPrivate: true,
-                content: '<div class="bg-process-details col-xs-12">'+
-                  '<p class="bg-detailed-desc"></p>'+
-                  '<div class="bg-process-stats">'+
-                  '<span><b>' + gettext('Start time') + ': </b>'+
-                  '<span class="bgprocess-start-time"></span>'+
-                  '</span></div>'+
-                  '</div>'+
-                  '<div class="bg-process-watcher col-xs-12">'+
-                  '</div>'+
-                  '<div class="bg-process-footer col-xs-12">'+
-                  '<div class="bg-process-status col-xs-6">'+
-                  '<span><b>' + gettext('Status') + ':</b></span><p></p>'+
-                  '</div>'+
-                  '<div class="bg-process-exec-time col-xs-6">'+
-                  '<div class="exec-div pull-right">'+
-                  '<span><b>' + gettext('Execution time') + ':</b></span><p></p>'+
-                  '</div>'+
-                  '</div>'+
-                  '</div>',
-                onCreate: function(myPanel, $container) {
-                  $container.addClass('pg-no-overflow');
-                }
-              });
-          p.load(pgBrowser.docker);
-      }
+        var p = new pgBrowser.Panel({
+          name: 'bg_process_watcher',
+          showTitle: true,
+          isCloseable: true,
+          isPrivate: true,
+          content: '<div class="bg-process-details col-xs-12">' +
+            '<p class="bg-detailed-desc"></p>' +
+            '<div class="bg-process-stats">' +
+            '<span><b>' + gettext('Start time') + ': </b>' +
+            '<span class="bgprocess-start-time"></span>' +
+            '</span></div>' +
+            '</div>' +
+            '<div class="bg-process-watcher col-xs-12">' +
+            '</div>' +
+            '<div class="bg-process-footer col-xs-12">' +
+            '<div class="bg-process-status col-xs-6">' +
+            '<span><b>' + gettext('Status') + ':</b></span><p></p>' +
+            '</div>' +
+            '<div class="bg-process-exec-time col-xs-6">' +
+            '<div class="exec-div pull-right">' +
+            '<span><b>' + gettext('Execution time') + ':</b></span><p></p>' +
+            '</div>' +
+            '</div>' +
+            '</div>',
+          onCreate: function(myPanel, $container) {
+            $container.addClass('pg-no-overflow');
+          },
+        });
+        p.load(pgBrowser.docker);
+      },
     });
 
   return pgBrowser.BackgroundProcessObsorver;
-});
+});
\ No newline at end of file
diff --git a/web/pgadmin/misc/depends/static/js/depends.js b/web/pgadmin/misc/depends/static/js/depends.js
index 0fc28b04..45b18975 100644
--- a/web/pgadmin/misc/depends/static/js/depends.js
+++ b/web/pgadmin/misc/depends/static/js/depends.js
@@ -1,7 +1,7 @@
 define('misc.depends', [
-  'sources/gettext', 'underscore', 'underscore.string', 'jquery', 'pgadmin.browser',
-  'alertify', 'pgadmin.alertifyjs'
-], function(gettext, _, S, $, pgBrowser, Alertify) {
+  'sources/gettext', 'underscore', 'underscore.string', 'jquery', 'backbone',
+  'pgadmin.browser', 'pgadmin.alertifyjs', 'pgadmin.backgrid',
+], function(gettext, _, S, $, Backbone, pgBrowser, Alertify, Backgrid) {
 
   if (pgBrowser.ShowNodeDepends)
     return pgBrowser.ShowNodeDepends;
@@ -20,19 +20,15 @@ define('misc.depends', [
       /* Parameter is used to set the proper label of the
        * backgrid header cell.
        */
-      var dependent = true,
-          dependentGrid = null,  // Refer to the backgrid object render under Dependents tab
-          dependenciesGrid = null; // Refer to the backgrid object render under Dependencies tab
-
       _.bindAll(this, 'showDependents', 'dependentsPanelVisibilityChanged',
-         'showDependencies', 'dependenciesPanelVisibilityChanged', '__updateCollection'
+        'showDependencies', 'dependenciesPanelVisibilityChanged', '__updateCollection'
       );
 
       // We will listened to the visibility change of the Dependencies and Dependents panel
       pgBrowser.Events.on('pgadmin-browser:panel-dependencies:' + wcDocker.EVENT.VISIBILITY_CHANGED,
-                        this.dependenciesPanelVisibilityChanged);
+        this.dependenciesPanelVisibilityChanged);
       pgBrowser.Events.on('pgadmin-browser:panel-dependents:' + wcDocker.EVENT.VISIBILITY_CHANGED,
-                        this.dependentsPanelVisibilityChanged);
+        this.dependentsPanelVisibilityChanged);
 
       // Defining Backbone Model for Dependencies and Dependents.
       var Model = Backbone.Model.extend({
@@ -43,28 +39,28 @@ define('misc.depends', [
           /* field contains 'Database Name' for 'Tablespace and Role node',
            * for other node it contains 'Restriction'.
            */
-          field: undefined
+          field: undefined,
         },
         // This function is used to fetch/set the icon for the type(Function, Role, Database, ....)
         parse: function(res) {
           var node = pgBrowser.Nodes[res.type];
           res.icon = node ? (_.isFunction(node['node_image']) ?
-                  (node['node_image']).apply(node, [null, null]) :
-                  (node['node_image'] || ('icon-' + res.type))) :
-                  ('icon-' + res.type);
-          res.type = S.titleize(res.type.replace(/_/g, " "), true);
+              (node['node_image']).apply(node, [null, null]) :
+              (node['node_image'] || ('icon-' + res.type))) :
+            ('icon-' + res.type);
+          res.type = S.titleize(res.type.replace(/_/g, ' '), true);
           return res;
-        }
+        },
       });
 
       // Defining Backbone Collection for Dependents.
-      this.dependentCollection = new (Backbone.Collection.extend({
-        model: Model
+      this.dependentCollection = new(Backbone.Collection.extend({
+        model: Model,
       }))(null);
 
       // Defining Backbone Collection for Dependencies.
-      this.dependenciesCollection = new (Backbone.Collection.extend({
-        model: Model
+      this.dependenciesCollection = new(Backbone.Collection.extend({
+        model: Model,
       }))(null);
 
       var self = this;
@@ -75,39 +71,40 @@ define('misc.depends', [
        */
       var appendGridToPanel = function(collection, panel, is_dependent) {
         var $container = panel[0].layout().scene().find('.pg-panel-content'),
-            $gridContainer = $container.find('.pg-panel-depends-container'),
-            grid = new Backgrid.Grid({
-              columns: [
-                {
-                  name : 'type',
-                  label: gettext('Type'),
-                  // Extend it to render the icon as per the type.
-                  cell: Backgrid.Cell.extend({
-                    render: function() {
-                      Backgrid.Cell.prototype.render.apply(this, arguments);
-                      this.$el.prepend($('<i>', {class: "wcTabIcon " + this.model.get('icon')}));
-                      return this;
-                    }
-                  }),
-                  editable: false
-                },
-                {
-                  name : 'name',
-                  label: gettext('Name'),
-                  cell: 'string',
-                  editable: false
+          $gridContainer = $container.find('.pg-panel-depends-container'),
+          grid = new Backgrid.Grid({
+            columns: [{
+              name: 'type',
+              label: gettext('Type'),
+                // Extend it to render the icon as per the type.
+              cell: Backgrid.Cell.extend({
+                render: function() {
+                  Backgrid.Cell.prototype.render.apply(this, arguments);
+                  this.$el.prepend($('<i>', {
+                    class: 'wcTabIcon ' + this.model.get('icon'),
+                  }));
+                  return this;
                 },
-                {
-                  name : 'field',
-                  label: '',  // label kept blank, it will change dynamically
-                  cell: 'string',
-                  editable: false
-                }
-              ],
-
-              collection: collection,
-              className: "backgrid presentation table backgrid-striped table-bordered table-hover",
-            });
+              }),
+              editable: false,
+            },
+            {
+              name: 'name',
+              label: gettext('Name'),
+              cell: 'string',
+              editable: false,
+            },
+            {
+              name: 'field',
+              label: '', // label kept blank, it will change dynamically
+              cell: 'string',
+              editable: false,
+            },
+            ],
+
+            collection: collection,
+            className: 'backgrid presentation table backgrid-striped table-bordered table-hover',
+          });
 
         // Condition is used to save grid object to change the label of the header.
         if (is_dependent)
@@ -122,11 +119,12 @@ define('misc.depends', [
 
       // We will listened to the visibility change of the Dependencies and Dependents panel
       pgBrowser.Events.on('pgadmin-browser:panel-dependencies:' + wcDocker.EVENT.VISIBILITY_CHANGED,
-                        this.dependenciesPanelVisibilityChanged);
+        this.dependenciesPanelVisibilityChanged);
       pgBrowser.Events.on('pgadmin-browser:panel-dependents:' + wcDocker.EVENT.VISIBILITY_CHANGED,
-                        this.dependentsPanelVisibilityChanged);
+        this.dependentsPanelVisibilityChanged);
       pgBrowser.Events.on(
-        'pgadmin:browser:node:updated', function() {
+        'pgadmin:browser:node:updated',
+        function() {
           if (this.dependenciesPanels && this.dependenciesPanels.length) {
             $(this.dependenciesPanels[0]).data('node-prop', '');
             this.dependenciesPanelVisibilityChanged(this.dependenciesPanels[0]);
@@ -153,10 +151,10 @@ define('misc.depends', [
 
             // If Dependencies panel exists and is focused then we need to listen the browser tree selection events.
             if ((dependenciesPanels[0].isVisible()) || dependenciesPanels.length != 1) {
-            pgBrowser.Events.on('pgadmin-browser:tree:selected', this.showDependencies);
+              pgBrowser.Events.on('pgadmin-browser:tree:selected', this.showDependencies);
             }
           }.bind(this)
-          );
+        );
       } else {
         appendGridToPanel(this.dependenciesCollection, this.dependenciesPanels, false);
 
@@ -178,7 +176,7 @@ define('misc.depends', [
               pgBrowser.Events.on('pgadmin-browser:tree:selected', this.showDependents);
             }
           }.bind(this)
-          );
+        );
       } else {
         appendGridToPanel(this.dependentCollection, this.dependentsPanels, true);
 
@@ -192,12 +190,11 @@ define('misc.depends', [
     // Fetch the actual data and update the collection
     __updateCollection: function(collection, panel, url, messages, node, item, type) {
       var msg = messages[0],
-          $container = panel[0].layout().scene().find('.pg-panel-content'),
-          $msgContainer = $container.find('.pg-panel-depends-message'),
-          $gridContainer = $container.find('.pg-panel-depends-container'),
-          treeHierarchy = node.getTreeNodeHierarchy(item),
-          n_value = -1,
-          n_type = type;
+        $container = panel[0].layout().scene().find('.pg-panel-content'),
+        $msgContainer = $container.find('.pg-panel-depends-message'),
+        $gridContainer = $container.find('.pg-panel-depends-container'),
+        treeHierarchy = node.getTreeNodeHierarchy(item),
+        n_type = type;
 
       // Avoid unnecessary reloads
       if (_.isEqual($(panel[0]).data('node-prop'), treeHierarchy)) {
@@ -230,20 +227,26 @@ define('misc.depends', [
            * it should be 'Restriction'.
            */
           if (this.dependent && (node.type == 'tablespace' || node.type == 'role'))
-            this.dependentGrid.columns.models[2].set({'label': gettext('Database')});
+            this.dependentGrid.columns.models[2].set({
+              'label': gettext('Database'),
+            });
           else {
-            this.dependenciesGrid.columns.models[2].set({'label': gettext('Restriction')});
-            this.dependentGrid.columns.models[2].set({'label': gettext('Restriction')});
+            this.dependenciesGrid.columns.models[2].set({
+              'label': gettext('Restriction'),
+            });
+            this.dependentGrid.columns.models[2].set({
+              'label': gettext('Restriction'),
+            });
           }
 
           // Hide message container and show grid container.
           $msgContainer.addClass('hidden');
           $gridContainer.removeClass('hidden');
 
-          var timer = setTimeout(function(){
+          var timer = setTimeout(function() {
             // notify user if request is taking longer than 1 second
 
-            $msgContainer.text(gettext("Retrieving data from the server..."));
+            $msgContainer.text(gettext('Retrieving data from the server...'));
             $msgContainer.removeClass('hidden');
             if ($gridContainer) {
               $gridContainer.addClass('hidden');
@@ -266,24 +269,23 @@ define('misc.depends', [
               pgBrowser.Events.trigger(
                 'pgadmin:node:retrieval:error', 'depends', xhr, error, message
               );
-              if (
-                !Alertify.pgHandleItemError(xhr, error, message, {
-                  item: item, info: treeHierarchy
-                })
-              ) {
+              if (!Alertify.pgHandleItemError(xhr, error, message, {
+                item: item,
+                info: treeHierarchy,
+              })) {
                 Alertify.pgNotifier(
                   error, xhr,
                   S(
-                    gettext("Error retrieving the information - %s")
+                    gettext('Error retrieving the information - %s')
                   ).sprintf(message || _label).value(),
                   function() {
-                    console.log(arguments);
+                    console.warn(arguments);
                   }
                 );
               }
               // show failed message.
-              $msgContainer.text(gettext("Failed to retrieve data from the server."));
-            }
+              $msgContainer.text(gettext('Failed to retrieve data from the server.'));
+            },
           });
         }
       }
@@ -305,25 +307,23 @@ define('misc.depends', [
       if (self.timeout) {
         clearTimeout(self.timeout);
       }
-      self.timeout =  setTimeout(
+      self.timeout = setTimeout(
         self.__updateCollection(
-          self.dependentCollection,
-          self.dependentsPanels,
-          node.generate_url(item, 'dependent', data, true),
-          [gettext('No object selected.'), gettext('No dependent information is available for the current object.'),
-            gettext('Fetching dependent information from the server...')],
-          node,
-          item,
-          data._type
+          self.dependentCollection, self.dependentsPanels,
+          node.generate_url(item, 'dependent', data, true), [
+            gettext('No object selected.'),
+            gettext('No dependent information is available for the current object.'),
+            gettext('Fetching dependent information from the server...'),
+          ], node, item, data._type
         ), 400
       );
     },
     dependentsPanelVisibilityChanged: function(panel) {
       if (panel.isVisible()) {
         var t = pgBrowser.tree,
-            i = t.selected(),
-            d = i && t.itemData(i),
-            n = i && d && pgBrowser.Nodes[d._type];
+          i = t.selected(),
+          d = i && t.itemData(i),
+          n = i && d && pgBrowser.Nodes[d._type];
 
         pgBrowser.ShowNodeDepends.showDependents.apply(pgBrowser.ShowNodeDepends, [i, d, n]);
 
@@ -349,13 +349,13 @@ define('misc.depends', [
       if (self.timeout) {
         clearTimeout(self.timeout);
       }
-      self.timeout =  setTimeout(
+      self.timeout = setTimeout(
         self.__updateCollection(
           self.dependenciesCollection,
           self.dependenciesPanels,
-          node.generate_url(item, 'dependency', data, true),
-          [gettext('Please select an object in the tree view.'), gettext('No dependency information is available for the current object.'),
-            gettext('Fetching dependency information from the server...')],
+          node.generate_url(item, 'dependency', data, true), [gettext('Please select an object in the tree view.'), gettext('No dependency information is available for the current object.'),
+            gettext('Fetching dependency information from the server...'),
+          ],
           node,
           item,
           data._type
@@ -365,9 +365,9 @@ define('misc.depends', [
     dependenciesPanelVisibilityChanged: function(panel) {
       if (panel.isVisible()) {
         var t = pgBrowser.tree,
-            i = t.selected(),
-            d = i && t.itemData(i),
-            n = i && d && pgBrowser.Nodes[d._type];
+          i = t.selected(),
+          d = i && t.itemData(i),
+          n = i && d && pgBrowser.Nodes[d._type];
 
         pgBrowser.ShowNodeDepends.showDependencies.apply(pgBrowser.ShowNodeDepends, [i, d, n]);
 
@@ -377,8 +377,8 @@ define('misc.depends', [
         // We don't need to listen the tree item selection event.
         pgBrowser.Events.off('pgadmin-browser:tree:selected', pgBrowser.ShowNodeDepends.showDependencies);
       }
-    }
+    },
   });
 
   return pgBrowser.ShowNodeDepends;
-});
+});
\ No newline at end of file
diff --git a/web/pgadmin/misc/file_manager/static/js/file_manager.js b/web/pgadmin/misc/file_manager/static/js/file_manager.js
index 4f5d932d..10de1ea8 100644
--- a/web/pgadmin/misc/file_manager/static/js/file_manager.js
+++ b/web/pgadmin/misc/file_manager/static/js/file_manager.js
@@ -1,694 +1,732 @@
 define('misc.file_manager', [
-      'sources/gettext', 'sources/url_for', 'jquery', 'underscore',
-      'pgadmin.alertifyjs'
-], function(gettext, url_for, $, _, alertify) {
-    pgAdmin = pgAdmin || window.pgAdmin || {};
-
-    /*
-     * Hmm... this module is already been initialized, we can refer to the old
-     * object from here.
-     */
-    if (pgAdmin.FileManager) {
-      return pgAdmin.FileManager;
-    }
-
-    pgAdmin.FileManager = {
-      init: function() {
-        if (this.initialized) {
-          return;
-        }
-
-        this.initialized = true;
+  'sources/gettext', 'sources/url_for', 'jquery', 'underscore',
+  'sources/pgadmin', 'pgadmin.alertifyjs',
+], function(gettext, url_for, $, _, pgAdmin, Alertify) {
+  pgAdmin = pgAdmin || window.pgAdmin || {};
+
+  /*
+   *
+   *
+   * Hmm... this module is already been initialized, we can refer to the old
+   * object from here.
+   */
+  if (pgAdmin.FileManager) {
+    return pgAdmin.FileManager;
+  }
 
-        // send a request to get transaction id
-        var getTransId = function(configs) {
-          return $.ajax({
-            data: configs,
-            type: "POST",
-            async: false,
-            url: url_for('file_manager.get_trans_id'),
-            dataType: "json",
-            contentType: "application/json; charset=utf-8",
-          });
-        };
+  pgAdmin.FileManager = {
+    init: function() {
+      if (this.initialized) {
+        return;
+      }
 
-        // Function to remove trans id from session
-        var removeTransId = function(trans_id) {
-          return $.ajax({
-            type: "GET",
-            async: false,
-            url: url_for('file_manager.delete_trans_id', {'trans_id': trans_id}),
-            dataType: "json",
-            contentType: "application/json; charset=utf-8",
+      this.initialized = true;
+
+      // Send a request to get transaction id
+      var getTransId = function(configs) {
+        return $.ajax({
+          data: configs,
+          type: 'POST',
+          async: false,
+          url: url_for('file_manager.get_trans_id'),
+          dataType: 'json',
+          contentType: 'application/json; charset=utf-8',
+        });
+      };
+
+      // Function to remove trans id from session
+      var removeTransId = function(trans_id) {
+        return $.ajax({
+          type: 'GET',
+          async: false,
+          url: url_for('file_manager.delete_trans_id', {
+            'trans_id': trans_id,
+          }),
+          dataType: 'json',
+          contentType: 'application/json; charset=utf-8',
+        });
+      };
+
+      var set_last_traversed_dir = function(path, trans_id) {
+        return $.ajax({
+          url: url_for('file_manager.save_last_dir', {
+            'trans_id': trans_id,
+          }),
+          type: 'POST',
+          data: JSON.stringify(path),
+          contentType: 'application/json',
+        });
+      };
+      // Declare the Storage dialog
+      Alertify.dialog('storageManagerDlg', function() {
+        // Dialog containter
+        var $container = $('<div class=\'storage_dialog\'></div>'),
+          trans_id;
+
+        /*
+         * Function: renderStoragePanel
+         *
+         * Renders the FileManager in the content div based on the given
+         * configuration parameters.
+         */
+        var renderStoragePanel = function(params) {
+          /*
+           * Clear the existing html in the storage content
+           */
+          var content = $container.find('.storage_content');
+          content.empty();
+          $.get(url_for('file_manager.index'), function(data) {
+            content.append(data);
           });
-        };
 
-        var set_last_traversed_dir = function(path, trans_id) {
-          return $.ajax({
-            url: url_for('file_manager.save_last_dir', {'trans_id': trans_id}),
-            type: 'POST',
-            data: JSON.stringify(path),
-            contentType: 'application/json'
-          });
+          var transId = getTransId(params);
+          var t_res;
+          if (transId.readyState == 4) {
+            t_res = JSON.parse(transId.responseText);
+          }
+          trans_id = t_res.data.fileTransId;
         };
-        // Declare the Storage dialog
-        alertify.dialog('storageManagerDlg', function() {
-          var controls = [], // Keep tracking of all the backform controls
-              // Dialog containter
-              $container = $("<div class='storage_dialog'></div>"),
-              trans_id;
-
-          /*
-           * Function: renderStoragePanel
-           *
-           * Renders the FileManager in the content div based on the given
-           * configuration parameters.
-           */
-          var renderStoragePanel = function(params) {
-            /*
-             * Clear the existing html in the storage content
-             */
-            var content = $container.find('.storage_content');
-            content.empty();
-            $.get(url_for('file_manager.index'), function(data) {
-              content.append(data);
-            });
 
-            var transId = getTransId(params);
-            var t_res;
-            if (transId.readyState == 4) {
-              t_res = JSON.parse(transId.responseText);
+        // Dialog property
+        return {
+          main: function(params) {
+            // Set title and button name
+            var self = this;
+            if (_.isUndefined(params['dialog_title'])) {
+              params['dialog_title'] = 'Storage manager';
             }
-            trans_id = t_res.data.fileTransId;
-          };
-
-          // Dialog property
-          return {
-            main: function(params) {
-              // Set title and button name
-              var self = this;
-              if (_.isUndefined(params['dialog_title'])) {
-                params['dialog_title'] = 'Storage manager';
-              }
-              this.set('title', params['dialog_title']);
-              if (_.isUndefined(params['btn_primary'])) {
-                params['btn_primary'] = 'Select';
-              }
-              this.set('label', params['btn_primary']);
-
-              params = JSON.stringify(params);
-              $container.find('.storage_content').remove();
-              $container.append("<div class='storage_content'></div>");
-              renderStoragePanel(params);
-              this.elements.dialog.style.minWidth = '630px';
-              this.show();
-              setTimeout(function() {
-                $($container.find('.file_manager')).on('enter-key', function() {
-                    $($(self.elements.footer).find('.file_manager_ok')).trigger('click')
-                });
-              }, 200);
-            },
-            settings: {
-              label: undefined
-            },
-            settingUpdated: function (key, oldValue, newValue) {
-              switch (key) {
-              case 'message':
-                  this.setMessage(newValue);
-                  break;
-              case 'label':
-                  if (this.__internal.buttons[0].element) {
-                      this.__internal.buttons[0].element.innerHTML = newValue;
-                  }
-                  break;
-              default:
-                  break;
+            this.set('title', params['dialog_title']);
+            if (_.isUndefined(params['btn_primary'])) {
+              params['btn_primary'] = 'Select';
+            }
+            this.set('label', params['btn_primary']);
+
+            params = JSON.stringify(params);
+            $container.find('.storage_content').remove();
+            $container.append('<div class=\'storage_content\'></div>');
+            renderStoragePanel(params);
+            this.elements.dialog.style.minWidth = '630px';
+            this.show();
+            setTimeout(function() {
+              $($container.find('.file_manager')).on('enter-key', function() {
+                $($(self.elements.footer).find('.file_manager_ok')).trigger('click');
+              });
+            }, 200);
+          },
+          settings: {
+            label: undefined,
+          },
+          settingUpdated: function(key, oldValue, newValue) {
+            switch (key) {
+            case 'message':
+              this.setMessage(newValue);
+              break;
+            case 'label':
+              if (this.__internal.buttons[0].element) {
+                this.__internal.buttons[0].element.innerHTML = newValue;
               }
+              break;
+            default:
+              break;
+            }
+          },
+          prepare: function() {
+            this.__internal.buttons[0].element.disabled = true;
+          },
+          setup: function() {
+            return {
+              buttons: [{
+                text: gettext('Select'),
+                className: 'btn btn-primary fa fa-file file_manager_ok pg-alertify-button disabled',
+              },
+              {
+                text: gettext('Cancel'),
+                className: 'btn btn-danger fa fa-times pg-alertify-button',
+              },
+              ],
+              focus: {
+                element: 0,
+              },
+              options: {
+                closableByDimmer: false,
+
+              },
+            };
+          },
+          callback: function(closeEvent) {
+            var innerbody;
+            if (closeEvent.button.text == gettext('Select')) {
+              var newFile = $('.storage_dialog #uploader .input-path').val(),
+                file_data = {
+                  'path': $('.currentpath').val(),
+                };
+
+              pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:storage_dialog', newFile);
+
+              set_last_traversed_dir(file_data, trans_id);
+              innerbody = $(this.elements.body).find('.storage_content');
+              $(innerbody).find('*').off();
+              innerbody.remove();
+              removeTransId(trans_id);
+            } else if (closeEvent.button.text == gettext('Cancel')) {
+              innerbody = $(this.elements.body).find('.storage_content');
+              $(innerbody).find('*').off();
+              innerbody.remove();
+              removeTransId(trans_id);
+              pgAdmin.Browser.Events.trigger('pgadmin-storage:cancel_btn:storage_dialog');
+            }
+          },
+          build: function() {
+            this.elements.content.appendChild($container.get(0));
+          },
+          hooks: {
+            onshow: function() {
+              $(this.elements.body).addClass('pgadmin-storage-body');
             },
-            prepare: function() {
-              this.__internal.buttons[0].element.disabled = true;
-            },
-            setup:function() {
-              return {
-                buttons:[
-                  {
-                    text: gettext("Select"), className: "btn btn-primary fa fa-file file_manager_ok pg-alertify-button disabled"
-                  },
-                  {
-                    text: gettext("Cancel"), className: "btn btn-danger fa fa-times pg-alertify-button"
-                  }
-                ],
-                focus: { element: 0 },
-                options: {
-                  closableByDimmer: false,
+          },
+        };
+      });
+
+      // Declare the Selection dialog
+      Alertify.dialog('fileSelectionDlg', function() {
+        // Dialog containter
+        var $container =
+          $('<div class=\'storage_dialog file_selection_dlg\'></div>'),
+          trans_id;
+
+        // Send a request to get transaction id
+        /*
+         * Function: renderStoragePanel
+         *
+         * Renders the FileManager in the content div based on the given
+         * configuration parameters.
+         */
+        var renderStoragePanel = function(configs) {
+          /*
+           * Clear the existing html in the storage content
+           */
+          var content = $container.find('.storage_content');
+          content.empty();
 
-                }
-              };
-            },
-            callback: function(closeEvent) {
-              if (closeEvent.button.text == gettext("Select")) {
-                var newFile = $('.storage_dialog #uploader .input-path').val(),
-                    file_data = {'path': $('.currentpath').val()};
+          $.get(url_for('file_manager.index'), function(data) {
+            content.append(data);
+          });
 
-                pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:storage_dialog', newFile);
+          var transId = getTransId(configs);
+          var t_res;
+          if (transId.readyState == 4) {
+            t_res = JSON.parse(transId.responseText);
+          }
+          trans_id = t_res.data.fileTransId;
+        };
 
-                set_last_traversed_dir(file_data, trans_id);
-                var innerbody = $(this.elements.body).find('.storage_content')
-                $(innerbody).find('*').off();
-                innerbody.remove();
-                removeTransId(trans_id);
-              } else if (closeEvent.button.text == gettext("Cancel")) {
-                var innerbody = $(this.elements.body).find('.storage_content')
-                $(innerbody).find('*').off();
-                innerbody.remove();
-                removeTransId(trans_id);
-                pgAdmin.Browser.Events.trigger('pgadmin-storage:cancel_btn:storage_dialog');
-              }
-            },
-            build: function() {
-              this.elements.content.appendChild($container.get(0));
-            },
-            hooks: {
-              onshow: function() {
-                $(this.elements.body).addClass('pgadmin-storage-body');
+        // Dialog property
+        return {
+          main: function(params) {
+            // Set title and button name
+            var self = this;
+            if (_.isUndefined(params['dialog_title'])) {
+              params['dialog_title'] = 'Select file';
+            }
+            this.set('title', params['dialog_title']);
+            if (_.isUndefined(params['btn_primary'])) {
+              params['btn_primary'] = 'Select';
+            }
+            this.set('label', params['btn_primary']);
+
+            params = JSON.stringify(params);
+            $container.find('.storage_content').remove();
+            $container.append('<div class=\'storage_content\'></div>');
+            renderStoragePanel(params);
+            this.elements.dialog.style.minWidth = '630px';
+            this.show();
+            setTimeout(function() {
+              $($container.find('.file_manager')).on('enter-key', function() {
+                $($(self.elements.footer).find('.file_manager_ok')).trigger('click');
+              });
+            }, 200);
+          },
+          settings: {
+            label: undefined,
+          },
+          settingUpdated: function(key, oldValue, newValue) {
+            switch (key) {
+            case 'message':
+              this.setMessage(newValue);
+              break;
+            case 'label':
+              if (this.__internal.buttons[0].element) {
+                this.__internal.buttons[0].element.innerHTML = newValue;
               }
+              break;
+            default:
+              break;
             }
-          };
-        });
+          },
+          prepare: function() {
+            this.__internal.buttons[0].element.disabled = true;
+          },
+          setup: function() {
+            return {
+              buttons: [{
+                text: gettext('Select'),
+                key: 13,
+                className: 'btn btn-primary fa fa-file file_manager_ok pg-alertify-button disabled',
+              },
+              {
+                text: gettext('Cancel'),
+                key: 27,
+                className: 'btn btn-danger fa fa-times pg-alertify-button',
+              },
+              ],
+              focus: {
+                element: 0,
+              },
+              options: {
+                closableByDimmer: false,
+                maximizable: false,
+                closable: false,
+                movable: true,
+              },
+            };
+          },
+          callback: function(closeEvent) {
+            var innerbody;
+
+            if (closeEvent.button.text == gettext('Select')) {
+              var newFile = $('.storage_dialog #uploader .input-path').val(),
+                file_data = {
+                  'path': $('.currentpath').val(),
+                };
+
+              pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:select_file', newFile);
+              innerbody = $(this.elements.body).find('.storage_content');
+              $(innerbody).find('*').off();
+              innerbody.remove();
+              removeTransId(trans_id);
+              // Ajax call to store the last directory visited once user press select button
+
+              set_last_traversed_dir(file_data, trans_id);
+            } else if (closeEvent.button.text == gettext('Cancel')) {
+              innerbody = $(this.elements.body).find('.storage_content');
+              $(innerbody).find('*').off();
+              innerbody.remove();
+              removeTransId(trans_id);
+              pgAdmin.Browser.Events.trigger('pgadmin-storage:cancel_btn:select_file');
+            }
+          },
+          build: function() {
+            this.elements.content.appendChild($container.get(0));
+          },
+          hooks: {
+            onshow: function() {
+              $(this.elements.body).addClass('pgadmin-storage-body');
+            },
+          },
+        };
+      });
 
-        // Declare the Selection dialog
-        alertify.dialog('fileSelectionDlg', function() {
-          var controls = [], // Keep tracking of all the backform controls
-              // Dialog containter
-              $container = $("<div class='storage_dialog file_selection_dlg'></div>");
-          var trans_id;
+      // Declare the Folder Selection dialog
+      Alertify.dialog('folderSelectionDlg', function() {
+        // Dialog containter
+        var $container =
+          $('<div class=\'storage_dialog folder_selection_dlg\'></div>'),
+          trans_id;
 
-          // send a request to get transaction id
+        // send a request to get transaction id
+        /*
+         * Function: renderStoragePanel
+         *
+         * Renders the FileManager in the content div based on the given
+         * configuration parameters.
+         */
+        var renderStoragePanel = function(params) {
           /*
-           * Function: renderStoragePanel
-           *
-           * Renders the FileManager in the content div based on the given
-           * configuration parameters.
+           * Clear the existing html in the storage content
            */
-          var renderStoragePanel = function(configs) {
-            /*
-             * Clear the existing html in the storage content
-             */
-            var content = $container.find('.storage_content');
-            content.empty();
-
-            $.get(url_for('file_manager.index'), function(data) {
-              content.append(data);
-            });
+          var content = $container.find('.storage_content');
+          content.empty();
 
-            var transId = getTransId(configs);
-            var t_res;
-            if (transId.readyState == 4) {
-              t_res = JSON.parse(transId.responseText);
-            }
-            trans_id = t_res.data.fileTransId;
-          };
-
-          // Dialog property
-          return {
-            main: function(params) {
-              // Set title and button name
-              var self = this;
-              if (_.isUndefined(params['dialog_title'])) {
-                params['dialog_title'] = 'Select file';
-              }
-              this.set('title', params['dialog_title']);
-              if (_.isUndefined(params['btn_primary'])) {
-                params['btn_primary'] = 'Select';
-              }
-              this.set('label', params['btn_primary']);
-
-              params = JSON.stringify(params);
-              $container.find('.storage_content').remove();
-              $container.append("<div class='storage_content'></div>");
-              renderStoragePanel(params);
-              this.elements.dialog.style.minWidth = '630px';
-              this.show();
-              setTimeout(function() {
-                $($container.find('.file_manager')).on('enter-key', function() {
-                    $($(self.elements.footer).find('.file_manager_ok')).trigger('click')
-                });
-              }, 200);
-            },
-            settings: {
-              label: undefined
-            },
-            settingUpdated: function (key, oldValue, newValue) {
-              switch (key) {
-              case 'message':
-                  this.setMessage(newValue);
-                  break;
-              case 'label':
-                  if (this.__internal.buttons[0].element) {
-                      this.__internal.buttons[0].element.innerHTML = newValue;
-                  }
-                  break;
-              default:
-                  break;
-              }
-            },
-            prepare: function() {
-              this.__internal.buttons[0].element.disabled = true;
-            },
-            setup:function() {
-              return {
-                buttons:[
-                  {
-                    text: gettext("Select"), key: 13, className: "btn btn-primary fa fa-file file_manager_ok pg-alertify-button disabled"
-                  },
-                  {
-                    text: gettext("Cancel"), key: 27, className: "btn btn-danger fa fa-times pg-alertify-button"
-                  }
-                ],
-                focus: { element: 0 },
-                options: {
-                  closableByDimmer: false,
-                  maximizable: false,
-                  closable: false,
-                  movable: true
-                }
-              };
-            },
-            callback: function(closeEvent) {
-              if (closeEvent.button.text == gettext("Select")) {
-                var newFile = $('.storage_dialog #uploader .input-path').val(),
-                    file_data = {'path': $('.currentpath').val()};
+          $.get(url_for('file_manager.index'), function(data) {
+            content.append(data);
+          });
 
-                pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:select_file', newFile);
-                var innerbody = $(this.elements.body).find('.storage_content')
-                $(innerbody).find('*').off();
-                innerbody.remove();
-                removeTransId(trans_id);
-                // Ajax call to store the last directory visited once user press select button
+          var transId = getTransId(params);
+          var t_res;
+          if (transId.readyState == 4) {
+            t_res = JSON.parse(transId.responseText);
+          }
+          trans_id = t_res.data.fileTransId;
+        };
 
-                set_last_traversed_dir(file_data, trans_id);
-              } else if (closeEvent.button.text == gettext("Cancel")) {
-                var innerbody = $(this.elements.body).find('.storage_content')
-                $(innerbody).find('*').off();
-                innerbody.remove();
-                removeTransId(trans_id);
-                pgAdmin.Browser.Events.trigger('pgadmin-storage:cancel_btn:select_file');
-              }
-            },
-            build: function() {
-              this.elements.content.appendChild($container.get(0));
-            },
-            hooks: {
-              onshow: function() {
-                $(this.elements.body).addClass('pgadmin-storage-body');
+        // Dialog property
+        return {
+          main: function(params) {
+            var self = this;
+            // Set title and button name
+            if (_.isUndefined(params['dialog_title'])) {
+              params['dialog_title'] = 'Select folder';
+            }
+            this.set('title', params['dialog_title']);
+            if (_.isUndefined(params['btn_primary'])) {
+              params['btn_primary'] = 'Select';
+            }
+            this.set('label', params['btn_primary']);
+
+            params = JSON.stringify(params);
+            $container.find('.storage_content').remove();
+            $container.append('<div class=\'storage_content\'></div>');
+            renderStoragePanel(params);
+            this.elements.dialog.style.minWidth = '630px';
+            this.show();
+            setTimeout(function() {
+              $($container.find('.file_manager')).on('enter-key', function() {
+                $($(self.elements.footer).find('.file_manager_ok')).trigger('click');
+              });
+            }, 200);
+          },
+          settings: {
+            label: undefined,
+          },
+          settingUpdated: function(key, oldValue, newValue) {
+            switch (key) {
+            case 'message':
+              this.setMessage(newValue);
+              break;
+            case 'label':
+              if (this.__internal.buttons[0].element) {
+                this.__internal.buttons[0].element.innerHTML = newValue;
               }
+              break;
+            default:
+              break;
             }
-          };
-        });
-
-        // Declare the Folder Selection dialog
-        alertify.dialog('folderSelectionDlg', function() {
-          var controls = [], // Keep tracking of all the backform controls
-              // Dialog containter
-              $container = $("<div class='storage_dialog folder_selection_dlg'></div>"),
-              trans_id;
-
-          // send a request to get transaction id
+          },
+          prepare: function() {
+            this.__internal.buttons[0].element.disabled = true;
+          },
+          setup: function() {
+            return {
+              buttons: [{
+                text: gettext('Select'),
+                key: 13,
+                className: 'btn btn-primary fa fa-file file_manager_ok pg-alertify-button disabled',
+              },
+              {
+                text: gettext('Cancel'),
+                key: 27,
+                className: 'btn btn-danger fa fa-times pg-alertify-button',
+              },
+              ],
+              focus: {
+                element: 0,
+              },
+              options: {
+                closableByDimmer: false,
+                maximizable: false,
+                closable: false,
+                movable: true,
+              },
+            };
+          },
+          callback: function(closeEvent) {
+            var innerbody;
+
+            if (closeEvent.button.text == gettext('Select')) {
+              var newFile = $('.storage_dialog #uploader .input-path').val(),
+                file_data = {
+                  'path': $('.currentpath').val(),
+                };
+              pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:select_folder', newFile);
+              innerbody = $(this.elements.body).find('.storage_content');
+              $(innerbody).find('*').off();
+              innerbody.remove();
+              removeTransId(trans_id);
+              // Ajax call to store the last directory visited once user press select button
+              set_last_traversed_dir(file_data, trans_id);
+            } else if (closeEvent.button.text == gettext('Cancel')) {
+              innerbody = $(this.elements.body).find('.storage_content');
+              $(innerbody).find('*').off();
+              innerbody.remove();
+              removeTransId(trans_id);
+              pgAdmin.Browser.Events.trigger('pgadmin-storage:cancel_btn:select_folder');
+            }
+          },
+          build: function() {
+            this.elements.content.appendChild($container.get(0));
+          },
+          hooks: {
+            onshow: function() {
+              $(this.elements.body).addClass('pgadmin-storage-body');
+            },
+          },
+        };
+      });
+
+      // Declare the Create mode dialog
+      Alertify.dialog('createModeDlg', function() {
+        // Dialog containter
+        var $container =
+          $('<div class=\'storage_dialog create_mode_dlg\'></div>'),
+          trans_id;
+
+        /*
+         * Function: renderStoragePanel
+         *
+         * Renders the FileManager in the content div based on the given
+         * configuration parameters.
+         */
+        var renderStoragePanel = function(params) {
           /*
-           * Function: renderStoragePanel
-           *
-           * Renders the FileManager in the content div based on the given
-           * configuration parameters.
+           * Clear the existing html in the storage content
            */
-          var renderStoragePanel = function(params) {
-            /*
-             * Clear the existing html in the storage content
-             */
-            var content = $container.find('.storage_content');
-            content.empty();
-
-            $.get(url_for('file_manager.index'), function(data) {
-              content.append(data);
-            });
+          var content = $container.find('.storage_content');
+          content.empty();
 
-            var transId = getTransId(params);
-            var t_res;
-            if (transId.readyState == 4) {
-              t_res = JSON.parse(transId.responseText);
-            }
-            trans_id = t_res.data.fileTransId;
-          };
-
-          // Dialog property
-          return {
-            main: function(params) {
-              var self = this;
-              // Set title and button name
-              if (_.isUndefined(params['dialog_title'])) {
-                params['dialog_title'] = 'Select folder';
-              }
-              this.set('title', params['dialog_title']);
-              if (_.isUndefined(params['btn_primary'])) {
-                params['btn_primary'] = 'Select';
-              }
-              this.set('label', params['btn_primary']);
-
-              params = JSON.stringify(params);
-              $container.find('.storage_content').remove();
-              $container.append("<div class='storage_content'></div>");
-              renderStoragePanel(params);
-              this.elements.dialog.style.minWidth = '630px';
-              this.show();
-              setTimeout(function() {
-                $($container.find('.file_manager')).on('enter-key', function() {
-                    $($(self.elements.footer).find('.file_manager_ok')).trigger('click')
-                });
-              }, 200);
-            },
-            settings: {
-              label: undefined
-            },
-            settingUpdated: function (key, oldValue, newValue) {
-              switch (key) {
-              case 'message':
-                  this.setMessage(newValue);
-                  break;
-              case 'label':
-                  if (this.__internal.buttons[0].element) {
-                      this.__internal.buttons[0].element.innerHTML = newValue;
-                  }
-                  break;
-              default:
-                  break;
-              }
-            },
-            prepare: function() {
-              this.__internal.buttons[0].element.disabled = true;
-            },
-            setup:function() {
-              return {
-                buttons:[
-                  {
-                    text: gettext("Select"), key: 13, className: "btn btn-primary fa fa-file file_manager_ok pg-alertify-button disabled"
-                  },
-                  {
-                    text: gettext("Cancel"), key: 27, className: "btn btn-danger fa fa-times pg-alertify-button"
-                  }
-                ],
-                focus: { element: 0 },
-                options: {
-                  closableByDimmer: false,
-                  maximizable: false,
-                  closable: false,
-                  movable: true
-                }
-              };
-            },
-            callback: function(closeEvent) {
-              if (closeEvent.button.text == gettext("Select")) {
-                var newFile = $('.storage_dialog #uploader .input-path').val(),
-                    file_data = {'path': $('.currentpath').val()};
-                pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:select_folder', newFile);
-                var innerbody = $(this.elements.body).find('.storage_content')
-                $(innerbody).find('*').off();
-                innerbody.remove();
-                removeTransId(trans_id);
-                // Ajax call to store the last directory visited once user press select button
-                set_last_traversed_dir(file_data, trans_id);
-              } else if (closeEvent.button.text == gettext("Cancel")) {
-                var innerbody = $(this.elements.body).find('.storage_content')
-                $(innerbody).find('*').off();
-                innerbody.remove();
-                removeTransId(trans_id);
-                pgAdmin.Browser.Events.trigger('pgadmin-storage:cancel_btn:select_folder');
-              }
-            },
-            build: function() {
-              this.elements.content.appendChild($container.get(0));
-            },
-            hooks: {
-              onshow: function() {
-                $(this.elements.body).addClass('pgadmin-storage-body');
-              }
-            }
-          };
-        });
+          $.get(url_for('file_manager.index'), function(data) {
+            content.append(data);
+          });
 
-        // Declare the Create mode dialog
-        alertify.dialog('createModeDlg', function() {
-          var controls = [], // Keep tracking of all the backform controls
-              // Dialog containter
-              $container = $("<div class='storage_dialog create_mode_dlg'></div>"),
-              trans_id;
+          var transId = getTransId(params);
+          var t_res;
+          if (transId.readyState == 4) {
+            t_res = JSON.parse(transId.responseText);
+          }
+          trans_id = t_res.data.fileTransId;
+        };
 
-          /*
-           * Function: renderStoragePanel
-           *
-           * Renders the FileManager in the content div based on the given
-           * configuration parameters.
-           */
-          var renderStoragePanel = function(params) {
-            /*
-             * Clear the existing html in the storage content
-             */
-            var content = $container.find('.storage_content');
-            content.empty();
-
-            $.get(url_for('file_manager.index'), function(data) {
-              content.append(data);
-            });
+        // Dialog property
+        return {
+          main: function(params) {
+            var self = this;
 
-            var transId = getTransId(params);
-            var t_res;
-            if (transId.readyState == 4) {
-              t_res = JSON.parse(transId.responseText);
+            // Set title and button name
+            if (_.isUndefined(params['dialog_title'])) {
+              params['dialog_title'] = 'Create file';
             }
-            trans_id = t_res.data.fileTransId;
-          };
-
-          // Dialog property
-          return {
-            main: function(params) {
-              var self = this,
-                  trans_id;
-              // Set title and button name
-              if (_.isUndefined(params['dialog_title'])) {
-                params['dialog_title'] = 'Create file';
-              }
-              this.set('title', params['dialog_title']);
-              if (_.isUndefined(params['btn_primary'])) {
-                params['btn_primary'] = 'Create';
-              }
-              this.set('label', params['btn_primary']);
-
-              params = JSON.stringify(params);
-              $container.find('.storage_content').remove();
-              $container.append("<div class='storage_content'></div>");
-              renderStoragePanel(params);
-              this.elements.dialog.style.minWidth = '630px';
-              this.show();
-              setTimeout(function() {
-                $($container.find('.file_manager')).on('enter-key', function() {
-                    $($(self.elements.footer).find('.file_manager_ok')).trigger('click')
-                });
-              }, 200);
-            },
-            settings: {
-              label: undefined
-            },
-            settingUpdated: function (key, oldValue, newValue) {
-              switch (key) {
-              case 'message':
-                  this.setMessage(newValue);
-                  break;
-              case 'label':
-                  if (this.__internal.buttons[0].element) {
-                      this.__internal.buttons[0].element.innerHTML = newValue;
-                  }
-                  break;
-              default:
-                  break;
+            this.set('title', params['dialog_title']);
+            if (_.isUndefined(params['btn_primary'])) {
+              params['btn_primary'] = 'Create';
+            }
+            this.set('label', params['btn_primary']);
+
+            params = JSON.stringify(params);
+            $container.find('.storage_content').remove();
+            $container.append('<div class=\'storage_content\'></div>');
+            renderStoragePanel(params);
+            this.elements.dialog.style.minWidth = '630px';
+            this.show();
+            setTimeout(function() {
+              $($container.find('.file_manager')).on('enter-key', function() {
+                $($(self.elements.footer).find('.file_manager_ok')).trigger('click');
+              });
+            }, 200);
+          },
+          settings: {
+            label: undefined,
+          },
+          settingUpdated: function(key, oldValue, newValue) {
+            switch (key) {
+            case 'message':
+              this.setMessage(newValue);
+              break;
+            case 'label':
+              if (this.__internal.buttons[0].element) {
+                this.__internal.buttons[0].element.innerHTML = newValue;
               }
-            },
-            prepare: function() {
-              this.__internal.buttons[0].element.disabled = true;
-            },
-            setup:function() {
-              return {
-                buttons:[
-                  {
-                    text: gettext("Create"), key: 13, className: "btn btn-primary fa fa-file file_manager_create file_manager_ok pg-alertify-button disabled"
-                  },
-                  {
-                    text: gettext("Cancel"), key: 27, className: "btn btn-danger fa fa-times file_manager_create_cancel pg-alertify-button"
-                  }
-                ],
-                focus: { element: 0 },
-                options: {
-                  closableByDimmer: false,
-                  maximizable: false,
-                  closable: false,
-                  movable: true
-                }
-              };
-            },
-            replace_file: function() {
-                var $yesBtn = $('.replace_file .btn_yes'),
-                     $noBtn = $('.replace_file .btn_no');
+              break;
+            default:
+              break;
+            }
+          },
+          prepare: function() {
+            this.__internal.buttons[0].element.disabled = true;
+          },
+          setup: function() {
+            return {
+              buttons: [{
+                text: gettext('Create'),
+                key: 13,
+                className: 'btn btn-primary fa fa-file file_manager_create file_manager_ok pg-alertify-button disabled',
+              },
+              {
+                text: gettext('Cancel'),
+                key: 27,
+                className: 'btn btn-danger fa fa-times file_manager_create_cancel pg-alertify-button',
+              },
+              ],
+              focus: {
+                element: 0,
+              },
+              options: {
+                closableByDimmer: false,
+                maximizable: false,
+                closable: false,
+                movable: true,
+              },
+            };
+          },
+          replace_file: function() {
+            var $yesBtn = $('.replace_file .btn_yes'),
+              $noBtn = $('.replace_file .btn_no');
+
+            $('.storage_dialog #uploader .input-path').attr('disabled', true);
+            $('.file_manager_ok').addClass('disabled');
+            $('.replace_file, .fm_dimmer').show();
+
+            $yesBtn.click(function() {
+              $('.replace_file, .fm_dimmer').hide();
+              $yesBtn.off();
+              $noBtn.off();
+              var newFile = $('.storage_dialog #uploader .input-path').val();
+
+              pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:create_file', newFile);
+              $('.file_manager_create_cancel').trigger('click');
+              $('.storage_dialog #uploader .input-path').attr('disabled', false);
+              $('.file_manager_ok').removeClass('disabled');
+            });
 
-                $('.storage_dialog #uploader .input-path').attr('disabled', true);
-                $('.file_manager_ok').addClass('disabled');
-                $('.replace_file, .fm_dimmer').show();
-
-                $yesBtn.click(function(e) {
-                  $('.replace_file, .fm_dimmer').hide();
-                  $yesBtn.off();
-                  $noBtn.off();
-                  var newFile = $('.storage_dialog #uploader .input-path').val()
-
-                  pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:create_file', newFile);
-                  $('.file_manager_create_cancel').trigger('click');
-                  $('.storage_dialog #uploader .input-path').attr('disabled', false);
-                  $('.file_manager_ok').removeClass('disabled');
-                });
-
-                $noBtn.click(function(e) {
-                  $('.replace_file, .fm_dimmer').hide();
-                  $yesBtn.off();
-                  $noBtn.off();
-                  $('.storage_dialog #uploader .input-path').attr('disabled', false);
-                  $('.file_manager_ok').removeClass('disabled');
-                });
-            },
-            is_file_exist: function() {
-              var full_path  = $('.storage_dialog #uploader .input-path').val(),
-                  path = full_path.substr(0, full_path.lastIndexOf('/') + 1),
-                  selected_item = full_path.substr(full_path.lastIndexOf('/') + 1),
+            $noBtn.click(function() {
+              $('.replace_file, .fm_dimmer').hide();
+              $yesBtn.off();
+              $noBtn.off();
+              $('.storage_dialog #uploader .input-path').attr('disabled', false);
+              $('.file_manager_ok').removeClass('disabled');
+            });
+          },
+          is_file_exist: function() {
+            var full_path = $('.storage_dialog #uploader .input-path').val(),
+              path = full_path.substr(0, full_path.lastIndexOf('/') + 1),
+              selected_item = full_path.substr(full_path.lastIndexOf('/') + 1),
+              is_exist = false;
+
+            var file_data = {
+              'path': path,
+              'name': selected_item,
+              'mode': 'is_file_exist',
+            };
+
+            $.ajax({
+              type: 'POST',
+              data: JSON.stringify(file_data),
+              url: url_for('file_manager.filemanager', {
+                'trans_id': trans_id,
+              }),
+              dataType: 'json',
+              contentType: 'application/x-download; charset=utf-8',
+              async: false,
+              success: function(resp) {
+                var data = resp.data.result;
+                if (data['Code'] === 1) {
+                  is_exist = true;
+                } else {
                   is_exist = false;
-
-              var file_data = {
+                }
+              },
+            });
+            return is_exist;
+          },
+          check_permission: function(path) {
+            var permission = false,
+              post_data = {
                 'path': path,
-                'name': selected_item,
-                'mode': 'is_file_exist'
+                'mode': 'permission',
               };
 
-              $.ajax({
-                type: 'POST',
-                data: JSON.stringify(file_data),
-                url: url_for('file_manager.filemanager', {'trans_id': trans_id}),
-                dataType: 'json',
-                contentType: "application/x-download; charset=utf-8",
-                async: false,
-                success: function(resp) {
-                  var data = resp.data.result;
-                  if(data['Code'] === 1) {
-                    is_exist = true;
-                  } else {
-                    is_exist = false;
-                  }
-                }
-              });
-              return is_exist;
-            },
-            check_permission: function(path) {
-              var permission = false,
-                  post_data = {
-                    'path': path,
-                    'mode': 'permission'
-                  };
-
-              $.ajax({
-                type: 'POST',
-                data: JSON.stringify(post_data),
-                url: url_for('file_manager.filemanager', {'trans_id': trans_id}),
-                dataType: 'json',
-                contentType: "application/json; charset=utf-8",
-                async: false,
-                success: function(resp) {
-                  var data = resp.data.result;
-                  if (data.Code === 1) {
-                    permission = true;
-                  } else {
-                    $('.file_manager_ok').addClass('disabled');
-                    alertify.error(data.Error);
-                  }
-                },
-                error: function() {
+            $.ajax({
+              type: 'POST',
+              data: JSON.stringify(post_data),
+              url: url_for('file_manager.filemanager', {
+                'trans_id': trans_id,
+              }),
+              dataType: 'json',
+              contentType: 'application/json; charset=utf-8',
+              async: false,
+              success: function(resp) {
+                var data = resp.data.result;
+                if (data.Code === 1) {
+                  permission = true;
+                } else {
                   $('.file_manager_ok').addClass('disabled');
-                  alertify.error( gettext('Error occurred while checking access permission.'));
-                }
-              });
-              return permission;
-            },
-            callback: function(closeEvent) {
-              if (closeEvent.button.text == gettext("Create")) {
-                var newFile = $('.storage_dialog #uploader .input-path').val(),
-                    file_data = {'path': $('.currentpath').val()};
-
-                if (!this.check_permission(newFile)) {
-                  closeEvent.cancel = true;
-                  return;
+                  Alertify.error(data.Error);
                 }
+              },
+              error: function() {
+                $('.file_manager_ok').addClass('disabled');
+                Alertify.error(gettext('Error occurred while checking access permission.'));
+              },
+            });
+            return permission;
+          },
+          callback: function(closeEvent) {
+            if (closeEvent.button.text == gettext('Create')) {
+              var newFile = $('.storage_dialog #uploader .input-path').val(),
+                file_data = {
+                  'path': $('.currentpath').val(),
+                },
+                innerbody;
 
-                if(!_.isUndefined(newFile) && newFile !== '' && this.is_file_exist()) {
-                  this.replace_file();
-                  closeEvent.cancel = true;
-                } else {
-                  pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:create_file', newFile);
-                  var innerbody = $(this.elements.body).find('.storage_content');
-                  $(innerbody).find('*').off();
-                  innerbody.remove();
-                  removeTransId(trans_id);
-                }
+              if (!this.check_permission(newFile)) {
+                closeEvent.cancel = true;
+                return;
+              }
 
-                set_last_traversed_dir(file_data, trans_id);
-              } else if (closeEvent.button.text == gettext("Cancel")) {
-                var innerbody = $(this.elements.body).find('.storage_content')
+              if (!_.isUndefined(newFile) && newFile !== '' && this.is_file_exist()) {
+                this.replace_file();
+                closeEvent.cancel = true;
+              } else {
+                pgAdmin.Browser.Events.trigger('pgadmin-storage:finish_btn:create_file', newFile);
+                innerbody = $(this.elements.body).find('.storage_content');
                 $(innerbody).find('*').off();
                 innerbody.remove();
                 removeTransId(trans_id);
-                pgAdmin.Browser.Events.trigger('pgadmin-storage:cancel_btn:create_file');
-              }
-            },
-            build: function() {
-              this.elements.content.appendChild($container.get(0));
-            },
-            hooks: {
-              onshow: function() {
-                $(this.elements.body).addClass('pgadmin-storage-body');
               }
+
+              set_last_traversed_dir(file_data, trans_id);
+            } else if (closeEvent.button.text == gettext('Cancel')) {
+              innerbody = $(this.elements.body).find('.storage_content');
+              $(innerbody).find('*').off();
+              innerbody.remove();
+              removeTransId(trans_id);
+              pgAdmin.Browser.Events.trigger('pgadmin-storage:cancel_btn:create_file');
             }
-          };
-        });
-      },
-      show_storage_dlg: function(params) {
-        alertify.storageManagerDlg(params).resizeTo('60%', '80%');
-      },
-      show_file_selection: function(params) {
-        alertify.fileSelectionDlg(params).resizeTo('60%', '80%');
-      },
-      show_folder_selection: function(params) {
-        alertify.folderSelectionDlg(params).resizeTo('60%', '80%');
-      },
-      show_create_dlg: function(params) {
-        alertify.createModeDlg(params).resizeTo('60%', '80%');
-      },
-      // call dialogs subject to dialog_type param
-      show_dialog: function(params) {
-        if(params.dialog_type == 'select_file') {
-          this.show_file_selection(params);
-        }
-        else if (params.dialog_type == 'select_folder') {
-          this.show_folder_selection(params);
-        }
-        else if (params.dialog_type == 'create_file') {
-          this.show_create_dlg(params);
-        }
-        else {
-          this.show_storage_dlg(params);
-        }
+          },
+          build: function() {
+            this.elements.content.appendChild($container.get(0));
+          },
+          hooks: {
+            onshow: function() {
+              $(this.elements.body).addClass('pgadmin-storage-body');
+            },
+          },
+        };
+      });
+    },
+    show_storage_dlg: function(params) {
+      Alertify.storageManagerDlg(params).resizeTo('60%', '80%');
+    },
+    show_file_selection: function(params) {
+      Alertify.fileSelectionDlg(params).resizeTo('60%', '80%');
+    },
+    show_folder_selection: function(params) {
+      Alertify.folderSelectionDlg(params).resizeTo('60%', '80%');
+    },
+    show_create_dlg: function(params) {
+      Alertify.createModeDlg(params).resizeTo('60%', '80%');
+    },
+    // Call dialogs subject to dialog_type param
+    show_dialog: function(params) {
+      if (params.dialog_type == 'select_file') {
+        this.show_file_selection(params);
+      } else if (params.dialog_type == 'select_folder') {
+        this.show_folder_selection(params);
+      } else if (params.dialog_type == 'create_file') {
+        this.show_create_dlg(params);
+      } else {
+        this.show_storage_dlg(params);
       }
-    };
+    },
+  };
 
-    return pgAdmin.FileManager;
-  });
+  return pgAdmin.FileManager;
+});
diff --git a/web/pgadmin/misc/file_manager/static/js/utility.js b/web/pgadmin/misc/file_manager/static/js/utility.js
index d433b8e2..74ae4e40 100755
--- a/web/pgadmin/misc/file_manager/static/js/utility.js
+++ b/web/pgadmin/misc/file_manager/static/js/utility.js
@@ -10,1341 +10,1280 @@
  */
 import loading_icon from 'acitree/image/load-root.gif';
 
-define(['jquery', 'underscore', 'underscore.string',
-  'pgadmin.alertifyjs', 'sources/gettext',
-  'sources/url_for', 'dropzone'
-  ],
-function($, _, S, alertify, gettext, url_for, Dropzone) {
-
-/*---------------------------------------------------------
-  Define functions used for various operations
----------------------------------------------------------*/
-
-// return file extension
-var getFileExtension = function(name) {
-  var found = name.lastIndexOf('.') + 1;
-  return (found > 0 ? name.substr(found) : "");
-};
-
-// returns filename without extension
-var getFileName = function(name) {
-  var fm_filename = name;
-  if (fm_filename.length > 15 ) {
-    fm_filename = name.substr(0, 10) +'...';
-  }
-  return fm_filename;
-};
-
-/* Common function to load:
- * en.js language file
- * file_manager_config.js config file
- * return transaction id
- */
-var loadData = function(url) {
-  return $.ajax({
-    async: false,
-    cache: false,
-    url: url,
-    dataType: 'jsonp',
-    contentType: "application/json; charset=utf-8"
-  });
-};
-
-// Set enable/disable state of list and grid view
-var setViewButtonsFor = function(viewMode) {
-  if (viewMode == 'grid') {
+define([
+  'jquery', 'underscore', 'underscore.string', 'pgadmin.alertifyjs',
+  'sources/gettext', 'sources/url_for', 'dropzone', 'sources/pgadmin',
+], function($, _, S, Alertify, gettext, url_for, Dropzone, pgAdmin) {
+
+  /*---------------------------------------------------------
+    Define functions used for various operations
+  ---------------------------------------------------------*/
+
+  // Return file extension
+  var getFileExtension = function(name) {
+    var found = name.lastIndexOf('.') + 1;
+    return (found > 0 ? name.substr(found) : '');
+  };
+
+  /* Common function to load:
+   * en.js language file
+   * file_manager_config.js config file
+   * return transaction id
+   */
+  var loadData = function(url) {
+    return $.ajax({
+      async: false,
+      cache: false,
+      url: url,
+      dataType: 'jsonp',
+      contentType: 'application/json; charset=utf-8',
+    });
+  };
+
+  // Set enable/disable state of list and grid view
+  var setViewButtonsFor = function(viewMode) {
+    if (viewMode == 'grid') {
       $('.grid').addClass('ON');
       $('.list').removeClass('ON');
-  } else {
+    } else {
       $('.list').addClass('ON');
       $('.grid').removeClass('ON');
-  }
-};
-
-var save_file_dialog_view = function(view, trans_id) {
-  return $.ajax({
-    url: url_for('file_manager.save_file_dialog_view', {'trans_id': trans_id}),
-    type: 'POST',
-    async: true,
-    data: JSON.stringify({'view':view}),
-    contentType: 'application/json'
-  });
-};
-
-var save_show_hidden_file_option = function(option, trans_id) {
-  return $.ajax({
-    url: url_for('file_manager.save_show_hidden_file_option', {'trans_id': trans_id}),
-    type: 'PUT',
-    async: true,
-    data: JSON.stringify({'show_hidden': option}),
-    contentType: 'application/json'
-  });
-};
-
-
-/*
- * preg_replace
- */
-var preg_replace = function(array_pattern, array_pattern_replace, str)  {
-  var i = 0, reg_exp, val_to_replace,
-      new_str = String(str);
-
-  while (i < array_pattern.length) {
-    reg_exp= RegExp(array_pattern[i], "g");
-    val_to_replace = array_pattern_replace[i];
-
-    new_str = new_str.replace (reg_exp, val_to_replace);
-    i += 1;
-  }
-
-  return new_str;
-};
-
- //nameFormat (), separate filename from extension
-var nameFormat = function(input) {
-  var filename = '';
-  if (input.lastIndexOf('.') != -1) {
-    filename  = input.substr(0, input.lastIndexOf('.'));
-    filename += '.' + input.split('.').pop();
-  } else {
-    filename = input;
-  }
-  return filename;
-};
-
-//Converts bytes to kb, mb, or gb as needed for display.
-var formatBytes = function(bytes) {
-  var n = parseFloat(bytes),
-      d = parseFloat(1024),
-      c = 0,
-      lg = pgAdmin.FileUtils.lg,
-      u = [lg.bytes,lg.kb,lg.mb,lg.gb];
+    }
+  };
+
+  var save_file_dialog_view = function(view, trans_id) {
+    return $.ajax({
+      url: url_for('file_manager.save_file_dialog_view', {
+        'trans_id': trans_id,
+      }),
+      type: 'POST',
+      async: true,
+      data: JSON.stringify({
+        'view': view,
+      }),
+      contentType: 'application/json',
+    });
+  };
 
-  while(true) {
-    if (n < d) {
-      return (Math.round(n * 100) / 100) + u[c];
+  var save_show_hidden_file_option = function(option, trans_id) {
+    return $.ajax({
+      url: url_for('file_manager.save_show_hidden_file_option', {
+        'trans_id': trans_id,
+      }),
+      type: 'PUT',
+      async: true,
+      data: JSON.stringify({
+        'show_hidden': option,
+      }),
+      contentType: 'application/json',
+    });
+  };
+
+  // nameFormat (), separate filename from extension
+  var nameFormat = function(input) {
+    var filename = '';
+    if (input.lastIndexOf('.') != -1) {
+      filename = input.substr(0, input.lastIndexOf('.'));
+      filename += '.' + input.split('.').pop();
+    } else {
+      filename = input;
     }
-    n /= d;
-    c += 1;
-  }
-};
-
-// Freeze toolbar buttons and display errors
-var handleError = function(errMsg) {
-  $('.storage_dialog .newfile').attr("disabled", "disabled");
-  $('.storage_dialog .upload').attr("disabled", "disabled");
-  $('.storage_dialog .create').attr("disabled", "disabled");
-};
-
-/*
- * Test if Data structure has the 'cap' capability
- * 'cap' is one of 'select', 'rename', 'delete', 'download'
- */
-var has_capability = function(data, cap) {
-  if (typeof(data.Capabilities) == "undefined") {
-    return true;
-  } else {
-    return ($.inArray(cap, data.Capabilities) > -1);
-  }
-};
-
-// return filename extension
-var getExtension = function(filename) {
-  if (filename.split('.').length == 1) {
-    return "";
-  }
-  return filename.split('.').pop();
-};
-
-// return filename without extension
-var getFilename = function(filename) {
-  if (filename.lastIndexOf('.') != -1) {
-    return filename.substring(0, filename.lastIndexOf('.'));
-  } else {
     return filename;
-  }
-};
+  };
 
-/*
- * Binds specific actions to the toolbar based on capability.
- * and show/hide buttons
- */
-var bindToolbar = function(data) {
+  /*
+   * Test if Data structure has the 'cap' capability
+   * 'cap' is one of 'select', 'rename', 'delete', 'download'
+   */
+  var has_capability = function(data, cap) {
+    if (typeof(data.Capabilities) == 'undefined') {
+      return true;
+    } else {
+      return ($.inArray(cap, data.Capabilities) > -1);
+    }
+  };
 
-  // hide/show rename, upload and create button
-  if(_.has(data, 'Capabilities')) {
-    _.each(data.Capabilities, function(cap) {
-      var target_btn = 'button.' + cap,
-          $target_el = $('.file_manager').find(target_btn);
-      if (!has_capability(data, cap) || pgAdmin.FileUtils.hideButtons()) {
-        $target_el.hide();
-      } else {
-        $target_el.show();
-      }
-    });
-  }
-
-  if (!has_capability(data, 'delete') || pgAdmin.FileUtils.hideButtons()) {
-    $('.file_manager').find('button.delete').hide();
-  } else {
-    $('.file_manager').find('button.delete').click(function() {
-      // hide dimmer
-      $('.fileinfo .delete_item, .fm_dimmer').show();
-    });
+  // return filename extension
+  var getExtension = function(filename) {
+    if (filename.split('.').length == 1) {
+      return '';
+    }
+    return filename.split('.').pop();
+  };
+
+  /*
+   * Binds specific actions to the toolbar based on capability.
+   * and show/hide buttons
+   */
+  var bindToolbar = function(data) {
 
-    // take action based on pressed button yes or no
-    $('.fileinfo .delete_item button.btn_yes').unbind().on('click', function() {
-      var path;
-      if ($('.fileinfo').data('view') == 'grid') {
-        path = decodeURI($('.fileinfo').find('#contents li.selected .clip span').attr('data-alt'));
-        if (path.lastIndexOf('/') == path.length - 1) {
-          data.Path = path;
-          deleteItem(data);
+    // hide/show rename, upload and create button
+    if (_.has(data, 'Capabilities')) {
+      _.each(data.Capabilities, function(cap) {
+        var target_btn = 'button.' + cap,
+          $target_el = $('.file_manager').find(target_btn);
+        if (!has_capability(data, cap) || pgAdmin.FileUtils.hideButtons()) {
+          $target_el.hide();
         } else {
-          deleteItem(data);
+          $target_el.show();
         }
-      } else {
-        path = $('.fileinfo').find('table#contents tbody tr.selected td:first-child').attr('title');
-        if (path.lastIndexOf('/') == path.length - 1) {
-          data.Path = path;
-          deleteItem(data);
+      });
+    }
+
+    if (!has_capability(data, 'delete') || pgAdmin.FileUtils.hideButtons()) {
+      $('.file_manager').find('button.delete').hide();
+    } else {
+      $('.file_manager').find('button.delete').click(function() {
+        // hide dimmer
+        $('.fileinfo .delete_item, .fm_dimmer').show();
+      });
+
+      // take action based on pressed button yes or no
+      $('.fileinfo .delete_item button.btn_yes').unbind().on('click', function() {
+        var path;
+        if ($('.fileinfo').data('view') == 'grid') {
+          path = decodeURI($('.fileinfo').find('#contents li.selected .clip span').attr('data-alt'));
+          if (path.lastIndexOf('/') == path.length - 1) {
+            data.Path = path;
+            deleteItem(data);
+          } else {
+            deleteItem(data);
+          }
         } else {
-          deleteItem(data);
+          path = $('.fileinfo').find('table#contents tbody tr.selected td:first-child').attr('title');
+          if (path.lastIndexOf('/') == path.length - 1) {
+            data.Path = path;
+            deleteItem(data);
+          } else {
+            deleteItem(data);
+          }
         }
-      }
-      // hide dimmer
-      $('.fileinfo .fm_dimmer').hide();
-    });
+        // hide dimmer
+        $('.fileinfo .fm_dimmer').hide();
+      });
 
-  }
-
-  // Download file on download button click
-  if (!has_capability(data, 'download') || pgAdmin.FileUtils.hideButtons()) {
-    $('.file_manager').find('button.download').hide();
-  } else {
-    $('.file_manager').find('button.download').unbind().click(function() {
-      var path;
-      if ($('.fileinfo').data('view') == 'grid') {
-        path = $('.fileinfo li.selected').find('.clip span').attr('data-alt');
-        window.open(pgAdmin.FileUtils.fileConnector + '?mode=download&path=' + path, '_blank');
-      } else {
-        path = $('.fileinfo').find('table#contents tbody tr.selected td:first-child').attr('title');
-        window.open(pgAdmin.FileUtils.fileConnector + '?mode=download&path=' + path, '_blank');
-      }
-    });
-  }
-};
-
-// enable/disable button when files/folder are loaded
-var enable_disable_btn = function() {
-  if ($('.fileinfo').data('view') == 'grid') {
-    var $grid_file = $('.file_manager').find('#contents li.selected');
-    $grid_file.removeClass('selected');
-    $('.file_manager').find('button.delete').prop('disabled', true);
-    $('.file_manager').find('button.download').prop('disabled', true);
-    $('.file_manager').find('button.rename').prop('disabled', true);
-    if ($grid_file.length > 0) {
-      $('.file_manager_ok').addClass('disabled');
-      $('.file_manager_ok').attr('disabled', true);
     }
-  } else {
-    var $list_file = $('.fileinfo').find('table#contents tbody tr.selected');
-    $list_file.removeClass('selected');
-    $('.file_manager').find('button.delete').prop('disabled', true);
-    $('.file_manager').find('button.download').prop('disabled', true);
-    $('.file_manager').find('button.rename').prop('disabled', true);
-    if ($list_file.length > 0) {
-      $('.file_manager_ok').addClass('disabled');
-      $('.file_manager_ok').attr('disabled', true);
+
+    // Download file on download button click
+    if (!has_capability(data, 'download') || pgAdmin.FileUtils.hideButtons()) {
+      $('.file_manager').find('button.download').hide();
+    } else {
+      $('.file_manager').find('button.download').unbind().click(function() {
+        var path;
+        if ($('.fileinfo').data('view') == 'grid') {
+          path = $('.fileinfo li.selected').find('.clip span').attr('data-alt');
+          window.open(pgAdmin.FileUtils.fileConnector + '?_=' + Date.now() + 'mode=download&path=' + path, '_blank');
+        } else {
+          path = $('.fileinfo').find('table#contents tbody tr.selected td:first-child').attr('title');
+          window.open(pgAdmin.FileUtils.fileConnector + '?_=' + Date.now() + 'mode=download&path=' + path, '_blank');
+        }
+      });
     }
-  }
-
-  $('.delete_item').hide();
-  // clear address bar
-  $('.file_manager #uploader .input-path').show();
-  $('.file_manager #uploader .show_selected_file').remove();
-};
-
-/*
- * Rename the current item and returns the new name.
- * by double clicking or by clicking the "Rename" button in
- * table(list) views.
- */
-var renameItem = function(data) {
-  var orig_name = getFilename(data.Filename),
-      finalName = '',
-      lg = pgAdmin.FileUtils.lg;
+  };
 
-  var getNewName = function(rname) {
-    if (rname !== '') {
-      var givenName = nameFormat(rname),
-          suffix = getExtension(data.Filename);
-      if (suffix.length > 0) {
-        givenName = givenName + '.' + suffix;
+  // enable/disable button when files/folder are loaded
+  var enable_disable_btn = function() {
+    if ($('.fileinfo').data('view') == 'grid') {
+      var $grid_file = $('.file_manager').find('#contents li.selected');
+      $grid_file.removeClass('selected');
+      $('.file_manager').find('button.delete').prop('disabled', true);
+      $('.file_manager').find('button.download').prop('disabled', true);
+      $('.file_manager').find('button.rename').prop('disabled', true);
+      if ($grid_file.length > 0) {
+        $('.file_manager_ok').addClass('disabled');
+        $('.file_manager_ok').attr('disabled', true);
       }
+    } else {
+      var $list_file = $('.fileinfo').find('table#contents tbody tr.selected');
+      $list_file.removeClass('selected');
+      $('.file_manager').find('button.delete').prop('disabled', true);
+      $('.file_manager').find('button.download').prop('disabled', true);
+      $('.file_manager').find('button.rename').prop('disabled', true);
+      if ($list_file.length > 0) {
+        $('.file_manager_ok').addClass('disabled');
+        $('.file_manager_ok').attr('disabled', true);
+      }
+    }
 
-      var oldPath = data.Path,
-          post_data = {
-            "mode": "rename",
-            "old": data.Path,
-            "new": givenName
-          };
+    $('.delete_item').hide();
+    // clear address bar
+    $('.file_manager #uploader .input-path').show();
+    $('.file_manager #uploader .show_selected_file').remove();
+  };
+
+  /*
+   * Rename the current item and returns the new name.
+   * by double clicking or by clicking the "Rename" button in
+   * table(list) views.
+   */
+  var renameItem = function(data) {
+    var finalName = '',
+      lg = pgAdmin.FileUtils.lg,
+      getNewName = function(rname) {
+        if (rname !== '') {
+          var givenName = nameFormat(rname),
+            suffix = getExtension(data.Filename);
+          if (suffix.length > 0) {
+            givenName = givenName + '.' + suffix;
+          }
+
+          var oldPath = data.Path,
+            post_data = {
+              'mode': 'rename',
+              'old': data.Path,
+              'new': givenName,
+            };
+
+          $.ajax({
+            type: 'POST',
+            data: JSON.stringify(post_data),
+            url: pgAdmin.FileUtils.fileConnector,
+            dataType: 'json',
+            contentType: 'application/json; charset=utf-8',
+            async: false,
+            success: function(resp) {
+              var result = resp.data.result;
+              if (result.Code === 1) {
+                var newPath = result['New Path'],
+                  newName = result['New Name'],
+                  title = $('#preview h1').attr('title');
+
+                if (typeof title != 'undefined' && title == oldPath) {
+                  $('#preview h1').text(newName);
+                }
+
+                if ($('.fileinfo').data('view') == 'grid') {
+                  $('.fileinfo span[data-alt="' + oldPath + '"]').parent().next('p span').text(newName);
+                  $('.fileinfo span[data-alt="' + oldPath + '"]').attr('data-alt', newPath);
+                } else {
+                  $('.fileinfo td[title="' + oldPath + '"]').text(newName);
+                  $('.fileinfo td[title="' + oldPath + '"]').attr('title', newPath);
+                }
+                $('#preview h1').html(newName);
+
+                // actualized data for binding
+                data.Path = newPath;
+                data.Filename = newName;
+
+                // UnBind toolbar functions.
+                $('.fileinfo').find('button.rename, button.delete, button.download').unbind();
+
+                Alertify.success(lg.successful_rename);
+              } else {
+                Alertify.error(result.Error);
+              }
+
+              finalName = result['New Name'];
+            },
+          });
+        }
+      };
+
+    getNewName(data.NewFilename);
+    return finalName;
+  };
+
+  /*
+   * delete the folder or files by clicking the "Delete" button
+   * in table(list) view
+   */
+  var deleteItem = function(data) {
+    var isDeleted = false,
+      lg = pgAdmin.FileUtils.lg;
+
+    var doDelete = function(data) {
+      var post_data = {
+        'mode': 'delete',
+        'path': data.Path,
+      };
 
       $.ajax({
         type: 'POST',
         data: JSON.stringify(post_data),
         url: pgAdmin.FileUtils.fileConnector,
         dataType: 'json',
-        contentType: "application/json; charset=utf-8",
+        contentType: 'application/json; charset=utf-8',
         async: false,
         success: function(resp) {
           var result = resp.data.result;
           if (result.Code === 1) {
-            var newPath = result['New Path'],
-                newName = result['New Name'],
-                title = $("#preview h1").attr("title");
-
-            if (typeof title !="undefined" && title == oldPath) {
-              $('#preview h1').text(newName);
+            isDeleted = true;
+            if (isDeleted) {
+              Alertify.success(lg.successful_delete);
+              var rootpath = result.Path.substring(0, result.Path.length - 1); // removing the last slash
+              rootpath = rootpath.substr(0, rootpath.lastIndexOf('/') + 1);
+              getFolderInfo(rootpath);
             }
-
-            if ($('.fileinfo').data('view') == 'grid') {
-              $('.fileinfo span[data-alt="' + oldPath + '"]').parent().next('p span').text(newName);
-              $('.fileinfo span[data-alt="' + oldPath + '"]').attr('data-alt', newPath);
-            } else {
-              $('.fileinfo td[title="' + oldPath + '"]').text(newName);
-              $('.fileinfo td[title="' + oldPath + '"]').attr('title', newPath);
-            }
-            $("#preview h1").html(newName);
-
-            // actualized data for binding
-            data.Path=newPath;
-            data.Filename=newName;
-
-            // UnBind toolbar functions.
-            $('.fileinfo').find('button.rename, button.delete, button.download').unbind();
-
-            alertify.success(lg.successful_rename);
           } else {
-            alertify.error(result.Error);
+            isDeleted = false;
+            Alertify.error(result.Error);
           }
-
-          finalName = result['New Name'];
-        }
+        },
       });
-    }
-  };
-
-  getNewName(data.NewFilename);
-  return finalName;
-};
+      return isDeleted;
+    };
 
-/*
- * delete the folder or files by clicking the "Delete" button
- * in table(list) view
- */
-var deleteItem = function(data) {
-  var isDeleted = false,
-      lg = pgAdmin.FileUtils.lg,
-      msg = lg.confirmation_delete;
+    doDelete(data);
+    return isDeleted;
+  };
 
-  var doDelete = function(data) {
-    var parent = data.Path.split('/').reverse().slice(1).reverse().join('/') + '/';
-    var post_data = {
-          "mode": "delete",
-          "path": data.Path
-        };
+  /*---------------------------------------------------------
+    Functions to Retrieve File and Folder Details
+  ---------------------------------------------------------*/
+  /*
+   * Retrieves information about the specified file as a JSON
+   * object and uses that data to populate a template for
+   * list views. Binds the toolbar for that file/folder to
+   * enable specific actions. Called whenever an item is
+   * clicked in list views.
+   */
+  var getFileInfo = function(file) {
+    // Update location for status, upload, & new folder functions.
+    pgAdmin.FileUtils.setUploader(file);
+    var capabilities = pgAdmin.FileUtils.data.capabilities,
+      is_file_valid = false,
+      post_data = {
+        'path': file,
+        'mode': 'getinfo',
+      };
 
+    // Retrieve the data & populate the template.
     $.ajax({
       type: 'POST',
       data: JSON.stringify(post_data),
       url: pgAdmin.FileUtils.fileConnector,
       dataType: 'json',
-      contentType: "application/json; charset=utf-8",
+      contentType: 'application/json; charset=utf-8',
       async: false,
       success: function(resp) {
-        var result = resp.data.result;
-        if (result.Code === 1) {
-          isDeleted = true;
-          if (isDeleted) {
-            alertify.success(lg.successful_delete);
-            var rootpath = result.Path.substring(0, result.Path.length-1); // removing the last slash
-                rootpath = rootpath.substr(0, rootpath.lastIndexOf('/') + 1);
-            getFolderInfo(rootpath);
+        var data = resp.data.result;
+        if (data.Code === 1) {
+          $('.file_manager_ok').removeClass('disabled');
+          $('.file_manager_ok').attr('disabled', false);
+          data.Capabilities = capabilities;
+          bindToolbar(data);
+          if (data.FileType == 'Directory') {
+            // Enable/Disable level up button
+            enab_dis_level_up();
+            $('.file_manager_ok').addClass('disabled');
+            $('.file_manager_ok').attr('disabled', true);
+            $('.file_manager button.delete, .file_manager button.rename').attr('disabled', 'disabled');
+            $('.file_manager button.download').attr('disabled', 'disabled');
+
+            if (file.charAt(file.length - 1) != '/' && file.charAt(file.length - 1) != '\\') {
+              file += '/';
+            }
+            getFolderInfo(file);
+          } else {
+            is_file_valid = true;
           }
         } else {
-          isDeleted = false;
-          alertify.error(result.Error);
+          $('.file_manager_ok').addClass('disabled');
+          $('.file_manager_ok').attr('disabled', true);
+          Alertify.error(data.Error);
         }
-      }
+      },
     });
-    return isDeleted;
+    return is_file_valid;
   };
 
-  doDelete(data);
-  return isDeleted;
-};
-
-/*---------------------------------------------------------
-  Functions to Retrieve File and Folder Details
----------------------------------------------------------*/
-/*
- * Retrieves information about the specified file as a JSON
- * object and uses that data to populate a template for
- * list views. Binds the toolbar for that file/folder to
- * enable specific actions. Called whenever an item is
- * clicked in list views.
- */
-var getFileInfo = function(file) {
-  // Update location for status, upload, & new folder functions.
-  pgAdmin.FileUtils.setUploader(file);
-  var capabilities = pgAdmin.FileUtils.data.capabilities;
-
-  // Retrieve the data & populate the template.
-  var d = new Date(), // to prevent IE cache issues
-    is_file_valid =  false;
-  var post_data = {
-    'path': file,
-    'mode': 'getinfo'
-  };
-  var lg = pgAdmin.FileUtils.lg;
-
-  $.ajax({
-    type: 'POST',
-    data: JSON.stringify(post_data),
-    url: pgAdmin.FileUtils.fileConnector,
-    dataType: 'json',
-    contentType: "application/json; charset=utf-8",
-    async: false,
-    success: function(resp) {
-      var data = resp.data.result;
-      if (data.Code === 1) {
-        $('.file_manager_ok').removeClass('disabled');
-        $('.file_manager_ok').attr('disabled', false);
-        var properties = '';
-        if (
-          data.Properties.Size || parseInt(data.Properties.Size)==0
-        ) {
-          properties += '<dt>' + lg.size + '</dt><dd>' + formatBytes(
-            data.Properties.Size
-          ) + '</dd>';
-        }
-        data.Capabilities = capabilities;
-        bindToolbar(data);
-        if (data.FileType == 'Directory') {
-          // Enable/Disable level up button
-          enab_dis_level_up();
-          $('.file_manager_ok').addClass('disabled');
-          $('.file_manager_ok').attr('disabled', true);
-          $('.file_manager button.delete, .file_manager button.rename').attr('disabled', 'disabled');
-          $('.file_manager button.download').attr('disabled', 'disabled');
+  var checkPermission = function(path) {
+    var permission = false,
+      post_data = {
+        'path': path,
+        'mode': 'permission',
+      };
 
-          if (file.charAt(file.length - 1) != '/' && file.charAt(file.length - 1) != '\\') {
-            file += '/';
-          }
-          getFolderInfo(file);
+    $.ajax({
+      type: 'POST',
+      data: JSON.stringify(post_data),
+      url: pgAdmin.FileUtils.fileConnector,
+      dataType: 'json',
+      contentType: 'application/json; charset=utf-8',
+      async: false,
+      success: function(resp) {
+        var data = resp.data.result;
+        if (data.Code === 1) {
+          permission = true;
         } else {
-          is_file_valid = true;
+          $('.file_manager_ok').addClass('disabled');
+          $('.file_manager_ok').attr('disabled', true);
+          Alertify.error(data.Error);
         }
-      } else {
+      },
+      error: function() {
         $('.file_manager_ok').addClass('disabled');
         $('.file_manager_ok').attr('disabled', true);
-        alertify.error(data.Error);
-      }
-    }
-  });
-  return is_file_valid;
-};
+        Alertify.error(
+          gettext('Error occurred while checking access permission.')
+        );
+      },
+    });
+    return permission;
+  };
 
-var checkPermission = function(path) {
-  var permission = false,
-      post_data = {
-        'path': path,
-        'mode': 'permission'
-      };
 
-  $.ajax({
-    type: 'POST',
-    data: JSON.stringify(post_data),
-    url: pgAdmin.FileUtils.fileConnector,
-    dataType: 'json',
-    contentType: "application/json; charset=utf-8",
-    async: false,
-    success: function(resp) {
-      var data = resp.data.result;
-      if (data.Code === 1) {
-        permission = true;
-      } else {
-        $('.file_manager_ok').addClass('disabled');
-        $('.file_manager_ok').attr('disabled', true);
-        alertify.error(data.Error);
-      }
-    },
-    error: function() {
-      $('.file_manager_ok').addClass('disabled');
-      $('.file_manager_ok').attr('disabled', true);
-      alertify.error( gettext('Error occurred while checking access permission.'));
-    }
-  });
-  return permission;
-};
 
+  /*
+   * Retrieves data for all items within the given folder and
+   * creates a list view.
+   */
+  var getFolderInfo = function(path, file_type) {
+    $('.storage_dialog #uploader .input-path').prop('disabled', true);
+    if (!file_type) {
+      file_type = '';
+    }
+    var capabilities = pgAdmin.FileUtils.data.Capabilities;
+    // Update location for status, upload, & new folder functions.
+    pgAdmin.FileUtils.setUploader(path);
 
+    // set default selected file type
+    if (file_type === '') {
+      file_type = $('.change_file_types select').val();
+    }
 
-/*
- * Retrieves data for all items within the given folder and
- * creates a list view.
- */
-var getFolderInfo = function(path, file_type) {
-  $('.storage_dialog #uploader .input-path').prop('disabled', true);
-  if (!file_type) {
-    file_type = '';
-  }
-  var capabilities = pgAdmin.FileUtils.data.Capabilities;
-  // Update location for status, upload, & new folder functions.
-  pgAdmin.FileUtils.setUploader(path);
-
-  // set default selected file type
-  if (file_type === '') {
-    file_type = $('.change_file_types select').val();
-  }
-
-  // navigate to directory or path when clicked on breadcrumbs
-  $('.file_manager a.breadcrumbs').unbind().on('click', function() {
-    var curr_path = $(this).attr('data-path'),
+    // navigate to directory or path when clicked on breadcrumbs
+    $('.file_manager a.breadcrumbs').unbind().on('click', function() {
+      var curr_path = $(this).attr('data-path'),
         current_dir = $(this).html(),
         move_to = curr_path.substring(
           0, curr_path.lastIndexOf(current_dir)
         ) + current_dir;
 
-    getFolderInfo(move_to);
-    enab_dis_level_up();
-  });
-
-   // hide select file if we are listing drives in windows.
-   if (pgAdmin.FileUtils.hideButtons()) {
-     $(".allowed_file_types .change_file_types").hide();
-   } else {
-     $(".allowed_file_types .change_file_types").show();
-   }
-
-  var loading_icon_url = url_for(
-    'static', {'filename': 'js/generated/' + loading_icon }
-  );
-
-  // Display an activity indicator.
-  $('.fileinfo').find('span.activity').html(
-    '<img src="' + loading_icon_url + '" alt="' + gettext("Loading...") + '"/>'
-  );
-
-  var post_data = {
-    'path': path,
-    'mode': 'getfolder',
-    'file_type': file_type || "*",
-    'show_hidden': $('#show_hidden').prop('checked')
-  };
+      getFolderInfo(move_to);
+      enab_dis_level_up();
+    });
 
-  var lg = pgAdmin.FileUtils.lg;
-  $.ajax({
-    type: 'POST',
-    data: JSON.stringify(post_data),
-    url: pgAdmin.FileUtils.fileConnector,
-    dataType: 'json',
-    contentType: "application/json; charset=utf-8",
-    async: false,
-    success: function(resp) {
-      $('.storage_dialog #uploader .input-path').prop('disabled', false);
-      var result = '',
-          data = resp.data.result;
+    // hide select file if we are listing drives in windows.
+    if (pgAdmin.FileUtils.hideButtons()) {
+      $('.allowed_file_types .change_file_types').hide();
+    } else {
+      $('.allowed_file_types .change_file_types').show();
+    }
 
-      // hide activity indicator
-      $('.fileinfo').find('span.activity').hide();
-      if (data.Code === 0) {
-        alertify.error(data.Error);
-        return;
+    var loading_icon_url = url_for(
+      'static', {
+        'filename': 'js/generated/' + loading_icon,
       }
-      // generate HTML for files/folder and render into container
-      if (!_.isEmpty(data)) {
-        if ($('.fileinfo').data('view') == 'grid') {
-          result += '<ul id="contents" class="grid">';
-          Object.keys(data).sort(function keyOrder(x, y) {
+    );
+
+    // Display an activity indicator.
+    $('.fileinfo').find('span.activity').html(
+      '<img src="' + loading_icon_url + '" alt="' + gettext('Loading...') + '/>'
+    );
+
+    var post_data = {
+      'path': path,
+      'mode': 'getfolder',
+      'file_type': file_type || '*',
+      'show_hidden': $('#show_hidden').prop('checked'),
+    };
+
+    var lg = pgAdmin.FileUtils.lg;
+    $.ajax({
+      type: 'POST',
+      data: JSON.stringify(post_data),
+      url: pgAdmin.FileUtils.fileConnector,
+      dataType: 'json',
+      contentType: 'application/json; charset=utf-8',
+      async: false,
+      success: function(resp) {
+        $('.storage_dialog #uploader .input-path').prop('disabled', false);
+        var result = '',
+          data = resp.data.result;
+
+        // hide activity indicator
+        $('.fileinfo').find('span.activity').hide();
+        if (data.Code === 0) {
+          Alertify.error(data.Error);
+          return;
+        }
+
+        var $this, orig_value, newvalue;
+
+        // generate HTML for files/folder and render into container
+        if (!_.isEmpty(data)) {
+          if ($('.fileinfo').data('view') == 'grid') {
+            result += '<ul id="contents" class="grid">';
+            Object.keys(data).sort(function keyOrder(x, y) {
               return pgAdmin.natural_sort(x.toLowerCase(), y.toLowerCase());
-            }).forEach(function (key) {
-            var props = (data[key]).Properties,
-                cap_classes = "";
+            }).forEach(function(key) {
+              var props = (data[key]).Properties,
+                cap_classes = '';
 
-            Object.keys(capabilities).forEach(function (cap) {
-              if (has_capability(data[key], capabilities[cap])) {
-                cap_classes += "cap_" + capabilities[cap];
-              }
-            });
+              Object.keys(capabilities).forEach(function(cap) {
+                if (has_capability(data[key], capabilities[cap])) {
+                  cap_classes += 'cap_' + capabilities[cap];
+                }
+              });
 
-            (data[key]).Capabilities = capabilities;
-            bindToolbar(data[key]);
+              (data[key]).Capabilities = capabilities;
+              bindToolbar(data[key]);
 
-            var class_type;
-            if ((data[key]).file_type == 'dir') {
-              class_type = 'fa fa-folder-open fm_folder';
-            } else if ((data[key]).file_type == 'drive') {
-              class_type = 'fa fa-hdd-o fm_drive';
-            } else {
-              class_type = 'fa fa-file-text fm_file';
-            }
+              var class_type;
+              if ((data[key]).file_type == 'dir') {
+                class_type = 'fa fa-folder-open fm_folder';
+              } else if ((data[key]).file_type == 'drive') {
+                class_type = 'fa fa-hdd-o fm_drive';
+              } else {
+                class_type = 'fa fa-file-text fm_file';
+              }
 
-            var fm_filename = (data[key]).Filename;
-            if (fm_filename.length > 15 ) {
-              fm_filename = (data[key]).Filename.substr(0, 10) +'...';
-            }
+              var fm_filename = (data[key]).Filename;
+              if (fm_filename.length > 15) {
+                fm_filename = (data[key]).Filename.substr(0, 10) + '...';
+              }
 
-            var file_name_original = encodeURI((data[key]).Filename);
-            var file_path_orig = encodeURI((data[key]).Path);
+              var file_name_original = encodeURI((data[key]).Filename);
+              var file_path_orig = encodeURI((data[key]).Path);
 
-            result += '<li class="' + cap_classes +
-              '"><div class="clip"><span data-alt="' +
+              result += '<li class="' + cap_classes +
+                '"><div class="clip"><span data-alt="' +
                 file_path_orig + '" class="' + class_type + '"></span>';
-            if ((data[key]).Protected == 1) {
-              result += '<span class="fa fa-lock fm_lock_icon" data-protected="protected"></span>';
-            }
+              if ((data[key]).Protected == 1) {
+                result += '<span class="fa fa-lock fm_lock_icon" data-protected="protected"></span>';
+              }
 
-            result += '</div>';
-            if (!has_capability(data[key], 'rename')) {
-              result += '<span>' + fm_filename + '</span>';
-            } else {
-              result +=
-                '<p><input type="text" class="fm_file_rename" />' +
-                '<span class="less_text" title="' + file_name_original+'">' + fm_filename +
-                '</span></p>';
-            }
-            if (props.Width && props.Width != '') {
-               result += '<span class="meta dimensions">' +
-                 props.Width + 'x' + props.Height + '</span>';
-            }
-            if (props.Size && props.Size != '') {
-              result += '<span class="meta size">' +
-                props.Size + '</span>';
-            }
-            if (props['Date Created'] && props['Date Created'] != '') {
-              result += '<span class="meta created">' +
-                props['Date Created'] + '</span>';
-            }
-            if (props['Date Modified'] && props['Date Modified'] != '') {
-              result += '<span class="meta modified">' +
-                props['Date Modified'] + '</span>';
-            }
-            result += '</li>';
-          });
+              result += '</div>';
+              if (!has_capability(data[key], 'rename')) {
+                result += '<span>' + fm_filename + '</span>';
+              } else {
+                result +=
+                  '<p><input type="text" class="fm_file_rename" />' +
+                  '<span class="less_text" title="' + file_name_original + '">' + fm_filename +
+                  '</span></p>';
+              }
+              if (props.Width && props.Width != '') {
+                result += '<span class="meta dimensions">' +
+                  props.Width + 'x' + props.Height + '</span>';
+              }
+              if (props.Size && props.Size != '') {
+                result += '<span class="meta size">' +
+                  props.Size + '</span>';
+              }
+              if (props['Date Created'] && props['Date Created'] != '') {
+                result += '<span class="meta created">' +
+                  props['Date Created'] + '</span>';
+              }
+              if (props['Date Modified'] && props['Date Modified'] != '') {
+                result += '<span class="meta modified">' +
+                  props['Date Modified'] + '</span>';
+              }
+              result += '</li>';
+            });
 
-          result += '</ul>';
-        } else {
-          result += '<table id="contents" class="list">';
-          result += '<thead><tr><th class="headerSortDown">';
-          result += '<span>' + lg.name +'</span></th>';
-          result += '<th><span>' + lg.size + '</span></th><th>';
-          result += '<span>' + lg.modified + '</span></th></tr></thead>';
-          result += '<tbody>';
-
-          Object.keys(data).sort(function keyOrder(x, y) {
+            result += '</ul>';
+          } else {
+            result += '<table id="contents" class="list">';
+            result += '<thead><tr><th class="headerSortDown">';
+            result += '<span>' + lg.name + '</span></th>';
+            result += '<th><span>' + lg.size + '</span></th><th>';
+            result += '<span>' + lg.modified + '</span></th></tr></thead>';
+            result += '<tbody>';
+
+            Object.keys(data).sort(function keyOrder(x, y) {
               return pgAdmin.natural_sort(x.toLowerCase(), y.toLowerCase());
-            }).forEach(function (key) {
-            var path = encodeURI((data[key]).Path),
+            }).forEach(function(key) {
+              var path = encodeURI((data[key]).Path),
                 props = (data[key]).Properties,
-                cap_classes = "", cap, class_type;
+                cap_classes = '',
+                cap, class_type;
 
-            for (cap in capabilities) {
-              if (has_capability(data[key], capabilities[cap])) {
-                cap_classes += " cap_" + capabilities[cap];
+              for (cap in capabilities) {
+                if (has_capability(data[key], capabilities[cap])) {
+                  cap_classes += ' cap_' + capabilities[cap];
+                }
               }
-            }
 
-            (data[key]).Capabilities = capabilities;
-            bindToolbar(data[key]);
+              (data[key]).Capabilities = capabilities;
+              bindToolbar(data[key]);
 
-            if ((data[key]).file_type == 'dir') {
-              class_type = 'fa fa-folder-open tbl_folder';
-            }
-            else if ((data[key]).file_type == 'drive') {
-              class_type = 'fa fa-hdd-o tbl_drive';
-            } else {
-              class_type = 'fa fa-file-text tbl_file';
-            }
+              if ((data[key]).file_type == 'dir') {
+                class_type = 'fa fa-folder-open tbl_folder';
+              } else if ((data[key]).file_type == 'drive') {
+                class_type = 'fa fa-hdd-o tbl_drive';
+              } else {
+                class_type = 'fa fa-file-text tbl_file';
+              }
 
-            var file_name_original = encodeURI((data[key]).Filename);
-            result += '<tr class="' + cap_classes + '">';
+              var file_name_original = encodeURI((data[key]).Filename);
+              result += '<tr class="' + cap_classes + '">';
 
-            var fm_filename = (data[key]).Filename;
-            if (fm_filename.length > 48) {
-              fm_filename = (data[key]).Filename.substr(0, 48) +'...';
-            }
+              var fm_filename = (data[key]).Filename;
+              if (fm_filename.length > 48) {
+                fm_filename = (data[key]).Filename.substr(0, 48) + '...';
+              }
 
-            result += '<td title="' + path + '" class="'+class_type+'">';
-            if ((data[key]).Protected == 1) {
-              result +=
-                '<i class="fa fa-lock tbl_lock_icon" data-protected="protected"></i>';
-            }
-            if (!has_capability(data[key], 'rename')) {
-              result += '<span title="' + (data[key]).Filename + '">' +
-                fm_filename + '</span></td>';
-            } else {
-              result += '<p><input type="text" class="fm_file_rename"/><span class="less_text" title="' +
-                file_name_original + '">' + fm_filename + '</span></p></td>';
-            }
-            if (props.Size && props.Size != '') {
-              result += '<td><span title="' + props.Size + '">' +
-                props.Size + '</span></td>';
-            } else {
-              result += '<td></td>';
-            }
+              result += '<td title="' + path + '" class="' + class_type + '">';
+              if ((data[key]).Protected == 1) {
+                result +=
+                  '<i class="fa fa-lock tbl_lock_icon" data-protected="protected"></i>';
+              }
+              if (!has_capability(data[key], 'rename')) {
+                result += '<span title="' + (data[key]).Filename + '">' +
+                  fm_filename + '</span></td>';
+              } else {
+                result += '<p><input type="text" class="fm_file_rename"/><span class="less_text" title="' +
+                  file_name_original + '">' + fm_filename + '</span></p></td>';
+              }
+              if (props.Size && props.Size != '') {
+                result += '<td><span title="' + props.Size + '">' +
+                  props.Size + '</span></td>';
+              } else {
+                result += '<td></td>';
+              }
 
-            if (props['Date Modified'] && props['Date Modified'] != '') {
-              result += '<td>' + props['Date Modified'] + '</td>';
-            } else {
-              result += '<td></td>';
-            }
+              if (props['Date Modified'] && props['Date Modified'] != '') {
+                result += '<td>' + props['Date Modified'] + '</td>';
+              } else {
+                result += '<td></td>';
+              }
 
-            result += '</tr>';
-          });
+              result += '</tr>';
+            });
 
-          result += '</tbody>';
-          result += '</table>';
-        }
-      } else {
-        if ($('.fileinfo').data('view') == 'grid') {
-          result += '<ul id="contents" class="grid"></ul>';
+            result += '</tbody>';
+            result += '</table>';
+          }
         } else {
-          result += '<table id="contents" class="list">';
-          result += '<thead><tr><th class="headerSortDown"><span>' +
-            lg.name + '</span></th><th><span>' + lg.size +
+          if ($('.fileinfo').data('view') == 'grid') {
+            result += '<ul id="contents" class="grid"></ul>';
+          } else {
+            result += '<table id="contents" class="list">';
+            result += '<thead><tr><th class="headerSortDown"><span>' +
+              lg.name + '</span></th><th><span>' + lg.size +
               '</span></th><th><span>' + lg.modified +
               '</span></th></tr></thead>';
-          result += '<tbody>';
-        }
-        result += '<h1 class="no_folder_found">' +
-          lg.could_not_retrieve_folder + '</h1>';
+            result += '<tbody>';
+          }
+          result += '<h1 class="no_folder_found">' +
+            lg.could_not_retrieve_folder + '</h1>';
 
-        var cap_no_folders = ['upload', 'create'];
+          var cap_no_folders = ['upload', 'create'];
 
-        data.Capabilities = cap_no_folders;
-        bindToolbar(data);
-      }
-
-      // Add the new markup to the DOM.
-      $('.fileinfo .file_listing').html(result);
+          data.Capabilities = cap_no_folders;
+          bindToolbar(data);
+        }
 
-      // rename file/folder
-      $('.file_manager button.rename').unbind().on('click',function(e) {
-        if ($('.fileinfo').data('view') == 'grid') {
-          e.stopPropagation();
-          var $this = $('.file_manager').find('#contents li.selected p'),
-              orig_value = decodeURI($this.find('span').attr('title')),
-              newvalue = orig_value.substring(0, orig_value.indexOf('.'));
+        // Add the new markup to the DOM.
+        $('.fileinfo .file_listing').html(result);
 
-          if (newvalue === '') {
-            newvalue = decodeURI(orig_value);
-          }
+        // rename file/folder
+        $('.file_manager button.rename').unbind().on('click', function(e) {
 
-          $this.find('input').toggle().val(newvalue).focus();
-          $this.find('span').toggle();
+          if ($('.fileinfo').data('view') == 'grid') {
+            e.stopPropagation();
+            $this = $('.file_manager').find('#contents li.selected p');
+            orig_value = decodeURI($this.find('span').attr('title'));
+            newvalue = orig_value.substring(0, orig_value.indexOf('.'));
 
-          // Rename folder/file on pressing enter key
-          $('.file_manager').unbind().on('keyup', function(e) {
-            if (e.keyCode == 13) {
-              e.stopPropagation();
-              $('.fileinfo #contents li.selected p').find(
-                'input'
-              ).trigger('blur');
+            if (newvalue === '') {
+              newvalue = decodeURI(orig_value);
             }
-          });
-        } else if ($('.fileinfo').data('view') == 'list') {
-          e.stopPropagation();
-          var $this = $('.fileinfo').find(
-                'table#contents tbody tr.selected td:first-child p'
-              ),
-              orig_value = decodeURI($this.find('span').html()),
-              newvalue = orig_value.substring(0, orig_value.lastIndexOf('.'));
 
-          if (orig_value.lastIndexOf('/') == orig_value.length - 1 || newvalue === '') {
-            newvalue = decodeURI(orig_value);
-          }
+            $this.find('input').toggle().val(newvalue).focus();
+            $this.find('span').toggle();
 
-          $this.find('input').toggle().val(newvalue).focus();
-          $this.find('span').toggle();
+            // Rename folder/file on pressing enter key
+            $('.file_manager').unbind().on('keyup', function(e) {
+              if (e.keyCode == 13) {
+                e.stopPropagation();
+                $('.fileinfo #contents li.selected p').find(
+                  'input'
+                ).trigger('blur');
+              }
+            });
+          } else if ($('.fileinfo').data('view') == 'list') {
+            e.stopPropagation();
+            $this = $('.fileinfo').find(
+              'table#contents tbody tr.selected td:first-child p'
+            );
+            orig_value = decodeURI($this.find('span').html()),
+              newvalue = orig_value.substring(0, orig_value.lastIndexOf('.'));
 
-          // Rename folder/file on pressing enter key
-          $('.file_manager').unbind().on('keyup', function(e) {
-            if (e.keyCode == 13) {
-              e.stopPropagation();
-              $('.fileinfo table#contents tr.selected td p').find(
-                'input'
-              ).trigger('blur');
+            if (orig_value.lastIndexOf('/') == orig_value.length - 1 || newvalue === '') {
+              newvalue = decodeURI(orig_value);
             }
-          });
-        }
-      });
 
-      // Rename UI handling
-      $('.fileinfo #contents li p').on('blur dblclick','input', function(e) {
-        e.stopPropagation();
+            $this.find('input').toggle().val(newvalue).focus();
+            $this.find('span').toggle();
 
-        var old_name = decodeURI($(this).siblings('span').attr('title')),
-            newvalue = old_name.substring(0, old_name.indexOf('.')),
-            last = getFileExtension(old_name);
+            // Rename folder/file on pressing enter key
+            $('.file_manager').unbind().on('keyup', function(e) {
+              if (e.keyCode == 13) {
+                e.stopPropagation();
+                $('.fileinfo table#contents tr.selected td p').find(
+                  'input'
+                ).trigger('blur');
+              }
+            });
+          }
+        });
 
-        if (old_name.indexOf('.') == 0) {
-          last = '';
-        }
+        // Rename UI handling
+        $('.fileinfo #contents li p').on('blur dblclick', 'input', function(e) {
+          e.stopPropagation();
 
-        if (newvalue == '') {
-          newvalue = decodeURI(old_name);
-        }
+          var old_name = decodeURI($(this).siblings('span').attr('title'));
+          newvalue = old_name.substring(0, old_name.indexOf('.'));
+          var last = getFileExtension(old_name),
+            data, new_name, path, full_name;
 
-        if (e.type=="keydown") {
-          if (e.which==13) {
-            var full_name = decodeURI($(this).val()) + (
-              last !== '' ? '.' + last: ''
-            );
+          if (old_name.indexOf('.') == 0) {
+            last = '';
+          }
 
-            $(this).toggle();
-            $(this).siblings('span').toggle().html(full_name);
-
-            var new_name = decodeURI($(this).val()),
-                path = decodeURI($(this).parent().parent().find(
-                  'span'
-                ).attr('data-alt')),
-                data = {
-                  'Filename': old_name,
-                  'Path': path,
-                  'NewFilename': new_name
-                };
-
-            if (newvalue !== new_name) {
-              renameItem(data);
-              var parent = $('.currentpath').val();
-              getFolderInfo(parent);
-            }
-            e.stopPropagation();
+          if (newvalue == '') {
+            newvalue = decodeURI(old_name);
           }
 
-          if (
-            e.which==38 || e.which==40 || e.which==37 ||
-            e.which==39 || e.keyCode == 32
-          ) {
+          if (e.type == 'keydown') {
+            if (e.which == 13) {
+              full_name = decodeURI($(this).val()) + (
+                last !== '' ? '.' + last : ''
+              );
+
+              $(this).toggle();
+              $(this).siblings('span').toggle().html(full_name);
+
+              new_name = decodeURI($(this).val());
+              path = decodeURI($(this).parent().parent().find(
+                'span'
+              ).attr('data-alt'));
+              data = {
+                'Filename': old_name,
+                'Path': path,
+                'NewFilename': new_name,
+              };
+
+              if (newvalue !== new_name) {
+                renameItem(data);
+                var parent = $('.currentpath').val();
+                getFolderInfo(parent);
+              }
               e.stopPropagation();
-          }
-        } else if (e.type=="focusout") {
-          if ($(this).css('display')=="inline-block" || $(this).css('display')=="inline") {
-            var full_name = decodeURI(
-                  $(this).val()
-                ) + (last !== ''? '.' + last: '');
-
-            $(this).toggle();
-            $(this).siblings('span').toggle().html(full_name);
-
-            var new_name = decodeURI($(this).val()),
-                path = decodeURI($(this).parent().parent().find(
-                  'span'
-                ).attr('data-alt')),
-                data = {
-                  'Filename': old_name,
-                  'Path': path,
-                  'NewFilename': new_name
-                };
-
-            if (newvalue !== new_name) {
-              renameItem(data);
-              getFolderInfo($('.currentpath').val());
             }
-          }
-        } else {
-          e.stopPropagation();
-        }
-      });
 
-      $('.fileinfo table#contents tr td p').on(
-        'blur dblclick', 'input', function(e) {
-        var old_name = decodeURI($(this).siblings('span').attr('title')),
-            newvalue = old_name.substring(0, old_name.indexOf('.')),
-            last = getFileExtension(old_name);
-        if (old_name.indexOf('.') == 0) {
-          last = '';
-        }
+            if (
+              e.which == 38 || e.which == 40 || e.which == 37 ||
+              e.which == 39 || e.keyCode == 32
+            ) {
+              e.stopPropagation();
+            }
+          } else if (e.type == 'focusout') {
+            if ($(this).css('display') == 'inline-block' || $(this).css('display') == 'inline') {
+              full_name = decodeURI(
+                $(this).val()
+              ) + (last !== '' ? '.' + last : '');
+
+              $(this).toggle();
+              $(this).siblings('span').toggle().html(full_name);
+
+              new_name = decodeURI($(this).val());
+              path = decodeURI($(this).parent().parent().find(
+                'span'
+              ).attr('data-alt'));
+              data = {
+                'Filename': old_name,
+                'Path': path,
+                'NewFilename': new_name,
+              };
+
+              if (newvalue !== new_name) {
+                renameItem(data);
+                getFolderInfo($('.currentpath').val());
+              }
+            }
+          } else {
+            e.stopPropagation();
+          }
+        });
 
-        if (newvalue == '') {
-          newvalue = old_name;
-        }
+        $('.fileinfo table#contents tr td p').on(
+          'blur dblclick', 'input',
+          function(e) {
+            var old_name = decodeURI($(this).siblings('span').attr('title')),
+              newvalue = old_name.substring(0, old_name.indexOf('.')),
+              last = getFileExtension(old_name);
+            if (old_name.indexOf('.') == 0) {
+              last = '';
+            }
 
-        if (e.type=="focusout") {
-          if ($(this).css('display')=="inline-block" || $(this).css('display')=="inline") {
-            var full_name = decodeURI($(this).val()) + (
-              last !== ''? '.' + last: ''
-            );
-            $(this).toggle();
-            $(this).siblings('span').toggle().html(full_name);
-
-            var new_name = decodeURI($(this).val()),
-                path = decodeURI($(this).parent().parent().attr('title')),
-                data = {
-                  'Filename': old_name,
-                  'Path': path,
-                  'NewFilename': new_name
-                };
-
-            if (newvalue !== new_name) {
-              renameItem(data);
-              var parent = path.split('/').reverse().slice(2).reverse().join('/') + '/';
-              getFolderInfo(parent);
+            if (newvalue == '') {
+              newvalue = old_name;
             }
-          }
-        } else {
-          e.stopPropagation();
-        }
-      });
 
-      var data_cap = {};
-      data_cap.Capabilities = capabilities;
-      /*
-       * Bind click events
-       * Select items - afolder dblclick
-       */
-      if ($('.fileinfo').data('view') == 'grid') {
-        // Get into folder on dblclick
-        $('.fileinfo').find('#contents li').dblclick(function(e) {
-          e.stopPropagation();
-          // Enable/Disable level up button
-          enab_dis_level_up();
+            if (e.type == 'focusout') {
+              if ($(this).css('display') == 'inline-block' || $(this).css('display') == 'inline') {
+                var full_name = decodeURI($(this).val()) + (
+                  last !== '' ? '.' + last : ''
+                );
+                $(this).toggle();
+                $(this).siblings('span').toggle().html(full_name);
+
+                var new_name = decodeURI($(this).val()),
+                  path = decodeURI($(this).parent().parent().attr('title')),
+                  data = {
+                    'Filename': old_name,
+                    'Path': path,
+                    'NewFilename': new_name,
+                  };
+
+                if (newvalue !== new_name) {
+                  renameItem(data);
+                  var parent = path.split('/').reverse().slice(2).reverse().join('/') + '/';
+                  getFolderInfo(parent);
+                }
+              }
+            } else {
+              e.stopPropagation();
+            }
+          });
+
+        var data_cap = {};
+        data_cap.Capabilities = capabilities;
+        /*
+         * Bind click events
+         * Select items - afolder dblclick
+         */
+        if ($('.fileinfo').data('view') == 'grid') {
+          // Get into folder on dblclick
+          $('.fileinfo').find('#contents li').dblclick(function(e) {
+            e.stopPropagation();
+            // Enable/Disable level up button
+            enab_dis_level_up();
 
-          var path = decodeURI($(this).find('span').attr('data-alt'));
+            var path = decodeURI($(this).find('span').attr('data-alt'));
 
-          if (path.lastIndexOf("/") == path.length - 1 || path.lastIndexOf("\\") == path.length - 1) {
-            $('.file_manager_ok').addClass('disabled');
-            $('.file_manager_ok').attr('disabled', true);
-            $('.file_manager button.delete, .file_manager button.rename').attr('disabled', 'disabled');
-            $('.file_manager button.download').attr('disabled', 'disabled');
+            if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
+              $('.file_manager_ok').addClass('disabled');
+              $('.file_manager_ok').attr('disabled', true);
+              $('.file_manager button.delete, .file_manager button.rename').attr('disabled', 'disabled');
+              $('.file_manager button.download').attr('disabled', 'disabled');
 
-            getFolderInfo(path);
+              getFolderInfo(path);
 
-          } else {
-            var is_valid_file = getFileInfo(path);
-            if (is_valid_file && check_file_capability(e, data_cap, 'grid')) {
-              $('.file_manager_ok').click();
+            } else {
+              var is_valid_file = getFileInfo(path);
+              if (is_valid_file && check_file_capability(e, data_cap, 'grid')) {
+                $('.file_manager_ok').click();
+              }
             }
-          }
-        });
+          });
 
-        $('.fileinfo').find('#contents li').click(function(e) {
-          e.stopPropagation();
-          var path = decodeURI($(this).find('.clip span').attr('data-alt')),
-              file_name = $(this).find('p span').attr('title'),
+          $('.fileinfo').find('#contents li').click(function(e) {
+            e.stopPropagation();
+            var path = decodeURI($(this).find('.clip span').attr('data-alt')),
               is_protected = $(this).find(
                 '.clip span.fm_lock_icon'
               ).attr('data-protected');
 
-          if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
-            if (
-              has_capability(data_cap, 'select_folder') &&
-              is_protected == undefined
-            ) {
-              $(this).parent().find('li.selected').removeClass('selected');
-              $(this).addClass('selected');
+            if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
+              if (
+                has_capability(data_cap, 'select_folder') &&
+                is_protected == undefined
+              ) {
+                $(this).parent().find('li.selected').removeClass('selected');
+                $(this).addClass('selected');
+
+                $('.file_manager_ok').removeClass('disabled');
+                $('.file_manager_ok').attr('disabled', false);
+                $('.file_manager button.delete, .file_manager button.rename').removeAttr(
+                  'disabled', 'disabled'
+                );
+                $('.file_manager button.download').attr(
+                  'disabled', 'disabled'
+                );
+                // set selected folder name in breadcrums
+                $('.file_manager #uploader .input-path').hide();
+                $('.file_manager #uploader .show_selected_file').remove();
+                $('<span class="show_selected_file">' + path + '</span>').appendTo(
+                  '.file_manager #uploader .filemanager-path-group'
+                );
+              }
+            } else {
+              if (
+                has_capability(data_cap, 'select_file') &&
+                is_protected == undefined
+              ) {
+                $(this).parent().find('li.selected').removeClass('selected');
+                $(this).addClass('selected');
+                $('.file_manager_ok').removeClass('disabled');
+                $('.file_manager_ok').attr('disabled', false);
+                $('.file_manager button.delete, .file_manager button.download, .file_manager button.rename').removeAttr(
+                  'disabled'
+                );
+                // set selected folder name in breadcrums
+                $('.file_manager #uploader .show_selected_file').remove();
+              }
 
-              $('.file_manager_ok').removeClass('disabled');
-              $('.file_manager_ok').attr('disabled', false);
-              $('.file_manager button.delete, .file_manager button.rename').removeAttr(
-                'disabled', 'disabled'
-              );
-              $('.file_manager button.download').attr(
-                'disabled', 'disabled'
-              );
-              // set selected folder name in breadcrums
-              $('.file_manager #uploader .input-path').hide();
-              $('.file_manager #uploader .show_selected_file').remove();
-              $('<span class="show_selected_file">'+path+'</span>').appendTo(
-                '.file_manager #uploader .filemanager-path-group'
-              );
-            }
-          } else {
-            if (
-              has_capability(data_cap, 'select_file') &&
-              is_protected == undefined
-            ) {
-              $(this).parent().find('li.selected').removeClass('selected');
-              $(this).addClass('selected');
-              $('.file_manager_ok').removeClass('disabled');
-              $('.file_manager_ok').attr('disabled', false);
-              $('.file_manager button.delete, .file_manager button.download, .file_manager button.rename').removeAttr(
-                'disabled'
-              );
-              // set selected folder name in breadcrums
-              $('.file_manager #uploader .show_selected_file').remove();
+              getFileInfo(path);
             }
-
-            getFileInfo(path);
-          }
-        });
-      } else {
-        $('.fileinfo table#contents tbody tr').on('click', function(e) {
-          e.stopPropagation();
-          var path = decodeURI($('td:first-child', this).attr('title')),
-              file_name = decodeURI($('td:first-child p span', this).attr(
-                'title'
-              )),
+          });
+        } else {
+          $('.fileinfo table#contents tbody tr').on('click', function(e) {
+            e.stopPropagation();
+            var path = decodeURI($('td:first-child', this).attr('title')),
               is_protected = $('td:first-child', this).find(
                 'i.tbl_lock_icon'
               ).attr('data-protected');
 
-          if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
-            if (has_capability(data_cap, 'select_folder') && is_protected == undefined) {
-              $(this).parent().find('tr.selected').removeClass('selected');
-              $('td:first-child', this).parent().addClass('selected');
-              $('.file_manager_ok').removeClass('disabled');
-              $('.file_manager_ok').attr('disabled', false);
-              $('.file_manager button.download').attr('disabled', 'disabled');
-              $('.file_manager button.delete, .file_manager button.rename').removeAttr('disabled');
+            if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
+              if (has_capability(data_cap, 'select_folder') && is_protected == undefined) {
+                $(this).parent().find('tr.selected').removeClass('selected');
+                $('td:first-child', this).parent().addClass('selected');
+                $('.file_manager_ok').removeClass('disabled');
+                $('.file_manager_ok').attr('disabled', false);
+                $('.file_manager button.download').attr('disabled', 'disabled');
+                $('.file_manager button.delete, .file_manager button.rename').removeAttr('disabled');
+
+                // set selected folder name in breadcrums
+                $('.file_manager #uploader .input-path').hide();
+                $('.file_manager #uploader .show_selected_file').remove();
+                $('<span class="show_selected_file">' + path + '</span>').appendTo(
+                  '.file_manager #uploader .filemanager-path-group'
+                );
+              }
+            } else {
+              if (has_capability(data_cap, 'select_file') && is_protected == undefined) {
+                $(this).parent().find('tr.selected').removeClass('selected');
+                $('td:first-child', this).parent().addClass('selected');
+                $('.file_manager button.delete, .file_manager button.download, .file_manager button.rename').removeAttr(
+                  'disabled'
+                );
+                // set selected folder name in breadcrums
+                $('.file_manager #uploader .show_selected_file').remove();
+              }
 
-              // set selected folder name in breadcrums
-              $('.file_manager #uploader .input-path').hide();
-              $('.file_manager #uploader .show_selected_file').remove();
-              $('<span class="show_selected_file">'+path+'</span>').appendTo(
-                '.file_manager #uploader .filemanager-path-group'
-              );
+              getFileInfo(path);
             }
-          } else {
-            if (has_capability(data_cap, 'select_file') && is_protected == undefined) {
-              $(this).parent().find('tr.selected').removeClass('selected');
-              $('td:first-child', this).parent().addClass('selected');
-              $('.file_manager button.delete, .file_manager button.download, .file_manager button.rename').removeAttr(
-                'disabled'
-              );
-              // set selected folder name in breadcrums
-              $('.file_manager #uploader .show_selected_file').remove();
-            }
-
-            getFileInfo(path);
-          }
-        });
+          });
 
-        $('.fileinfo table#contents tbody tr').on('dblclick', function(e) {
-          e.stopPropagation();
-          // Enable/Disable level up button
-          enab_dis_level_up();
-          var path = $('td:first-child', this).attr('title');
+          $('.fileinfo table#contents tbody tr').on('dblclick', function(e) {
+            e.stopPropagation();
+            // Enable/Disable level up button
+            enab_dis_level_up();
+            var path = $('td:first-child', this).attr('title');
 
-          if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
-            $('.file_manager_ok').addClass('disabled');
-            $('.file_manager_ok').attr('disabled', true);
-            $('.file_manager button.download').attr('disabled', 'disabled');
-            $('.file_manager button.delete, .file_manager button.rename').attr('disabled', 'disabled');
-            getFolderInfo(path);
-          } else {
-            var is_valid_file = getFileInfo(path), is_protected;
-            if (is_valid_file && check_file_capability(e, data_cap, 'table')) {
-              $('.file_manager_ok').click();
+            if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
+              $('.file_manager_ok').addClass('disabled');
+              $('.file_manager_ok').attr('disabled', true);
+              $('.file_manager button.download').attr('disabled', 'disabled');
+              $('.file_manager button.delete, .file_manager button.rename').attr('disabled', 'disabled');
+              getFolderInfo(path);
+            } else {
+              var is_valid_file = getFileInfo(path);
+              if (
+                is_valid_file && check_file_capability(e, data_cap, 'table')
+              ) {
+                $('.file_manager_ok').click();
+              }
             }
-          }
-        });
+          });
 
-      }
-      //input_object.set_cap(data_cap);
-    },
-    error: function() {
-      $('.storage_dialog #uploader .input-path').prop('disabled', false);
-    }
-  });
-};
+        }
+        //input_object.set_cap(data_cap);
+      },
+      error: function() {
+        $('.storage_dialog #uploader .input-path').prop('disabled', false);
+      },
+    });
+  };
 
-// Enable/Disable level up button
-var enab_dis_level_up = function() {
-  $('.file_manager #uploader .input-path').show();
-  $('.show_selected_file').remove();
+  // Enable/Disable level up button
+  var enab_dis_level_up = function() {
+    $('.file_manager #uploader .input-path').show();
+    $('.show_selected_file').remove();
 
-  setTimeout(function() {
-    var b = $('.currentpath').val(),
+    setTimeout(function() {
+      var b = $('.currentpath').val(),
         $level_up = $('.file_manager').find('button.level-up'),
         $home_btn = $('.file_manager').find('button.home');
 
-    if (b === '/') {
-      $level_up.attr('disabled', 'disabled');
-      $home_btn.attr('disabled', 'disabled');
+      if (b === '/') {
+        $level_up.attr('disabled', 'disabled');
+        $home_btn.attr('disabled', 'disabled');
+      } else {
+        $home_btn.removeAttr('disabled');
+        $level_up.removeAttr('disabled');
+      }
+    }, 100);
+  };
+
+  // Check if user can Select file
+  var check_file_capability = function(event, data_cap, view_type) {
+    var current_element = event.currentTarget,
+      is_protected;
+
+    if (view_type == 'grid') {
+      is_protected = $(current_element).find(
+        '.clip span.fm_lock_icon'
+      ).attr('data-protected');
     } else {
-      $home_btn.removeAttr('disabled');
-      $level_up.removeAttr('disabled');
+      is_protected = $(current_element).find('td:first-child').find(
+        'i.tbl_lock_icon'
+      ).attr('data-protected');
     }
-  }, 100);
-};
-
-// Check if user can Select file
-var check_file_capability = function(event, data_cap, view_type) {
-  var current_element = event.currentTarget,
-      path, file_name, is_protected;
-
-  if (view_type == 'grid') {
-    path = decodeURI($(current_element).find('.clip span').attr('data-alt')),
-    file_name = $(current_element).find('p span').attr('title'),
-    is_protected = $(current_element).find(
-      '.clip span.fm_lock_icon'
-    ).attr('data-protected');
-  } else {
-    path = decodeURI($(current_element).find('td:first-child').attr('title')),
-    file_name = decodeURI($(current_element).find('td:first-child p span').attr(
-      'title'
-    )),
-    is_protected = $(current_element).find('td:first-child').find(
-      'i.tbl_lock_icon'
-    ).attr('data-protected');
-  }
-
-  return has_capability(data_cap, 'select_file') && is_protected == undefined;
-}
-
-/*---------------------------------------------------------
-  Initialization - Entry point
----------------------------------------------------------*/
-/*
- * get transaction id to generate request url and
- * to generate config files on runtime
- */
-pgAdmin.FileUtils = {
-  init: function() {
-    var fm_url = url_for('file_manager.get_trans_id'),
+
+    return has_capability(data_cap, 'select_file') &&
+      is_protected == undefined;
+  };
+
+  /*---------------------------------------------------------
+    Initialization - Entry point
+  ---------------------------------------------------------*/
+  /*
+   * get transaction id to generate request url and
+   * to generate config files on runtime
+   */
+  pgAdmin.FileUtils = {
+    init: function() {
+      var fm_url = url_for('file_manager.get_trans_id'),
         transId = loadData(fm_url),
         t_res,
         t_id;
 
-    if (transId.readyState == 4) {
-      t_res = JSON.parse(transId.responseText);
-    }
-    t_id = t_res.data.fileTransId;
-    var root_url = url_for("file_manager.index"),
-        file_manager_config_json = root_url+t_id+'/file_manager_config.json',
-        file_manager_config_js = root_url+'file_manager_config.js',
-        fileConnector = root_url+'filemanager/'+t_id+'/',
+      if (transId.readyState == 4) {
+        t_res = JSON.parse(transId.responseText);
+      }
+      t_id = t_res.data.fileTransId;
+      var root_url = url_for('file_manager.index'),
+        file_manager_config_json = root_url + t_id + '/file_manager_config.json',
+        fileConnector = root_url + 'filemanager/' + t_id + '/',
         cfg = loadData(file_manager_config_json),
         config;
 
-    this.fileConnector = fileConnector;
-    this.transId = t_id;
-    // load user configuration file
-    if (cfg.readyState == 4) {
-      this.config = config = JSON.parse(cfg.responseText);
-    }
+      this.fileConnector = fileConnector;
+      this.transId = t_id;
+      // load user configuration file
+      if (cfg.readyState == 4) {
+        this.config = config = JSON.parse(cfg.responseText);
+      }
 
-    // set main url to filemanager and its capabilites
-    var fileRoot = config.options.fileRoot,
+      // set main url to filemanager and its capabilites
+      var fileRoot = config.options.fileRoot,
         capabilities = config.options.capabilities;
 
-    /*
-     * Get localized messages from file
-     * through culture var or from URL
-     */
+      /*
+       * Get localized messages from file
+       * through culture var or from URL
+       */
 
-    var lg = [],
-        enjs = url_for("file_manager.index") + "en.js",
+      var lg = [],
+        enjs = url_for('file_manager.index') + 'en.js',
         lgf = loadData(enjs);
 
-    if (lgf.readyState == 4) {
-      this.lg = lg = JSON.parse(lgf.responseText);
-    }
+      if (lgf.readyState == 4) {
+        this.lg = lg = JSON.parse(lgf.responseText);
+      }
 
-    // create and enable user to create new file
-    if (
-      config.options.dialog_type == 'select_file' ||
-      config.options.dialog_type == 'create_file' ||
-      config.options.dialog_type == 'storage_dialog'
-    ) {
-      // Create file selection dropdown
-      var allowed_types = config.options.allowed_file_types,
+      // create and enable user to create new file
+      if (
+        config.options.dialog_type == 'select_file' ||
+        config.options.dialog_type == 'create_file' ||
+        config.options.dialog_type == 'storage_dialog'
+      ) {
+        // Create file selection dropdown
+        var allowed_types = config.options.allowed_file_types,
           types_len = allowed_types.length,
-          select_box = '',
-          file_type = '';
+          select_box = '';
 
-      if (types_len > 0) {
-        var i = 0, j = 0, t,
+        if (types_len > 0) {
+          var i = 0,
+            t,
             selected = false,
             have_all_types = false;
 
-        var select_box = "<div class='change_file_types'>" +
-          gettext("Show hidden files and folders") +
-          "? <input type='checkbox' id='show_hidden' onclick='pgAdmin.FileUtils.handleClick(this)' tabindex='11'>" +
-          "<span></span>" +
-          "<select name='type' tabindex='12'>";
-
-        while(i < types_len) {
-          t = allowed_types[i];
-          if (!selected && (types_len == 1 || t != '*')) {
-            select_box += "<option value=" + t + " selected>" + t + "</option>";
-            selected = true;
-            have_all_types = (have_all_types || (t == '*'));
-          } else {
-            select_box += '<option value="' + t +'">' +
-              (t == '*' ? gettext('All Files') : t) + "</option>";
-            have_all_types = (have_all_types || (t == '*'));
+          select_box = '<div class=\'change_file_types\'>' +
+            gettext('Show hidden files and folders') +
+            '? <input type=\'checkbox\' id=\'show_hidden\' onclick=\'pgAdmin.FileUtils.handleClick(this)\' tabindex=\'11\'>' +
+            '<span></span>' +
+            '<select name=\'type\' tabindex=\'12\'>';
+
+          while (i < types_len) {
+            t = allowed_types[i];
+            if (!selected && (types_len == 1 || t != '*')) {
+              select_box += '<option value=' + t + ' selected>' + t + '</option>';
+              selected = true;
+              have_all_types = (have_all_types || (t == '*'));
+            } else {
+              select_box += '<option value="' + t + '">' +
+                (t == '*' ? gettext('All Files') : t) + '</option>';
+              have_all_types = (have_all_types || (t == '*'));
+            }
+            i++;
           }
-          i++;
-        }
 
-        if (!have_all_types) {
-          select_box += '<option value="*">' + gettext('All Files') + '</option>';
+          if (!have_all_types) {
+            select_box += '<option value="*">' + gettext('All Files') + '</option>';
+          }
+          select_box += '</select><label>' + gettext('Format') + ': </label></div>';
         }
-        select_box += "</select><label>" + gettext('Format') + ": </label></div>";
-      }
 
-      $(".allowed_file_types").html(select_box);
+        $('.allowed_file_types').html(select_box);
 
-      $(".allowed_file_types select").on('change', function() {
-        var selected_val = $(this).val(),
+        $('.allowed_file_types select').on('change', function() {
+          var selected_val = $(this).val(),
             curr_path = $('.currentpath').val();
-        getFolderInfo(curr_path, selected_val);
-      });
-
-      // If user have preference to show hidden files
-      if (config.options.show_hidden_files) {
-        setTimeout(function() {
-          $("#show_hidden").click();
-        }, 10);
-      }
-      // handle show hidden files functionality
-      this.handleClick = function(cb) {
-        var data = {
-          'is_checked': false
-        };
+          getFolderInfo(curr_path, selected_val);
+        });
 
-        if(cb.checked) {
-          $("div.allowed_file_types select").val("*").trigger("change");
-          data['is_checked'] = true;
-        } else {
-          // User wants to hide it again
-          $("div.allowed_file_types select").prop('selectedIndex', 0).trigger("change");
-          data['is_checked'] = false;
+        // If user have preference to show hidden files
+        if (config.options.show_hidden_files) {
+          setTimeout(function() {
+            $('#show_hidden').click();
+          }, 10);
         }
-        // Save it in preference
-        save_show_hidden_file_option(data['is_checked'], pgAdmin.FileUtils.transId);
-        return;
+        // handle show hidden files functionality
+        this.handleClick = function(cb) {
+          var data = {
+            'is_checked': false,
+          };
+
+          if (cb.checked) {
+            $('div.allowed_file_types select').val('*').trigger('change');
+            data['is_checked'] = true;
+          } else {
+            // User wants to hide it again
+            $('div.allowed_file_types select').prop('selectedIndex', 0).trigger('change');
+            data['is_checked'] = false;
+          }
+          // Save it in preference
+          save_show_hidden_file_option(data['is_checked'], pgAdmin.FileUtils.transId);
+          return;
+        };
       }
-    }
 
-    /*---------------------------------------------------------
-      Item Actions - Object events
-    ---------------------------------------------------------*/
+      /*---------------------------------------------------------
+        Item Actions - Object events
+      ---------------------------------------------------------*/
 
-    // switch to folder view
-    $('.file_manager .fileinfo').on('click', function(e) {
-      $('.file_manager #uploader .input-path').val($('.currentpath').val())
-      enable_disable_btn();
-    });
+      // Switch to folder view
+      $('.file_manager .fileinfo').on('click', function() {
+        $('.file_manager #uploader .input-path').val($('.currentpath').val());
+        enable_disable_btn();
+      });
+
+      // Refresh current directory
+      $('.file_manager .refresh').on('click', function() {
+        enable_disable_btn();
+
+        var curr_path = $('.currentpath').val(),
+          path;
 
-    // refresh current directory
-    $('.file_manager .refresh').on('click', function(e) {
-      enable_disable_btn();
-      var curr_path = $('.currentpath').val();
         $('.file_manager #uploader .input-path').val(curr_path);
-        if(curr_path.endsWith("/")) {
-            var path = curr_path.substring(0, curr_path.lastIndexOf("/")) + "/";
+        if (curr_path.endsWith('/')) {
+          path = curr_path.substring(0, curr_path.lastIndexOf('/')) + '/';
         } else {
-            var path = curr_path.substring(0, curr_path.lastIndexOf("\\")) + "\\";
+          path = curr_path.substring(0, curr_path.lastIndexOf('\\')) + '\\';
         }
-      getFolderInfo(path);
-    });
+        getFolderInfo(path);
+      });
 
-    // hide message prompt and dimmer if clicked no
-    $('.delete_item button.btn_no').on('click', function() {
-      $('.delete_item, .fileinfo .fm_dimmer').hide();
-    });
+      // hide message prompt and dimmer if clicked no
+      $('.delete_item button.btn_no').on('click', function() {
+        $('.delete_item, .fileinfo .fm_dimmer').hide();
+      });
 
-    // Disable home button on load
-    $('.file_manager').find('button.home').attr('disabled', 'disabled');
-    $('.file_manager').find('button.rename').attr('disabled', 'disabled');
+      // Disable home button on load
+      $('.file_manager').find('button.home').attr('disabled', 'disabled');
+      $('.file_manager').find('button.rename').attr('disabled', 'disabled');
 
-    // stop click event on dimmer click
-    $('.fileinfo .fm_dimmer').on('click', function(e) {
-      e.stopPropagation();
-    });
+      // stop click event on dimmer click
+      $('.fileinfo .fm_dimmer').on('click', function(e) {
+        e.stopPropagation();
+      });
 
-    $('.fileinfo .replace_file').not(
-      $(this).find('span.pull-right')
-    ).on(
-    'click', function(e) {
-      $('#uploader .filemanager-btn-group').unbind().on(
-        'click', function() {
-          $('.fileinfo .delete_item, .fileinfo .replace_file, .fileinfo .fm_dimmer').hide();
+      $('.fileinfo .replace_file').not(
+        $(this).find('span.pull-right')
+      ).on(
+        'click',
+        function(e) {
+          $('#uploader .filemanager-btn-group').unbind().on(
+            'click',
+            function() {
+              $('.fileinfo .delete_item, .fileinfo .replace_file, .fileinfo .fm_dimmer').hide();
+            });
+          e.stopPropagation();
         });
-      e.stopPropagation();
-    });
 
-    // Set initial view state.
-    $('.fileinfo').data('view', config.options.defaultViewMode);
-    setViewButtonsFor(config.options.defaultViewMode);
-
-    // Upload click event
-    $('.file_manager .uploader').on('click', 'a', function(e) {
-      e.preventDefault();
-      var b = $('.currentpath').val();
-      var node_val = $(this).next().text();
-      parent = b.substring(0, b.slice(0, -1).lastIndexOf(node_val));
-      getFolderInfo(parent);
-    });
+      // Set initial view state.
+      $('.fileinfo').data('view', config.options.defaultViewMode);
+      setViewButtonsFor(config.options.defaultViewMode);
+
+      // Upload click event
+      $('.file_manager .uploader').on('click', 'a', function(e) {
+        e.preventDefault();
+        var b = $('.currentpath').val(),
+          node_val = $(this).next().text(),
+          parent = b.substring(0, b.slice(0, -1).lastIndexOf(node_val));
+        getFolderInfo(parent);
+      });
 
-    // re-render the home view
-    $('.file_manager .home').click(function() {
-      var currentViewMode = $('.fileinfo').data('view');
-      $('.fileinfo').data('view', currentViewMode);
-      getFolderInfo('/');
-      enab_dis_level_up();
-    });
+      // re-render the home view
+      $('.file_manager .home').click(function() {
+        var currentViewMode = $('.fileinfo').data('view');
+        $('.fileinfo').data('view', currentViewMode);
+        getFolderInfo('/');
+        enab_dis_level_up();
+      });
 
-    // Go one directory back
-    $(".file_manager .level-up").click(function() {
-      var b = $('.currentpath').val();
-      // Enable/Disable level up button
-      enab_dis_level_up();
+      // Go one directory back
+      $('.file_manager .level-up').click(function() {
+        var b = $('.currentpath').val();
+        // Enable/Disable level up button
+        enab_dis_level_up();
 
-      if (b.endsWith('\\') || b.endsWith('/')) {
-        b = b.substring(0, b.length - 1)
-      }
+        if (b.endsWith('\\') || b.endsWith('/')) {
+          b = b.substring(0, b.length - 1);
+        }
 
-      if (b != '/') {
-          if(b.lastIndexOf('/') > b.lastIndexOf('\\')) {
-            var parent = b.substring(0, b.slice(0, -1).lastIndexOf("/")) + "/";
+        if (b != '/') {
+          var parent;
+          if (b.lastIndexOf('/') > b.lastIndexOf('\\')) {
+            parent = b.substring(0, b.slice(0, -1).lastIndexOf('/')) + '/';
           } else {
-            var parent = b.substring(0, b.slice(0, -1).lastIndexOf("\\")) + "\\";
+            parent = b.substring(0, b.slice(0, -1).lastIndexOf('\\')) + '\\';
           }
 
-          var d = $(".fileinfo").data("view");
-          $(".fileinfo").data("view", d);
+          var d = $('.fileinfo').data('view');
+          $('.fileinfo').data('view', d);
           getFolderInfo(parent);
-      }
-    });
+        }
+      });
 
-    // set buttons to switch between grid and list views.
-    $('.file_manager .grid').click(function() {
-      setViewButtonsFor('grid');
-      $('.fileinfo').data('view', 'grid');
-      enable_disable_btn();
-      getFolderInfo($('.currentpath').val());
-      save_file_dialog_view('grid', pgAdmin.FileUtils.transId);
-    });
+      // set buttons to switch between grid and list views.
+      $('.file_manager .grid').click(function() {
+        setViewButtonsFor('grid');
+        $('.fileinfo').data('view', 'grid');
+        enable_disable_btn();
+        getFolderInfo($('.currentpath').val());
+        save_file_dialog_view('grid', pgAdmin.FileUtils.transId);
+      });
 
-    // Show list mode
-    $('.file_manager .list').click(function() {
-      setViewButtonsFor('list');
-      $('.fileinfo').data('view', 'list');
-      enable_disable_btn();
-      getFolderInfo($('.currentpath').val());
-      save_file_dialog_view('list', pgAdmin.FileUtils.transId);
-    });
+      // Show list mode
+      $('.file_manager .list').click(function() {
+        setViewButtonsFor('list');
+        $('.fileinfo').data('view', 'list');
+        enable_disable_btn();
+        getFolderInfo($('.currentpath').val());
+        save_file_dialog_view('list', pgAdmin.FileUtils.transId);
+      });
 
-    // Provide initial values for upload form, status, etc.
-    pgAdmin.FileUtils.setUploader(fileRoot);
+      // Provide initial values for upload form, status, etc.
+      pgAdmin.FileUtils.setUploader(fileRoot);
 
-    var data;
-    this.data = data = {
-      'Capabilities': capabilities
-    };
+      var data;
+      this.data = data = {
+        'Capabilities': capabilities,
+      };
 
-    function InputObject() {
-      this.init= function(cap) {
-        var self = this,
+      function InputObject() {
+        this.init = function(cap) {
+          var self = this,
             check_obj = function(path, check) {
 
-              var path = decodeURI(path);
+              path = decodeURI(path);
               if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
                 if (
                   has_capability(self.data_cap, 'select_folder')
@@ -1360,13 +1299,13 @@ pgAdmin.FileUtils = {
                   // set selected folder name in breadcrums
                   $('.file_manager #uploader .input-path').hide();
                   $('.file_manager #uploader .show_selected_file').remove();
-                  $('<span class="show_selected_file">'+path+'</span>').appendTo(
+                  $('<span class="show_selected_file">' + path + '</span>').appendTo(
                     '.file_manager #uploader .filemanager-path-group'
                   );
                 } else {
                   $('.file_manager_ok').addClass('disabled');
                   $('.file_manager_ok').attr('disabled', true);
-                  if(check) {
+                  if (check) {
                     // Enable/Disable level up button
                     enab_dis_level_up();
 
@@ -1388,13 +1327,13 @@ pgAdmin.FileUtils = {
                   $('.file_manager #uploader .show_selected_file').remove();
                 }
 
-                if(check) {
+                if (check) {
                   if (config.options.dialog_type == 'create_file') {
-                    var status = checkPermission(path)
+                    var status = checkPermission(path);
                     if (status) {
                       $('.file_manager').trigger('enter-key');
                     }
-                  } else if(config.options.dialog_type == 'select_file') {
+                  } else if (config.options.dialog_type == 'select_file') {
                     var file_status = getFileInfo(path);
                     if (file_status) {
                       $('.file_manager').trigger('enter-key');
@@ -1404,331 +1343,331 @@ pgAdmin.FileUtils = {
               }
             };
 
-        self.data_cap = cap;
+          self.data_cap = cap;
 
-        $('.storage_dialog #uploader .input-path').keyup(function(e) {
-          if(e.keyCode == 13) {
-            e.stopPropagation();
-            var path = $(this).val();
-            if(path == '') {
-              path = '/';
-            }
+          $('.storage_dialog #uploader .input-path').keyup(function(e) {
+            if (e.keyCode == 13) {
+              e.stopPropagation();
+              var path = $(this).val();
+              if (path == '') {
+                path = '/';
+              }
 
-            if(config.options.platform_type === "win32") {
-              path = path.replace(/\//g, '\\')
-            } else {
-              path = path.replace(/\\/g, '/')
-              if (!S.startsWith(path, '/')) {
-                path = '/' + path;
+              if (config.options.platform_type === 'win32') {
+                path = path.replace(/\//g, '\\');
+              } else {
+                path = path.replace(/\\/g, '/');
+                if (!S.startsWith(path, '/')) {
+                  path = '/' + path;
+                }
               }
-            }
 
-            $(this).val(path);
-            setTimeout(function() {
-              check_obj(path, true);
-            });
+              $(this).val(path);
+              setTimeout(function() {
+                check_obj(path, true);
+              });
 
-            return;
-          }
-          check_obj($(this).val(), false);
-        });
-      }
-      this.set_cap = function(cap) {
-        this.data_cap = cap;
+              return;
+            }
+            check_obj($(this).val(), false);
+          });
+        };
+        this.set_cap = function(cap) {
+          this.data_cap = cap;
+        };
       }
-    }
-    var input_object = new InputObject();
-    input_object.init(data);
-
-    // Upload file
-    if (has_capability(data, 'upload')) {
-      Dropzone.autoDiscover = false;
-  // we remove simple file upload element
-  $('.file-input-container').remove();
-  $('.upload').remove();
-  $( ".create" ).before( '<button value="Upload" type="button" title="Upload File" name="upload" id="upload" class="btn fa fa-upload upload" tabindex="6"><span></span></button> ' );
-
-  $('#uploader .upload').unbind().click(function() {
-    // we create prompt
-    var msg  = '<div id="dropzone-container">' +
-          '<button class="fa fa-times dz_cross_btn" tabindex="7"></button>' +
-          '<div id="multiple-uploads" class="dropzone"></div>' +
-          '<div class="prompt-info">' + lg.file_size_limit +
-          config.upload.fileSizeLimit + ' ' + lg.mb + '.</div>',
-          error_flag = false,
-          path = $('.currentpath').val(),
-          filesizelimit = config.upload.fileSizeLimit,
-          // default dropzone value
-          fileSize = (filesizelimit != 'auto') ? filesizelimit : 256,
-          acceptFiles;
-
-    if (config.security.uploadPolicy == 'DISALLOW_ALL') {
-      acceptFiles = '.' + config.security.uploadRestrictions.join(',.');
-    } else {
-      // We allow any extension since we have no easy way to handle the the
-      // built-in `acceptedFiles` params would be handled later by the
-      // connector.
-      acceptFiles = null;
-    }
+      var input_object = new InputObject();
+      input_object.init(data);
+
+      // Upload file
+      if (has_capability(data, 'upload')) {
+        Dropzone.autoDiscover = false;
+        // we remove simple file upload element
+        $('.file-input-container').remove();
+        $('.upload').remove();
+        $('.create').before('<button value="Upload" type="button" title="Upload File" name="upload" id="upload" class="btn fa fa-upload upload" tabindex="6"><span></span></button> ');
+
+        $('#uploader .upload').unbind().click(function() {
+          // we create prompt
+          var msg = '<div id="dropzone-container">' +
+            '<button class="fa fa-times dz_cross_btn" tabindex="7"></button>' +
+            '<div id="multiple-uploads" class="dropzone"></div>' +
+            '<div class="prompt-info">' + lg.file_size_limit +
+            config.upload.fileSizeLimit + ' ' + lg.mb + '.</div>',
+            path = $('.currentpath').val(),
+            filesizelimit = config.upload.fileSizeLimit,
+            // default dropzone value
+            fileSize = (filesizelimit != 'auto') ? filesizelimit : 256,
+            acceptFiles;
+
+          if (config.security.uploadPolicy == 'DISALLOW_ALL') {
+            acceptFiles = '.' + config.security.uploadRestrictions.join(',.');
+          } else {
+            // We allow any extension since we have no easy way to handle the the
+            // built-in `acceptedFiles` params would be handled later by the
+            // connector.
+            acceptFiles = null;
+          }
 
-    $('.file_manager .upload_file').toggle();
-    $('.file_manager .upload_file').html(msg);
-
-    //var previewTemplate = '<div id="dropzone-container">';
-    var previewTemplate = '<div class="file_upload_main dz-preview dz-file-preview">'+
-          '<div class="show_error">' +
-          '<p class="size dz-size" data-dz-size></p>' +
-          '<p class="name dz-filename" data-dz-name></p>' +
-          '</div>' +
-          '<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>' +
-          '<div class="dz-success-mark"><span></span></div>' +
-          '<div class="dz-error-mark"><span></span></div>' +
-          '<div class="dz-error-message"><span data-dz-errormessage></span></div>' +
-          '<a href="javascript:void(0);" class="fa fa-trash dz_file_remove" data-dz-remove></a>' +
-          '</div>';
-
-    $("div#multiple-uploads").dropzone({
-      paramName: "newfile",
-      url: pgAdmin.FileUtils.fileConnector,
-      maxFilesize: fileSize,
-      maxFiles: config.upload.number,
-      addRemoveLinks: true,
-      previewTemplate: previewTemplate,
-      parallelUploads: config.upload.number,
-      dictMaxFilesExceeded: lg.dz_dictMaxFilesExceeded.replace(
-        "%s", config.upload.number
-      ),
-      dictDefaultMessage: lg.dz_dictDefaultMessage,
-      dictInvalidFileType: lg.dz_dictInvalidFileType,
-      dictFileTooBig: lg.file_too_big + ' ' + lg.file_size_limit +
-        config.upload.fileSizeLimit + ' ' + lg.mb,
-      acceptedFiles: acceptFiles,
-      autoProcessQueue: true,
-      init: function() {
-        var dropzone = this;
-
-        $('.dz_cross_btn').unbind().on('click', function() {
           $('.file_manager .upload_file').toggle();
+          $('.file_manager .upload_file').html(msg);
+
+          //var previewTemplate = '<div id="dropzone-container">';
+          var previewTemplate = '<div class="file_upload_main dz-preview dz-file-preview">' +
+            '<div class="show_error">' +
+            '<p class="size dz-size" data-dz-size></p>' +
+            '<p class="name dz-filename" data-dz-name></p>' +
+            '</div>' +
+            '<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>' +
+            '<div class="dz-success-mark"><span></span></div>' +
+            '<div class="dz-error-mark"><span></span></div>' +
+            '<div class="dz-error-message"><span data-dz-errormessage></span></div>' +
+            '<a href="javascript:void(0);" class="fa fa-trash dz_file_remove" data-dz-remove></a>' +
+            '</div>';
+
+          $('div#multiple-uploads').dropzone({
+            paramName: 'newfile',
+            url: pgAdmin.FileUtils.fileConnector,
+            maxFilesize: fileSize,
+            maxFiles: config.upload.number,
+            addRemoveLinks: true,
+            previewTemplate: previewTemplate,
+            parallelUploads: config.upload.number,
+            dictMaxFilesExceeded: lg.dz_dictMaxFilesExceeded.replace(
+              '%s', config.upload.number
+            ),
+            dictDefaultMessage: lg.dz_dictDefaultMessage,
+            dictInvalidFileType: lg.dz_dictInvalidFileType,
+            dictFileTooBig: lg.file_too_big + ' ' + lg.file_size_limit +
+              config.upload.fileSizeLimit + ' ' + lg.mb,
+            acceptedFiles: acceptFiles,
+            autoProcessQueue: true,
+            init: function() {
+              $('.dz_cross_btn').unbind().on('click', function() {
+                $('.file_manager .upload_file').toggle();
+              });
+            },
+            sending: function(file, xhr, formData) {
+              formData.append('mode', 'add');
+              formData.append('currentpath', path);
+              $('.upload_file .dz_cross_btn').attr('disabled', 'disabled');
+              setTimeout(function() {}, 10000);
+            },
+            success: function(file, response) {
+              var data = response.data.result,
+                $this = $(file.previewTemplate);
+
+              if (data.Code == 1) {
+                setTimeout(function() {
+                  $this.find('.dz-upload').addClass('success');
+                }, 1000);
+                $this.find('.dz-upload').css('width', '100%').html('100%');
+                Alertify.success(lg.upload_success);
+              } else {
+                $this.find('.dz-upload').addClass('error');
+                $this.find('.dz-upload').css('width', '0%').html('0%');
+                Alertify.error(data.Error);
+              }
+              getFolderInfo(path);
+            },
+            totaluploadprogress: function() {},
+            complete: function(file) {
+              if (file.status == 'error') {
+                Alertify.error(lg.upload_error);
+              }
+              $('.upload_file .dz_cross_btn').removeAttr('disabled');
+              getFolderInfo(path);
+            },
+          });
         });
-      },
-      sending: function(file, xhr, formData) {
-        formData.append("mode", "add");
-        formData.append("currentpath", path);
-        $('.upload_file .dz_cross_btn').attr('disabled', 'disabled');
-        setTimeout(function() {}, 10000);
-      },
-      success: function(file, response) {
-        var data = response.data.result,
-            $this = $(file.previewTemplate);
+      }
 
-        if (data.Code == 1) {
-          setTimeout(function() {
-            $this.find(".dz-upload").addClass("success");
-          }, 1000);
-          $this.find(".dz-upload").css('width', "100%").html("100%");
-          alertify.success(lg.upload_success);
+      this.getDetailView(fileRoot);
+    },
+    /*
+     * Sets the folder status, upload, and new folder functions
+     * to the path specified. Called on initial page load and
+     * whenever a new directory is selected.
+     */
+    setUploader: function(path) {
+      var config = this.config;
+      var lg = this.lg;
+      $('.storage_dialog #uploader').find('a').remove();
+      $('.storage_dialog #uploader').find('b').remove();
+
+      if (config.options.platform_type === 'win32') {
+        path = path.replace(/\//g, '\\');
+      } else {
+        path = path.replace(/\\/g, '/');
+      }
+
+      path = decodeURI(path);
+      if (config.options.platform_type === 'win32') {
+        if (config.options.show_volumes && path == '\\') {
+          $('.storage_dialog #uploader .input-path').val('');
         } else {
-          $this.find(".dz-upload").addClass("error");
-          $this.find(".dz-upload").css('width', "0%").html("0%");
-          alertify.error(data.Error);
-        }
-        getFolderInfo(path);
-      },
-      totaluploadprogress: function(progress) {},
-      complete: function(file) {
-        if (file.status == "error") {
-          alertify.error(lg.upload_error);
+          $('.storage_dialog #uploader .input-path').val(path);
         }
-        $('.upload_file .dz_cross_btn').removeAttr('disabled');
-        getFolderInfo(path);
+      } else if (!config.options.platform_type === 'win32' &&
+        (path == '' || !S.startsWith(path, '/'))) {
+        path = '/' + path;
+        $('.storage_dialog #uploader .input-path').val(path);
+      } else {
+        $('.storage_dialog #uploader .input-path').val(path);
       }
-    });
-  });
-}
-
-    this.getDetailView(fileRoot);
-  },
-   /*
-   * Sets the folder status, upload, and new folder functions
-   * to the path specified. Called on initial page load and
-   * whenever a new directory is selected.
-   */
-  setUploader: function(path) {
-    var config = this.config;
-    var lg = this.lg;
-    $('.storage_dialog #uploader').find('a').remove();
-    $('.storage_dialog #uploader').find('b').remove();
-
-    if(config.options.platform_type === "win32") {
-      path = path.replace(/\//g, '\\')
-    } else {
-      path = path.replace(/\\/g, '/')
-    }
 
-    path = decodeURI(path);
-    if (config.options.platform_type === "win32") {
-      if (config.options.show_volumes && path == '\\') {
-        $('.storage_dialog #uploader .input-path').val('');
+      if (path.lastIndexOf('\\') == -1 && path.lastIndexOf('/') == -1) {
+        $('.currentpath').val(path);
+      } else if (path.lastIndexOf('/') > path.lastIndexOf('\\')) {
+        $('.currentpath').val(path.substr(0, path.lastIndexOf('/') + 1));
       } else {
-          $('.storage_dialog #uploader .input-path').val(path);
+        $('.currentpath').val(path.substr(0, path.lastIndexOf('\\') + 1));
       }
-    } else if (!config.options.platform_type === "win32" &&
-          (path == '' || !S.startsWith(path, '/'))) {
-      path = '/' + path;
-      $('.storage_dialog #uploader .input-path').val(path);
-    } else {
-      $('.storage_dialog #uploader .input-path').val(path);
-    }
-
-    if( path.lastIndexOf('\\') == -1 && path.lastIndexOf('/') == -1) {
-      $('.currentpath').val(path);
-    } else if(path.lastIndexOf('/') > path.lastIndexOf('\\')) {
-      $('.currentpath').val(path.substr(0, path.lastIndexOf('/') + 1));
-    } else {
-      $('.currentpath').val(path.substr(0, path.lastIndexOf('\\') + 1));
-    }
 
-    enab_dis_level_up();
-    if ($('.storage_dialog #uploader h1 span').length === 0) {
-      $('<span>'+lg.current_folder+'</span>').appendTo($('.storage_dialog #uploader h1'));
-    }
+      enab_dis_level_up();
+      if ($('.storage_dialog #uploader h1 span').length === 0) {
+        $('<span>' + lg.current_folder + '</span>').appendTo($('.storage_dialog #uploader h1'));
+      }
 
-    $('.storage_dialog #uploader .input-path').attr('title', path);
-    $('.storage_dialog #uploader .input-path').attr('data-path', path);
+      $('.storage_dialog #uploader .input-path').attr('title', path);
+      $('.storage_dialog #uploader .input-path').attr('data-path', path);
 
-    // create new folder
-    $('.create').unbind().click(function() {
-      var foldername =  lg.new_folder;
-      var $file_element,
+      // create new folder
+      $('.create').unbind().click(function() {
+        var foldername = lg.new_folder;
+        var $file_element,
           $file_element_list,
           folder_div;
 
 
-      $('.file_manager button.create').attr('disabled', 'disabled');
-      if ($('.fileinfo').data('view') == 'grid') {
-
-        // template for creating new folder
-        folder_div =
-          "<li class='cap_download cap_delete cap_select_file cap_select_folder cap_rename cap_create cap_upload'>" +
-          "<div class='clip'><span data-alt='' class='fa fa-folder-open fm_folder'></span></div>" +
-          "<p><input type='text' class='fm_file_rename'><span title=''>New_Folder</span></p>" +
-          "<span class='meta size'></span><span class='meta created'></span><span class='meta modified'></span></li>";
-
-        path = $('.currentpath').val();
-        $file_element =  $(folder_div);
-        $('.fileinfo #contents.grid').append($file_element);
-        $file_element.find('p span').toggle();
-        $file_element.find('p input').toggle().val(lg.new_folder).select();
-
-        // rename folder/file on pressing enter key
-        $('.file_manager').bind().on('keyup', function(e) {
-          if (e.keyCode == 13) {
-            e.stopPropagation();
-            $file_element.find('p input').trigger('blur');
-          }
-        });
+        $('.file_manager button.create').attr('disabled', 'disabled');
+        if ($('.fileinfo').data('view') == 'grid') {
 
-        // rename folder/file on blur
-        $file_element.find('p input').on('blur', function(e) {
-          $('.file_manager button.create').removeAttr('disabled');
-          var text_value = $file_element.find('p input').val();
+          // template for creating new folder
+          folder_div =
+            '<li class=\'cap_download cap_delete cap_select_file cap_select_folder cap_rename cap_create cap_upload\'>' +
+            '<div class=\'clip\'><span data-alt=\'\' class=\'fa fa-folder-open fm_folder\'></span></div>' +
+            '<p><input type=\'text\' class=\'fm_file_rename\'><span title=\'\'>New_Folder</span></p>' +
+            '<span class=\'meta size\'></span><span class=\'meta created\'></span><span class=\'meta modified\'></span></li>';
 
           path = $('.currentpath').val();
+          $file_element = $(folder_div);
+          $('.fileinfo #contents.grid').append($file_element);
+          $file_element.find('p span').toggle();
+          $file_element.find('p input').toggle().val(lg.new_folder).select();
 
-          $file_element.find('p input').toggle();
-          $file_element.find('p span').toggle().html(text_value);
-          if (text_value === undefined) {
-            text_value = lg.new_folder;
-          }
-          getFolderName(text_value);
-          getFolderInfo(path);
-        });
+          // rename folder/file on pressing enter key
+          $('.file_manager').bind().on('keyup', function(e) {
+            if (e.keyCode == 13) {
+              e.stopPropagation();
+              $file_element.find('p input').trigger('blur');
+            }
+          });
 
-      } else if ($('.fileinfo').data('view') == 'list') {
-        // template to create new folder in table view
-        folder_div = $(
-          "<tr class='cap_download cap_delete cap_select_file cap_select_folder cap_rename cap_create cap_upload'>" +
-          "<td title='' class='fa fa-folder-open tbl_folder'>" +
-          "<p><input type='text' class='fm_file_rename'><span>" +
-          lg.new_folder + "</span></p>" +
-          "</td><td><span title=''></span></td>" +
-          "<td></td>" +
-          "</tr>"
-        );
+          // rename folder/file on blur
+          $file_element.find('p input').on('blur', function() {
+            $('.file_manager button.create').removeAttr('disabled');
+            var text_value = $file_element.find('p input').val();
 
-        $file_element_list =  $(folder_div);
-        $('.fileinfo #contents.list').prepend($file_element_list);
-        $file_element_list.find('p span').toggle();
-        $file_element_list.find('p input').toggle().val(lg.new_folder).select();
+            path = $('.currentpath').val();
 
-        // rename folder/file on pressing enter key
-        $('.file_manager').bind().on('keyup', function(e) {
-          if (e.keyCode == 13) {
-            e.stopPropagation();
-            $file_element_list.find('p input').trigger('blur');
-          }
-        });
+            $file_element.find('p input').toggle();
+            $file_element.find('p span').toggle().html(text_value);
+            if (text_value === undefined) {
+              text_value = lg.new_folder;
+            }
+            getFolderName(text_value);
+            getFolderInfo(path);
+          });
 
-        // rename folder/file on blur
-        $file_element_list.find('p input').on('blur', function(e) {
-          $('.file_manager button.create').removeAttr('disabled');
-          var text_value = $file_element_list.find('p input').val();
-          path = $('.currentpath').val();
-          $file_element_list.find('p input').toggle();
-          $file_element_list.find('p span').toggle().html(text_value);
-          if (text_value === undefined) {
-            text_value = lg.new_folder;
-          }
-          getFolderName(text_value);
-          getFolderInfo(path);
-        });
-      }
+        } else if ($('.fileinfo').data('view') == 'list') {
+          // template to create new folder in table view
+          folder_div = $(
+            '<tr class=\'cap_download cap_delete cap_select_file cap_select_folder cap_rename cap_create cap_upload\'>' +
+            '<td title=\'\' class=\'fa fa-folder-open tbl_folder\'>' +
+            '<p><input type=\'text\' class=\'fm_file_rename\'><span>' +
+            lg.new_folder + '</span></p>' +
+            '</td><td><span title=\'\'></span></td>' +
+            '<td></td>' +
+            '</tr>'
+          );
+
+          $file_element_list = $(folder_div);
+          $('.fileinfo #contents.list').prepend($file_element_list);
+          $file_element_list.find('p span').toggle();
+          $file_element_list.find('p input').toggle().val(lg.new_folder).select();
+
+          // rename folder/file on pressing enter key
+          $('.file_manager').bind().on('keyup', function(e) {
+            if (e.keyCode == 13) {
+              e.stopPropagation();
+              $file_element_list.find('p input').trigger('blur');
+            }
+          });
 
-      // create a new folder
-      var getFolderName = function(value) {
-        var fname = value;
-
-        if (fname != '') {
-          foldername = fname;
-          var d = new Date(); // to prevent IE cache issues
-          $.getJSON(pgAdmin.FileUtils.fileConnector + '?mode=addfolder&path=' + $('.currentpath').val() + '&name=' + foldername, function(resp) {
-            var result = resp.data.result;
-            if (result.Code === 1) {
-              alertify.success(lg.successful_added_folder);
-              getFolderInfo(result.Parent);
-            } else {
-              alertify.error(result.Error);
+          // rename folder/file on blur
+          $file_element_list.find('p input').on('blur', function() {
+            $('.file_manager button.create').removeAttr('disabled');
+            var text_value = $file_element_list.find('p input').val();
+            path = $('.currentpath').val();
+            $file_element_list.find('p input').toggle();
+            $file_element_list.find('p span').toggle().html(text_value);
+            if (text_value === undefined) {
+              text_value = lg.new_folder;
             }
+            getFolderName(text_value);
+            getFolderInfo(path);
           });
-        } else {
-          alertify.error(lg.no_foldername);
         }
-      };
 
-    });
-  },
-  /* Decides whether to retrieve file or folder info based on
-   * the path provided.
-   */
-  getDetailView: function(path) {
-    if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
-      var allowed_types = this.config.options.allowed_file_types;
-      var set_type = allowed_types[0];
-      if (allowed_types[0] == "*") {
-        set_type = allowed_types[1];
+        // create a new folder
+        var getFolderName = function(value) {
+          var fname = value;
+
+          if (fname != '') {
+            foldername = fname;
+            // Add _ variable in URL for avoiding the caching
+            $.getJSON(
+              pgAdmin.FileUtils.fileConnector + '?_=' + Date.now() + 'mode=addfolder&path=' + $('.currentpath').val() + '&name=' + foldername,
+              function(resp) {
+                var result = resp.data.result;
+                if (result.Code === 1) {
+                  Alertify.success(lg.successful_added_folder);
+                  getFolderInfo(result.Parent);
+                } else {
+                  Alertify.error(result.Error);
+                }
+              }
+            );
+          } else {
+            Alertify.error(lg.no_foldername);
+          }
+        };
+
+      });
+    },
+    /* Decides whether to retrieve file or folder info based on
+     * the path provided.
+     */
+    getDetailView: function(path) {
+      if (path.lastIndexOf('/') == path.length - 1 || path.lastIndexOf('\\') == path.length - 1) {
+        var allowed_types = this.config.options.allowed_file_types;
+        var set_type = allowed_types[0];
+        if (allowed_types[0] == '*') {
+          set_type = allowed_types[1];
+        }
+        getFolderInfo(path, set_type);
       }
-      getFolderInfo(path, set_type);
-    }
-  },
-  // helpful in show/hide toolbar button for Windows
-  hideButtons: function() {
+    },
+    // helpful in show/hide toolbar button for Windows
+    hideButtons: function() {
       return (
         this.config.options.platform_type == 'win32' &&
         $('.currentpath').val() === ''
       );
-  },
+    },
 
-};
-return pgAdmin.FileUtils;
+  };
+  return pgAdmin.FileUtils;
 });
 //@ sourceURL=utility.js
diff --git a/web/pgadmin/misc/sql/static/js/sql.js b/web/pgadmin/misc/sql/static/js/sql.js
index 1caf048b..1a6200d8 100644
--- a/web/pgadmin/misc/sql/static/js/sql.js
+++ b/web/pgadmin/misc/sql/static/js/sql.js
@@ -1,7 +1,7 @@
 define('misc.sql', [
-  'sources/gettext', 'underscore', 'underscore.string', 'jquery', 'pgadmin.browser',
-  'alertify', 'pgadmin.alertifyjs'
-], function(gettext, _, S, $, pgBrowser, Alertify) {
+  'sources/gettext', 'underscore', 'underscore.string', 'jquery',
+  'sources/pgadmin', 'pgadmin.browser', 'pgadmin.alertifyjs',
+], function(gettext, _, S, $, pgAdmin, pgBrowser, Alertify) {
 
   pgBrowser.ShowNodeSQL = pgBrowser.ShowNodeSQL || {};
 
@@ -28,7 +28,8 @@ define('misc.sql', [
       );
 
       pgBrowser.Events.on(
-        'pgadmin:browser:node:updated', function() {
+        'pgadmin:browser:node:updated',
+        function() {
           if (this.sqlPanels && this.sqlPanels.length) {
             $(this.sqlPanels[0]).data('node-prop', '');
             this.sqlPanelVisibilityChanged(this.sqlPanels[0]);
@@ -49,9 +50,8 @@ define('misc.sql', [
               );
             }
           }.bind(this)
-          );
-      }
-      else {
+        );
+      } else {
         if ((sqlPanels[0].isVisible()) || sqlPanels.length != 1) {
           pgBrowser.Events.on('pgadmin-browser:tree:selected', this.showSQL);
         }
@@ -67,15 +67,13 @@ define('misc.sql', [
       this.timeout && clearTimeout(this.timeout);
 
       var that = this;
-      this.timeout =  setTimeout(
+      this.timeout = setTimeout(
         function() {
           var sql = '';
           if (node) {
-            sql = '-- ' + gettext("No SQL could be generated for the selected object.");
-            var self = this,
-                n_type = data._type,
-                n_value = -1,
-                treeHierarchy = node.getTreeNodeHierarchy(item);
+            sql = '-- ' + gettext('No SQL could be generated for the selected object.');
+            var n_type = data._type,
+              treeHierarchy = node.getTreeNodeHierarchy(item);
 
             // Avoid unnecessary reloads
             if (_.isEqual($(that.sqlPanels[0]).data('node-prop'), treeHierarchy)) {
@@ -88,19 +86,19 @@ define('misc.sql', [
 
               sql = '';
               var url = node.generate_url(item, 'sql', data, true),
-                  timer;
+                timer;
 
               $.ajax({
                 url: url,
-                type:'GET',
-                beforeSend: function(jqXHR, settings) {
+                type: 'GET',
+                beforeSend: function() {
                   // Generate a timer for the request
-                  timer = setTimeout(function(){
-                  // notify user if request is taking longer than 1 second
+                  timer = setTimeout(function() {
+                    // Notify user if request is taking longer than 1 second
 
-                  pgAdmin.Browser.editor.setValue(
-                    gettext("Retrieving data from the server...")
-                  );
+                    pgAdmin.Browser.editor.setValue(
+                      gettext('Retrieving data from the server...')
+                    );
                   }, 1000);
                 },
                 success: function(res) {
@@ -114,22 +112,19 @@ define('misc.sql', [
                   pgBrowser.Events.trigger(
                     'pgadmin:node:retrieval:error', 'sql', xhr, error, message, item
                   );
-                  if (
-                    !Alertify.pgHandleItemError(xhr, error, message, {
-                      item: item, info: treeHierarchy
-                    })
-                  ) {
+                  if (!Alertify.pgHandleItemError(xhr, error, message, {
+                    item: item,
+                    info: treeHierarchy,
+                  })) {
                     Alertify.pgNotifier(
                       error, xhr,
-                      S(gettext("Error retrieving the information - %s")).sprintf(
+                      S(gettext('Error retrieving the information - %s')).sprintf(
                         message || _label
                       ).value(),
-                      function() {
-                        console.log(arguments);
-                      }
+                      function() {}
                     );
                   }
-                }
+                },
               });
             }
           }
@@ -142,9 +137,9 @@ define('misc.sql', [
     sqlPanelVisibilityChanged: function(panel) {
       if (panel.isVisible()) {
         var t = pgBrowser.tree,
-            i = t.selected(),
-            d = i && t.itemData(i),
-            n = i && d && pgBrowser.Nodes[d._type];
+          i = t.selected(),
+          d = i && t.itemData(i),
+          n = i && d && pgBrowser.Nodes[d._type];
 
         pgBrowser.ShowNodeSQL.showSQL.apply(pgBrowser.ShowNodeSQL, [i, d, n]);
 
@@ -154,8 +149,8 @@ define('misc.sql', [
         // We don't need to listen the tree item selection event.
         pgBrowser.Events.off('pgadmin-browser:tree:selected', pgBrowser.ShowNodeSQL.showSQL);
       }
-    }
+    },
   });
 
   return pgBrowser.ShowNodeSQL;
-});
+});
\ No newline at end of file
diff --git a/web/pgadmin/misc/static/explain/js/explain.js b/web/pgadmin/misc/static/explain/js/explain.js
index b726250b..7e25b2ed 100644
--- a/web/pgadmin/misc/static/explain/js/explain.js
+++ b/web/pgadmin/misc/static/explain/js/explain.js
@@ -1,33 +1,32 @@
-define (
-  'pgadmin.misc.explain',
-  ['sources/url_for', 'jquery', 'underscore', 'underscore.string', 'sources/pgadmin', 'backbone', 'snapsvg'],
-  function(url_for, $, _, S, pgAdmin, Backbone, Snap) {
-
-pgAdmin = pgAdmin || window.pgAdmin || {};
-var pgExplain = pgAdmin.Explain;
-
-// Snap.svg plug-in to write multitext as image name
-Snap.plugin(function (Snap, Element, Paper, glob) {
-  Paper.prototype.multitext = function (x, y, txt, max_width, attributes) {
-    var svg = Snap(),
-        abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
-        isWordBroken = false,
+define('pgadmin.misc.explain', [
+  'sources/url_for', 'jquery', 'underscore', 'underscore.string',
+  'sources/pgadmin', 'backbone', 'snapsvg',
+], function(url_for, $, _, S, pgAdmin, Backbone, Snap) {
+
+  pgAdmin = pgAdmin || window.pgAdmin || {};
+
+  // Snap.svg plug-in to write multitext as image name
+  Snap.plugin(function(Snap, Element, Paper) {
+    Paper.prototype.multitext = function(x, y, txt, max_width, attributes) {
+      var svg = Snap(),
+        abc = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
         temp = svg.text(0, 0, abc);
 
-    temp.attr(attributes);
+      temp.attr(attributes);
 
-    /*
-     * Find letter width in pixels and
-     * index from where the text should be broken
-     */
-    var letter_width = temp.getBBox().width / abc.length,
+      /*
+       * Find letter width in pixels and
+       * index from where the text should be broken
+       */
+      var letter_width = temp.getBBox().width / abc.length,
         word_break_index = Math.round((max_width / letter_width)) - 1;
 
-    svg.remove();
+      svg.remove();
 
-    var words = txt.split(" "),
+      var words = txt.split(' '),
         width_so_far = 0,
-        lines=[], curr_line = '',
+        lines = [],
+        curr_line = '',
         /*
          * Function to divide string into multiple lines
          * and store them in an array if it size crosses
@@ -35,7 +34,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
          */
         splitTextInMultiLine = function(leading, so_far, line) {
           var l = line.length,
-              res = [];
+            res = [];
 
           if (l == 0)
             return res;
@@ -47,268 +46,432 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
             res.push(leading + ' ' + line);
           } else {
             if (leading)
-                res.push(leading);
+              res.push(leading);
             if (line.length > word_break_index + 1)
-                res.push(line.slice(0, word_break_index) + '-');
+              res.push(line.slice(0, word_break_index) + '-');
             else
-                res.push(line);
+              res.push(line);
             res = res.concat(splitTextInMultiLine('', 0, line.slice(word_break_index)));
           }
 
           return res;
         };
 
-    for (var i = 0; i < words.length; i++) {
-      var tmpArr = splitTextInMultiLine(
-            curr_line, width_so_far, words[i]
-          );
+      for (var i = 0; i < words.length; i++) {
+        var tmpArr = splitTextInMultiLine(
+          curr_line, width_so_far, words[i]
+        );
 
-      if (curr_line) {
-        lines = lines.slice(0, lines.length - 1);
+        if (curr_line) {
+          lines = lines.slice(0, lines.length - 1);
+        }
+        lines = lines.concat(tmpArr);
+        curr_line = lines[lines.length - 1];
+        width_so_far = (curr_line.length * letter_width);
       }
-      lines = lines.concat(tmpArr);
-      curr_line = lines[lines.length - 1];
-      width_so_far = (curr_line.length * letter_width);
-    }
-
-    // Create multiple tspan for each string in array
-    var t = this.text(x,y,lines).attr(attributes);
-    t.selectAll("tspan:nth-child(n+2)").attr({
-      dy: "1.2em",
-      x: x
-    });
-    return t;
-  };
-});
 
-if (pgAdmin.Explain)
+      // Create multiple tspan for each string in array
+      var t = this.text(x, y, lines).attr(attributes);
+      t.selectAll('tspan:nth-child(n+2)').attr({
+        dy: '1.2em',
+        x: x,
+      });
+      return t;
+    };
+  });
+
+  if (pgAdmin.Explain)
     return pgAdmin.Explain;
 
-var pgExplain = pgAdmin.Explain = {
-   // Prefix path where images are stored
-   prefix: url_for('misc.index') + 'static/explain/img/'
-};
+  var pgExplain = pgAdmin.Explain = {
+    // Prefix path where images are stored
+    prefix: url_for('misc.index') + 'static/explain/img/',
+  };
 
-/*
- * A map which is used to fetch the image to be drawn and
- * text which will appear below it
- */
-var imageMapper = {
-    "Aggregate" : {
-        "image":"ex_aggregate.svg", "image_text":"Aggregate"
+  /*
+   * A map which is used to fetch the image to be drawn and
+   * text which will appear below it
+   */
+  var imageMapper = {
+    'Aggregate': {
+      'image': 'ex_aggregate.svg',
+      'image_text': 'Aggregate',
+    },
+    'Append': {
+      'image': 'ex_append.svg',
+      'image_text': 'Append',
+    },
+    'Bitmap Index Scan': function(data) {
+      return {
+        'image': 'ex_bmp_index.svg',
+        'image_text': data['Index Name'],
+      };
+    },
+    'Bitmap Heap Scan': function(data) {
+      return {
+        'image': 'ex_bmp_heap.svg',
+        'image_text': data['Relation Name'],
+      };
+    },
+    'BitmapAnd': {
+      'image': 'ex_bmp_and.svg',
+      'image_text': 'Bitmap AND',
+    },
+    'BitmapOr': {
+      'image': 'ex_bmp_or.svg',
+      'image_text': 'Bitmap OR',
+    },
+    'CTE Scan': {
+      'image': 'ex_cte_scan.svg',
+      'image_text': 'CTE Scan',
+    },
+    'Function Scan': {
+      'image': 'ex_result.svg',
+      'image_text': 'Function Scan',
+    },
+    'Foreign Scan': {
+      'image': 'ex_foreign_scan.svg',
+      'image_text': 'Foreign Scan',
+    },
+    'Gather': {
+      'image': 'ex_gather_motion.svg',
+      'image_text': 'Gather',
+    },
+    'Group': {
+      'image': 'ex_group.svg',
+      'image_text': 'Group',
+    },
+    'GroupAggregate': {
+      'image': 'ex_aggregate.svg',
+      'image_text': 'Group Aggregate',
+    },
+    'Hash': {
+      'image': 'ex_hash.svg',
+      'image_text': 'Hash',
+    },
+    'Hash Join': function(data) {
+      if (!data['Join Type']) return {
+        'image': 'ex_join.svg',
+        'image_text': 'Join',
+      };
+      switch (data['Join Type']) {
+      case 'Anti':
+        return {
+          'image': 'ex_hash_anti_join.svg',
+          'image_text': 'Hash Anti Join',
+        };
+      case 'Semi':
+        return {
+          'image': 'ex_hash_semi_join.svg',
+          'image_text': 'Hash Semi Join',
+        };
+      default:
+        return {
+          'image': 'ex_hash.svg',
+          'image_text': String('Hash ' + data['Join Type'] + ' Join'),
+        };
+      }
+    },
+    'HashAggregate': {
+      'image': 'ex_aggregate.svg',
+      'image_text': 'Hash Aggregate',
+    },
+    'Index Only Scan': function(data) {
+      return {
+        'image': 'ex_index_only_scan.svg',
+        'image_text': data['Index Name'],
+      };
+    },
+    'Index Scan': function(data) {
+      return {
+        'image': 'ex_index_scan.svg',
+        'image_text': data['Index Name'],
+      };
+    },
+    'Index Scan Backword': {
+      'image': 'ex_index_scan.svg',
+      'image_text': 'Index Backward Scan',
+    },
+    'Limit': {
+      'image': 'ex_limit.svg',
+      'image_text': 'Limit',
+    },
+    'LockRows': {
+      'image': 'ex_lock_rows.svg',
+      'image_text': 'Lock Rows',
+    },
+    'Materialize': {
+      'image': 'ex_materialize.svg',
+      'image_text': 'Materialize',
+    },
+    'Merge Append': {
+      'image': 'ex_merge_append.svg',
+      'image_text': 'Merge Append',
+    },
+    'Merge Join': function(data) {
+      switch (data['Join Type']) {
+      case 'Anti':
+        return {
+          'image': 'ex_merge_anti_join.svg',
+          'image_text': 'Merge Anti Join',
+        };
+      case 'Semi':
+        return {
+          'image': 'ex_merge_semi_join.svg',
+          'image_text': 'Merge Semi Join',
+        };
+      default:
+        return {
+          'image': 'ex_merge.svg',
+          'image_text': String('Merge ' + data['Join Type'] + ' Join'),
+        };
+      }
     },
-    'Append' : {
-        "image":"ex_append.svg","image_text":"Append"
+    'ModifyTable': function(data) {
+      switch (data['Operation']) {
+      case 'Insert':
+        return {
+          'image': 'ex_insert.svg',
+          'image_text': 'Insert',
+        };
+      case 'Update':
+        return {
+          'image': 'ex_update.svg',
+          'image_text': 'Update',
+        };
+      case 'Delete':
+        return {
+          'image': 'ex_delete.svg',
+          'image_text': 'Delete',
+        };
+      }
     },
-    "Bitmap Index Scan" : function(data) {
+    'Nested Loop': function(data) {
+      switch (data['Join Type']) {
+      case 'Anti':
+        return {
+          'image': 'ex_nested_loop_anti_join.svg',
+          'image_text': 'Nested Loop Anti Join',
+        };
+      case 'Semi':
         return {
-            "image":"ex_bmp_index.svg", "image_text":data['Index Name']
+          'image': 'ex_nested_loop_semi_join.svg',
+          'image_text': 'Nested Loop Semi Join',
         };
+      default:
+        return {
+          'image': 'ex_nested.svg',
+          'image_text': 'Nested Loop ' + data['Join Type'] + ' Join',
+        };
+      }
+    },
+    'Recursive Union': {
+      'image': 'ex_recursive_union.svg',
+      'image_text': 'Recursive Union',
+    },
+    'Result': {
+      'image': 'ex_result.svg',
+      'image_text': 'Result',
+    },
+    'Sample Scan': {
+      'image': 'ex_scan.svg',
+      'image_text': 'Sample Scan',
+    },
+    'Scan': {
+      'image': 'ex_scan.svg',
+      'image_text': 'Scan',
+    },
+    'Seek': {
+      'image': 'ex_seek.svg',
+      'image_text': 'Seek',
+    },
+    'SetOp': function(data) {
+      var strategy = data['Strategy'],
+        command = data['Command'];
+
+      if (strategy == 'Hashed') {
+        if (S.startsWith(command, 'Intersect')) {
+          if (command == 'Intersect All')
+            return {
+              'image': 'ex_hash_setop_intersect_all.svg',
+              'image_text': 'Hashed Intersect All',
+            };
+          return {
+            'image': 'ex_hash_setop_intersect.svg',
+            'image_text': 'Hashed Intersect',
+          };
+        } else if (S.startsWith(command, 'Except')) {
+          if (command == 'Except All')
+            return {
+              'image': 'ex_hash_setop_except_all.svg',
+              'image_text': 'Hashed Except All',
+            };
+          return {
+            'image': 'ex_hash_setop_except.svg',
+            'image_text': 'Hash Except',
+          };
+        }
+        return {
+          'image': 'ex_hash_setop_unknown.svg',
+          'image_text': 'Hashed SetOp Unknown',
+        };
+      }
+      return {
+        'image': 'ex_setop.svg',
+        'image_text': 'SetOp',
+      };
+    },
+    'Seq Scan': function(data) {
+      return {
+        'image': 'ex_scan.svg',
+        'image_text': data['Relation Name'],
+      };
+    },
+    'Subquery Scan': {
+      'image': 'ex_subplan.svg',
+      'image_text': 'SubQuery Scan',
+    },
+    'Sort': {
+      'image': 'ex_sort.svg',
+      'image_text': 'Sort',
+    },
+    'Tid Scan': {
+      'image': 'ex_tid_scan.svg',
+      'image_text': 'Tid Scan',
+    },
+    'Unique': {
+      'image': 'ex_unique.svg',
+      'image_text': 'Unique',
+    },
+    'Values Scan': {
+      'image': 'ex_values_scan.svg',
+      'image_text': 'Values Scan',
+    },
+    'WindowAgg': {
+      'image': 'ex_window_aggregate.svg',
+      'image_text': 'Window Aggregate',
     },
-    "Bitmap Heap Scan" : function(data) {
-  return {"image":"ex_bmp_heap.svg","image_text":data['Relation Name']};
-},
-"BitmapAnd" : {"image":"ex_bmp_and.svg","image_text":"Bitmap AND"},
-"BitmapOr" : {"image":"ex_bmp_or.svg","image_text":"Bitmap OR"},
-"CTE Scan" : {"image":"ex_cte_scan.svg","image_text":"CTE Scan"},
-"Function Scan" : {"image":"ex_result.svg","image_text":"Function Scan"},
-"Foreign Scan" : {"image":"ex_foreign_scan.svg","image_text":"Foreign Scan"},
-"Gather" : {"image":"ex_gather_motion.svg","image_text":"Gather"},
-"Group" : {"image":"ex_group.svg","image_text":"Group"},
-"GroupAggregate": {"image":"ex_aggregate.svg","image_text":"Group Aggregate"},
-"Hash" : {"image":"ex_hash.svg","image_text":"Hash"},
-"Hash Join": function(data) {
-  if (!data['Join Type']) return {"image":"ex_join.svg","image_text":"Join"};
-  switch(data['Join Type']) {
-    case 'Anti': return {"image":"ex_hash_anti_join.svg","image_text":"Hash Anti Join"};
-    case 'Semi': return {"image":"ex_hash_semi_join.svg","image_text":"Hash Semi Join"};
-    default: return {"image":"ex_hash.svg","image_text":String("Hash " + data['Join Type'] + " Join" )};
-  }
-},
-"HashAggregate" : {"image":"ex_aggregate.svg","image_text":"Hash Aggregate"},
-"Index Only Scan" : function(data) {
-  return {"image":"ex_index_only_scan.svg","image_text":data['Index Name']};
-},
-"Index Scan" : function(data) {
-  return {"image":"ex_index_scan.svg","image_text":data['Index Name']};
-},
-"Index Scan Backword" : {"image":"ex_index_scan.svg","image_text":"Index Backward Scan"},
-"Limit" : {"image":"ex_limit.svg","image_text":"Limit"},
-"LockRows" : {"image":"ex_lock_rows.svg","image_text":"Lock Rows"},
-"Materialize" : {"image":"ex_materialize.svg","image_text":"Materialize"},
-"Merge Append": {"image":"ex_merge_append.svg","image_text":"Merge Append"},
-"Merge Join": function(data) {
-  switch(data['Join Type']) {
-    case 'Anti': return {"image":"ex_merge_anti_join.svg","image_text":"Merge Anti Join"};
-    case 'Semi': return {"image":"ex_merge_semi_join.svg","image_text":"Merge Semi Join"};
-    default: return {"image":"ex_merge.svg","image_text":String("Merge " + data['Join Type'] + " Join" )};
-  }
-},
-"ModifyTable" : function(data) {
-  switch (data['Operation']) {
-    case "Insert": return { "image":"ex_insert.svg",
-                            "image_text":"Insert"
-                           };
-    case "Update": return {"image":"ex_update.svg","image_text":"Update"};
-    case "Delete": return {"image":"ex_delete.svg","image_text":"Delete"};
-  }
-},
-'Nested Loop' : function(data) {
-  switch(data['Join Type']) {
-    case 'Anti': return {"image":"ex_nested_loop_anti_join.svg","image_text":"Nested Loop Anti Join"};
-    case 'Semi': return {"image":"ex_nested_loop_semi_join.svg","image_text":"Nested Loop Semi Join"};
-    default: return {"image":"ex_nested.svg","image_text":"Nested Loop " + data['Join Type'] + " Join"};
-  }
-},
-"Recursive Union" : {"image":"ex_recursive_union.svg","image_text":"Recursive Union"},
-"Result" : {"image":"ex_result.svg","image_text":"Result"},
-"Sample Scan" : {"image":"ex_scan.svg","image_text":"Sample Scan"},
-"Scan" : {"image":"ex_scan.svg","image_text":"Scan"},
-"Seek" : {"image":"ex_seek.svg","image_text":"Seek"},
-"SetOp" : function(data) {
-  var strategy = data['Strategy'],
-      command = data['Command'];
-
-  if(strategy == "Hashed") {
-    if(S.startsWith(command, "Intersect")) {
-      if(command == "Intersect All")
-        return {"image":"ex_hash_setop_intersect_all.svg","image_text":"Hashed Intersect All"};
-      return {"image":"ex_hash_setop_intersect.svg","image_text":"Hashed Intersect"};
-    }
-    else if (S.startsWith(command, "Except")) {
-      if(command == "Except All")
-        return {"image":"ex_hash_setop_except_all.svg","image_text":"Hashed Except All"};
-      return {"image":"ex_hash_setop_except.svg","image_text":"Hash Except"};
-    }
-    return {"image":"ex_hash_setop_unknown.svg","image_text":"Hashed SetOp Unknown"};
-  }
-  return {"image":"ex_setop.svg","image_text":"SetOp"};
-},
-"Seq Scan": function(data) {
-  return {"image":"ex_scan.svg","image_text":data['Relation Name']};
-},
-"Subquery Scan" : {"image":"ex_subplan.svg","image_text":"SubQuery Scan"},
-"Sort" : {"image":"ex_sort.svg","image_text":"Sort"},
-"Tid Scan" : {"image":"ex_tid_scan.svg","image_text":"Tid Scan"},
-"Unique" : {"image":"ex_unique.svg","image_text":"Unique"},
-"Values Scan" : {"image":"ex_values_scan.svg","image_text":"Values Scan"},
-"WindowAgg" : {"image":"ex_window_aggregate.svg","image_text":"Window Aggregate"},
-"WorkTable Scan" : {"image":"ex_worktable_scan.svg","image_text":"WorkTable Scan"},
-"Undefined" : {"image":"ex_unknown.svg","image_text":"Undefined"},
-}
-
-// Some predefined constants used to calculate image location and its border
-var pWIDTH =100.;
-var pHEIGHT = 100.;
-var IMAGE_WIDTH =50;
-var IMAGE_HEIGHT = 50;
-var offsetX = 200,
+    'WorkTable Scan': {
+      'image': 'ex_worktable_scan.svg',
+      'image_text': 'WorkTable Scan',
+    },
+    'Undefined': {
+      'image': 'ex_unknown.svg',
+      'image_text': 'Undefined',
+    },
+  };
+
+  // Some predefined constants used to calculate image location and its border
+  var pWIDTH = 100.;
+  var pHEIGHT = 100.;
+  var IMAGE_WIDTH = 50;
+  var IMAGE_HEIGHT = 50;
+  var offsetX = 200,
     offsetY = 60;
-var ARROW_WIDTH = 10,
+  var ARROW_WIDTH = 10,
     ARROW_HEIGHT = 10,
     DEFAULT_ARROW_SIZE = 2;
-var TXT_ALIGN = 5,
-    TXT_SIZE = "15px";
-var TOTAL_WIDTH = undefined,
-    TOTAL_HEIGHT = undefined;
-var xMargin = 25,
+  var TXT_ALIGN = 5,
+    TXT_SIZE = '15px';
+  var xMargin = 25,
     yMargin = 25;
-var MIN_ZOOM_FACTOR = 0.01,
+  var MIN_ZOOM_FACTOR = 0.01,
     MAX_ZOOM_FACTOR = 2,
     INIT_ZOOM_FACTOR = 1;
-var ZOOM_RATIO = 0.05;
+  var ZOOM_RATIO = 0.05;
 
 
-// Backbone model for each plan property of input JSON object
-var PlanModel = Backbone.Model.extend({
+  // Backbone model for each plan property of input JSON object
+  var PlanModel = Backbone.Model.extend({
     defaults: {
-        "Plans": [],
-        level: [],
-        "image": undefined,
-        "image_text": undefined,
-        xpos: undefined,
-        ypos: undefined,
-        width: pWIDTH,
-        height: pHEIGHT
+      'Plans': [],
+      level: [],
+      'image': undefined,
+      'image_text': undefined,
+      xpos: undefined,
+      ypos: undefined,
+      width: pWIDTH,
+      height: pHEIGHT,
     },
     parse: function(data) {
-        var idx = 1,
-            lvl = data.level = data.level || [idx],
-            plans = [],
-            node_type = data['Node Type'],
-            // Calculating relative xpos of current node from top node
-            xpos = data.xpos = data.xpos - pWIDTH,
-            // Calculating relative ypos of current node from top node
-            ypos = data.ypos,
-            maxChildWidth = 0;
-
-        data['width'] = pWIDTH;
-        data['height'] = pHEIGHT;
-
-        /*
-         * calculating xpos, ypos, width and height if current node is a subplan
-         */
-        if (data['Parent Relationship'] === "SubPlan") {
-            data['width'] += (xMargin * 2) + (xMargin / 2);
-            data['height'] += (yMargin * 2);
-            data['ypos'] += yMargin;
-            xpos -= xMargin;
-            ypos += yMargin;
-        }
+      var idx = 1,
+        lvl = data.level = data.level || [idx],
+        plans = [],
+        node_type = data['Node Type'],
+        // Calculating relative xpos of current node from top node
+        xpos = data.xpos = data.xpos - pWIDTH,
+        // Calculating relative ypos of current node from top node
+        ypos = data.ypos,
+        maxChildWidth = 0;
+
+      data['width'] = pWIDTH;
+      data['height'] = pHEIGHT;
+
+      /*
+       * calculating xpos, ypos, width and height if current node is a subplan
+       */
+      if (data['Parent Relationship'] === 'SubPlan') {
+        data['width'] += (xMargin * 2) + (xMargin / 2);
+        data['height'] += (yMargin * 2);
+        data['ypos'] += yMargin;
+        xpos -= xMargin;
+        ypos += yMargin;
+      }
 
-        if(S.startsWith(node_type, "(slice"))
-            node_type = node_type.substring(0,7);
+      if (S.startsWith(node_type, '(slice'))
+        node_type = node_type.substring(0, 7);
 
-        // Get the image information for current node
-        var mappedImage = (_.isFunction(imageMapper[node_type]) &&
-                imageMapper[node_type].apply(undefined, [data])) ||
-                imageMapper[node_type] || {
-                  "image": "ex_unknown.svg", "image_text": node_type
-                };
+      // Get the image information for current node
+      var mappedImage = (_.isFunction(imageMapper[node_type]) &&
+          imageMapper[node_type].apply(undefined, [data])) ||
+        imageMapper[node_type] || {
+          'image': 'ex_unknown.svg',
+          'image_text': node_type,
+        };
 
-        data["image"] = mappedImage["image"];
-        data["image_text"] = mappedImage["image_text"];
+      data['image'] = mappedImage['image'];
+      data['image_text'] = mappedImage['image_text'];
 
-        // Start calculating xpos, ypos, width and height for child plans if any
-        if ('Plans' in data) {
+      // Start calculating xpos, ypos, width and height for child plans if any
+      if ('Plans' in data) {
 
-            data['width'] += offsetX;
+        data['width'] += offsetX;
 
-            _.each(data['Plans'], function(p) {
-                var level = _.clone(lvl),
-                    plan = new PlanModel();
+        _.each(data['Plans'], function(p) {
+          var level = _.clone(lvl),
+            plan = new PlanModel();
 
-                level.push(idx);
-                plan.set(plan.parse(_.extend(
-                    p, {
-                        "level": level,
-                        xpos: xpos - offsetX,
-                        ypos: ypos
-                    })));
+          level.push(idx);
+          plan.set(plan.parse(_.extend(
+            p, {
+              'level': level,
+              xpos: xpos - offsetX,
+              ypos: ypos,
+            })));
 
-                if (maxChildWidth < plan.get('width')) {
-                    maxChildWidth = plan.get('width');
-                }
+          if (maxChildWidth < plan.get('width')) {
+            maxChildWidth = plan.get('width');
+          }
 
-                var childHeight = plan.get('height');
+          var childHeight = plan.get('height');
 
-                if (idx !== 1) {
-                    data['height'] = data['height'] + childHeight + offsetY;
-                } else if (childHeight > data['height']) {
-                    data['height'] = childHeight;
-                }
-                ypos += childHeight + offsetY;
+          if (idx !== 1) {
+            data['height'] = data['height'] + childHeight + offsetY;
+          } else if (childHeight > data['height']) {
+            data['height'] = childHeight;
+          }
+          ypos += childHeight + offsetY;
 
-                plans.push(plan);
-                idx++;
-            });
-        }
+          plans.push(plan);
+          idx++;
+        });
+      }
 
-        // Final Width and Height of current node
-        data['width'] += maxChildWidth;
-        data['Plans'] = plans;
+      // Final Width and Height of current node
+      data['width'] += maxChildWidth;
+      data['Plans'] = plans;
 
-        return data;
+      return data;
     },
 
     /*
@@ -319,13 +482,13 @@ var PlanModel = Backbone.Model.extend({
       var res = Backbone.Model.prototype.toJSON.apply(this, arguments);
 
       if (non_recursive) {
-            delete res['Plans'];
+        delete res['Plans'];
       } else {
-            var plans = [];
-            _.each(res['Plans'], function(p) {
-              plans.push(p.toJSON());
-            });
-            res['Plans'] = plans;
+        var plans = [];
+        _.each(res['Plans'], function(p) {
+          plans.push(p.toJSON());
+        });
+        res['Plans'] = plans;
       }
       return res;
     },
@@ -335,207 +498,225 @@ var PlanModel = Backbone.Model.extend({
       // Calculate end point of first starting straight line (startx1, starty1)
       // Calculate start point of 2nd straight line (endx1, endy1)
       var midX1 = startX + ((endX - startX) / 3),
-          midX2 = startX + (2 * ((endX - startX) / 3));
+        midX2 = startX + (2 * ((endX - startX) / 3));
 
       //create arrow head
       var arrow = g.polygon(
-                    [0, ARROW_HEIGHT,
-                    (ARROW_WIDTH / 2),ARROW_HEIGHT,
-                    (ARROW_HEIGHT / 4), 0,
-                    0, ARROW_WIDTH]
-                    ).transform("r90");
+        [0, ARROW_HEIGHT,
+          (ARROW_WIDTH / 2), ARROW_HEIGHT,
+          (ARROW_HEIGHT / 4), 0,
+          0, ARROW_WIDTH,
+        ]
+      ).transform('r90');
       var marker = arrow.marker(
-                         0, 0, ARROW_WIDTH, ARROW_HEIGHT, 0, (ARROW_WIDTH / 2)
-                         ).attr(arrowOpts);
+        0, 0, ARROW_WIDTH, ARROW_HEIGHT, 0, (ARROW_WIDTH / 2)
+      ).attr(arrowOpts);
 
       // First straight line
       g.line(
         startX, startY, midX1, startY
-        ).attr(opts);
+      ).attr(opts);
 
       // Diagonal line
       g.line(
-        midX1-1, startY, midX2, endY
-        ).attr(opts);
+        midX1 - 1, startY, midX2, endY
+      ).attr(opts);
 
       // Last straight line
       var line = g.line(
-                   midX2, endY, endX, endY
-                   ).attr(opts);
-      line.attr({markerEnd: marker})
+        midX2, endY, endX, endY
+      ).attr(opts);
+      line.attr({
+        markerEnd: marker,
+      });
     },
 
     // Draw image, its name and its tooltip
     draw: function(s, xpos, ypos, pXpos, pYpos, graphContainer, toolTipContainer) {
-        var g = s.g();
-        var currentXpos = xpos + this.get('xpos') ,
-            currentYpos = ypos + this.get('ypos'),
-            isSubPlan = (this.get('Parent Relationship') === "SubPlan");
-
-        // Draw the subplan rectangle
-        if (isSubPlan) {
-          g.rect(
-            currentXpos - this.get('width') + pWIDTH + xMargin,
-            currentYpos - this.get('height') + pHEIGHT + yMargin - TXT_ALIGN,
-            this.get('width') - xMargin,
-            this.get('height') + (currentYpos - yMargin),
-            5
-          ).attr({
-              stroke: '#444444',
-              'strokeWidth': 1.2,
-              fill: 'gray',
-              fillOpacity: 0.2
-          });
+      var g = s.g();
+      var currentXpos = xpos + this.get('xpos'),
+        currentYpos = ypos + this.get('ypos'),
+        isSubPlan = (this.get('Parent Relationship') === 'SubPlan');
 
-          //provide subplan name
-          var text = g.text(
-            currentXpos  + pWIDTH - ( this.get('width') / 2) - xMargin,
-            currentYpos + pHEIGHT  - (this.get('height') / 2) - yMargin,
-            this.get('Subplan Name')
-          ).attr({
-            fontSize: TXT_SIZE, "text-anchor":"start",
-            fill: 'red'
-          });
-        }
+      // Draw the subplan rectangle
+      if (isSubPlan) {
+        g.rect(
+          currentXpos - this.get('width') + pWIDTH + xMargin,
+          currentYpos - this.get('height') + pHEIGHT + yMargin - TXT_ALIGN,
+          this.get('width') - xMargin,
+          this.get('height') + (currentYpos - yMargin),
+          5
+        ).attr({
+          stroke: '#444444',
+          'strokeWidth': 1.2,
+          fill: 'gray',
+          fillOpacity: 0.2,
+        });
 
-        // Draw the actual image for current node
-        var image = g.image(
-            pgExplain.prefix + this.get('image'),
-            currentXpos + (pWIDTH - IMAGE_WIDTH) / 2,
-            currentYpos + (pHEIGHT - IMAGE_HEIGHT) / 2,
-            IMAGE_WIDTH,
-            IMAGE_HEIGHT
-        );
+        // Provide subplan name
+        g.text(
+          currentXpos + pWIDTH - (this.get('width') / 2) - xMargin,
+          currentYpos + pHEIGHT - (this.get('height') / 2) - yMargin,
+          this.get('Subplan Name')
+        ).attr({
+          fontSize: TXT_SIZE,
+          'text-anchor': 'start',
+          fill: 'red',
+        });
+      }
 
-        // Draw tooltip
-        var image_data = this.toJSON();
-        image.mouseover(function(evt){
-
-          // Empty the tooltip content if it has any and add new data
-          toolTipContainer.empty();
-          var tooltip = $('<table></table>',{
-                           class: "pgadmin-tooltip-table"
-                        }).appendTo(toolTipContainer);
-          _.each(image_data, function(value,key) {
-            if(key !== 'image' && key !== 'Plans' &&
-               key !== 'level' && key !== 'image' &&
-               key !== 'image_text' && key !== 'xpos' &&
-               key !== 'ypos' && key !== 'width' &&
-               key !== 'height') {
-              tooltip.append( '<tr><td class="label explain-tooltip">' + key + '</td><td class="label explain-tooltip-val">' + value + '</td></tr>' );
-            };
-          });
+      // Draw the actual image for current node
+      var image = g.image(
+        pgExplain.prefix + this.get('image'),
+        currentXpos + (pWIDTH - IMAGE_WIDTH) / 2,
+        currentYpos + (pHEIGHT - IMAGE_HEIGHT) / 2,
+        IMAGE_WIDTH,
+        IMAGE_HEIGHT
+      );
+
+      // Draw tooltip
+      var image_data = this.toJSON();
+      image.mouseover(function() {
+
+        // Empty the tooltip content if it has any and add new data
+        toolTipContainer.empty();
+        var tooltip = $('<table></table>', {
+          class: 'pgadmin-tooltip-table',
+        }).appendTo(toolTipContainer);
+        _.each(image_data, function(value, key) {
+          if (key !== 'image' && key !== 'Plans' &&
+            key !== 'level' && key !== 'image' &&
+            key !== 'image_text' && key !== 'xpos' &&
+            key !== 'ypos' && key !== 'width' &&
+            key !== 'height') {
+            tooltip.append('<tr><td class="label explain-tooltip">' + key + '</td><td class="label explain-tooltip-val">' + value + '</td></tr>');
+          }
+        });
 
-          var zoomFactor = graphContainer.data('zoom-factor');
+        var zoomFactor = graphContainer.data('zoom-factor');
 
-          // Calculate co-ordinates for tooltip
-          var toolTipX = ((currentXpos + pWIDTH) * zoomFactor - graphContainer.scrollLeft());
-          var toolTipY = ((currentYpos + pHEIGHT) * zoomFactor - graphContainer.scrollTop());
+        // Calculate co-ordinates for tooltip
+        var toolTipX = ((currentXpos + pWIDTH) * zoomFactor - graphContainer.scrollLeft());
+        var toolTipY = ((currentYpos + pHEIGHT) * zoomFactor - graphContainer.scrollTop());
 
-          // Recalculate x.y if tooltip is going out of screen
-          if(graphContainer.width() < (toolTipX + toolTipContainer[0].clientWidth))
-            toolTipX -= (toolTipContainer[0].clientWidth + (pWIDTH*zoomFactor));
-          //if(document.children[0].clientHeight < (toolTipY + toolTipContainer[0].clientHeight))
-          if(graphContainer.height() < (toolTipY + toolTipContainer[0].clientHeight))
-            toolTipY -= (toolTipContainer[0].clientHeight + ((pHEIGHT/2)*zoomFactor));
+        // Recalculate x.y if tooltip is going out of screen
+        if (graphContainer.width() < (toolTipX + toolTipContainer[0].clientWidth))
+          toolTipX -= (toolTipContainer[0].clientWidth + (pWIDTH * zoomFactor));
+        //if(document.children[0].clientHeight < (toolTipY + toolTipContainer[0].clientHeight))
+        if (graphContainer.height() < (toolTipY + toolTipContainer[0].clientHeight))
+          toolTipY -= (toolTipContainer[0].clientHeight + ((pHEIGHT / 2) * zoomFactor));
 
-          toolTipX = toolTipX < 0 ? 0 : (toolTipX);
-          toolTipY = toolTipY < 0 ? 0 : (toolTipY);
+        toolTipX = toolTipX < 0 ? 0 : (toolTipX);
+        toolTipY = toolTipY < 0 ? 0 : (toolTipY);
 
-          // Show toolTip at respective x,y coordinates
-          toolTipContainer.css({'opacity': '0.8'});
-          toolTipContainer.css('left', toolTipX);
-          toolTipContainer.css( 'top', toolTipY);
+        // Show toolTip at respective x,y coordinates
+        toolTipContainer.css({
+          'opacity': '0.8',
         });
-
-        // Remove tooltip when mouse is out from node's area
-        image.mouseout(function() {
-          toolTipContainer.empty();
-          toolTipContainer.css({'opacity': '0'});
-          toolTipContainer.css('left', 0);
-          toolTipContainer.css( 'top', 0);
+        toolTipContainer.css('left', toolTipX);
+        toolTipContainer.css('top', toolTipY);
+      });
+
+      // Remove tooltip when mouse is out from node's area
+      image.mouseout(function() {
+        toolTipContainer.empty();
+        toolTipContainer.css({
+          'opacity': '0',
         });
+        toolTipContainer.css('left', 0);
+        toolTipContainer.css('top', 0);
+      });
+
+      // Draw text below the node
+      var node_label = this.get('Schema') == undefined ?
+        this.get('image_text') :
+        (this.get('Schema') + '.' + this.get('image_text'));
+      g.multitext(
+        currentXpos + (pWIDTH / 2) + TXT_ALIGN,
+        currentYpos + pHEIGHT - TXT_ALIGN,
+        node_label,
+        150, {
+          'font-size': TXT_SIZE,
+          'text-anchor': 'middle',
+        }
+      );
+
+      // Draw Arrow to parent only its not the first node
+      if (!_.isUndefined(pYpos)) {
+        var startx = currentXpos + pWIDTH;
+        var starty = currentYpos + (pHEIGHT / 2);
+        var endx = pXpos - ARROW_WIDTH;
+        var endy = pYpos + (pHEIGHT / 2);
+        var start_cost = this.get('Startup Cost'),
+          total_cost = this.get('Total Cost');
+        var arrow_size = DEFAULT_ARROW_SIZE;
+
+        // Calculate arrow width according to cost of a particular plan
+        if (start_cost != undefined && total_cost != undefined) {
+          arrow_size = Math.round(Math.log((start_cost + total_cost) / 2 + start_cost));
+          arrow_size = arrow_size < 1 ? 1 : arrow_size > 10 ? 10 : arrow_size;
+        }
 
-        // Draw text below the node
-        var node_label = (this.get('Schema') == undefined ?
-                            this.get('image_text') :
-                            this.get('Schema')+"."+this.get('image_text'));
-        var label = g.g();
-        g.multitext(
-          currentXpos + (pWIDTH / 2) + TXT_ALIGN,
-          currentYpos + pHEIGHT - TXT_ALIGN,
-          node_label,
-          150,
-          {"font-size": TXT_SIZE ,"text-anchor":"middle"}
-        );
 
-        // Draw Arrow to parent only its not the first node
-        if (!_.isUndefined(pYpos)) {
-            var startx = currentXpos + pWIDTH;
-            var starty = currentYpos + (pHEIGHT / 2);
-            var endx = pXpos - ARROW_WIDTH;
-            var endy = pYpos + (pHEIGHT / 2);
-            var start_cost = this.get("Startup Cost"),
-                total_cost = this.get("Total Cost");
-            var arrow_size = DEFAULT_ARROW_SIZE;
-            // Calculate arrow width according to cost of a particular plan
-            if(start_cost != undefined && total_cost != undefined) {
-              var arrow_size = Math.round(Math.log((start_cost+total_cost)/2 + start_cost));
-              arrow_size = arrow_size < 1 ? 1 : arrow_size > 10 ? 10 : arrow_size;
-            }
-
-
-            var arrow_view_box = [0, 0, 2*ARROW_WIDTH, 2*ARROW_HEIGHT];
-            var opts = {stroke: "#000000", strokeWidth: arrow_size + 1},
-                subplanOpts = {stroke: "#866486", strokeWidth: arrow_size + 1},
-                arrowOpts = {viewBox: arrow_view_box.join(" ")};
-
-            // Draw an arrow from current node to its parent
-            this.drawPolyLine(
-              g, startx, starty, endx, endy,
-              isSubPlan ? subplanOpts : opts, arrowOpts
-            );
-        }
+        var arrow_view_box = [0, 0, 2 * ARROW_WIDTH, 2 * ARROW_HEIGHT];
+        var opts = {
+            stroke: '#000000',
+            strokeWidth: arrow_size + 1,
+          },
+          subplanOpts = {
+            stroke: '#866486',
+            strokeWidth: arrow_size + 1,
+          },
+          arrowOpts = {
+            viewBox: arrow_view_box.join(' '),
+          };
+
+        // Draw an arrow from current node to its parent
+        this.drawPolyLine(
+          g, startx, starty, endx, endy,
+          isSubPlan ? subplanOpts : opts, arrowOpts
+        );
+      }
 
-        var plans = this.get('Plans');
+      var plans = this.get('Plans');
 
-        // Draw nodes for current plan's children
-        _.each(plans, function(p) {
-            p.draw(s, xpos, ypos, currentXpos, currentYpos, graphContainer, toolTipContainer);
-        });
-    }
-});
+      // Draw nodes for current plan's children
+      _.each(plans, function(p) {
+        p.draw(s, xpos, ypos, currentXpos, currentYpos, graphContainer, toolTipContainer);
+      });
+    },
+  });
 
-// Main backbone model to store JSON object
-var MainPlanModel = Backbone.Model.extend({
+  // Main backbone model to store JSON object
+  var MainPlanModel = Backbone.Model.extend({
     defaults: {
-        "Plan": undefined,
-        xpos: 0,
-        ypos: 0,
+      'Plan': undefined,
+      xpos: 0,
+      ypos: 0,
     },
     initialize: function() {
-        this.set("Plan", new PlanModel());
+      this.set('Plan', new PlanModel());
     },
 
     // Parse the JSON data and fetch its children plans
     parse: function(data) {
-        if (data && 'Plan' in data) {
-           var plan = this.get("Plan");
-           plan.set(
-             plan.parse(
-               _.extend(
-                 data['Plan'], {
-                   xpos: 0,
-                   ypos: 0
-                 })));
-
-           data['xpos'] = 0;
-           data['ypos'] = 0;
-           data['width'] = plan.get('width') + (xMargin * 2);
-           data['height'] = plan.get('height') + (yMargin * 4);
-
-           delete data['Plan'];
-        }
+      if (data && 'Plan' in data) {
+        var plan = this.get('Plan');
+        plan.set(
+          plan.parse(
+            _.extend(
+              data['Plan'], {
+                xpos: 0,
+                ypos: 0,
+              })));
+
+        data['xpos'] = 0;
+        data['ypos'] = 0;
+        data['width'] = plan.get('width') + (xMargin * 2);
+        data['height'] = plan.get('height') + (yMargin * 4);
+
+        delete data['Plan'];
+      }
 
       return data;
     },
@@ -549,147 +730,162 @@ var MainPlanModel = Backbone.Model.extend({
       return res;
     },
     draw: function(s, xpos, ypos, graphContainer, toolTipContainer) {
-        var g = s.g();
+      var g = s.g();
 
-        //draw the border
-        g.rect(
-	        0, 0, this.get('width') - 10, this.get('height') - 10, 5
-	    ).attr({
-            fill: '#FFF'
-        });
+      //draw the border
+      g.rect(
+        0, 0, this.get('width') - 10, this.get('height') - 10, 5
+      ).attr({
+        fill: '#FFF',
+      });
 
-        //Fetch total width, height
-        TOTAL_WIDTH = this.get('width');
-        TOTAL_HEIGHT = this.get('height');
-        var plan = this.get('Plan');
+      var plan = this.get('Plan');
 
-        //Draw explain graph
-        plan.draw(g, xpos, ypos, undefined, undefined, graphContainer, toolTipContainer);
-    }
-});
+      // Draw explain graph
+      plan.draw(
+        g, xpos, ypos, undefined, undefined, graphContainer, toolTipContainer
+      );
+    },
+  });
+
+  // Parse and draw full graphical explain
+  _.extend(pgExplain, {
+    // Assumption container is a jQuery object
+    DrawJSONPlan: function(container, plan) {
+      container.empty();
+      var curr_zoom_factor = 1.0;
+
+      var zoomArea = $('<div></div>', {
+          class: 'pg-explain-zoom-area btn-group',
+          role: 'group',
+        }).appendTo(container),
+        zoomInBtn = $('<button></button>', {
+          class: 'btn pg-explain-zoom-btn badge',
+          title: 'Zoom in',
+        }).appendTo(zoomArea).append(
+          $('<i></i>', {
+            class: 'fa fa-search-plus',
+          })),
+        zoomToNormal = $('<button></button>', {
+          class: 'btn pg-explain-zoom-btn badge',
+          title: 'Zoom to original',
+        }).appendTo(zoomArea).append(
+          $('<i></i>', {
+            class: 'fa fa-arrows-alt',
+          })),
+        zoomOutBtn = $('<button></button>', {
+          class: 'btn pg-explain-zoom-btn badge',
+          title: 'Zoom out',
+        }).appendTo(zoomArea).append(
+          $('<i></i>', {
+            class: 'fa fa-search-minus',
+          }));
+
+      // Main div to be drawn all images on
+      var planDiv = $('<div></div>', {
+          class: 'pgadmin-explain-container',
+        }).appendTo(container),
+        // Div to draw tool-tip on
+        toolTip = $('<div></div>', {
+          id: 'toolTip',
+          class: 'pgadmin-explain-tooltip',
+        }).appendTo(container);
+      toolTip.empty();
+      planDiv.data('zoom-factor', curr_zoom_factor);
+
+      var w = 0,
+        h = yMargin;
+
+      _.each(plan, function(p) {
+        var main_plan = new MainPlanModel();
+
+        // Parse JSON data to backbone model
+        main_plan.set(main_plan.parse(p));
+        w = main_plan.get('width');
+        h = main_plan.get('height');
+
+        var s = Snap(w, h),
+          $svg = $(s.node).detach();
+        planDiv.append($svg);
+        main_plan.draw(s, w - xMargin, yMargin, planDiv, toolTip);
+
+        var initPanelWidth = planDiv.width();
+
+        /*
+         * Scale graph in case its width is bigger than panel width
+         * in which the graph is displayed
+         */
+        if (initPanelWidth < w) {
+          var width_ratio = initPanelWidth / w;
+
+          curr_zoom_factor = width_ratio;
+          curr_zoom_factor = curr_zoom_factor < MIN_ZOOM_FACTOR ? MIN_ZOOM_FACTOR : curr_zoom_factor;
+          curr_zoom_factor = curr_zoom_factor > INIT_ZOOM_FACTOR ? INIT_ZOOM_FACTOR : curr_zoom_factor;
+
+          var zoomInMatrix = new Snap.matrix();
+          zoomInMatrix.scale(curr_zoom_factor, curr_zoom_factor);
+
+          $svg.find('g').first().attr({
+            transform: zoomInMatrix,
+          });
+          $svg.attr({
+            'width': w * curr_zoom_factor,
+            'height': h * curr_zoom_factor,
+          });
+          planDiv.data('zoom-factor', curr_zoom_factor);
+        }
+
+        zoomInBtn.on('click', function() {
+          curr_zoom_factor = ((curr_zoom_factor + ZOOM_RATIO) > MAX_ZOOM_FACTOR) ? MAX_ZOOM_FACTOR : (curr_zoom_factor + ZOOM_RATIO);
+          var zoomInMatrix = new Snap.matrix();
+          zoomInMatrix.scale(curr_zoom_factor, curr_zoom_factor);
+
+          $svg.find('g').first().attr({
+            transform: zoomInMatrix,
+          });
+          $svg.attr({
+            'width': w * curr_zoom_factor,
+            'height': h * curr_zoom_factor,
+          });
+          planDiv.data('zoom-factor', curr_zoom_factor);
+          zoomInBtn.blur();
+        });
+
+        zoomOutBtn.on('click', function() {
+          curr_zoom_factor = ((curr_zoom_factor - ZOOM_RATIO) < MIN_ZOOM_FACTOR) ? MIN_ZOOM_FACTOR : (curr_zoom_factor - ZOOM_RATIO);
+          var zoomInMatrix = new Snap.matrix();
+          zoomInMatrix.scale(curr_zoom_factor, curr_zoom_factor);
 
-// Parse and draw full graphical explain
-_.extend(
-    pgExplain, {
-        // Assumption container is a jQuery object
-        DrawJSONPlan: function(container, plan) {
-          var my_plans = [];
-          container.empty();
-          var curr_zoom_factor = 1.0;
-
-          var zoomArea =$('<div></div>', {
-                class: 'pg-explain-zoom-area btn-group',
-                role: 'group'
-                }).appendTo(container),
-              zoomInBtn = $('<button></button>', {
-                class: 'btn pg-explain-zoom-btn badge',
-                title: 'Zoom in'
-                }).appendTo(zoomArea).append(
-                  $('<i></i>',{
-                    class: 'fa fa-search-plus'
-                  })),
-              zoomToNormal = $('<button></button>', {
-                class: 'btn pg-explain-zoom-btn badge',
-                title: 'Zoom to original'
-                }).appendTo(zoomArea).append(
-                  $('<i></i>',{
-                    class: 'fa fa-arrows-alt'
-                  })),
-              zoomOutBtn = $('<button></button>', {
-                class: 'btn pg-explain-zoom-btn badge',
-                title: 'Zoom out'
-                }).appendTo(zoomArea).append(
-                  $('<i></i>', {
-                    class: 'fa fa-search-minus'
-                  }));
-
-          // Main div to be drawn all images on
-          var planDiv = $('<div></div>',
-                           {class: "pgadmin-explain-container"}
-                         ).appendTo(container),
-              // Div to draw tool-tip on
-              toolTip = $('<div></div>',
-                           {id: "toolTip",
-                           class: "pgadmin-explain-tooltip"
-                           }
-                         ).appendTo(container);
-          toolTip.empty();
+          $svg.find('g').first().attr({
+            transform: zoomInMatrix,
+          });
+          $svg.attr({
+            'width': w * curr_zoom_factor,
+            'height': h * curr_zoom_factor,
+          });
           planDiv.data('zoom-factor', curr_zoom_factor);
+          zoomOutBtn.blur();
+        });
 
-          var w = 0, h = 0,
-              x = xMargin, h = yMargin;
-
-          _.each(plan, function(p) {
-            var main_plan = new MainPlanModel();
-
-            // Parse JSON data to backbone model
-            main_plan.set(main_plan.parse(p));
-            w = main_plan.get('width');
-            h = main_plan.get('height');
-
-            var s = Snap(w, h),
-                $svg = $(s.node).detach();
-            planDiv.append($svg);
-            main_plan.draw(s, w - xMargin, yMargin, planDiv, toolTip);
-
-            var initPanelWidth = planDiv.width(),
-                initPanelHeight = planDiv.height();
-
-             /*
-              * Scale graph in case its width is bigger than panel width
-              * in which the graph is displayed
-              */
-            if(initPanelWidth < w) {
-              var width_ratio = initPanelWidth / w;
-
-              curr_zoom_factor = width_ratio;
-              curr_zoom_factor = curr_zoom_factor < MIN_ZOOM_FACTOR ? MIN_ZOOM_FACTOR : curr_zoom_factor;
-              curr_zoom_factor = curr_zoom_factor > INIT_ZOOM_FACTOR ? INIT_ZOOM_FACTOR : curr_zoom_factor;
-
-              var zoomInMatrix = new Snap.matrix();
-              zoomInMatrix.scale(curr_zoom_factor, curr_zoom_factor);
-
-              $svg.find('g').first().attr({transform: zoomInMatrix});
-              $svg.attr({'width': w * curr_zoom_factor, 'height': h * curr_zoom_factor});
-              planDiv.data('zoom-factor', curr_zoom_factor);
-            }
-
-            zoomInBtn.on('click', function(e){
-              curr_zoom_factor = ((curr_zoom_factor + ZOOM_RATIO) > MAX_ZOOM_FACTOR) ? MAX_ZOOM_FACTOR : (curr_zoom_factor + ZOOM_RATIO);
-              var zoomInMatrix = new Snap.matrix();
-              zoomInMatrix.scale(curr_zoom_factor, curr_zoom_factor);
-
-              $svg.find('g').first().attr({transform: zoomInMatrix});
-              $svg.attr({'width': w * curr_zoom_factor, 'height': h * curr_zoom_factor});
-              planDiv.data('zoom-factor', curr_zoom_factor);
-              zoomInBtn.blur();
-            });
-
-            zoomOutBtn.on('click', function(e) {
-              curr_zoom_factor = ((curr_zoom_factor - ZOOM_RATIO) < MIN_ZOOM_FACTOR) ? MIN_ZOOM_FACTOR : (curr_zoom_factor - ZOOM_RATIO);
-              var zoomInMatrix = new Snap.matrix();
-              zoomInMatrix.scale(curr_zoom_factor, curr_zoom_factor);
-
-              $svg.find('g').first().attr({transform: zoomInMatrix});
-              $svg.attr({'width': w * curr_zoom_factor, 'height': h * curr_zoom_factor});
-              planDiv.data('zoom-factor', curr_zoom_factor);
-              zoomOutBtn.blur();
-            });
-
-            zoomToNormal.on('click', function(e) {
-              curr_zoom_factor = INIT_ZOOM_FACTOR;
-              var zoomInMatrix = new Snap.matrix();
-              zoomInMatrix.scale(curr_zoom_factor, curr_zoom_factor);
-
-              $svg.find('g').first().attr({transform: zoomInMatrix});
-              $svg.attr({'width': w * curr_zoom_factor, 'height': h * curr_zoom_factor});
-              planDiv.data('zoom-factor', curr_zoom_factor);
-              zoomToNormal.blur();
-            });
+        zoomToNormal.on('click', function() {
+          curr_zoom_factor = INIT_ZOOM_FACTOR;
+          var zoomInMatrix = new Snap.matrix();
+          zoomInMatrix.scale(curr_zoom_factor, curr_zoom_factor);
+
+          $svg.find('g').first().attr({
+            transform: zoomInMatrix,
+          });
+          $svg.attr({
+            'width': w * curr_zoom_factor,
+            'height': h * curr_zoom_factor,
           });
+          planDiv.data('zoom-factor', curr_zoom_factor);
+          zoomToNormal.blur();
+        });
+      });
 
-        }
-    });
+    },
+  });
 
-    return pgExplain;
+  return pgExplain;
 });
diff --git a/web/pgadmin/misc/statistics/static/js/statistics.js b/web/pgadmin/misc/statistics/static/js/statistics.js
index 8cc3a1e5..39ff7bb3 100644
--- a/web/pgadmin/misc/statistics/static/js/statistics.js
+++ b/web/pgadmin/misc/statistics/static/js/statistics.js
@@ -1,8 +1,9 @@
 define('misc.statistics', [
-  'sources/gettext', 'underscore', 'underscore.string', 'jquery',
-  'pgadmin.browser', 'backgrid',
-  'alertify', 'sources/size_prettify'
-], function(gettext, _, S, $, pgBrowser, Backgrid, Alertify, sizePrettify) {
+  'sources/gettext', 'underscore', 'underscore.string', 'jquery', 'backbone',
+  'pgadmin.browser', 'pgadmin.backgrid', 'alertify', 'sources/size_prettify',
+], function(
+  gettext, _, S, $, Backbone, pgBrowser, Backgrid, Alertify, sizePrettify
+) {
 
   if (pgBrowser.NodeStatistics)
     return pgBrowser.NodeStatistics;
@@ -13,69 +14,78 @@ define('misc.statistics', [
     return pgBrowser.NodeStatistics;
   }
 
-  var SizeFormatter = Backgrid.SizeFormatter = function () {};
+  var SizeFormatter = Backgrid.SizeFormatter = function() {};
   _.extend(SizeFormatter.prototype, {
-      /**
-         Takes a raw value from a model and returns the human readable formatted
-         string for display.
-
-         @member Backgrid.SizeFormatter
-         @param {*} rawData
-         @param {Backbone.Model} model Used for more complicated formatting
-         @return {*}
-      */
-      fromRaw: function (rawData, model) {
-        return sizePrettify(rawData);
-      },
-      toRaw: function (formattedData, model) {
-        return formattedData;
-      }
+    /**
+       Takes a raw value from a model and returns the human readable formatted
+       string for display.
+
+       @member Backgrid.SizeFormatter
+       @param {*} rawData
+       @param {Backbone.Model} model Used for more complicated formatting
+       @return {*}
+    */
+    fromRaw: function(rawData) {
+      return sizePrettify(rawData);
+    },
+    toRaw: function(formattedData) {
+      return formattedData;
+    },
   });
 
   var PGBooleanCell = Backgrid.Extension.SwitchCell.extend({
-      defaults: _.extend({}, Backgrid.Extension.SwitchCell.prototype.defaults)
-  }),
-  typeCellMapper = {
-    // boolean
-    16: PGBooleanCell,
-    // int8
-    20: Backgrid.IntegerCell,
-    // int2
-    21: Backgrid.IntegerCell,
-    // int4
-    23: Backgrid.IntegerCell,
-    // float4
-    700: Backgrid.NumberCell,
-    // float8
-    701: Backgrid.NumberCell,
-    // numeric
-    1700: Backgrid.NumberCell,
-    // abstime
-    702: Backgrid.DatetimeCell,
-    // reltime
-    703: Backgrid.DatetimeCell,
-    // date
-    1082: Backgrid.DatetimeCell.extend({
-      includeDate: true, includeTime: false, includeMilli: false
-    }),
-    // time
-    1083: Backgrid.DatetimeCell.extend({
-      includeDate: false, includeTime: true, includeMilli: true
-    }),
-    // timestamp
-    1114: Backgrid.DatetimeCell.extend({
-      includeDate: true, includeTime: true, includeMilli: true
+      defaults: _.extend({}, Backgrid.Extension.SwitchCell.prototype.defaults),
     }),
-    // timestamptz
-    1184: 'string'/* Backgrid.DatetimeCell.extend({
-      includeDate: true, includeTime: true, includeMilli: true
-    }) */,
-    1266: 'string'/* Backgrid.DatetimeCell.extend({
-      includeDate: false, includeTime: true, includeMilli: true
-    }) */
-  },
-  GRID_CLASSES = "backgrid presentation table backgrid-striped table-bordered table-hover",
-  wcDocker = window.wcDocker;
+    typeCellMapper = {
+      // boolean
+      16: PGBooleanCell,
+      // int8
+      20: Backgrid.IntegerCell,
+      // int2
+      21: Backgrid.IntegerCell,
+      // int4
+      23: Backgrid.IntegerCell,
+      // float4
+      700: Backgrid.NumberCell,
+      // float8
+      701: Backgrid.NumberCell,
+      // numeric
+      1700: Backgrid.NumberCell,
+      // abstime
+      702: Backgrid.DatetimeCell,
+      // reltime
+      703: Backgrid.DatetimeCell,
+      // date
+      1082: Backgrid.DatetimeCell.extend({
+        includeDate: true,
+        includeTime: false,
+        includeMilli: false,
+      }),
+      // time
+      1083: Backgrid.DatetimeCell.extend({
+        includeDate: false,
+        includeTime: true,
+        includeMilli: true,
+      }),
+      // timestamp
+      1114: Backgrid.DatetimeCell.extend({
+        includeDate: true,
+        includeTime: true,
+        includeMilli: true,
+      }),
+      // timestamptz
+      1184: 'string'
+        /* Backgrid.DatetimeCell.extend({
+              includeDate: true, includeTime: true, includeMilli: true
+            }) */
+        ,
+      1266: 'string',
+      /* Backgrid.DatetimeCell.extend({
+            includeDate: false, includeTime: true, includeMilli: true
+          }) */
+    },
+    GRID_CLASSES = 'backgrid presentation table backgrid-striped table-bordered table-hover',
+    wcDocker = window.wcDocker;
 
   _.extend(
     PGBooleanCell.prototype.defaults.options, {
@@ -83,7 +93,7 @@ define('misc.statistics', [
       offText: gettext('False'),
       onColor: 'success',
       offColor: 'primary',
-      size: 'mini'
+      size: 'mini',
     }
   );
 
@@ -101,23 +111,23 @@ define('misc.statistics', [
       _.extend(
         this, {
           initialized: true,
-          collection: new (Backbone.Collection)(null),
+          collection: new(Backbone.Collection)(null),
           statistic_columns: [{
             editable: false,
             name: 'statistics',
-            label: gettext("Statistics"),
+            label: gettext('Statistics'),
             cell: 'string',
             headerCell: Backgrid.Extension.CustomHeaderCell,
-            cellHeaderClasses: 'width_percent_25'
-          },{
+            cellHeaderClasses: 'width_percent_25',
+          }, {
             editable: false,
             name: 'value',
-            label: gettext("Value"),
-            cell: 'string'
+            label: gettext('Value'),
+            cell: 'string',
           }],
           panel: pgBrowser.docker.findPanels('statistics'),
           columns: null,
-          grid: null
+          grid: null,
         });
 
       var self = this;
@@ -125,12 +135,13 @@ define('misc.statistics', [
       // We will listen to the visibility change of the statistics panel
       pgBrowser.Events.on(
         'pgadmin-browser:panel-statistics:' +
-          wcDocker.EVENT.VISIBILITY_CHANGED,
-          this.panelVisibilityChanged
+        wcDocker.EVENT.VISIBILITY_CHANGED,
+        this.panelVisibilityChanged
       );
 
       pgBrowser.Events.on(
-        'pgadmin:browser:node:updated', function() {
+        'pgadmin:browser:node:updated',
+        function() {
           if (this.panel && this.panel.length) {
             $(this.panel[0]).data('node-prop', '');
             this.panelVisibilityChanged(this.panel[0]);
@@ -147,16 +158,16 @@ define('misc.statistics', [
           function() {
             self.panel = pgBrowser.docker.findPanels('statistics');
             if (self.panel[0].isVisible() ||
-                self.panel.length != 1) {
+              self.panel.length != 1) {
               pgBrowser.Events.on(
                 'pgadmin-browser:tree:selected', this.showStatistics
               );
             }
           }.bind(this)
-          );
+        );
       } else {
         if (self.panel[0].isVisible() ||
-            self.panel.length != 1) {
+          self.panel.length != 1) {
           pgBrowser.Events.on(
             'pgadmin-browser:tree:selected', this.showStatistics
           );
@@ -164,7 +175,7 @@ define('misc.statistics', [
       }
       if (self.panel.length > 0 && self.panel[0].isVisible()) {
         pgBrowser.Events.on(
-            'pgadmin-browser:tree:selected', this.showStatistics
+          'pgadmin-browser:tree:selected', this.showStatistics
         );
       }
     },
@@ -172,31 +183,30 @@ define('misc.statistics', [
     // Fetch the actual data and update the collection
     __updateCollection: function(url, node, item, node_type) {
       var $container = this.panel[0].layout().scene().find('.pg-panel-content'),
-          $msgContainer = $container.find('.pg-panel-statistics-message'),
-          $gridContainer = $container.find('.pg-panel-statistics-container'),
-          collection = this.collection,
-          panel = this.panel,
-          self = this,
-          msg = '',
-          n_type = node_type;
+        $msgContainer = $container.find('.pg-panel-statistics-message'),
+        $gridContainer = $container.find('.pg-panel-statistics-container'),
+        panel = this.panel,
+        self = this,
+        msg = '',
+        n_type = node_type;
 
       if (node) {
-        msg = gettext("No statistics are available for the selected object.");
+        msg = gettext('No statistics are available for the selected object.');
         /* We fetch the statistics only for those node who set the parameter
          * showStatistics function.
          */
 
-          // Avoid unnecessary reloads
-          var treeHierarchy = node.getTreeNodeHierarchy(item);
-          var cache_flag = {
-            node_type: node_type,
-            url: url
-          };
-          if (_.isEqual($(panel[0]).data('node-prop'), cache_flag)) {
-            return;
-          }
-          // Cache the current IDs for next time
-          $(panel[0]).data('node-prop', cache_flag);
+        // Avoid unnecessary reloads
+        var treeHierarchy = node.getTreeNodeHierarchy(item);
+        var cache_flag = {
+          node_type: node_type,
+          url: url,
+        };
+        if (_.isEqual($(panel[0]).data('node-prop'), cache_flag)) {
+          return;
+        }
+        // Cache the current IDs for next time
+        $(panel[0]).data('node-prop', cache_flag);
 
         if (node.hasStatistics) {
           msg = '';
@@ -204,13 +214,13 @@ define('misc.statistics', [
           // Set the url, fetch the data and update the collection
           $.ajax({
             url: url,
-            type:'GET',
-            beforeSend: function(jqXHR, settings) {
+            type: 'GET',
+            beforeSend: function() {
               // Generate a timer for the request
-              timer = setTimeout(function(){
+              timer = setTimeout(function() {
                 // notify user if request is taking longer than 1 second
 
-                $msgContainer.text(gettext("Retrieving data from the server..."));
+                $msgContainer.text(gettext('Retrieving data from the server...'));
                 $msgContainer.removeClass('hidden');
                 if (self.grid) {
                   self.grid.remove();
@@ -237,20 +247,20 @@ define('misc.statistics', [
                 self.grid = new Backgrid.Grid({
                   columns: self.columns,
                   collection: self.collection,
-                  className: GRID_CLASSES
+                  className: GRID_CLASSES,
                 });
                 self.grid.render();
                 $gridContainer.empty();
                 $gridContainer.append(self.grid.$el);
 
                 if (!$msgContainer.hasClass('hidden')) {
-                  $msgContainer.addClass('hidden')
+                  $msgContainer.addClass('hidden');
                 }
                 $gridContainer.removeClass('hidden');
 
               } else if (res.info) {
                 if (!$gridContainer.hasClass('hidden')) {
-                  $gridContainer.addClass('hidden')
+                  $gridContainer.addClass('hidden');
                 }
                 $msgContainer.text(res.info);
                 $msgContainer.removeClass('hidden');
@@ -261,24 +271,21 @@ define('misc.statistics', [
               pgBrowser.Events.trigger(
                 'pgadmin:node:retrieval:error', 'statistics', xhr, error, message, item
               );
-              if (
-                !Alertify.pgHandleItemError(xhr, error, message, {
-                  item: item, info: treeHierarchy
-                })
-              ) {
+              if (!Alertify.pgHandleItemError(xhr, error, message, {
+                item: item,
+                info: treeHierarchy,
+              })) {
                 Alertify.pgNotifier(
                   error, xhr,
-                  S(gettext("Error retrieving the information - %s")).sprintf(
+                  S(gettext('Error retrieving the information - %s')).sprintf(
                     message || _label
                   ).value(),
-                  function() {
-                    console.log(arguments);
-                  }
+                  function() {}
                 );
               }
               // show failed message.
-              $msgContainer.text(gettext("Failed to retrieve data from the server."));
-            }
+              $msgContainer.text(gettext('Failed to retrieve data from the server.'));
+            },
           });
         }
       }
@@ -309,38 +316,38 @@ define('misc.statistics', [
         if (self.timeout) {
           clearTimeout(self.timeout);
         }
-        self.timeout =  setTimeout(
+        self.timeout = setTimeout(
           function() {
             self.__updateCollection.call(
               self, node.generate_url(item, 'stats', data, true), node, item, data._type
             );
           }, 400);
-        }
+      }
     },
 
     __createMultiLineStatistics: function(data, prettifyFields) {
       var rows = data['rows'],
-          columns = data['columns'];
+        columns = data['columns'];
 
       this.columns = [];
       for (var idx in columns) {
         var rawColumn = columns[idx],
-        cell_type = typeCellMapper[rawColumn['type_code']] || 'string';
+          cell_type = typeCellMapper[rawColumn['type_code']] || 'string';
 
         // Don't show PID comma separated
-        if(rawColumn['name'] == 'PID') {
+        if (rawColumn['name'] == 'PID') {
           cell_type = cell_type.extend({
-            orderSeparator: ''
+            orderSeparator: '',
           });
         }
 
         var col = {
-            editable: false,
-            name: rawColumn['name'],
-            cell: cell_type
+          editable: false,
+          name: rawColumn['name'],
+          cell: cell_type,
         };
         if (_.indexOf(prettifyFields, rawColumn['name']) != -1) {
-          col['formatter'] = SizeFormatter
+          col['formatter'] = SizeFormatter;
         }
         this.columns.push(col);
 
@@ -351,8 +358,9 @@ define('misc.statistics', [
 
     __createSingleLineStatistics: function(data, prettifyFields) {
       var row = data['rows'][0],
-          columns = data['columns'],
-          res = [];
+        columns = data['columns'],
+        res = [],
+        name;
 
       this.columns = this.statistic_columns;
       for (var idx in columns) {
@@ -360,7 +368,9 @@ define('misc.statistics', [
         res.push({
           'statistics': name,
           // Check if row is undefined?
-          'value': row && row[name] ? ((_.indexOf(prettifyFields, name) != -1) ? sizePrettify(row[name]) : row[name]) : null
+          'value': row && row[name] ?
+            ((_.indexOf(prettifyFields, name) != -1) ?
+              sizePrettify(row[name]) : row[name]) : null,
         });
       }
 
@@ -370,9 +380,9 @@ define('misc.statistics', [
     panelVisibilityChanged: function(panel) {
       if (panel.isVisible()) {
         var t = pgBrowser.tree,
-            i = t.selected(),
-            d = i && t.itemData(i),
-            n = i && d && pgBrowser.Nodes[d._type];
+          i = t.selected(),
+          d = i && t.itemData(i),
+          n = i && d && pgBrowser.Nodes[d._type];
 
         pgBrowser.NodeStatistics.showStatistics.apply(
           pgBrowser.NodeStatistics, [i, d, n]
@@ -390,7 +400,7 @@ define('misc.statistics', [
           pgBrowser.NodeStatistics.showStatistics
         );
       }
-    }
+    },
   });
 
   return pgBrowser.NodeStatistics;
diff --git a/web/pgadmin/preferences/static/js/preferences.js b/web/pgadmin/preferences/static/js/preferences.js
index 635a6b70..d025be15 100644
--- a/web/pgadmin/preferences/static/js/preferences.js
+++ b/web/pgadmin/preferences/static/js/preferences.js
@@ -1,428 +1,455 @@
 define('pgadmin.preferences', [
-  'sources/gettext', 'sources/url_for', 'jquery', 'underscore', 'alertify',
-  'sources/pgadmin', 'backform', 'pgadmin.browser', 'pgadmin.backform'
-], function(gettext, url_for, $, _, alertify, pgAdmin, Backform, pgBrowser) {
+  'sources/gettext', 'sources/url_for', 'jquery', 'underscore', 'backbone',
+  'pgadmin.alertifyjs', 'sources/pgadmin', 'pgadmin.backform',
+  'pgadmin.browser',
+], function(
+  gettext, url_for, $, _, Backbone, Alertify, pgAdmin, Backform, pgBrowser
+) {
   // This defines the Preference/Options Dialog for pgAdmin IV.
-    pgAdmin = pgAdmin || window.pgAdmin || {};
 
-    /*
-     * Hmm... this module is already been initialized, we can refer to the old
-     * object from here.
-     */
-    if (pgAdmin.Preferences)
-        return pgAdmin.Preferences;
+  /*
+   * Hmm... this module is already been initialized, we can refer to the old
+   * object from here.
+   */
+  if (pgAdmin.Preferences)
+    return pgAdmin.Preferences;
 
-    pgAdmin.Preferences = {
-      init: function() {
-        if (this.initialized)
-          return;
+  pgAdmin.Preferences = {
+    init: function() {
+      if (this.initialized)
+        return;
+
+      this.initialized = true;
+
+      // Declare the Preferences dialog
+      Alertify.dialog('preferencesDlg', function() {
+
+        var jTree, // Variable to create the aci-tree
+          controls = [], // Keep tracking of all the backform controls
+          // created by the dialog.
+          // Dialog containter
+          $container = $('<div class=\'preferences_dialog\'></div>');
+
+
+        /*
+         * Preference Model
+         *
+         * This model will be used to keep tracking of the changes done for
+         * an individual option.
+         */
+        var PreferenceModel = Backbone.Model.extend({
+          idAttribute: 'id',
+          defaults: {
+            id: undefined,
+            value: undefined,
+          },
+        });
 
-        this.initialized = true;
+        /*
+         * Preferences Collection object.
+         *
+         * We will use only one collection object to keep track of all the
+         * preferences.
+         */
+        var changed = {},
+          preferences = this.preferences = new(Backbone.Collection.extend({
+            model: PreferenceModel,
+            url: url_for('preferences.index'),
+            updateAll: function() {
+              // We will send only the modified data to the server.
+              for (var key in changed) {
+                this.get(key).save();
+              }
 
-        // Declare the Preferences dialog
-        alertify.dialog('preferencesDlg', function() {
+              return true;
+            },
+          }))(null);
 
-          var jTree,         // Variable to create the aci-tree
-              controls = [], // Keep tracking of all the backform controls
-                             // created by the dialog.
-              // Dialog containter
-              $container = $("<div class='preferences_dialog'></div>");
+        preferences.on('reset', function() {
+          // Reset the changed variables
+          changed = {};
+        });
 
+        preferences.on('change', function(m) {
+          var id = m.get('id');
+          if (!(id in changed)) {
+            // Keep track of the original value
+            changed[id] = m._previousAttributes.value;
+          } else if (_.isEqual(m.get('value'), changed[id])) {
+            // Remove unchanged models.
+            delete changed[id];
+          }
+        });
 
+        /*
+         * Function: renderPreferencePanel
+         *
+         * Renders the preference panel in the content div based on the given
+         * preferences.
+         */
+        var renderPreferencePanel = function(prefs) {
           /*
-           * Preference Model
-           *
-           * This model will be used to keep tracking of the changes done for
-           * an individual option.
+           * Clear the existing html in the preferences content
            */
-          var PreferenceModel = Backbone.Model.extend({
-            idAttribute: 'id',
-            defaults: {
-              id: undefined,
-              value: undefined
-            }
-          });
-
+          var content = $container.find('.preferences_content');
           /*
-           * Preferences Collection object.
-           *
-           * We will use only one collection object to keep track of all the
-           * preferences.
+           * We should clean up the existing controls.
            */
-          var changed = {},
-              preferences = this.preferences = new (Backbone.Collection.extend({
-                model: PreferenceModel,
-                url: url_for('preferences.index'),
-                updateAll: function() {
-                  var cnt = 0;
-                  // We will send only the modified data to the server.
-                  for (var key in changed) {
-                    this.get(key).save();
-                  }
+          if (controls) {
+            _.each(controls, function(c) {
+              if ('$sel' in c) {
+                if (c.$sel.data('select2').isOpen()) c.$sel.data('select2').close();
+              }
+              c.remove();
+            });
+          }
+          content.empty();
+          controls = [];
 
-                  return true;
-                }
-              }))(null);
+          /*
+           * We will create new set of controls and render it based on the
+           * list of preferences using the Backform Field, Control.
+           */
+          _.each(prefs, function(p) {
+
+            var m = preferences.get(p.id);
+            m.errorModel = new Backbone.Model();
+            var f = new Backform.Field(
+                _.extend({}, p, {
+                  id: 'value',
+                  name: 'value',
+                })
+              ),
+              cntr = new(f.get('control'))({
+                field: f,
+                model: m,
+              });
+            content.append(cntr.render().$el);
 
-          preferences.on('reset', function() {
-            // Reset the changed variables
-            changed = {};
+            // We will keep track of all the controls rendered at the
+            // moment.
+            controls.push(cntr);
           });
 
-          preferences.on('change', function(m) {
-            var id = m.get('id');
-            if (!(id in changed)) {
-              // Keep track of the original value
-              changed[id] = m._previousAttributes.value;
-            } else if (_.isEqual(m.get('value'), changed[id])) {
-              // Remove unchanged models.
-              delete changed[id];
-            }
-          });
+        };
+
+        /*
+         * Function: dialogContentCleanup
+         *
+         * Do the dialog container cleanup on openning.
+         */
+
+        var dialogContentCleanup = function() {
+            // Remove the existing preferences
+            if (!jTree)
+              return;
 
-          /*
-           * Function: renderPreferencePanel
-           *
-           * Renders the preference panel in the content div based on the given
-           * preferences.
-           */
-          var renderPreferencePanel = function(prefs) {
             /*
-             * Clear the existing html in the preferences content
+             * Remove the aci-tree (mainly to remove the jquery object of
+             * aciTree from the system for this container).
              */
-            var content = $container.find('.preferences_content');
+            try {
+              jTree.aciTree('destroy');
+            } catch (ex) {
+              // Sometimes - it fails to destroy the tree properly and throws
+              // exception.
+              console.warn(ex.stack || ex);
+            }
+            jTree.off('acitree', treeEventHandler);
+
+            // We need to reset the data from the preferences too
+            preferences.reset();
+
             /*
-             * We should clean up the existing controls.
+             * Clean up the existing controls.
              */
             if (controls) {
               _.each(controls, function(c) {
-                if ('$sel' in c) {
-                  if (c.$sel.data('select2').isOpen()) c.$sel.data('select2').close();
-                }
                 c.remove();
               });
             }
-            content.empty();
             controls = [];
 
-            /*
-             * We will create new set of controls and render it based on the
-             * list of preferences using the Backform Field, Control.
-             */
-            _.each(prefs, function(p) {
-
-              var m = preferences.get(p.id);
-              m.errorModel = new Backbone.Model();
-              var f = new Backform.Field(
-                    _.extend({}, p, {id: 'value', name: 'value'})
-                    ),
-                  cntr = new (f.get("control")) ({
-                    field: f,
-                    model: m
-                  });
-                  content.append(cntr.render().$el);
-
-                  // We will keep track of all the controls rendered at the
-                  // moment.
-                  controls.push(cntr);
-            });
-
-          };
-
+            // Remove all the objects now.
+            $container.empty();
+          },
           /*
-           * Function: dialogContentCleanup
+           * Function: selectFirstCategory
            *
-           * Do the dialog container cleanup on openning.
+           * Whenever a user select a module instead of a category, we should
+           * select the first categroy of it.
            */
+          selectFirstCategory = function(api, item) {
+            var data = item ? api.itemData(item) : null;
 
-          var dialogContentCleanup = function() {
-              // Remove the existing preferences
-              if (!jTree)
-                return;
-
-              /*
-               * Remove the aci-tree (mainly to remove the jquery object of
-               * aciTree from the system for this container).
-               */
-              try {
-                jTreeApi = jTree.aciTree('destroy');
-              } catch(ex) {
-                // Sometimes - it fails to destroy the tree properly and throws
-                // exception.
-              }
-              jTree.off('acitree', treeEventHandler);
-
-              // We need to reset the data from the preferences too
-              preferences.reset();
-
-              /*
-               * Clean up the existing controls.
-               */
-              if (controls) {
-                _.each(controls, function(c) {
-                  c.remove();
+            if (data && data.preferences) {
+              api.select(item);
+              return;
+            }
+            item = api.first(item);
+            selectFirstCategory(api, item);
+          },
+          /*
+           * A map on how to create controls for each datatype in preferences
+           * dialog.
+           */
+          getControlMappedForType = function(p) {
+            switch (p.type) {
+            case 'text':
+              return 'input';
+            case 'boolean':
+              p.options = {
+                onText: gettext('True'),
+                offText: gettext('False'),
+                onColor: 'success',
+                offColor: 'default',
+                size: 'mini',
+              };
+              return 'switch';
+            case 'node':
+              p.options = {
+                onText: gettext('Show'),
+                offText: gettext('Hide'),
+                onColor: 'success',
+                offColor: 'default',
+                size: 'mini',
+              };
+              return 'switch';
+            case 'integer':
+              return 'numeric';
+            case 'numeric':
+              return 'numeric';
+            case 'date':
+              return 'datepicker';
+            case 'datetime':
+              return 'datetimepicker';
+            case 'options':
+              var opts = [],
+                has_value = false;
+                // Convert the array to SelectControl understandable options.
+              _.each(p.options, function(o) {
+                if ('label' in o && 'value' in o) {
+                  opts.push({
+                    'label': o.label,
+                    'value': o.value,
+                  });
+                  if (o.value == p.value)
+                    has_value = true;
+                } else {
+                  opts.push({
+                    'label': o,
+                    'value': o,
+                  });
+                  if (o == p.value)
+                    has_value = true;
+                }
+              });
+              if (p.select2 && p.select2.tags == true && p.value && has_value == false) {
+                opts.push({
+                  'label': p.value,
+                  'value': p.value,
                 });
               }
-              controls = [];
+              p.options = opts;
+              return 'select2';
+            case 'multiline':
+              return 'textarea';
+            case 'switch':
+              return 'switch';
+            default:
+              if (console && console.warn) {
+                  // Warning for developer only.
+                console.warn(
+                    'Hmm.. We don\'t know how to render this type - \'\'' + p.type + '\' of control.'
+                  );
+              }
+              return 'input';
+            }
+          },
+          /*
+           * function: treeEventHandler
+           *
+           * It is basically a callback, which listens to aci-tree events,
+           * and act accordingly.
+           *
+           * + Selection of the node will existance of the preferences for
+           *   the selected tree-node, if not pass on to select the first
+           *   category under a module, else pass on to the render function.
+           *
+           * + When a new node is added in the tree, it will add the relavent
+           *   preferences in the preferences model collection, which will be
+           *   called during initialization itself.
+           *
+           *
+           */
+          treeEventHandler = function(event, api, item, eventName) {
+            // Look for selected item (if none supplied)!
+            item = item || api.selected();
 
-              // Remove all the objects now.
-              $container.empty();
-            },
-            /*
-             * Function: selectFirstCategory
-             *
-             * Whenever a user select a module instead of a category, we should
-             * select the first categroy of it.
-             */
-            selectFirstCategory = function(api, item) {
-              var  data = item ? api.itemData(item) : null;
+            // Event tree item has itemData
+            var d = item ? api.itemData(item) : null;
 
-              if (data && data.preferences) {
-                  api.select(item);
-                  return;
-              }
-              item = api.first(item);
-              selectFirstCategory(api, item);
-            },
             /*
-             * A map on how to create controls for each datatype in preferences
-             * dialog.
+             * boolean (switch/checkbox), string, enum (combobox - enumvals),
+             * integer (min-max), font, color
              */
-            getControlMappedForType = function(p) {
-              switch(p.type) {
-                case 'text':
-                    return 'input';
-                case 'boolean':
-                  p.options = {
-                      onText: gettext('True'),
-                      offText: gettext('False'),
-                      onColor: 'success',
-                      offColor: 'default',
-                      size: 'mini'
-                    };
-                  return 'switch';
-                case 'node':
-                    p.options = {
-                      onText: gettext('Show'),
-                      offText: gettext('Hide'),
-                      onColor: 'success',
-                      offColor: 'default',
-                      size: 'mini'
-                    };
-                    return 'switch';
-                case 'integer':
-                  return 'numeric';
-                case 'numeric':
-                  return 'numeric';
-                case 'date':
-                  return 'datepicker';
-                case 'datetime':
-                  return 'datetimepicker';
-                case 'options':
-                  var opts = [],
-                      has_value = false;
-                  // Convert the array to SelectControl understandable options.
-                  _.each(p.options, function(o) {
-                    if('label' in o && 'value' in o){
-                      opts.push({'label': o.label, 'value': o.value});
-                      if (o.value == p.value)
-                        has_value = true;
-                    } else {
-                      opts.push({'label': o, 'value': o});
-                      if (o == p.value)
-                         has_value = true;
-                    }
-                  });
-                  if (p.select2 && p.select2.tags == true && p.value && has_value == false){
-                    opts.push({'label': p.value, 'value': p.value});
-                  }
-                  p.options = opts;
-                  return 'select2';
-                case 'multiline':
-                  return 'textarea';
-                case 'switch':
-                  return 'switch';
-                default:
-                    if (console && console.log) {
-                      // Warning for developer only.
-                       console.log(
-                         "Hmm.. We don't know how to render this type - ''" + type + "' of control."
-                       );
-                    }
-                  return 'input';
+            switch (eventName) {
+            case 'selected':
+              if (!d)
+                return true;
+
+              if (d.preferences) {
+                  /*
+                   * Clear the existing html in the preferences content
+                   */
+                renderPreferencePanel(d.preferences);
+
+                return true;
+              } else {
+                selectFirstCategory(api, item);
               }
-            },
-            /*
-             * function: treeEventHandler
-             *
-             * It is basically a callback, which listens to aci-tree events,
-             * and act accordingly.
-             *
-             * + Selection of the node will existance of the preferences for
-             *   the selected tree-node, if not pass on to select the first
-             *   category under a module, else pass on to the render function.
-             *
-             * + When a new node is added in the tree, it will add the relavent
-             *   preferences in the preferences model collection, which will be
-             *   called during initialization itself.
-             *
-             *
-             */
-            treeEventHandler = function(event, api, item, eventName) {
-              // Look for selected item (if none supplied)!
-              item = item || api.selected();
-
-              // Event tree item has itemData
-              var d = item ? api.itemData(item) : null;
-
-              /*
-               * boolean (switch/checkbox), string, enum (combobox - enumvals),
-               * integer (min-max), font, color
-               */
-              switch (eventName) {
-                case "selected":
-                  if (!d)
-                    return true;
-
-                  if (d.preferences) {
+              break;
+            case 'added':
+              if (!d)
+                return true;
+
+                // We will add the preferences in to the preferences data
+                // collection.
+              if (d.preferences && _.isArray(d.preferences)) {
+                _.each(d.preferences, function(p) {
+                  preferences.add({
+                    'id': p.id,
+                    'value': p.value,
+                    'category_id': d.id,
+                    'mid': d.mid,
+                    'name': p.name,
+                  });
                     /*
-                     * Clear the existing html in the preferences content
+                     * We don't know until now, how to render the control for
+                     * this preference.
                      */
-                    renderPreferencePanel(d.preferences);
-
-                    return true;
-                  } else{
-                    selectFirstCategory(api, item);
+                  if (!p.control) {
+                    p.control = getControlMappedForType(p);
                   }
-                  break;
-                case 'added':
-                  if (!d)
-                    return true;
-
-                  // We will add the preferences in to the preferences data
-                  // collection.
-                  if (d.preferences && _.isArray(d.preferences)) {
-                    _.each(d.preferences, function(p) {
-                      preferences.add({
-                        'id': p.id, 'value': p.value, 'category_id': d.id,
-                        'mid': d.mid, 'name': p.name,
-                      });
-                      /*
-                       * We don't know until now, how to render the control for
-                       * this preference.
-                       */
-                      if (!p.control) {
-                        p.control = getControlMappedForType(p);
-                      }
-                      if (p.help_str) {
-                        p.helpMessage = p.help_str;
-                      }
-                    });
+                  if (p.help_str) {
+                    p.helpMessage = p.help_str;
                   }
-                  d.sortable = false;
-                  break;
-                case 'loaded':
-                  // Let's select the first category from the prefrences.
-                  // We need to wait for sometime before all item gets loaded
-                  // properly.
-                  setTimeout(
-                    function() {
-                      selectFirstCategory(api, null);
-                    }, 300);
-                  break;
+                });
               }
-              return true;
+              d.sortable = false;
+              break;
+            case 'loaded':
+                // Let's select the first category from the prefrences.
+                // We need to wait for sometime before all item gets loaded
+                // properly.
+              setTimeout(
+                  function() {
+                    selectFirstCategory(api, null);
+                  }, 300);
+              break;
+            }
+            return true;
           };
 
-          // Dialog property
-          return {
-            main: function() {
-
-              // Remove the existing content first.
-              dialogContentCleanup();
-
-              $container.append(
-                "<div class='pg-el-xs-3 preferences_tree aciTree'></div>"
-              ).append(
-                "<div class='pg-el-xs-9 preferences_content'>" +
-                gettext('Category is not selected.') +
-                "</div>"
-              );
-
-              // Create the aci-tree for listing the modules and categories of
-              // it.
-              jTree = $container.find('.preferences_tree');
-              jTree.on('acitree', treeEventHandler);
-
-              jTree.aciTree({
-                selectable: true,
-                expand: true,
-                ajax: {
-                  url: url_for('preferences.index')
-                }
-              });
+        // Dialog property
+        return {
+          main: function() {
+
+            // Remove the existing content first.
+            dialogContentCleanup();
+
+            $container.append(
+              '<div class=\'pg-el-xs-3 preferences_tree aciTree\'></div>'
+            ).append(
+              '<div class=\'pg-el-xs-9 preferences_content\'>' +
+              gettext('Category is not selected.') +
+              '</div>'
+            );
+
+            // Create the aci-tree for listing the modules and categories of
+            // it.
+            jTree = $container.find('.preferences_tree');
+            jTree.on('acitree', treeEventHandler);
+
+            jTree.aciTree({
+              selectable: true,
+              expand: true,
+              ajax: {
+                url: url_for('preferences.index'),
+              },
+            });
 
-              this.show();
-            },
-            setup: function() {
-              return {
-                buttons:[{
-                  text: '', key: 112,
-                  className: 'btn btn-default pull-left fa fa-lg fa-question',
-                  attrs:{
-                    name:'dialog_help', type:'button',
-                    label: gettext('Preferences'),
-                    url: url_for(
-                      'help.static', {'filename': 'preferences.html'}
-                    )
-                  }
-                },{
-                  text: gettext('OK'), key: 13, className: "btn btn-primary fa fa-lg fa-save pg-alertify-button"
-                },{
-                  text: gettext('Cancel'), key: 27, className: "btn btn-danger fa fa-lg fa-times pg-alertify-button"
-                }],
-                focus: { element: 0 },
-                options: {
-                  padding: !1,
-                  overflow: !1,
-                  title: gettext('Preferences'),
-                  closableByDimmer: false,
-                  modal:false,
-                  pinnable: false
-                }
-              };
-            },
-            callback: function(e) {
-              if (e.button.element.name == "dialog_help") {
-                  e.cancel = true;
-                  pgBrowser.showHelp(e.button.element.name, e.button.element.getAttribute('url'),
-                    null, null, e.button.element.getAttribute('label'));
-                  return;
-               }
-
-              if (e.button.text == gettext('OK')){
-                  preferences.updateAll();
-                  // Refresh preferences cache
-                  setTimeout(pgBrowser.cache_preferences(), 2000);
-              }
-            },
-            build: function() {
-              this.elements.content.appendChild($container.get(0));
-              alertify.pgDialogBuild.apply(this)
-            },
-            hooks: {
-              onshow: function() {
-                $(this.elements.body).addClass('pgadmin-preference-body');
-              }
+            this.show();
+          },
+          setup: function() {
+            return {
+              buttons: [{
+                text: '',
+                key: 112,
+                className: 'btn btn-default pull-left fa fa-lg fa-question',
+                attrs: {
+                  name: 'dialog_help',
+                  type: 'button',
+                  label: gettext('Preferences'),
+                  url: url_for(
+                    'help.static', {
+                      'filename': 'preferences.html',
+                    }
+                  ),
+                },
+              }, {
+                text: gettext('OK'),
+                key: 13,
+                className: 'btn btn-primary fa fa-lg fa-save pg-alertify-button',
+              }, {
+                text: gettext('Cancel'),
+                key: 27,
+                className: 'btn btn-danger fa fa-lg fa-times pg-alertify-button',
+              }],
+              focus: {
+                element: 0,
+              },
+              options: {
+                padding: !1,
+                overflow: !1,
+                title: gettext('Preferences'),
+                closableByDimmer: false,
+                modal: false,
+                pinnable: false,
+              },
+            };
+          },
+          callback: function(e) {
+            if (e.button.element.name == 'dialog_help') {
+              e.cancel = true;
+              pgBrowser.showHelp(e.button.element.name, e.button.element.getAttribute('url'),
+                null, null, e.button.element.getAttribute('label'));
+              return;
             }
-          };
-        });
-
-      },
-      show: function() {
-        alertify.preferencesDlg(true).resizeTo('60%', '60%');
-      }
-    };
 
-    return pgAdmin.Preferences;
-  });
+            if (e.button.text == gettext('OK')) {
+              preferences.updateAll();
+              // Refresh preferences cache
+              setTimeout(pgBrowser.cache_preferences(), 2000);
+            }
+          },
+          build: function() {
+            this.elements.content.appendChild($container.get(0));
+            Alertify.pgDialogBuild.apply(this);
+          },
+          hooks: {
+            onshow: function() {
+              $(this.elements.body).addClass('pgadmin-preference-body');
+            },
+          },
+        };
+      });
+
+    },
+    show: function() {
+      Alertify.preferencesDlg(true).resizeTo('60%', '60%');
+    },
+  };
+
+  return pgAdmin.Preferences;
+});
diff --git a/web/pgadmin/settings/static/js/settings.js b/web/pgadmin/settings/static/js/settings.js
index 2194955c..634368cf 100644
--- a/web/pgadmin/settings/static/js/settings.js
+++ b/web/pgadmin/settings/static/js/settings.js
@@ -1,59 +1,59 @@
-define('pgadmin.settings',
-  [
-    'jquery', 'alertify', 'sources/pgadmin', 'underscore', 'backform',
-    'sources/gettext', 'sources/url_for', 'pgadmin.backform'
-  ],
+define('pgadmin.settings', [
+  'jquery', 'pgadmin.alertifyjs', 'sources/pgadmin',
+  'sources/gettext', 'sources/url_for', 'pgadmin.backform',
+], function($, Alertify, pgAdmin, gettext, url_for) {
+
   // This defines the Preference/Options Dialog for pgAdmin IV.
-  function($, alertify, pgAdmin, _, Backform, gettext, url_for) {
-    pgAdmin = pgAdmin || window.pgAdmin || {};
+  pgAdmin = pgAdmin || window.pgAdmin || {};
 
-    /*
-     * Hmm... this module is already been initialized, we can refer to the old
-     * object from here.
-     */
-    if (pgAdmin.Settings)
-        return pgAdmin.Settings;
+  /*
+   * Hmm... this module is already been initialized, we can refer to the old
+   * object from here.
+   */
+  if (pgAdmin.Settings)
+    return pgAdmin.Settings;
 
-    pgAdmin.Settings = {
-      init: function() {
-        if (this.initialized)
-          return;
+  pgAdmin.Settings = {
+    init: function() {
+      if (this.initialized)
+        return;
 
-        this.initialized = true;
-      },
-      // We will force unload method to not to save current layout
-      // and reload the window
-      show: function() {
-        var obj = this;
-        alertify.confirm(gettext('Reset layout'),
-          gettext('Are you sure you want to reset the current layout? This will cause the application to reload and any un-saved data will be lost.'),
-          function() {
-            var reloadingIndicator = $('<div id="reloading-indicator"></div>');
-            $('body').append(reloadingIndicator);
-            // Delete the record from database as well, then only reload page
-            $.ajax({
-              url: url_for('settings.reset_layout'),
-              type: 'DELETE',
-              async: false,
-              success: function() {
-                // Prevent saving layout on server for next page reload.
-                $(window).unbind('unload');
-                window.onbeforeunload = null;
-                // Now reload page
-                location.reload(true);
-              },
-              error: function() {
-                console.log('Something went wrong on server while resetting layout');
-              }
-            });
+      this.initialized = true;
+    },
+    // We will force unload method to not to save current layout
+    // and reload the window
+    show: function() {
+      Alertify.confirm(gettext('Reset layout'),
+        gettext('Are you sure you want to reset the current layout? This will cause the application to reload and any un-saved data will be lost.'),
+        function() {
+          var reloadingIndicator = $('<div id="reloading-indicator"></div>');
+          $('body').append(reloadingIndicator);
+          // Delete the record from database as well, then only reload page
+          $.ajax({
+            url: url_for('settings.reset_layout'),
+            type: 'DELETE',
+            async: false,
+            success: function() {
+              // Prevent saving layout on server for next page reload.
+              $(window).unbind('unload');
+              window.onbeforeunload = null;
+              // Now reload page
+              location.reload(true);
+            },
+            error: function() {
+              console.warn(
+                'Something went wrong on server while resetting layout.'
+              );
+            },
+          });
 
-          },
-          function() {
-            // Do nothing as user canceled the operation.
-          }
-        );
-      }
-    };
+        },
+        function() {
+          // Do nothing as user canceled the operation.
+        }
+      );
+    },
+  };
 
-    return pgAdmin.Settings;
-  });
+  return pgAdmin.Settings;
+});
