Browse Source

[ui] Convert Hue to jQuery

* Updated Beeswax
* Upgraded jQuery to 1.7
* Styled filechooser
* Added fileuploader
* Initial support for table creation
* Initial import for Shell app
* Improved Filebrowser and JobDesigner, WIP
* Improved usability and look'n'feel
* Added sign out link and fixed login page
* Updated colors, fixed bugs on filebrowser
* Update H1 consistency on Beeswax
* Updated H1 consistency in JobBrowser
* Sample material for Babel i18n
* Implementation of common header and footer on Desktop
Enrico Berti 15 years ago
parent
commit
5239e04e96
100 changed files with 9385 additions and 4845 deletions
  1. 4 0
      .gitignore
  2. 21 18
      apps/about/src/about/templates/index.mako
  3. 76 19
      apps/beeswax/src/beeswax/templates/beeswax_components.mako
  4. 97 76
      apps/beeswax/src/beeswax/templates/choose_delimiter.mako
  5. 124 57
      apps/beeswax/src/beeswax/templates/choose_file.mako
  6. 23 7
      apps/beeswax/src/beeswax/templates/configuration.mako
  7. 14 7
      apps/beeswax/src/beeswax/templates/confirm.html
  8. 8 3
      apps/beeswax/src/beeswax/templates/create_table_index.mako
  9. 526 282
      apps/beeswax/src/beeswax/templates/create_table_manually.mako
  10. 80 77
      apps/beeswax/src/beeswax/templates/define_columns.mako
  11. 12 6
      apps/beeswax/src/beeswax/templates/describe_partitions.mako
  12. 177 101
      apps/beeswax/src/beeswax/templates/describe_table.mako
  13. 345 224
      apps/beeswax/src/beeswax/templates/execute.mako
  14. 29 23
      apps/beeswax/src/beeswax/templates/explain.mako
  15. 0 70
      apps/beeswax/src/beeswax/templates/header_footer.mako
  16. 44 0
      apps/beeswax/src/beeswax/templates/layout.mako
  17. 68 29
      apps/beeswax/src/beeswax/templates/list_designs.mako
  18. 65 45
      apps/beeswax/src/beeswax/templates/list_history.mako
  19. 9 3
      apps/beeswax/src/beeswax/templates/load_table.mako
  20. 175 131
      apps/beeswax/src/beeswax/templates/my_queries.mako
  21. 9 3
      apps/beeswax/src/beeswax/templates/parameterization.mako
  22. 9 4
      apps/beeswax/src/beeswax/templates/report_gen.mako
  23. 9 4
      apps/beeswax/src/beeswax/templates/save_results.mako
  24. 71 24
      apps/beeswax/src/beeswax/templates/show_tables.mako
  25. 4 5
      apps/beeswax/src/beeswax/templates/util.mako
  26. 115 104
      apps/beeswax/src/beeswax/templates/watch_results.mako
  27. 58 53
      apps/beeswax/src/beeswax/templates/watch_wait.mako
  28. 0 1183
      apps/beeswax/static/css/beeswax.css
  29. 0 90
      apps/filebrowser/src/filebrowser/plugin/toolbar.py
  30. 1249 0
      apps/filebrowser/src/filebrowser/static/fileuploader.js
  31. 45 46
      apps/filebrowser/src/filebrowser/templates/chmod.mako
  32. 3 9
      apps/filebrowser/src/filebrowser/templates/chooser.mako
  33. 32 30
      apps/filebrowser/src/filebrowser/templates/chown.mako
  34. 66 51
      apps/filebrowser/src/filebrowser/templates/display.mako
  35. 78 23
      apps/filebrowser/src/filebrowser/templates/edit.mako
  36. 19 11
      apps/filebrowser/src/filebrowser/templates/editor_components.mako
  37. 15 9
      apps/filebrowser/src/filebrowser/templates/fileop.mako
  38. 121 0
      apps/filebrowser/src/filebrowser/templates/header_footer.mako
  39. 16 6
      apps/filebrowser/src/filebrowser/templates/listdir.mako
  40. 383 45
      apps/filebrowser/src/filebrowser/templates/listdir_components.mako
  41. 14 14
      apps/filebrowser/src/filebrowser/templates/mkdir.mako
  42. 19 18
      apps/filebrowser/src/filebrowser/templates/move.mako
  43. 14 14
      apps/filebrowser/src/filebrowser/templates/rename.mako
  44. 41 14
      apps/filebrowser/src/filebrowser/templates/upload.mako
  45. 3 5
      apps/filebrowser/src/filebrowser/templates/upload_done.mako
  46. 727 658
      apps/filebrowser/src/filebrowser/views.py
  47. 8 13
      apps/hello/src/hello/templates/hello.mako
  48. 2 2
      apps/hello/src/hello/views.py
  49. 19 22
      apps/help/src/help/templates/display.mako
  50. 8 4
      apps/jobbrowser/src/jobbrowser/templates/attempt.mako
  51. 224 145
      apps/jobbrowser/src/jobbrowser/templates/job.mako
  52. 43 63
      apps/jobbrowser/src/jobbrowser/templates/jobbrowser_components.mako
  53. 113 94
      apps/jobbrowser/src/jobbrowser/templates/jobs.mako
  54. 160 112
      apps/jobbrowser/src/jobbrowser/templates/task.mako
  55. 87 97
      apps/jobbrowser/src/jobbrowser/templates/tasks.mako
  56. 42 36
      apps/jobbrowser/src/jobbrowser/templates/tasktracker.mako
  57. 51 35
      apps/jobbrowser/src/jobbrowser/templates/tasktrackers.mako
  58. 5 0
      apps/jobsub/babel.cfg
  59. 23 0
      apps/jobsub/src/jobsub/locale/django.pot
  60. BIN
      apps/jobsub/src/jobsub/locale/en_US/LC_MESSAGES/django.mo
  61. 23 0
      apps/jobsub/src/jobsub/locale/en_US/LC_MESSAGES/django.po
  62. BIN
      apps/jobsub/src/jobsub/locale/it/LC_MESSAGES/django.mo
  63. 23 0
      apps/jobsub/src/jobsub/locale/it/LC_MESSAGES/django.po
  64. 4 3
      apps/jobsub/src/jobsub/templates/confirm.html
  65. 55 47
      apps/jobsub/src/jobsub/templates/edit.html
  66. 19 18
      apps/jobsub/src/jobsub/templates/forms/basic_parameterization.html
  67. 29 27
      apps/jobsub/src/jobsub/templates/forms/jar.html
  68. 213 183
      apps/jobsub/src/jobsub/templates/forms/streaming.html
  69. 76 11
      apps/jobsub/src/jobsub/templates/layout.html
  70. 101 54
      apps/jobsub/src/jobsub/templates/list.html
  71. 25 23
      apps/jobsub/src/jobsub/templates/parameterize.html
  72. 27 25
      apps/jobsub/src/jobsub/templates/scripteditor.html
  73. 2 2
      apps/jobsub/src/jobsub/templates/types.html
  74. 58 32
      apps/jobsub/src/jobsub/templates/watch.html
  75. 25 18
      apps/jobsub/src/jobsub/templates/watch_submission.html
  76. 31 17
      apps/shell/src/shell/templates/failed_to_create.mako
  77. 239 22
      apps/shell/src/shell/templates/index.mako
  78. 26 14
      apps/shell/src/shell/templates/no_such_user.mako
  79. 24 13
      apps/shell/src/shell/templates/not_running_spawning.mako
  80. 0 49
      apps/shell/src/shell/templates/shared_components.mako
  81. 2 0
      apps/useradmin/babel.cfg
  82. 39 0
      apps/useradmin/src/useradmin/locale/django.pot
  83. 39 0
      apps/useradmin/src/useradmin/locale/en_US/LC_MESSAGES/django.po
  84. 40 0
      apps/useradmin/src/useradmin/locale/it/LC_MESSAGES/django.po
  85. 12 8
      apps/useradmin/src/useradmin/templates/confirm.mako
  86. 38 35
      apps/useradmin/src/useradmin/templates/edit_user.mako
  87. 92 18
      apps/useradmin/src/useradmin/templates/list_users.mako
  88. 10 2
      apps/useradmin/static/css/useradmin.css
  89. 28 0
      desktop/core/ext-py/Babel-0.9.6/COPYING
  90. 181 0
      desktop/core/ext-py/Babel-0.9.6/ChangeLog
  91. 39 0
      desktop/core/ext-py/Babel-0.9.6/INSTALL.txt
  92. 4 0
      desktop/core/ext-py/Babel-0.9.6/MANIFEST.in
  93. 18 0
      desktop/core/ext-py/Babel-0.9.6/PKG-INFO
  94. 12 0
      desktop/core/ext-py/Babel-0.9.6/README.txt
  95. 39 0
      desktop/core/ext-py/Babel-0.9.6/babel/__init__.py
  96. 790 0
      desktop/core/ext-py/Babel-0.9.6/babel/core.py
  97. 991 0
      desktop/core/ext-py/Babel-0.9.6/babel/dates.py
  98. BIN
      desktop/core/ext-py/Babel-0.9.6/babel/global.dat
  99. 209 0
      desktop/core/ext-py/Babel-0.9.6/babel/localedata.py
  100. BIN
      desktop/core/ext-py/Babel-0.9.6/babel/localedata/aa.dat

+ 4 - 0
.gitignore

@@ -1,10 +1,14 @@
 # OS X nonsense
 .DS_Store
+._*
 
 # Python compiled files
 *.pyc
 *.pyo
 
+# Language compiled files
+*.mo
+
 # vim tmp files
 .*.swp
 .*.swo

+ 21 - 18
apps/about/src/about/templates/index.mako

@@ -13,24 +13,27 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<!DOCTYPE html>
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+${commonheader("About jHue", "about", "100px")}
+	<div class="menubar">
+		<div class="menubar-inner">
+			<div class="container-fluid">
+				<ul class="nav">
+					<li><a href="${url("desktop.views.dump_config")}">Configuration</a></li>
+					<li><a href="${url("desktop.views.check_config")}">Check for misconfiguration</a></li>
+					<li><a href="${url("desktop.views.log_view")}">Server Logs</a></li>
+				</ul>
+			</div>
+		</div>
+	</div>
+	
+	<div class="container-fluid">
 
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
-	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-	<title>About - Hue</title>
-</head>
-
-<body>
-	<center>
 		<img src="/static/art/help/logo.png" />
-		<p>Hue</p>
-		<p>${version}</p>
-                <p>&nbsp;</p>
-                <p><a target="_blank" href="${url("desktop.views.dump_config")}">Configuration</a></p>
-                <p><a target="_blank" href="${url("desktop.views.check_config")}">Check for Misconfiguration</a></p>
-                <p><a target="_blank" href="${url("desktop.views.log_view")}">Server Logs</a></p>
-	</center>
-</body>
+		<p>Hue ${version}</p>
+
+	</div>
 
-</html>
+${commonfooter()}

+ 76 - 19
apps/beeswax/src/beeswax/templates/beeswax_components.mako

@@ -16,6 +16,66 @@
 <%!
   from desktop.lib.django_util import extract_field_data
 %>
+<%def name="fieldName(field)">
+
+</%def>
+
+<%def name="label(
+  field, 
+  render_default=False, 
+  data_filters=None,
+  hidden=False, 
+  notitle=False, 
+  tag='input', 
+  klass=None, 
+  attrs=None, 
+  value=None, 
+  help=False, 
+  help_attrs=None, 
+  dd_attrs=None, 
+  dt_attrs=None, 
+  title_klass=None,
+  button_text=False
+  )">
+<%
+  if value is None:
+    value = extract_field_data(field)
+
+  def make_attr_str(attributes):
+    if attributes is None:
+      attributes = {}
+    ret_str = ""
+    for key, value in attributes.iteritems():
+      if key == "klass":
+        key = "class"
+      ret_str += "%s='%s'" % (key.replace("_", "-"), unicode(value))
+    return ret_str
+
+  if not attrs:
+    attrs = {}
+  if not render_default:
+    attrs.setdefault('type', 'text')
+    
+  if data_filters:
+    attrs.data_filters = data_filters
+  
+  classes = []
+  if klass:
+    classes.append(klass)
+  if hidden: 
+    classes.append("jframe-hidden")
+  cls = ' '.join(classes)
+
+  title_classes = []
+  if title_klass:
+    title_classes.append(title_klass)
+  if notitle or hidden:
+    title_classes.append("jframe-hidden")
+  titlecls = ' '.join(title_classes)
+%>
+	${field.label_tag() | n}
+</%def>
+
 
 <%def name="field(
   field, 
@@ -73,8 +133,6 @@
   % if field.is_hidden:
     ${unicode(field) | n}
   % else:
-    <dt class="${titlecls}" ${make_attr_str(dt_attrs) | n}>${field.label_tag() | n}</dt>
-    <dd class="${cls}" ${make_attr_str(dd_attrs) | n}>
       % if render_default:
         ${unicode(field) | n}
       % else:
@@ -83,20 +141,20 @@
         % elif tag == 'button':
           <button name="${field.html_name | n}" ${make_attr_str(attrs) | n} value="${value}"/>${button_text or field.name or ''}</button>
         % elif tag == 'checkbox':
-          <input type="checkbox" name="${field.html_name | n}" ${make_attr_str(attrs) | n} ${value and "CHECKED" or ""}/>${button_text or field.name or ''}</input>
+			% if help:
+				<input type="checkbox" name="${field.html_name | n}" ${make_attr_str(attrs) | n} ${value and "CHECKED" or ""}/ /> <span rel="popover" data-content="${help}" >${button_text or field.name or ''}</span>
+			% else:
+				<input type="checkbox" name="${field.html_name | n}" ${make_attr_str(attrs) | n} ${value and "CHECKED" or ""}/> <span>${button_text or field.name or ''}</span>
+			% endif
         % else:
           <${tag} name="${field.html_name | n}" value="${extract_field_data(field) or ''}" ${make_attr_str(attrs) | n} />
         % endif
+		
       % endif
-      % if help:
-        <p class="jframe-inline" data-filters="HelpTip" ${make_attr_str(help_attrs) | n}>${help}</p>
-      % endif
-    </dd>
     % if len(field.errors):
-      <dd class="beeswax_error jframe-error">
          ${unicode(field.errors) | n}
-       </dd>
     % endif
+
   % endif
 </%def>
 
@@ -121,14 +179,13 @@
   ${pageref(page.num_pages())}
 </%def>
 <%def name="pagination(page)">
-  <div class="toolbar bw-designs_toolbar bw-navigation">
-    <p class="bw-showing_msg">Showing ${page.start_index()} to ${page.end_index()} of ${page.total_count()} items</p>
-    <div class="bw-nav_links">
-      <a title="Beginning of List" ${toppage(page)} class="bw-firstBlock">Beginning of List</a>
-      <a title="Previous Page" ${prevpage(page)} class="bw-prevBlock">Previous Page</a>
-      <p>page ${page.number} of ${page.num_pages()}</p>
-      <a title="Next page" ${nextpage(page)} class="bw-nextBlock">Next Page</a>
-      <a title="End of List" ${bottompage(page)} class="bw-lastBlock">End of List</a>
-    </div>
-  </div>
+	<p>Showing ${page.start_index()} to ${page.end_index()} of ${page.total_count()} items, page ${page.number} of ${page.num_pages()}</p>
+	<div class="pagination">
+	  <ul>
+	    <li class="prev"><a title="Beginning of List" ${toppage(page)} class="bw-firstBlock">&larr; Beginning of List</a></li>
+	    <li><a title="Previous Page" ${prevpage(page)} class="bw-prevBlock">Previous Page</a></li>
+		<li><a title="Next page" ${nextpage(page)} class="bw-nextBlock">Next Page</a></li>
+	    <li class="next"><a title="End of List" ${bottompage(page)} class="bw-lastBlock">End of List &rarr;</a></li>
+	  </ul>
+	</div>
 </%def>

+ 97 - 76
apps/beeswax/src/beeswax/templates/choose_delimiter.mako

@@ -13,83 +13,104 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="comps" file="beeswax_components.mako" />
 <%namespace name="util" file="util.mako" />
-${wrappers.head('Choose a Delimiter')}
-<div class="toolbar">
-  <ul data-filters="Breadcrumb" class="clearfix">
-    ## TODO(marcus) These links should be part of the form, and do POST
-    <li><a href="${ url('beeswax.create_table.import_wizard') }">Choose File</a></li>
-    <li class="tabSelected"><a href="${ url('beeswax.create_table.import_wizard') }">Choose Delimiter</a></li>
-    <li><a href="${ url('beeswax.create_table.import_wizard') }">Define Columns</a></li>
-  </ul>
-</div>
-<div class="view" id="choose-delimiter">
-    <div class="bw-choose-delimiter">
-        <div class="hue-bc-section">
-          <form action ="${action}" method="POST">
-            <div class="jframe-hidden">
-              ${util.render_form(file_form)}
-              ${comps.field(delim_form['file_type'])}
-            </div>
-            <a name="step2"></a>
-            <dt>Step 2: Choose A Delimiter</dt>
-            <dd>
-              <dl class="clearfix">
-                <dt>
-                  % if initial:
-                    <div class="bw-confirm_delim" style="display: none">
-                      <p class="delimiter_confirmation">Beeswax has determined that this file is delimited by ${delim_readable}.  Is this correct?</p>
-                      <label>
-                        Yes
-                        ## TODO(marcus)  The YES button does nothing
-                        <input type="submit" name="submit_delim" value="Select this Delimiter" class="jframe-hidden"/>
-                      </label>
-                      <label>
-                        No
-                        ## TODO(marcus)  The NO + preview jump out of jframe
-                        <input type="button" name="No" class="jframe-hidden"/>
-                      </label>
-                    </div>
-                  % endif
-                  <div class="bw-select_delim" class="jframe-hidden">
-		  <dl>
-                    ${comps.field(delim_form["delimiter"], render_default=True, help=r'Enter the column delimiter.  Must be a single character.  Use syntax like "\001" or "\t" for special characters.', dd_attrs=dict(data_filters='SelectWithOther'))}
-		  </dl>
-                    <input class="jframe-hidden" type="submit" value="Preview" name="submit_preview"/>
-                    <input class="jframe-hidden" type="submit" value="Select this Delimiter" name="submit_delim"/>
-                  </div>
-                  <div class="delimiter_preview_holder">
-                    <table class="delimiter_preview">
-                      <thead>
-                        <tr>
-                          % for i in range(n_cols):
-                            <th>col_${i+1}</th>
-                          % endfor
-                        </tr>
-                      </thead>
-                      <tbody>
-                        % for row in fields_list:
-                          <tr>
-                            % for val in row:
-                            <td>${val}</td>
-                            % endfor
-                          </tr>
-                        % endfor
-                      </tbody>
-                    </table>
-                  </div>
-                </dt>
-              </dl>
-              <a class="jframe-submit_form jframe-visible hue-multipart-next" data-extra-data="{'submit_delim': 'Step 3: Define Your Columns'}">
-              Step 3: Define Your Columns&raquo;
-              </a>
-              <input type="submit" name="submit_delim" value="Step 3: Define Your Columns" class="jframe-hidden"/>
-            </dd>
-	    </dl>
-        </form>
-      </div>
+${commonheader("Beeswax: Create table from file", "beeswax", "100px")}
+${layout.menubar(section='tables')}
+<div class="container-fluid">
+<div class="sidebar">
+	<div class="well">
+		<h6>Actions</h6>
+		<ul>
+      		<li><a href="${ url('beeswax.create_table.import_wizard')}">Create a new table from file</a></li>
+			<li><a href="${ url('beeswax.create_table.create_table')}">Create a new table manually</a></li>
+		</ul>
     </div>
 </div>
-${wrappers.foot()}
+
+
+<div class="content">
+	<h1>Create a new table from file</h1>
+	<ul class="pills">
+	  <li><a href="${ url('beeswax.create_table.import_wizard') }">Step 1: Choose File</a></li>
+	  <li class="active"><a href="#">Step 2: Choose Delimiter</a></li>
+	  <li><a href="#">Step 3: Define Columns</a></li>
+	</ul>
+	<br/>
+	<form id="delimiterForm" action="${action}" method="POST">
+		<div class="hidden">
+			${util.render_form(file_form)}
+			${comps.field(delim_form['file_type'])}
+		</div>
+		<fieldset>
+			<legend>Choose A Delimiter</legend>
+			<div class="clearfix">
+				${comps.label(delim_form["delimiter"])}
+				<div class="input">
+					${comps.field(delim_form["delimiter"], render_default=True, attrs=dict(
+						klass=""
+					))}
+					% if initial:
+						<span class="help-inline">
+							Beeswax has determined that this file is delimited by ${delim_readable}.
+						</span>
+					% endif
+					<span class="help-block">
+					Enter the column delimiter.  Must be a single character.  Use syntax like "\001" or "\t" for special characters.
+					</span>
+				</div>
+			</div>
+		</fieldset>
+		<div class="actions">
+			<input id="submit_preview" class="btn" type="submit" value="Preview" name="submit_preview"/>
+			<input class="btn primary" type="submit" name="submit_delim" value="Select this delimiter" />
+		</div>
+	</form>
+	<br/>
+	<ul class="tabs">
+		<li class="active"><a href="#tablePreview">Table preview</a></li>
+	</ul>
+	<div class="tab-content">
+		<div class="active tab-pane" id="tablePreview">
+			<table>
+		      <thead>
+		        <tr>
+		          % for i in range(n_cols):
+		            <th>col_${i+1}</th>
+		          % endfor
+		        </tr>
+		      </thead>
+		      <tbody>
+		        % for row in fields_list:
+		          <tr>
+		            % for val in row:
+		            <td>${val}</td>
+		            % endfor
+		          </tr>
+		        % endfor
+		      </tbody>
+		    </table>
+		</div>
+	</div>
+</div>
+</div>
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$("#id_delimiter_1").css("margin-left","4px").attr("placeholder","Please write here your delimiter").hide();
+		$("#id_delimiter_0").change(function(){
+			if ($(this).val() == "__other__"){
+				$("#id_delimiter_1").show();
+			}
+			else {
+				$("#id_delimiter_1").hide();
+				$("#submit_preview").click();
+			}
+		});
+	});
+</script>
+
+${commonfooter()}

+ 124 - 57
apps/beeswax/src/beeswax/templates/choose_file.mako

@@ -13,64 +13,131 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="comps" file="beeswax_components.mako" />
-${wrappers.head('Choose a File')}
-<div class="toolbar">
-  <ul class="clearfix" data-filters="Breadcrumb">
-    <li class="tabSelected"><a href="${ url('beeswax.create_table.import_wizard') }">Choose File</a></li>
-    <li><a>Choose Delimiter</a></li>
-    <li><a>Define Columns</a></li>
-  </ul>
+${commonheader("Beeswax: Create table from file", "beeswax", "100px")}
+${layout.menubar(section='tables')}
+
+<div class="container-fluid">
+<div class="sidebar">
+	<div class="well">
+		<h6>Actions</h6>
+		<ul>
+      		<li><a href="${ url('beeswax.create_table.import_wizard')}">Create a new table from file</a></li>
+			<li><a href="${ url('beeswax.create_table.create_table')}">Create a new table manually</a></li>
+		</ul>
+    </div>
 </div>
-<div class="view" id="choose-file">
-    <div class="bw-choose-file">
-      <div class="hue-bc-section">
-          <a name="step1"></a>
-            <form action="${action}" method="POST">
-              <dt>Step 1: Name Your Table and Choose A File</dt>
-              <dd>
-              <p>Enter the name of your new table and a file (compressed files are okay) to base this new table definition on.</p>
-              <dl class="clearfix">
-                ${comps.field(file_form["name"], attrs=dict(
-                  klass='required bw-validate-name',
-                  data_filters="OverText",
-                  alt='table_name',
-                ),
-                help="Name of the new table.  Table names must be globally unique.  Table names tend to correspond as well to the directory where the data will be stored.",
-                help_attrs=dict(
-                  data_help_direction='1'
-                )
-              )}
-              ${comps.field(file_form["comment"], attrs=dict(
-                  klass='bw-table-comment',
-                  data_filters="OverText",
-                  alt='Optional'
-                ),
-                help="Use a table comment to describe your table.  For example, you might mention the data's provenance, and any caveats users of this table should expect.")}
 
-                ${comps.field(file_form["path"], attrs=dict(
-                    klass='required bw-validate-file',
-                    data_filters="OverText",
-                    alt="/user/user_name/data_dir",
-                  ),
-                  help="The HDFS path to the file that you would like to base this new table definition on.  It can be compressed (gzip) or not.")}
-                <a class="hue-choose_file" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height' : 16, 'top' : 3, 'left' : 6 }" data-chooseFor="path">Choose File</a>
-                <div class="bw-import_data">
-                  ${comps.field(file_form["do_import"],
-                    render_default=True,
-                    help="Check this box if you want to import the data in this file after creating the table definition.  Leave it unchecked if you just want to define an empty table."
-                  )}
-                </div>
-                ## TODO(marcus): Button style?
-                <a class="hue-multipart-next jframe-submit_form jframe-visible" style="display:none" data-extra-data="{'submit_file' : 'Step 2: Choose Your Delimiter'}">
-                  Step 2: Choose Your Delimiter&raquo;
-                </a>
-                  <input type="submit" name="submit_file" value="Step 2: Choose Your Delimiter" class="jframe-hidden jframe-submit_form hue-multipart-next jframe-visible"/>
-              </dl>
-            </form>
-          </dd>
-        </div>
-      </div>
+
+<div class="content">
+	<h1>Create a new table from file</h1>
+	<ul class="pills">
+	  <li class="active"><a href="${ url('beeswax.create_table.import_wizard') }">Step 1: Choose File</a></li>
+	  <li><a href="#">Step 2: Choose Delimiter</a></li>
+	  <li><a href="#">Step 3: Define Columns</a></li>
+	</ul>
+	<br/>
+	<form action="${action}" method="POST">
+		<fieldset>
+			<legend>Name Your Table and Choose A File</legend>
+			<div class="clearfix">
+				${comps.label(file_form["name"])}
+				<div class="input">
+					${comps.field(file_form["name"], attrs=dict(
+						placeholder="table_name",
+						klass=""
+					))}
+					<span class="help-block">
+					Name of the new table.  Table names must be globally unique.  Table names tend to correspond as well to the directory where the data will be stored.
+					</span>
+				</div>
+			</div>
+			<div class="clearfix">
+				${comps.label(file_form["comment"])}
+				<div class="input">
+					${comps.field(file_form["comment"], attrs=dict(
+						placeholder="Optional",
+						klass=""
+					))}
+					<span class="help-block">
+					Use a table comment to describe your table.  For example, you might mention the data's provenance, and any caveats users of this table should expect.
+					</span>
+				</div>
+			</div>
+			<div class="clearfix">
+				${comps.label(file_form["path"])}
+				<div class="input">
+					${comps.field(file_form["path"], attrs=dict(
+						placeholder="/user/user_name/data_dir",
+						klass=""
+					))}
+					<span class="help-inline"><a id="pathChooser" href="#" data-filechooser-destination="path">Choose File</a></span>
+					<span class="help-block">
+					The HDFS path to the file that you would like to base this new table definition on.  It can be compressed (gzip) or not.
+					</span>
+				</div>
+			</div>
+			<div class="clearfix">
+				${comps.label(file_form["do_import"])}
+				<div class="input">
+					${comps.field(file_form["do_import"], render_default=True, attrs=dict(
+						klass=""
+					))}
+					<span class="help-block">
+					Check this box if you want to import the data in this file after creating the table definition.  Leave it unchecked if you just want to define an empty table.
+					</span>
+				</div>
+			</div>
+		</fieldset>
+		<div class="actions">
+			<input type="submit" class="btn primary" name="submit_file" value="Choose a delimiter" />
+		</div>
+	</form>
+	
+</div>
+<div id="chooseFile" class="modal hide fade">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3>Choose a file</h3>
+	</div>
+	<div class="modal-body">  
+		<div id="filechooser">
+		</div>
+	</div>
+	<div class="modal-footer">
+	</div>
+</div>
 </div>
-${wrappers.foot()}
+<style>
+	#filechooser {
+		min-height:100px;
+		overflow-y:scroll;
+	}
+</style>
+
+
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$("#pathChooser").click(function(){
+			var _destination = $(this).attr("data-filechooser-destination");
+			$("#filechooser").jHueFileChooser({
+				onFileChoose: function(filePath){
+					$("input[name='"+_destination+"']").val(filePath);
+					$("#chooseFile").modal("hide");
+				}
+			});
+			$("#chooseFile").modal("show");
+		});
+		
+		$("#chooseFile").modal({
+			keyboard: true,
+			backdrop: true
+		})
+	});
+</script>
+
+${commonfooter()}

+ 23 - 7
apps/beeswax/src/beeswax/templates/configuration.mako

@@ -13,18 +13,23 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="util" file="util.mako" />
-${wrappers.head('Hive Configuration Variables', section='hive configuration')}
-<h1 class="jframe-hidden">Hive Configuration Variables</h1>
+${commonheader("Hive Configuration Variables", "beeswax", "100px")}
+${layout.menubar(section='hive configuration')}
+<div class="container-fluid">
+<h1>Hive Configuration Variables</h1>
 <div class="toolbar">
   <div class="bw-input-filter">
-    <input type="text" class="jframe-hidden" data-filters="OverText, ArtInput, FilterInput" data-art-input-type="search"
+    <!--input type="text" class="jframe-hidden" data-filters="OverText, ArtInput, FilterInput" data-art-input-type="search"
       title="Filter by Name"
-      data-filter-elements="tbody tr" value=""/>
+      data-filter-elements="tbody tr" value=""/-->
   </div>
 </div>
-<table class="sortable" data-filters="HtmlTable" cellpadding="0" cellspacing="0">
+<table class="datatables">
   <thead>
     <tr>
       <th>Key</th>
@@ -40,4 +45,15 @@ ${wrappers.head('Hive Configuration Variables', section='hive configuration')}
     % endfor
   </tbody>
 </table>
-${wrappers.foot()}
+</div>
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".datatables").dataTable({
+			"bPaginate": false,
+		    "bLengthChange": false,
+		    "bFilter": false,
+			"bInfo": false,
+		});
+	});
+</script>
+${commonfooter()}

+ 14 - 7
apps/beeswax/src/beeswax/templates/confirm.html

@@ -15,13 +15,20 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
-{% block title %}{{ title }}{% endblock %}
 {% block content %}
-<div class="prompt_popup">
-	<h1 class="jframe-hidden">Are you sure?</h1>
-	<form action="{{ url }}" method="POST">
-		{{title}}
-		<input type="submit" value="Yes" class="jframe-hidden">
-	</form>
+<form action="{{ url }}" method="POST">>
+<div class="modal-header">
+	<a href="#" class="close">&times;</a>
+	<h3>Confirm action</h3>
 </div>
+<div class="modal-body">  
+  <div class="alert-message block-message warning">
+        {{title}}
+  </div>
+</div>
+<div class="modal-footer">
+	<input type="submit" class="btn primary" value="Yes"/>
+	<a href="#" class="btn secondary hideModal">No</a>
+</div>
+</form>
 {% endblock %}

+ 8 - 3
apps/beeswax/src/beeswax/templates/create_table_index.mako

@@ -13,8 +13,12 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
-${wrappers.head("Beeswax: Create Table")}
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
+${commonheader("Beeswax: Create Table", "beeswax", "100px")}
+<div class="container-fluid">
   <div class="toolbar">
   </div>
 
@@ -27,4 +31,5 @@ ${wrappers.head("Beeswax: Create Table")}
     </ul>
   </div>
 </div>
-${wrappers.foot()}
+</div>
+${commonfooter()}

+ 526 - 282
apps/beeswax/src/beeswax/templates/create_table_manually.mako

@@ -13,295 +13,539 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
+<%!
+from desktop.views import commonheader, commonfooter
+%>
 <%namespace name="comps" file="beeswax_components.mako" />
-<%namespace name="wrappers" file="header_footer.mako" />
-${wrappers.head('Create a Table', toolbar=has_tables, section='new table')}
-<div class="toolbar">
-  <ul class="clearfix" data-filters="Breadcrumb, BreadcrumbForm" data-bc-sections=".hue-bc-section" data-bc-form="form">
-    <li><a href="#step1">Name</a></li>
-    <li><a href="#step2">Record Format</a></li>
-    <li><a href="#step3">Serialization</a></li>
-    <li><a href="#step4">File Format</a></li>
-    <li><a href="#step5">Location</a></li>
-    <li><a href="#step6">Columns</a></li>
-  </ul>
+<%namespace name="layout" file="layout.mako" />
+${commonheader("Beeswax: Create table manually", "beeswax", "100px")}
+${layout.menubar(section='tables')}
+<div class="container-fluid">
+<div class="sidebar">
+	<div class="well">
+		<h6>Actions</h6>
+		<ul>
+      		<li><a href="${ url('beeswax.create_table.import_wizard')}">Create a new table from file</a></li>
+			<li><a href="${ url('beeswax.create_table.create_table')}">Create a new table manually</a></li>
+		</ul>
+    </div>
 </div>
-<div id="table-setup" class="view">
-  <form action="#" method="POST" class="jframe_padded" data-filters="FormValidator">
-    <dl class="bw-table-setup">
-
-  <div class="hue-bc-section">
-        <a name="step1"></a>
-        <dt>Step 1: Create Your Table</dt>
-        <dd>
-          <p>Let's start with a name and description for where we'll store your data.</p>
-          <dl class="clearfix">
-            ${comps.field(table_form["name"], attrs=dict(
-                klass='required bw-validate-name',
-                data_filters="OverText",
-                alt='table_name',
-              ),
-              help="Name of the new table.  Table names must be globally unique.  Table names tend to correspond as well to the directory where the data will be stored.",
-              help_attrs=dict(
-                data_help_direction='1'
-              )
-            )}
-            ${comps.field(table_form["comment"], attrs=dict(
-                klass='bw-table-comment',
-                data_filters="OverText",
-                alt='Optional'
-              ),
-              help="Use a table comment to describe your table.  For example, you might mention the data's provenance, and any caveats users of this table should expect.")}
-          </dl>
-          <a href="#step2" class="hue-multipart-next">Step 2: Choose Your Record Format &raquo;</a>
-        </dd>
-      </div>
 
-      <div class="hue-bc-section">
-        <a name="step2"></a>
-        <dt>Step 2: Choose Your Record Format</dt>
-        <dd>
-          <p>Individual records are broken up into columns
-          either with delimiters (e.g., CSV or TSV) or using
-          a specific serialization / deserialization (SerDe) implementation.
-          (One common specialized SerDe is for parsing out columns with a regular
-          expression.)
-          </p>
-          <dl class="bw-format clearfix">
-            <% 
-              selected = table_form["row_format"].data or table_form["row_format"].field.initial
-            %>
-            <dt class="bw-format-delimited relays" data-filters="DataGroupToggle" data-group-toggle="{'group': '.bw-config-data li', 'show':'.bw-delim-options'}">
-              <label>
-                Delimited
-                <input type="radio" name="table-row_format" value="Delimited" class="validate-one-required:'.bw-format'" title="Please choose one of these record formats." data-error-container=''
-                  % if selected == "Delimited":
-                    checked
-                  % endif
-                >
-              </label>
-              <div class="jframe-errors"></div>
-            </dt>
-            <dd>Data files use delimiters, like commas (CSV) or tabs.</dd>
-            <dt class="bw-format-SerDe relays" data-filters="DataGroupToggle" data-group-toggle="{'group': '.bw-config-data li', 'show':'.bw-serde-options'}">
-              <label>
-                SerDe
-                <input type="radio" name="table-row_format" value="SerDe"
-                  % if selected == "SerDe":
-                    checked
-                  % endif
-                >
-              </label>
-            </dt>
-            <dd>Enter a specialized serialization implementation.</dd>
-          </dl>
-          <a href="#step3" class="hue-multipart-next">Step 3: Configure Record Serialization &raquo;</a>
-        </dd>
-      </div>
 
-      <div class="hue-bc-section">
-        <a name="step3"></a>
-        <dt>Step 3: Configure Record Serialization</dt>
-        <dd>
-          <ul class="bw-config-data">
-            <li class="bw-delim-options">
-              <p class="jframe-hidden">If your records are delimited, please configure these fields:</p>
-              Hive only supports single-character delimiters.
-              <dl>
-                ${comps.field(table_form["field_terminator"], render_default=True, help=r'Enter the column delimiter.  Must be a single character.  Use syntax like "\001" or "\t" for special characters.', dd_attrs=dict(data_filters="SelectWithOther"))}
-                ${comps.field(table_form["collection_terminator"], render_default=True, help="Use for array types.", dd_attrs=dict(data_filters="SelectWithOther"))}
-                ${comps.field(table_form["map_key_terminator"], render_default=True, help="Use for map types.", dd_attrs=dict(data_filters="SelectWithOther"))}
-              </dl>
-            </li>
-            <li class="bw-serde-options">
-              <p class="jframe-hidden">If you're using SerDe data, please configure these fields:</p>
-              <dl>
-                ${comps.field(table_form["serde_name"],
-                  help="Enter the Java Classname of your SerDe. <em>e.g.</em>, org.apache.hadoop.hive.contrib.serde2.RegexSerDe",
-                  attrs=dict(
-                    klass='required',
-                    data_filters="OverText",
-                    alt='com.acme.hive.SerDe',
-                  )
-                )}
-                <%!
-                  help=r'Properties to pass to the (de)serialization mechanism. <em>e.g.,</em>, "input.regex" = "([^ ]*) ([^ ]*) ([^ ]*) (-|\\[[^\\]]*\\]) ([^ \"]*|\"[^\"]*\") (-|[0-9]*) (-|[0-9]*)(?: ([^ \"]*|\"[^\"]*\") ([^ \"]*|\"[^\"]*\"))?", "output.format.string" = "%1$s %2$s %3$s %4$s %5$s %6$s %7$s %8$s %9$s"'
-                %>
+<div class="content">
+	<h1>Create a new table manually</h1>
+	<ul class="pills">
+		<li class="active"><a href="#step1" class="step">Step 1: Name</a></li>
+	    <li><a href="#step2" class="step">Step 2: Record Format</a></li>
+	    <li><a href="#step3" class="step">Step 3: Serialization</a></li>
+	    <li><a href="#step4" class="step">Step 4: File Format</a></li>
+	    <li><a href="#step5" class="step">Step 5: Location</a></li>
+	    <li><a href="#step6" class="step">Step 6: Columns</a></li>
+	</ul>
+	<br/>
+	<form action="#" method="POST" id="mainForm">
+		<div id="step1" class="stepDetails">
+			<fieldset>
+				<legend>Create your table</legend>
+				<div class="clearfix">
+					<div class="input">
+						<span>Let's start with a name and description for where we'll store your data.</span>
+					</div>
+				</div>
+				<div class="clearfix">
+					${comps.label(table_form["name"])}
+					<div class="input">
+						${comps.field(table_form["name"], attrs=dict(
+							placeholder='table_name',
+			              )
+			            )}
+						<span class="help-block">
+						Name of the new table.  Table names must be globally unique.  Table names tend to correspond as well to the directory where the data will be stored.
+						</span>
+					</div>
+				</div>
+				<div class="clearfix">
+					${comps.label(table_form["comment"])}
+					<div class="input">
+						${comps.field(table_form["comment"], attrs=dict(
+							placeholder='Optional',
+			              )
+			            )}
+						<span class="help-block">
+						Use a table comment to describe your table.  For example, you might mention the data's provenance, and any caveats users of this table should expect.
+						</span>
+					</div>
+				</div>
+			</fieldset>
+		</div>
+		<div id="step2" class="stepDetails hidden">
+			<fieldset>
+				<legend>Choose Your Record Format</legend>
+				<div class="clearfix">
+					<div class="input">
+						<span>Individual records are broken up into columns
+				          either with delimiters (e.g., CSV or TSV) or using
+				          a specific serialization / deserialization (SerDe) implementation.
+				          (One common specialized SerDe is for parsing out columns with a regular
+				          expression.)</span>
+					</div>
+				</div>
+				<% 
+	              selected = table_form["row_format"].data or table_form["row_format"].field.initial
+	            %>
+				<div class="clearfix">
+					<label id="formatRadio">Record format</label>
+					<div class="input">
+						<ul class="inputs-list">
+							<li>
+								<label>
+			                    	<input type="radio" name="table-row_format" value="Delimited" 
+					                  % if selected == "Delimited":
+					                    checked
+					                  % endif
+					                >
+									<span>Delimited</span>
+								</label>
+								<span class="help-block">
+								Data files use delimiters, like commas (CSV) or tabs.
+								</span>
+			                </li>
+							<li>
+								<label>
+			                    	<input type="radio" name="table-row_format" value="SerDe" 
+					                  % if selected == "SerDe":
+					                    checked
+					                  % endif
+					                >
+									<span>SerDe</span>
+								</label>
+								<span class="help-block">
+								Enter a specialized serialization implementation.
+								</span>
+							</li>
+						</ul>
+					</div>
+				</div>
+			</fieldset>
+		</div>
+		<div id="step3" class="stepDetails hidden">
+			<fieldset>
+				<legend>Configure Record Serialization</legend>
+				<div id="step3Delimited" class="stepDetailsInner">
+					<div class="clearfix">
+						<div class="input">
+							<span>Hive only supports single-character delimiters. </span>
+						</div>
+					</div>
+					<div class="clearfix">
+						${comps.label(table_form["field_terminator"])}
+						<div class="input">
+							${comps.field(table_form["field_terminator"], render_default=True)}
+							<span class="help-block">
+							Enter the column delimiter.  Must be a single character.  Use syntax like "\001" or "\t" for special characters.
+							</span>
+						</div>
+					</div>
+					<div class="clearfix">
+						${comps.label(table_form["collection_terminator"])}
+						<div class="input">
+							${comps.field(table_form["collection_terminator"], render_default=True)}
+							<span class="help-block">
+							Use for array types.
+							</span>
+						</div>
+					</div>
+					<div class="clearfix">
+						${comps.label(table_form["map_key_terminator"])}
+						<div class="input">
+							${comps.field(table_form["map_key_terminator"], render_default=True)}
+							<span class="help-block">
+							Use for map types.
+							</span>
+						</div>
+					</div>
+				</div>
+				<div id="step3SerDe" class="hidden stepDetailsInner">
+					<div class="clearfix">
+						${comps.label(table_form["serde_name"])}
+						<div class="input">
+							${comps.field(table_form["serde_name"], attrs=dict(
+								placeholder='com.acme.hive.SerDe',
+				              )
+				            )}
+							<span class="help-block">
+							Enter the Java Classname of your SerDe. <em>e.g.</em>, org.apache.hadoop.hive.contrib.serde2.RegexSerDe
+							</span>
+						</div>
+					</div>
+					<div class="clearfix">
+						${comps.label(table_form["serde_properties"])}
+						<div class="input">
+							${comps.field(table_form["serde_properties"], attrs=dict(
+								placeholder='"prop" = "value", "prop2" = "value2"',
+				              )
+				            )}
+							<span class="help-block">
+							Properties to pass to the (de)serialization mechanism. <em>e.g.,</em>, "input.regex" = "([^ ]*) ([^ ]*) ([^ ]*) (-|\\[[^\\]]*\\]) ([^ \"]*|\"[^\"]*\") (-|[0-9]*) (-|[0-9]*)(?: ([^ \"]*|\"[^\"]*\") ([^ \"]*|\"[^\"]*\"))?", "output.format.string" = "%1$s %2$s %3$s %4$s %5$s %6$s %7$s %8$s %9$s"
+							</span>
+						</div>
+					</div>
+				</div>
+			</fieldset>
+		</div>
+		<div id="step4" class="stepDetails hidden">
+			<fieldset>
+				<legend>Choose a File Format</legend>
+				<div class="clearfix">
+					<div class="input">
+						Use <strong>TextFile</strong> for newline-delimited text files.
+						Use <strong>SequenceFile</strong> for Hadoop's binary serialization format.
+						Use <strong>InputFormat</strong> to choose a custom implementation.<br/>
+					</div>
+				</div>
+				
+				<div class="clearfix">
+					<label id="fileFormatRadio">File format</label>
+					<div class="input">
+						${comps.field(table_form["file_format"],
+			              render_default=True, 
+			              klass="bw-file_formats",
+			              notitle=True
+			            )}		
+					</div>
+				</div>
+				<div id="inputFormatDetails" class="hidden">
+					<div class="clearfix">
+						${comps.label(table_form["input_format_class"])}
+						<div class="input">
+							${comps.field(table_form["input_format_class"], attrs=dict(
+								placeholder='com.acme.data.MyInputFormat',
+				              )
+				            )}
+							<span class="help-block">
+							Java Class used to read data
+							</span>
+						</div>
+					</div>
+					<div class="clearfix">
+						${comps.label(table_form["output_format_class"])}
+						<div class="input">
+							${comps.field(table_form["output_format_class"], attrs=dict(
+								placeholder='com.acme.data.MyOutputFormat',
+				              )
+				            )}
+							<span class="help-block">
+							Java Class used to write data
+							</span>
+						</div>
+					</div>
+				</div>
+			</fieldset>
+		</div>
+		<div id="step5" class="stepDetails hidden">
+			<fieldset>
+				<legend>Choose Where Your Table's Data is Stored</legend>
+				
+				<div class="clearfix">
+					<label>Location</label>
+					<div class="input">
+						<ul class="inputs-list">
+							<li>
+								<label>
+			                    	${comps.field(table_form["use_default_location"],
+						                render_default=True
+						              )}
+									<span>Use default location</span>
+								</label>
+								<span class="help-block">
+									Store your table in the default location (controlled by Hive, and typically <em>/user/hive/warehouse/table_name</em>).
+								</span>
+			                </li>
+						</ul>
+					</div>
+				</div>
+				
+				<div id="location" class="hidden">
+					<div class="clearfix">
+						${comps.label(table_form["external_location"])}
+						<div class="input">
+							${comps.field(table_form["external_location"], attrs=dict(
+								placeholder='/user/user_name/data_dir',
+				              )
+				            )}
+							<span class="help-inline"><a id="pathChooser" href="#" data-filechooser-destination="table-external_location">Choose File</a></span>
+							<span class="help-block">
+							Enter the path (on HDFS) to your table's data location
+							</span>
+						</div>
+					</div>
+				</div>
+			</fieldset>
+		</div>
+			<div id="step6" class="stepDetails hidden">
+				<fieldset>
+					<legend>Configure Table Columns</legend>
+					% for form in columns_form.forms:
+		                ${render_column(form)}
+		            %endfor
+					<div class="hidden">
+		              ${unicode(columns_form.management_form) | n}
+		            </div>
+					<div class="clearfix">
+						<div class="input">
+							<button class="btn" value="True" name="columns-add" type="submit">Add a column</button>
+						</div>
+					</div>
+				</fieldset>
+				<fieldset>
+					<legend>Configure Partitions</legend>
+					<div class="clearfix">
+						<div class="input">
+							If your data is naturally partitioned (by, say, date),
+				              partitions are a way to tell Hive that data
+				              for a specific partition value are stored together.
+				              Hive establishes a mapping between directories on disk
+				              (<em>e.g.,</em> <code>/user/hive/warehouse/logs/dt=20100101/</code>)
+				              and the data for that day.  Partitions are virtual
+				              columns; they are not represented in the data themselves,
+				              but are determined by the data location.  Hive implements
+				              query optimizations such that queries that are specific
+				              to a single partition need not read the data in other partitions.
+						</div>
+					</div>
+					% for form in partitions_form.forms:
+	                  ${render_column(form, True)}
+	                % endfor
+					<div class="hidden">
+		              ${unicode(partitions_form.management_form) | n}
+		            </div>
+					<div class="clearfix">
+						<div class="input">
+							<button class="btn" value="True" name="partitions-add" type="submit">Add a partition</button>
+						</div>
+					</div>
+		
+				</fieldset>
+			</div>
+		<div class="actions">
+			<input id="backBtn" type="button" class="btn hidden" value="Back" />
+			<input id="nextBtn" type="button" class="btn primary" value="Next" />
+			<input id="submit" type="submit" class="btn primary hidden" value="Create table" />
+		</div>
+	</form>
+</div>
 
-                ${comps.field(table_form["serde_properties"],
-                  help=help,
-                  attrs=dict(
-                    data_filters="OverText",
-                    alt=r'"prop" = "value", "prop2" = "value2"'
-                  )
-                )}
-              </dl>
-            </li>
-          </ul>
-          <a href="#step4" class="hue-multipart-next">Step 4: Choose a File Format &raquo;</a>
-        </dd>
-      </div>
+		<%def name="render_column(form, is_partition_form=False)">
+			<div class="cnt">
+			<div class="clearfix">
+				<label>Column name</label>
+				<div class="input">
+					<input name="${form["column_name"].html_name | n}" value="${form["column_name"].data or ''}" placeholder="Column Name"/>
+					<span class="help-inline">
+					Column name must be single words that start with a letter or a digit.
+					</span>
+				</div>
+			</div>
+			<div class="clearfix">
+				<label>Column type</label>
+				<div class="input columnType">
+					${comps.field(form["column_type"],
+                        render_default=True
+                      )}
+					<span class="help-inline">
+					Type for this column.  Certain advanced types (namely, structs) are not exposed in this interface.
+					</span>
+				</div>
+			</div>
+			 % if is_partition_form == False: 
+			<div class="arraySpec hidden">
+				<div class="clearfix">
+					<label>Array value type</label>
+					<div class="input">
+						${comps.field(form["array_type"], render_default=True)}
+						<span class="help-inline">
+						Type of the array values.
+						</span>
+					</div>
+				</div>
+			</div>
+			<div class="mapSpec hidden">
+				<div class="clearfix">
+					<label>Map Key type</label>
+					<div class="input">
+						${comps.field(form["map_key_type"], render_default=True)}
+						<span class="help-inline">
+						Type of the map keys.
+						</span>
+					</div>
+				</div>
+				<div class="clearfix">
+					<label>Map Value type</label>
+					<div class="input">
+						${comps.field(form["map_value_type"], render_default=True)}
+						<span class="help-inline">
+						Type of the map values.
+						</span>
+					</div>
+				</div>
+			</div>
+			% endif
+			<div class="clearfix">
+				<div class="input">
+					${comps.field(form['_deleted'], tag="button", button_text="Remove", notitle=True, attrs=dict(
+						type="submit",
+						title="Delete this column",
+						klass="btn small danger"
+					), value=True)}
+					
+				</div>
+			</div>
+            ${unicode(form["_exists"]) | n}
 
-      <div class="hue-bc-section">
-        <a name="step4"></a>
-        <dt>Step 4: Choose a File Format</dt>
-        <dd>
-          <ul>
-            <li>Use TextFile for newline-delimited text files.</li>
-            <li>Use SequenceFile for Hadoop's binary serialization format.</li>
-            <li>Use InputFormat to choose a custom implementation.</li>
-          </ul>
-          <dl>
-            ${comps.field(table_form["file_format"],
-              render_default=True, 
-              klass="bw-file_formats",
-              notitle=True
-            )}
-            <div class="jframe-hidden bw-io_formats">
-              ${comps.field(table_form["input_format_class"],
-                help="Java Class to read data",
-                attrs=dict(
-                  data_filters="OverText",
-                  alt='com.acme.data.MyInputFormat'
-                )
-              )}
-              ${comps.field(table_form["output_format_class"],
-                help="Java Class used to write data",
-                attrs=dict(
-                  data_filters="OverText",
-                  alt='com.acme.data.MyOutputFormat'
-                )
-              )}
-            </div>
-          </dl>
-          <a href="#step5" class="hue-multipart-next">Step 5: Choose Where To Save Your Table &raquo;</a>
-        </dd>
-      </div>
+			</div>
+		
+            </%def>
+            
+         
 
-      <div class="hue-bc-section">
-        <a name="step5"></a>
-        <dt>Step 5: Choose Where Your Table's Data is Stored</dt>
-        <dd class="bw-file_location">
-          <dl>
-            <div class="bw-default_location">
-              ${comps.field(table_form["use_default_location"],
-                render_default=True, 
-                help="Store your table in the default location (controlled by Hive, and typically <code>/user/hive/warehouse/table_name</code>)."
-              )}
-            </div>
-            <div class="bw-external_loc jframe-hidden">
-              ${comps.field(table_form["external_location"],
-                help="Enter the path (on HDFS) to your table's data location",
-                attrs=dict(
-                  klass='required',
-                  data_filters="OverText",
-                  alt='/user/user_name/data_dir'
-                )
-              )}<a class="hue-choose_file" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16, 'top': 3, 'left': 6 }" data-chooseFor="table-external_location">Choose File</a>
-            </div>
-          </dl>
-          <a href="#step6" class="hue-multipart-next">Final Step: Configure Table Columns &raquo;</a>
-        </dd>
-      </div>
 
-      <div class="hue-bc-section">
-        <a name="step6"></a>
-        <dt>Final Step: Configure Table Columns</dt>
-        <dd>
-          <dl class="bw-columns">
-            <%def name="render_column(form, is_partition_form=False)">
-              <div class="bw-column">
-                <dt class="bw-column_header bw-inactive">
-                  <input name="${form["column_name"].html_name | n}" value="${form["column_name"].data or ''}" class="required bw-column_name" alt="Column Name" data-filters="OverText"/>
-                  <p class="jframe-inline" data-filters="HelpTip" data-help-direction="1">
-                    Column name must be single words that start
-                    with a letter or a digit.
-                  </p>
-                  <div class="bw-remove_column">
-                    ${unicode(form["_deleted"]) | n}
-                  </div>
-                </dt>
-                <dd class="bw-column">
-                  <dl>
-                    <div class="bw-col_type jframe-inline">
-                      ${comps.field(form["column_type"],
-                        render_default=True,
-                        help="Type for this column.  Certain advanced types (namely, structs) are not exposed in this interface.",
-                        help_attrs=dict(
-                          data_help_direction='12'
-                        )
-                      )}
-                    </div>
-                    % if is_partition_form == False: 
-                      <div class="bw-array_type jframe-inline">
-                        ${comps.field(
-                            form["array_type"],
-                            render_default=True,
-                            help="Type of the array values.",
-                          )}
-                      </div>
-                      <div class="bw-map_data">
-                        <div class="bw-map_key_type jframe-inline">
-                          ${comps.field(form["map_key_type"], render_default=True, help="Type of the map keys.")}
-                        </div>
-                        <div class="bw-map_value_type jframe-inline">
-                          ${comps.field(form["map_value_type"], render_default=True, help="Type of the map values.")}
-                        </div>
-                      </div>
-                    % endif
-                    ${unicode(form["_exists"]) | n}
-                    
-                  </dl>
-                </dd>
-              </div>
-            </%def>
-            <div class="bw-column-forms">
-              <p>Configure the columns of your table.</p>
-              % for form in columns_form.forms:
-                ${render_column(form)}
-              %endfor
-            </div>
-            <div class="bw-add_column">
-              ${unicode(columns_form.management_form) | n}
-            </div>
-            <h2>Partitions</h2>
-              ## See http://wiki.apache.org/hadoop/Hive/Tutorial
-              <p>
-              If your data is naturally partitioned (by, say, date),
-              partitions are a way to tell Hive that data
-              for a specific partition value are stored together.
-              Hive establishes a mapping between directories on disk
-              (<em>e.g.,</em> <code>/user/hive/warehouse/logs/dt=20100101/</code>)
-              and the data for that day.  Partitions are virtual
-              columns; they are not represented in the data themselves,
-              but are determined by the data location.  Hive implements
-              query optimizations such that queries that are specific
-              to a single partition need not read the data in other partitions.
-              </p>
-              <div class="bw-partition-forms">
-                % for form in partitions_form.forms:
-                  ${render_column(form, True)}
-                % endfor
-              </div>
-              <div class="bw-add_partition bw-add_column">
-                ${unicode(partitions_form.management_form) | n}
-              </div>
-          </dl>
-          <input type="submit" class="bw-create_table_submit">
-        </dd>
-      </div>
-    </dl>
-  </dd>
+<div id="chooseFile" class="modal hide fade">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3>Choose a file</h3>
+	</div>
+	<div class="modal-body">  
+		<div id="filechooser">
+		</div>
+	</div>
+	<div class="modal-footer">
+	</div>
+</div>
 
-</dl>
+<style>
+	#filechooser {
+		min-height:100px;
+		overflow-y:scroll;
+	}
+</style>
+</div>
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		
+		$("#pathChooser").click(function(){
+			var _destination = $(this).attr("data-filechooser-destination");
+			$("#filechooser").jHueFileChooser({
+				onFileChoose: function(filePath){
+					$("input[name='"+_destination+"']").val(filePath);
+					$("#chooseFile").modal("hide");
+				}
+			});
+			$("#chooseFile").modal("show");
+		});
+		
+		$("#chooseFile").modal({
+			keyboard: true,
+			backdrop: true
+		})
+		
+		
+		$(".step").click(function(event){
+			event.preventDefault();
+			$(".stepDetails").hide();
+			var _step = $(this).attr("href");
+			$(_step).show();
+			$("#backBtn").hide();
+			if (_step != "#step1"){
+				$("#backBtn").show();
+			}
+			if (_step != "#step6"){
+				$("#nextBtn").show();
+				$("#submit").hide();
+			}
+			else {
+				$("#nextBtn").hide();
+				$("#submit").show();
+			}
+			$(".step").parent().removeClass("active");
+			$(this).parent().addClass("active");
+		});
+		$("#nextBtn").click(function(){
+			$("ul.pills li.active").next().find("a").click();
+		});
+		$("#backBtn").click(function(){
+			$("ul.pills li.active").prev().find("a").click();
+		});
+		var _url = location.href;
+		if (_url.indexOf("#")>-1){
+			$(".step[href='"+_url.substring(_url.indexOf("#"),_url.length)+"']").click();
+		}
+		
+		$("#id_table-field_terminator_1").css("margin-left","4px").attr("placeholder","Write here your field terminator").hide();
+		$("#id_table-field_terminator_0").change(function(){
+			if ($(this).val() == "__other__"){
+				$("#id_table-field_terminator_1").show();
+			}
+			else {
+				$("#id_table-field_terminator_1").hide();
+			}
+		});
+		$("#id_table-collection_terminator_1").css("margin-left","4px").attr("placeholder","Write here your collection terminator").hide();
+		$("#id_table-collection_terminator_0").change(function(){
+			if ($(this).val() == "__other__"){
+				$("#id_table-collection_terminator_1").show();
+			}
+			else {
+				$("#id_table-collection_terminator_1").hide();
+			}
+		});
+		$("#id_table-map_key_terminator_1").css("margin-left","4px").attr("placeholder","Write here your map key terminator").hide();
+		$("#id_table-map_key_terminator_0").change(function(){
+			if ($(this).val() == "__other__"){
+				$("#id_table-map_key_terminator_1").show();
+			}
+			else {
+				$("#id_table-map_key_terminator_1").hide();
+			}
+		});
+		
+		$("input[name='table-row_format']").change(function(){
+			$(".stepDetailsInner").hide();
+			$("#step3"+$(this).val()).show();
+		});
 
-  <div style="display:none">
-    <div class="beeswax_column_form_template jframe-hidden" style="display: none">
-      ${render_column(columns_form.empty_form())}
-    </div>
-    <div class="beeswax_partition_form_template jframe-hidden" style="display: none">
-      ${render_column(partitions_form.empty_form(), true)}
-    </div>
-  </div>
-</form>
-${wrappers.foot()}
+		$("input[name='table-file_format']").change(function(){
+			$("#inputFormatDetails").hide();
+			if ($(this).val() == "InputFormat"){
+				$("#inputFormatDetails").slideDown();
+			}
+		});
+		
+		$("#id_table-use_default_location").change(function(){
+			if (!$(this).is(":checked")){
+				$("#location").slideDown();
+			}
+			else {
+				$("#location").slideUp();
+			}
+		});
+		
+		
+		$("#step6").find("button").click(function(){
+			$("#mainForm").attr("action","#step6");
+		});
+		
+		$(".columnType").find("select").change(function(){
+			$(this).parents(".cnt").find(".arraySpec").hide();
+			$(this).parents(".cnt").find(".mapSpec").hide();
+			if ($(this).val() == "array"){
+				$(this).parents(".cnt").find(".arraySpec").show();
+			}
+			if ($(this).val() == "map"){
+				$(this).parents(".cnt").find(".mapSpec").show();
+			}
+		});
+		
+		$("#step4").find("ul").addClass("inputs-list");
+	});
+</script>
+${commonfooter()}

+ 80 - 77
apps/beeswax/src/beeswax/templates/define_columns.mako

@@ -13,84 +13,87 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="comps" file="beeswax_components.mako" />
 <%namespace name="util" file="util.mako" />
-${wrappers.head('Define Columns')}
-<div class="toolbar">
-  <ul class="clearfix" data-filters="Breadcrumb">
-    ## TODO(marcus) These links should be part of the form, and do POST
-    <li><a href="${ url('beeswax.create_table.import_wizard') }">Choose File</a></li>
-    <li><a href="${ url('beeswax.create_table.import_wizard') }">Choose Delimiter</a></li>
-    <li class="tabSelected"><a href="${ url('beeswax.create_table.import_wizard') }">Define Columns</a></li>
-  </ul>
+${commonheader("Beeswax: Create table from file", "beeswax", "100px")}
+${layout.menubar(section='tables')}
+<div class="container-fluid">
+<div class="sidebar">
+	<div class="well">
+		<h6>Actions</h6>
+		<ul>
+      		<li><a href="${ url('beeswax.create_table.import_wizard')}">Create a new table from file</a></li>
+			<li><a href="${ url('beeswax.create_table.create_table')}">Create a new table manually</a></li>
+		</ul>
+    </div>
 </div>
-<div class="view" id="define-columns">
-  <div class="bw-define-columns">
-    <form action="${action}" method="POST">
-      <div class="jframe-hidden">
-        ${util.render_form(file_form)}
-        ${util.render_form(delim_form)}
-        ${unicode(column_formset.management_form) | n}
-      </div>
-      <div class="hue-bc-section">
-      <dt> Step 3: Define Your Columns </dt>
-      <%
-        n_rows = len(fields_list)
-        if n_rows > 2: n_rows = 2
-      %>
-      <dd>
-          Beeswax has attempted to determine the types of your columns.  Please check them as you name the columns.
-        <dl class="clearfix">
-          <br/>
-          <dt> </dt>
-          <dd>
-            <table class="row_headers jframe-visible" style="display:none">
-              % for i in range(n_rows):
-                <tr><td> Row ${i + 1} </td></tr>
-              % endfor
-              <tr><td>&nbsp;</td></tr>
-              <tr><td class="input_row_header"> Column Name </td></tr>
-              <tr><td class="input_row_header"> Type </td></tr>
-            </table>
-            <div class="table_holder">
-              <table class="data_table">
-                % for i, row in enumerate(fields_list[:n_rows]):
-                  <tr>
-                    <td class="jframe-hidden"> Row ${i + 1} </td>
-                    % for val in row:
-                      <td>${val}</td>
-                    % endfor
-                  </tr>
-                % endfor
-                <tr><td colspan="${n_cols}">&nbsp;</td></tr>
-                <tr>
-                  % for form in column_formset.forms:
-                    <td>
-                      ${comps.field(form["column_name"],
-                        render_default=False,
-                        help="Column name",
-                      )}
-                      ${comps.field(form["column_type"],
-                        render_default=True,
-                        help="Type for this column",
-                      )}
-                      ${unicode(form["_exists"]) | n}
-                    </td>
-                  %endfor
-                </tr>
-              </table>
-            </div>
-          </dd>
-          </dl>
-          <a class="jframe-submit_form jframe-visible hue-multipart-next" data-extra-data="{'submit_create': 'Finish Creating Table'}" style="display:none">
-          Finish Creating Table
-          </a>
-          <input type="submit" name="submit_create" value="Finish Creating Table" class="jframe-hidden"/>
-          <br/><br/><br/>
-        </dd>
-      </div>
-    </form>
-  </div>
+
+
+<div class="content">
+	<h1>Create a new table from file</h1>
+	<ul class="pills">
+	  <li><a href="${ url('beeswax.create_table.import_wizard') }">Step 1: Choose File</a></li>
+	  <li><a href="${ url('beeswax.create_table.import_wizard') }">Step 2: Choose Delimiter</a></li>
+	  <li class="active"><a href="#">Step 3: Define Columns</a></li>
+	</ul>
+	<br/>
+	<form action="${action}" method="POST" class="form-stacked">
+		<div class="hidden">
+			${util.render_form(file_form)}
+	        ${util.render_form(delim_form)}
+	        ${unicode(column_formset.management_form) | n}
+		</div>
+		<%
+	        n_rows = len(fields_list)
+	        if n_rows > 2: n_rows = 2
+	      %>
+		<fieldset>
+			<legend>Define your columns</legend>
+			<div class="clearfix">
+				
+				<div class="input">
+					<table>
+						<tr>
+							<td>&nbsp;</td>
+							% for form in column_formset.forms:
+			                    <td>
+									${comps.label(form["column_name"])}
+									${comps.field(form["column_name"],
+										render_default=False,
+										attrs=dict(
+											placeholder="Column name"
+										)
+									)}
+									<br/><br/>
+									${comps.label(form["column_type"])}
+									${comps.field(form["column_type"],
+										render_default=True
+									)}
+									${unicode(form["_exists"]) | n}
+			                    </td>
+			                  %endfor
+						</tr>
+						% for i, row in enumerate(fields_list[:n_rows]):
+		                  <tr>
+		                    <td><em>Row #${i + 1}</em></td>
+		                    % for val in row:
+		                      <td>${val}</td>
+		                    % endfor
+		                  </tr>
+		                % endfor
+					</table>
+					
+				</div>
+			</div>
+		</fieldset>
+		<div class="actions">
+			<input class="btn primary" type="submit" name="submit_create" value="Create Table" />
+		</div>
+	</form>
 </div>
-${wrappers.foot()}
+</div>
+${commonfooter()}

+ 12 - 6
apps/beeswax/src/beeswax/templates/describe_partitions.mako

@@ -13,12 +13,17 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
-<%! from urllib import quote %>
-<%! from filebrowser.views import location_to_url %>
-${wrappers.head("Beeswax Table Partitions: " + table.tableName, section='tables')}
+<%! 
+  from urllib import quote
+  from filebrowser.views import location_to_url 
+  from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
+${commonheader("Beeswax Table Partitions: " + table.tableName, "beeswax", "100px")}
+${layout.menubar(section='tables')}
 
-<h2>Partitions</h2>
+<div class="container-fluid">
+<h1>Partitions</h1>
 
 <table>
 <tr>
@@ -47,4 +52,5 @@ ${wrappers.head("Beeswax Table Partitions: " + table.tableName, section='tables'
   <tr><td>Table has no partitions.</td></tr>
 % endif
 </table>
-${wrappers.foot()}
+</div>
+${commonfooter()}

+ 177 - 101
apps/beeswax/src/beeswax/templates/describe_table.mako

@@ -13,7 +13,10 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="comps" file="beeswax_components.mako" />
 <%
   if is_view:
@@ -21,10 +24,11 @@
   else:
     view_or_table_noun = "Table"
 %>
-${wrappers.head("Beeswax %s Metadata: %s" % (view_or_table_noun, table.tableName), section='tables')}
+${commonheader("Beeswax %s Metadata: %s" % (view_or_table_noun, table.tableName), "beeswax", "100px")}
+${layout.menubar(section='tables')}
 <%def name="column_table(cols)">
-  <div class="bw-col_table_wrapper">
-    <table class="sortable" data-filters="HtmlTable" cellpadding="0" cellspacing="0">
+
+    <table class="datatables">
       <thead>
         <tr>
           <th>Name</th>
@@ -42,111 +46,183 @@ ${wrappers.head("Beeswax %s Metadata: %s" % (view_or_table_noun, table.tableName
         % endfor
       </tbody>
     </table>
-  </div>
+
 </%def>
 
-<div id="describe_table resizable" class="view" data-filters="SplitView">
-  <div class="left_col">
-    <h2>${table.tableName}</h2>
-    <div class="jframe_padded">
-      <dl>
-        % if table.parameters.get("comment", False):
-          <dt class="hue-dt_cap">Description</dt>
-          <dd class="hue-dd_bottom">${ table.parameters.get("comment") }</dd>
-        % endif
-        <dt class="hue-dt_cap">Actions</dt>
-        <dd class="hue-dd_bottom bw-actions">
-          <ul>
-	    % if not is_view:
-	      <li class="jframe-clear" data-filters="CollapsingElements"><a class="bw-load_data collapser">Import Data</a>
-                <div class="collapsible jframe-hidden">
-                  <form action="${ url("beeswax.views.load_table", table=table_name) }">
-                    <dl>
-                      <div class="bw-dataNote">
-                      Note that loading data will move data from its location into the table's storage location.
-                      </div>
-                      ## Any existing data will be erased!
-                      <div class="bw-overwriteLabel">Overwrite existing data ? <input type="checkbox" name="overwrite" class="bw-overwriteCheckbox"/></div>
-                      ##Path (on HDFS) of files to load.
-                      ${comps.field(load_form["path"], title_klass='bw-pathLabel', attrs=dict(
-                        klass='bw-loadPath',
-                        data_filters="OverText",
-                        alt='/user/data'))}
-                      <div class="clearfix" data-filters="ArtButtonBar">
-                        <a class="hue-choose_file" data-filters="ArtButton" 
-                          data-icon-styles="{'width': 16, 'height': 16, 'top': 1, 'left': 4 }" data-chooseFor="path">Choose File</a>
-                        <input type="submit" class="bw-loadSubmit" data-filters="ArtButton" value="Submit"/>
-                      </div>
-                      
-                      % for pf in load_form.partition_columns:
-                        ${comps.field(load_form[pf], render_default=True)}
-                      % endfor
-                      ## This table is partitioned.  Therefore,
-                      ## you must specify what partition
-                      ## this data corresponds to.
-                    </dl>
-                  </form>
-                </div>
-	      </li>
-	    % endif
-            <li class="jframe-clear"><a href="${ url("beeswax.views.read_table", table=table_name) }" class="bw-browse_data">Browse Data</a></li>
-	    <li class="jframe-clear"><a href="${ url("beeswax.views.drop_table", table=table_name) }" class="bw-drop_table">Drop ${view_or_table_noun}</a></li>
-	    % if not is_view:
-	      <li class="jframe-clear"><a href="${hdfs_link}" target="FileBrowser" class="tip bw-location_link" data-filters="PointyTip" data-tip-direction="11" rel="${ table.sd.location }">View File Location</a></li>
-	    % endif
-          </ul>
-        </dd>
-      </dl>
+<div class="container-fluid">
+<h1>Beeswax Table Metadata: ${table.tableName}</h1>
+
+<div class="sidebar withTitle">
+	<div class="well">
+		<h6>Actions</h6>
+		<ul>
+        <li><a href="#" data-controls-modal="importData" data-backdrop="true" data-keyboard="true">Import Data</a></li>
+		<li><a href="${ url("beeswax.views.read_table", table=table_name) }">Browse Data</a></li>
+        <li><a href="#" data-controls-modal="dropTable" data-backdrop="true" data-keyboard="true">Drop ${view_or_table_noun}</a></li>
+        <li><a href="${hdfs_link}" rel="${ table.sd.location }">View File Location</a></li>
+		</ul>
+      	
     </div>
-  </div>
-  <div class="right_col">
-    <div data-filters="Tabs">
-      <ul class="toolbar tabs">
-        <li><span>Columns</span></li>
+</div>
+
+<div class="content">
+
+	% if table.parameters.get("comment", False):
+    <h5>${ table.parameters.get("comment") }</h5>
+	% endif
+	
+	<ul class="tabs">
+		<li class="active"><a href="#columns">Columns</a></li>
         % if len(table.partitionKeys) > 0:
-          <li><span>Partition Columns</span></li>
-        % endif
-        % if top_rows is not None:
-          <li><span>Sample</span></li>
+			<li><a href="#partitionColumns">Partition Columns</a></li>
         % endif
-      </ul>
-      <ul class="tab_sections jframe-clear">
-	## Tab 1: Column description
-        <li>${column_table(table.sd.cols)}</li>
-	## Tab 2: Partition info (if present)
+		% if top_rows is not None:
+			<li><a href="#sample">Sample</a></li>
+		% endif
+	</ul>
+	
+	<div class="tab-content">
+		<div class="active tab-pane" id="columns">
+			${column_table(table.sd.cols)}
+		</div>
         % if len(table.partitionKeys) > 0:
-          <li>
+          <div class="tab-pane" id="partitionColumns">
             ${column_table(table.partitionKeys)}
             <a href="${ url("beeswax.views.describe_partitions", table=table_name) }">Show Partitions</a>
-          </li>
+          </div>
         % endif
-	## Tab 3: Sample rows (if present)
-        % if top_rows is not None:
-          <li class="bw-table_sample">
-            <table data-filters="HtmlTable" cellpadding="0" cellspacing="0">
-              <thead>
-                <tr>
-                  % for col in table.sd.cols:
-                    <th>${col.name}</th>
-                  % endfor
-                </tr>
-              </thead>
-              <tbody>
-                % for i, row in enumerate(top_rows):
-                  <tr>
-                    % for item in row:
-                      <td>${ item }</td>
-                    % endfor
-                  </tr>
-                % endfor
-              </tbody>
-            </table>
-          </li>
-        % endif
-      </ul>
-    </div>
-  </div>
+		% if top_rows is not None:
+			<div class="tab-pane" id="sample">
+				<table class="datatables">
+	              <thead>
+	                <tr>
+	                  % for col in table.sd.cols:
+	                    <th>${col.name}</th>
+	                  % endfor
+	                </tr>
+	              </thead>
+	              <tbody>
+	                % for i, row in enumerate(top_rows):
+	                  <tr>
+	                    % for item in row:
+	                      <td>${ item }</td>
+	                    % endfor
+	                  </tr>
+	                % endfor
+	              </tbody>
+	            </table>
+        	</div>
+		% endif
+</div>
 </div>
-  
 
-${wrappers.foot()}
+<div id="dropTable" class="modal hide fade">
+	<form id="dropTableForm" method="POST" action="${ url("beeswax.views.drop_table", table=table_name) }">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3>Drop Table</h3>
+	</div>
+	<div class="modal-body">  
+	  <div id="dropTableMessage" class="alert-message block-message warning">
+	        
+	  </div>
+	</div>
+	<div class="modal-footer">
+		<input type="submit" class="btn primary" value="Yes"/>
+		<a href="#" class="btn secondary hideModal">No</a>
+	</div>
+	</form>
+</div>
+
+
+
+<div id="importData" class="modal hide fade">
+	<form method="POST" action="${ url("beeswax.views.load_table", table=table_name) }" class="form-stacked">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3>Import data</h3>
+	</div>
+	<div class="modal-body">  
+	  <div class="alert-message block-message warning">
+	        <p>Note that loading data will move data from its location into the table's storage location.</p>
+	  </div>
+	
+
+      
+	  <div class="clearfix">
+	  ${comps.label(load_form["path"], title_klass='loadPath', attrs=dict(
+        ))}
+    	<div class="input">
+		     ${comps.field(load_form["path"], title_klass='loadPath', attrs=dict(
+		       klass='loadPath span8'
+		       ))}
+		</div>
+		</div>
+      
+      % for pf in load_form.partition_columns:
+		<div class="clearfix">
+			${comps.label(load_form[pf], render_default=True)}
+	    	<div class="input">
+	        	${comps.field(load_form[pf], render_default=True, attrs=dict(
+			       klass='span8'
+			       ))}
+			</div>
+		</div>
+
+      % endfor  
+	
+		<div class="clearfix">
+			<div class="input">
+				<input type="checkbox" name="overwrite"/> Overwrite existing data
+			</div>
+		</div>
+	  
+
+	<div id="filechooser">
+	</div>
+	</div>
+	<div class="modal-footer">
+		<input type="submit" class="btn primary" value="Submit"/>
+		<a href="#" class="btn secondary hideModal">Cancel</a>
+	</div>
+	</form>
+</div>
+</div>
+<style>
+	#filechooser {
+		display:none;
+		min-height:100px;
+		overflow-y:scroll;
+	}
+</style>
+
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".tabs").tabs();
+		$("#filechooser").jHueFileChooser({
+			onFileChoose: function(filePath){
+				$(".loadPath").val(filePath);
+				$("#filechooser").slideUp();
+			}
+		});
+		$(".datatables").dataTable({
+			"bPaginate": false,
+		    "bLengthChange": false,
+			"bInfo": false,
+			"bFilter": false
+		});
+		
+		$.getJSON("${ url("beeswax.views.drop_table", table=table_name) }",function(data){
+			$("#dropTableMessage").text(data.title);
+		});
+		$(".hideModal").click(function(){
+			$(this).closest(".modal").modal("hide");
+		});
+		$(".loadPath").click(function(){
+			$("#filechooser").slideDown();
+		});
+
+	});
+</script>
+
+${commonfooter()}

+ 345 - 224
apps/beeswax/src/beeswax/templates/execute.mako

@@ -15,252 +15,373 @@
 ## limitations under the License.
 <%!
   from desktop.lib.django_util import extract_field_data
+  from desktop.views import commonheader, commonfooter
 %>
 
 <%namespace name="comps" file="beeswax_components.mako" />
-<%namespace name="wrappers" file="header_footer.mako" />
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="util" file="util.mako" />
 
 <%def name="query()">
-  <dl class="bw-query">
-    <dt class="bw-query_header clearfix hue-help_links_small">
-      % if design and not design.is_auto and design.name:
-        <label>
-          ${design.name}
-          % if design.desc:
-            <p class="jframe-inline" data-filters="InfoTip" data-help-direction="6">${design.desc}</p>
-          % endif
-        </label>
-      % else:
-        <label>New Query</label>
-      % endif
-      <ul class="query_edit_actions clearfix">
-        <li class="bw-query_save_buttons" data-filters="ArtButtonBar">
-          <a href="${ url('beeswax.views.execute_query') }"
-            class="bw-query_new" data-filters="ArtButton"
-            data-icon-styles="{'width': 16, 'height': 16, 'top': 4, 'left': 5}">New</a>
 
-          % if design and not design.is_auto and design.name:
-            <input type="submit" name="saveform-save" value="Save" class="bw-query_save" data-filters="ArtButton"
-              data-icon-styles="{'width':16,'height':16, 'left':7}"/>
-          % endif
-          <input type="submit" name="saveform-saveas" value="Save As..." class="bw-query_save_as" data-filters="ArtButton"
-            data-icon-styles="{'width':16,'height':16, 'left':7}"/>
-          <a href="#settings" class="bw-query_settings_toggle" data-filters="ArtButton" data-icon-styles="{'width':16, 'height': 16}">Advanced</a>
-          <input type="submit" name="button-explain" value="Explain" class="bw-query_explain" data-filters="ArtButton"
-           data-icon-styles="{'width':16,'height':16, left: 7}"/>
-          <input type="submit" name="button-submit" value="Execute" class="bw-query_execute" data-filters="ArtButton"
-           data-icon-styles="{'width':16,'height':16, 'left':52, 'top':3}"/>
-        </li>
-      </ul>
-    </dt>
-    <dd class="bw-query_bottom default" style="height: auto;">
-      <textarea class="bw-query-field" data-filters="OverText, PostEditor"
-        alt="Example: SELECT * FROM tablename" name="${form.query["query"].html_name | n}">${extract_field_data(form.query["query"]) or ''}</textarea>
-        % if len(form.query["query"].errors):
-          <div class="validation-advice">
-             ${unicode(form.query["query"].errors) | n}
+		<fieldset>
+			% if design and not design.is_auto and design.name:
+		          <legend>${design.name}</legend>
+		          % if design.desc:
+		            <p>${design.desc}</p>
+		          % endif
+
+		      % else:
+		        <legend>Query</legend>
+		      % endif
+
+          <div class="clearfix">
+            <div class="input">
+              	<textarea class="span12" rows="9" placeholder="Example: SELECT * FROM tablename" name="${form.query["query"].html_name | n}" id="queryField">${extract_field_data(form.query["query"]) or ''}</textarea>
+				<div id="validationResults">
+				% if len(form.query["query"].errors):
+					${unicode(form.query["query"].errors) | n}
+				 % endif
+				</div>
+            </div>
           </div>
-        % endif
-    </dd>
-  </dl>
-  <div class="bw-query_save_form">
-    ${comps.field(form.saveform['name'])}
-    ${comps.field(form.saveform['desc'])}
-  </div>
+        </fieldset>
+
+		
+		 
+		<div class="actions">
+			<a id="executeQuery" class="btn primary">Execute</a>
+			% if design and not design.is_auto and design.name:
+            <a id="saveQuery" class="btn">Save</a>
+          	% endif
+          	<a id="saveQueryAs" class="btn">Save as...</a>
+          
+			<a id="explainQuery" class="btn">Explain</a>
+			&nbsp; or <a href="${ url('beeswax.views.execute_query') }">create a new query</a>
+		</div>
+          
+          
+
+      
+ <!--      
+<a href="#settings">see the advanced settings</a>
+    <div>
+      ${comps.field(form.saveform['name'])}
+      ${comps.field(form.saveform['desc'])}
+    </div>
+-->
 </%def>
 
 
+${commonheader("Hive Query", "beeswax", "100px")}
+${layout.menubar(section='query')}
+<div class="container-fluid">
+<h1>Hive Query</h1>
+<div class="sidebar withTitle">
+	<div class="well">
+	<form id="advancedSettingsForm" action="${action}" method="POST" class="form-stacked noPadding">
+		<h4>Advanced settings</h4>
+		<h6>Hive settings</h6>
+		% for i, f in enumerate(form.settings.forms):
+		% if i > 0:
+			<hr/>
+		% endif
+		
+		<div class="clearfix">
+			${comps.label(f['key'])}
+			<div class="input">
+				${comps.field(f['key'], attrs=dict(
+					placeholder="mapred.reduce.tasks",
+					klass="span3 settingsField"
+				))}
+			</div>
+		</div>
+		
+		<div class="clearfix">
+			${comps.label(f['value'])}
+			<div class="input">
+				${comps.field(f['value'], attrs=dict(
+					placeholder="1",
+					klass="span3"
+				))}
+			</div>
+		</div>
+		<div class="clearfix">
+			${comps.field(f['_deleted'], tag="button", button_text="Remove", notitle=True, attrs=dict(
+				type="submit",
+				title="Delete this setting",
+				klass="btn small danger settingsDelete"
+			), value=True)}	
+		</div>
+		${comps.field(f['_exists'], hidden=True)}
+	    % endfor
+		<div class="clearfix">
+			<a class="btn small" data-form-prefix="settings">Add</a>
+		</div>
 
-${wrappers.head('Hive Query', section='query')}
-% if error_message:
-<div class="alert_popup jframe_renders">
-  <dl class="bw-query_error">
-    <dt class="hue-dt_cap">Your Query Has the Following Error(s):</dt>
-    <dd class="hue-dd_bottom jframe-error">
-      <div class="validation-advice">
-        ${error_message}
-      </div>
-      % if log:
-        <div class="bw-error_tab_msg">
-          (click the <b>Error Log</b> tab above the editor input for details)
-        </div>
-      % endif
-    </dd>
-  </dl>
-</div>
-% endif
+		
+		<h6>File Resources</h6>
+		 % for i, f in enumerate(form.file_resources.forms):
+              % if i > 0:
+                <hr/>
+              % endif
 
-<div class="view" id="execute">
-  <form action="${action}" method="POST" data-filters="FormValidator, SizeTo" data-size-to-height="0" style="overflow:hidden">
-    <div class="resizable" data-filters="SplitView">
-      <%
-        if form.settings.forms or form.file_resources.forms or form.functions.forms:
-          width = 230
-        else:
-          width = 0
-      %>
-      <div class="left_col" style="width: ${width}px;">
-        <a name="settings"></a>
-        <dl class="jframe_padded bw-query_settings">
-          <dt class="hue-dt_cap">Hive Settings</dt>
-          <dd class="hue-dd_bottom">
-            <dl>
-              % for i, f in enumerate(form.settings.forms):
-                % if i > 0:
-                  <hr/>
-                % endif
-                ${comps.field(f['key'], attrs=dict(
-                  alt="mapred.reduce.tasks",
-                  data_filters="OverText"
-                ))}
-                <div class="bw-query_settings_delete">
-                  ${comps.field(f['_deleted'], tag="button", button_text="x", notitle=True, attrs=dict(
-                      type="submit",
-                      title="Delete this setting"
-                    ), value=True)}
-                </div>
+			<div class="clearfix">
+				${comps.label(f['type'])}
+				<div class="input">
+					${comps.field(f['type'], render_default=True, attrs=dict(
+						klass="span3"
+					))}
+				</div>
+			</div>
+			
+			<div class="clearfix">
+				${comps.label(f['path'])}
+				<div class="input">
+					${comps.field(f['path'], attrs=dict(
+						placeholder="/user/foo/udf.jar",
+						klass="span3 file_resourcesField"
+					))}
+				</div>
+			</div>
+			<div class="clearfix">
+				<a href="#" data-filechooser-destination="${f['path'].html_name | n}" class="btn small">Choose a File</a>
 
-                ${comps.field(f['value'], attrs=dict(
-                  alt="1",
-                  data_filters="OverText",
-                ))}
-                ${comps.field(f['_exists'], hidden=True)}
-              % endfor
-              <div class="bw-query_settings_add">
-                <button id="id_settings-add" value="True" name="settings-add" type="submit">+</button>
-                <div class="jframe-hidden">${unicode(form.settings.management_form) | n }</div>
-              </div>
-            </dl>
-          </dd>
-          <dt class="hue-dt_cap">File Resources</dt>
-          <dd class="hue-dd_bottom">
-            <dl>
-              % for i, f in enumerate(form.file_resources.forms):
-                % if i > 0:
-                  <hr/>
-                % endif
+				${comps.field(f['_deleted'], tag="button", button_text="Remove", notitle=True, attrs=dict(
+					type="submit",
+					title="Delete this setting",
+					klass="btn small danger file_resourcesDelete"
+				), value=True)}
+				
+				${comps.field(f['_exists'], hidden=True)}
+			</div>
+            % endfor
+			<div class="clearfix">
+				<a class="btn small" data-form-prefix="file_resources">Add</a>
+			</div>
 
-                ${comps.field(f['type'], render_default=True)}
-                <div class="bw-query_settings_delete">
-                  ${comps.field(f['_deleted'], tag="button", button_text="x", notitle=True, attrs=dict(
-                      type="submit",
-                      title="Delete this setting"
-                    ), value=True)}
-                </div>
+		<h6>User-defined Functions</h6>
+		% for i, f in enumerate(form.functions.forms):
+          % if i > 0:
+            <hr/>
+          % endif
 
-                ${comps.field(f['path'], attrs=dict(
-                  alt="/user/foo/udf.jar",
-                  data_filters="OverText",
-                ))}
-                <div class="jframe-button_subbar_below clearfix">
-                  <a class="hue-choose_file" data-filters="ArtButton" data-chooseFor="${f['path'].html_name | n}" data-icon-styles="{'width':16, 'height':16, 'top':2}">Choose a File</a>
-                </div>
-                ${comps.field(f['_exists'], hidden=True)}
-              % endfor
-              <div class="bw-query_settings_add">
-                <button id="id_file_resources-add" value="True" name="file_resources-add" type="submit">+</button>
-                <div class="jframe-hidden">${unicode(form.file_resources.management_form) | n }</div>
-              </div>
-            </dl>
-          </dd>
-          <dt class="hue-dt_cap">User-defined Functions</dt>
-          <dd class="hue-dd_bottom">
-            <dl>
-              % for i, f in enumerate(form.functions.forms):
-                % if i > 0:
-                  <hr/>
-                % endif
+			<div class="clearfix">
+				${comps.label(f['name'])}
+				<div class="input">
+					${comps.field(f['name'], attrs=dict(
+						placeholder="myFunction",
+						klass="span3 functionsField"
+					))}
+				</div>
+			</div>
+			<div class="clearfix">
+				${comps.label(f['class_name'])}
+				<div class="input">
+					${comps.field(f['class_name'], attrs=dict(
+						placeholder="com.acme.example",
+						klass="span3"
+					))}
+				</div>
+			</div>
 
-                ${comps.field(f['name'], attrs=dict(
-                  alt="myFunction",
-                  data_filters="OverText",
-                ))}
-                <div class="bw-query_settings_delete">
-                  ${comps.field(f['_deleted'], tag="button", button_text="x", notitle=True, attrs=dict(
-                      type="submit",
-                      title="Delete this setting"
-                    ), value=True)}
-                </div>
+    		<div class="clearfix">
+				${comps.field(f['_deleted'], tag="button", button_text="Remove", notitle=True, attrs=dict(
+					type="submit",
+					title="Delete this setting",
+					klass="btn small danger"
+				), value=True)}
+			</div>
+         
+          ${comps.field(f['_exists'], hidden=True)}
+        % endfor
+		<div class="clearfix">
+			<a class="btn small" data-form-prefix="functions">Add</a>
+		</div>
+		
+		<h6>Parametrization</h6>
+		${comps.field(form.query["is_parameterized"],
+            notitle = True,
+            tag = "checkbox",
+            button_text = "Enable Parameterization", 
+            help = "If checked (the default), you can include parameters like $parameter_name in your query, and users will be prompted for a value when the query is run.",
+            help_attrs= dict(
+              data_help_direction='11'
+            )
+        )}
+		<h6>Email Notification</h6>
+		${comps.field(form.query["email_notify"],
+                      notitle = True,
+                      tag = "checkbox",
+                      button_text = "Email me on complete",
+                      help = "If checked, you will receive an email notification when the query completes.",
+                      help_attrs= dict(
+                        data_help_direction='11'
+                      )
+                     )}
+		<input type="hidden" name="${form.query["query"].html_name | n}" class="query" value="" />
+	</form>
+    </div>
+</div>
 
-                ${comps.field(f['class_name'], attrs=dict(
-                  alt="com.acme.example",
-                  data_filters="OverText",
-                ))}
-                ${comps.field(f['_exists'], hidden=True)}
-              % endfor
-              <div class="bw-query_settings_add">
-                <button id="id_functions-add" value="True" name="functions-add" type="submit">+</button>
-                <div class="jframe-hidden">${unicode(form.functions.management_form) | n }</div>
-              </div>
-            </dl>
-          </dd>
-          <dt class="hue-dt_cap">Parameterization</dt>
-          <dd class="hue-dd_bottom">
-            <dl class="hue-bw_parameters">
-              ${comps.field(form.query["is_parameterized"],
-                  notitle = True,
-                  tag = "checkbox",
-                  button_text = "Enable Parameterization", 
-                  help = "If checked (the default), you can include parameters like $parameter_name in your query, and users will be prompted for a value when the query is run.",
-                  help_attrs= dict(
-                    data_help_direction='11'
-                  )
-              )}
-            </dl>
-          </dd>
-          <dt class="hue-dt_cap">Email Notification</dt>
-          <dd class="hue-dd_bottom">
-            <dl class="hue-bw_parameters">
-          ${comps.field(form.query["email_notify"],
-                        notitle = True,
-                        tag = "checkbox",
-                        button_text = "Email me on complete",
-                        help = "If checked, you will receive an email notification when the query completes.",
-                        help_attrs= dict(
-                          data_help_direction='11'
-                        )
-                       )}
-            </dl>
-          </dd>
-        </dl>
-      </div>
-      <div class="right_col">
+<div class="content">
+	<div class="form-stacked">
+		% if error_message:
+			<div class="alert-message block-message error">
+				<p><strong>Your Query Has the Following Error(s):</strong></p>
+				<p>${error_message}</p>
+				% if log:
+					<small>click the <b>Error Log</b> tab below for details</small>
+				% endif
+			</div>
+		% endif
+	
         % if on_success_url:
           <input type="hidden" name="on_success_url" value="${on_success_url}"/>
         % endif
 
         % if error_messages or log:
-          <div data-filters="Tabs">
-            <ul class="toolbar bw-results_tabs jframe-right clearfix tabs" data-filters="Tabs">
-              <li><span>Query</span></li>
-              % if error_message or log:
-              <li><span>
-                % if log:
-                  Error Log
-                % endif
-              </span></li>
-              % endif
-            </ul>
-            <ul class="tab_sections jframe-clear">
-              <li>
-                ${query()}
-              </li>
-              % if error_message or log:
-                <li class="bw-results_log jframe_padded">
-                  % if log:
-                    <pre>${log}</pre>
-                  % endif
-                </li>
-              % endif
-            </ul>
-          </div>
-        % else:
-          ${query()}
-        % endif
+			<ul class="tabs">
+				<li class="active"><a href="#queryPane">Query</a></li>
+				% if error_message or log:
+              	<li><a href="#errorPane">
+					% if log:
+						Error Log
+					% else:
+						&nbsp;
+	                % endif
+				</a></li>
+				% endif
+			</ul>
+            
+			<div class="tab-content">
+				<div class="active tab-pane" id="queryPane">
+					${query()}
+				</div>
+				% if error_message or log:
+					<div class="tab-pane" id="errorPane">
+					% if log:
+						<pre>${log}</pre>
+					% endif
+					</div>
+				% endif
+			</div>
+		% else:
+			${query()}
+		% endif
+	</div>
+</div>
 
-      </div>
-    </div>
-  </form>
+
+
+<div id="chooseFile" class="modal hide fade">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3>Choose a file</h3>
+	</div>
+	<div class="modal-body">  
+		<div id="filechooser">
+		</div>
+	</div>
+	<div class="modal-footer">
+	</div>
+</div>
+
+<style>
+	#filechooser {
+		min-height:100px;
+		overflow-y:scroll;
+	}
+</style>
 </div>
-${wrappers.foot()}
+
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".tabs").tabs();
+		$("*[rel=popover]").popover({
+			offset: 10
+		});
+		// hack!!!
+		$("select").addClass("span3");
+		
+		$("a[data-form-prefix]").each(function(){
+			var _prefix = $(this).attr("data-form-prefix");
+			var _nextID = 0;
+			if ($("."+_prefix+"Field").length){
+				_nextID= ($("."+_prefix+"Field").last().attr("name").substr(_prefix.length+1).split("-")[0]*1)+1;
+			}
+			$("<input>").attr("type","hidden").attr("name",_prefix+"-next_form_id").attr("value",_nextID).appendTo($("#advancedSettingsForm"));
+			$("."+_prefix+"Delete").click(function(e){
+				e.preventDefault();
+				$("input[name="+_prefix+"-add]").attr("value","");
+				$("<input>").attr("type","hidden").attr("name", $(this).attr("name")).attr("value","True").appendTo($("#advancedSettingsForm"));
+				checkAndSubmit();
+			});
+		});
+		
+		$("a[data-form-prefix]").click(function(){
+			var _prefix = $(this).attr("data-form-prefix");
+			$("<input>").attr("type","hidden").attr("name",_prefix+"-add").attr("value","True").appendTo($("#advancedSettingsForm"));
+			checkAndSubmit();
+		});
+		
+		$("a[data-filechooser-destination]").click(function(){
+			var _destination = $(this).attr("data-filechooser-destination");
+			$("#filechooser").jHueFileChooser({
+				onFileChoose: function(filePath){
+					$("input[name='"+_destination+"']").val(filePath);
+					$("#chooseFile").modal("hide");
+				}
+			});
+			$("#chooseFile").modal("show");
+		});
+		
+		$("#executeQuery").click(function(){
+			$("<input>").attr("type","hidden").attr("name","button-submit").attr("value","Execute").appendTo($("#advancedSettingsForm"));
+			checkAndSubmit();
+		});
+		
+		$("#saveQuery").click(function(){
+			$("<input>").attr("type","hidden").attr("name","saveform-save").attr("value","Save").appendTo($("#advancedSettingsForm"));
+			checkAndSubmit();
+		});
+		
+		$("#saveQueryAs").click(function(){
+			$("<input>").attr("type","hidden").attr("name","saveform-saveas").attr("value","Save As...").appendTo($("#advancedSettingsForm"));
+			checkAndSubmit();
+		});
+		
+		$("#explainQuery").click(function(){
+			$("<input>").attr("type","hidden").attr("name","button-explain").attr("value","Explain").appendTo($("#advancedSettingsForm"));
+			checkAndSubmit();
+		});
+		
+		$("#queryField").change(function(){
+			$(".query").val($(this).val());
+		});
+		
+		$("#queryField").focus(function(){
+			$(this).removeClass("fieldError");
+			$("#validationResults").empty();
+		});
+				
+		function checkAndSubmit(){
+			$(".query").val($("#queryField").val());
+			if ($.trim($("#queryField").val()) == ""){
+				$("#queryField").addClass("fieldError");
+				$("#validationResults").html('<ul class="errorlist"><li>This field is required.</li></ul>');
+			}
+			else {
+				$("#advancedSettingsForm").submit();
+			}
+		}
+		
+		$("#chooseFile").modal({
+			keyboard: true,
+			backdrop: true
+		})
+	});
+</script>
+
+
+${commonfooter()}

+ 29 - 23
apps/beeswax/src/beeswax/templates/explain.mako

@@ -13,30 +13,36 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
+<%!
+from desktop.views import commonheader, commonfooter
+%>
 <%namespace name="comps" file="beeswax_components.mako" />
-<%namespace name="wrappers" file="header_footer.mako" />
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="util" file="util.mako" />
-${wrappers.head('Query Explanation', section='saved queries')}
-<div class="view, resizable" id="watch_wait" data-filters="SplitView">
-  <div class="left_col">
-    ${util.render_query_context(query_context)}
-  </div>
-  <div class="right_col jframe_padded">
-    <div data-filters="Tabs">
-      <ul class="toolbar bw-results_tabs tabs jframe-right clearfix">
-        <li><span>Explanation</span></li>
-        <li><span>Query</span></li>
-      </ul>
+${commonheader("Query Explanation", "beeswax", "100px")}
+${layout.menubar(section='saved queries')}
 
-      <ul class="tab_sections jframe-clear">
-        <li>
-          <pre>${explanation}</pre>
-        </li>
-        <li>
-          <pre>${query}</pre>
-        </li>
-      </ul>
-    </div>
-  </div>
+<div class="container-fluid">
+	<h1>Query Explanation: ${util.render_query_context(query_context)}</h1>
+
+	<ul class="tabs">
+		<li class="active"><a href="#explanation">Explanation</a></li>
+      	<li><a href="#query">Query</a></li>
+	</ul>
+    
+	<div class="tab-content">
+		<div class="active tab-pane" id="explanation">
+			<pre>${explanation}</pre>
+		</div>
+		<div class="tab-pane" id="query">
+			<pre>${query}</pre>
+		</div>
+	</div>
+	
+	<script type="text/javascript" charset="utf-8">
+		$(document).ready(function(){
+			$(".tabs").tabs();
+		});
+	</script>
 </div>
-${wrappers.foot()}
+${commonfooter()}

+ 0 - 70
apps/beeswax/src/beeswax/templates/header_footer.mako

@@ -1,70 +0,0 @@
-## Licensed to Cloudera, Inc. under one
-## or more contributor license agreements.  See the NOTICE file
-## distributed with this work for additional information
-## regarding copyright ownership.  Cloudera, Inc. licenses this file
-## to you under the Apache License, Version 2.0 (the
-## "License"); you may not use this file except in compliance
-## with the License.  You may obtain a copy of the License at
-##
-##     http://www.apache.org/licenses/LICENSE-2.0
-##
-## Unless required by applicable law or agreed to in writing, software
-## distributed under the License is distributed on an "AS IS" BASIS,
-## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-## See the License for the specific language governing permissions and
-## limitations under the License.
-##
-##
-## no spaces in this method please; we're declaring a CSS class, and ART uses this value for stuff, and it splits on spaces, and 
-## multiple spaces and line breaks cause issues
-<%!
-def is_selected(section, matcher):
-  if section == matcher:
-    return "selected"
-  else:
-    return ""
-%>
-
-<%def name="head(title='Beeswax for Hive', toolbar=True, section=False)">
-<html>
-  <head>
-    <title>${title}</title>
-  </head>
-  <body class="hue-shared">
-  <div class="toolbar">
-    <a href="${ url('beeswax.views.index') }"><img src="/beeswax/static/art/beeswax-logo.png" width="55" height="55" alt="Beeswax" class="beeswax_logo"></a>
-    % if toolbar:
-    <ul class="bw-nav" data-filters="ArtButtonBar">
-      <li><a href="${ url('beeswax.views.execute_query') }" 
-        class="bw-nav_icon bw-query_nav ${is_selected(section, 'query')}" data-filters="ArtButton"
-        data-icon-styles="{'width': 16, 'height': 16, 'top': 4, 'left': 5}">Query Editor</a></li>
-      <li><a href="${ url('beeswax.views.my_queries') }"
-        class="bw-nav_icon bw-my_queries_nav ${is_selected(section, 'my queries')}" data-filters="ArtButton"
-        data-icon-styles="{'width': 16, 'height': 16, 'top': 4, 'left': 5}">My Queries</a></li>
-      <li><a href="${ url('beeswax.views.list_designs') }" 
-        class="bw-nav_icon bw-queries_nav ${is_selected(section, 'saved queries')}" data-filters="ArtButton"
-        data-icon-styles="{'width': 16, 'height': 16, 'top': 4, 'left': 5}">Saved Queries</a></li>
-    ## <li><a href="${ url('beeswax.views.edit_report') }" class="bw-nav_icon bw-new_report_gen_nav ${is_selected(section, 'report generator')}" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16, 'top': 4, 'left': 5}">Report Generator</a></li>
-      <li><a href="${ url('beeswax.views.list_query_history') }" 
-        class="bw-nav_icon bw-history_nav ${is_selected(section, 'history')}" data-filters="ArtButton"
-        data-icon-styles="{'width': 16, 'height': 16, 'top': 4, 'left': 5}">History</a></li>
-      <li><a href="${ url('beeswax.views.show_tables') }" 
-        class="bw-nav_icon bw-tables_nav ${is_selected(section, 'tables')}" data-filters="ArtButton"
-        data-icon-styles="{'width': 16, 'height': 16, 'top': 4, 'left': 5}">Tables</a></li>
-      <li><a href="${ url('beeswax.views.configuration') }" 
-        class="bw-nav_icon bw-config_nav ${is_selected(section, 'hive configuration')}" data-filters="ArtButton"
-        data-icon-styles="{'width': 16, 'height': 16, 'top': 4, 'left': 5}">Settings</a>
-      </li>
-      <li><a class="jframe-refresh large" data-filters="ArtButton">Refresh</a></li>
-    </ul>
-    % endif
-  </div>
-  <hr class="jframe-hidden"/>
-</%def>
-
-<%def name="foot()">
-  </body>
-</html>
-</%def>
-
-

+ 44 - 0
apps/beeswax/src/beeswax/templates/layout.mako

@@ -0,0 +1,44 @@
+## Licensed to Cloudera, Inc. under one
+## or more contributor license agreements.  See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership.  Cloudera, Inc. licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##
+##     http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+##
+##
+## no spaces in this method please; we're declaring a CSS class, and ART uses this value for stuff, and it splits on spaces, and 
+## multiple spaces and line breaks cause issues
+<%!
+def is_selected(section, matcher):
+  if section == matcher:
+    return "selected"
+  else:
+    return ""
+%>
+
+<%def name="menubar(section='')">
+	<div class="menubar">
+		<div class="menubar-inner">
+			<div class="container-fluid">
+				<ul class="nav">
+					<li><a href="/beeswax/execute" class="${is_selected(section, 'query')}">Query Editor</a></li>
+					<li><a href="/beeswax/my_queries" class="${is_selected(section, 'my queries')}">My Queries</a></li>
+					<li><a href="/beeswax/list_designs" class="${is_selected(section, 'saved queries')}">Saved Queries</a></li>
+					<li><a href="/beeswax/query_history" class="${is_selected(section, 'history')}">History</a></li>
+					<li><a href="/beeswax/tables" class="${is_selected(section, 'tables')}">Tables</a></li>
+					<li><a href="/beeswax/configuration" class="${is_selected(section, 'hive configuration')}">Settings</a></li>
+				</ul>
+			</div>
+		</div>
+	</div>
+</%def>
+

+ 68 - 29
apps/beeswax/src/beeswax/templates/list_designs.mako

@@ -15,21 +15,23 @@
 ## limitations under the License.
 <%!
 from django.template.defaultfilters import timesince
+from desktop.views import commonheader, commonfooter
 %>
 <%namespace name="comps" file="beeswax_components.mako" />
-<%namespace name="wrappers" file="header_footer.mako" />
-${wrappers.head("Beeswax: Queries", section='saved queries')}
-
-<div id="list_designs" class="view">
-  ${comps.pagination(page)}
-  <h2 class="jframe-hidden">Saved Queries:</h2>
-  <table data-filters="HtmlTable" class="selectable" cellpadding="0" cellspacing="0">
+<%namespace name="layout" file="layout.mako" />
+${commonheader("Beeswax: Queries", "beeswax", "100px")}
+${layout.menubar(section='saved queries')}
+<div class="container-fluid">
+<h1>Beeswax: Queries</h1>
+  <table class="datatables">
     <thead>
       <tr>
-        <th colspan="2">Name</th>
+        <th>Name</th>
+		<th>Description</th>
         <th>Owner</th>
         <th>Type</th>
-        <th colspan="2">Last Modified</th>
+        <th>Last Modified</th>
+		<th></th>
       </tr>
     </thead>
     <tbody>
@@ -40,9 +42,7 @@ ${wrappers.head("Beeswax: Queries", section='saved queries')}
       <%
         may_edit = user == design.owner
       %>
-      <tr data-dblclick-delegate="{'dblclick_loads':'.bw-query_edit, .bw-query_clone'}" class="jframe-no_select hue-help_links_small"
-      data-filters="ContextMenu"
-      data-context-menu-actions="[{'events':['contextmenu','click:relay(a.bw-options)'],'menu':'ul.context-menu'}]">
+      <tr>
         <td>
           % if may_edit:
             % if design.type == models.SavedQuery.REPORT:
@@ -53,24 +53,10 @@ ${wrappers.head("Beeswax: Queries", section='saved queries')}
           % else:
             ${design.name}
           % endif
-          
-          
-          <ul class="jframe-hidden context-menu">
-            % if may_edit:
-              % if design.type == models.SavedQuery.REPORT:
-                <li><a href="${ url('beeswax.views.edit_report', design_id=design.id) }" class="bw-query_edit frame_tip" title="Edit this report.">Edit</a></li>
-              % else:
-                <li><a href="${ url('beeswax.views.execute_query', design_id=design.id) }" class="bw-query_edit frame_tip" title="Edit this query.">Edit</a></li>
-              % endif
-              <li><a href="${ url('beeswax.views.delete_design', design_id=design.id) }" class="bw-query_delete frame_tip" title="Delete this query.">Delete</a></li>
-              <li><a href="${ url('beeswax.views.list_query_history') }?design_id=${design.id}" class="bw-query_history frame_tip" title="View the usage history of this query.">Usage History</a></li>
-            % endif
-            <li><a href="${ url('beeswax.views.clone_design', design_id=design.id) }" class="bw-query_clone frame_tip" title="Copy this query.">Clone</a></li>
-          </ul>
         </td>
         <td>
           % if design.desc:
-           <p class="jframe-inline" data-filters="InfoTip">${design.desc}</p>
+           <p>${design.desc}</p>
           % endif
         </td>
         <td>${design.owner.username}</td>
@@ -85,11 +71,64 @@ ${wrappers.head("Beeswax: Queries", section='saved queries')}
           ${ timesince(design.mtime) } ago
         </td>
         <td>
-          <a class="bw-options">options</a>
+	      	% if may_edit:
+			<a class="btn small contextEnabler" data-menuid="${design.id}">Options</a>
+			<ul class="contextMenu" id="menu${design.id}">
+	             % if design.type == models.SavedQuery.REPORT:
+	               <li><a href="${ url('beeswax.views.edit_report', design_id=design.id) }" title="Edit this report." class="contextItem">Edit</a></li>
+	             % else:
+	               <li><a href="${ url('beeswax.views.execute_query', design_id=design.id) }" title="Edit this query." class="contextItem">Edit</a></li>
+	             % endif
+	             <li><a href="javascript:void(0)" data-confirmation-url="${ url('beeswax.views.delete_design', design_id=design.id) }" title="Delete this query." class="contextItem confirmationModal">Delete</a></li>
+	             <li><a href="${ url('beeswax.views.list_query_history') }?design_id=${design.id}" title="View the usage history of this query." class="contextItem">Usage History</a></li>
+			</ul>
+	        % endif
         </td>
       </tr>
     % endfor
     </tbody>
   </table>
+${comps.pagination(page)}
+
+
+<div id="deleteQuery" class="modal hide fade">
+	<form id="deleteQueryForm" action="" method="POST">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3 id="deleteQueryMessage">Confirm action</h3>
+	</div>
+	<div class="modal-footer">
+		<input type="submit" class="btn primary" value="Yes"/>
+		<a href="#" class="btn secondary hideModal">No</a>
+	</div>
+	</form>
+</div>
 </div>
-${wrappers.foot()}
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".tabs").tabs();
+		$(".datatables").dataTable({
+			"bPaginate": false,
+		    "bLengthChange": false,
+			"bInfo": false,
+			"bFilter": false
+		});
+		$(".contextEnabler").jHueContextMenu();
+		$("#deleteQuery").modal({
+			backdrop: "static",
+			keyboard: true
+		});
+		$(".confirmationModal").live("click", function(){
+			$.getJSON($(this).attr("data-confirmation-url"), function(data){
+				$("#deleteQueryForm").attr("action", data.url);
+				$("#deleteQueryMessage").text(data.title);
+			});
+			$("#deleteQuery").modal("show");
+		});
+		$(".hideModal").click(function(){
+			$("#deleteQuery").modal("hide");
+		});
+	});
+</script>
+
+${commonfooter()}

+ 65 - 45
apps/beeswax/src/beeswax/templates/list_history.mako

@@ -13,10 +13,14 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="comps" file="beeswax_components.mako" />
 <%!  from beeswax.views import collapse_whitespace %>
-${wrappers.head("Beeswax: Query History", section='history')}
+${commonheader("Beeswax: Query History", "beeswax", "100px")}
+${layout.menubar(section='history')}
 <%def name="show_saved_query(design, history)">
   % if design:
     % if request.user == design.owner:
@@ -41,50 +45,45 @@ ${wrappers.head("Beeswax: Query History", section='history')}
     [ Auto generated action ]
   % endif
 </%def>
-
-<div class="toolbar">
-  <div class="bw-input-filter">
-    <input type="text" class="jframe-hidden" data-filters="OverText, ArtInput, FilterInput" data-art-input-type="search"
-      title="Filter by Name"
-      data-filter-elements="tbody tr" value=""/>
-  </div>
+<div class="container-fluid">
+<h1>Beeswax: Query History</h1>
+<div class="sidebar withTitle">
+	<div class="well">
+		<h6>Actions</h6>
+		<ul>
+	    % if filter_params.get('user') == '_all':
+	      <%
+	        my_querydict = filter_params.copy()
+	        my_querydict['user'] = request.user.username
+	      %>
+		<li><a href="?${my_querydict.urlencode()}">Show my queries</a></li>
+	 	% else:
+	      <%
+	        my_querydict = filter_params.copy()
+	        my_querydict['user'] = '_all'
+	      %>
+	      <li><a href="?${my_querydict.urlencode()}">Show everyone's queries</a></li>
+	    % endif
+	
+	 	% if filter_params.get('auto_query', None):
+	      <%
+	        my_querydict = filter_params.copy()
+	        my_querydict['auto_query'] = ''
+	      %>
+	      <li><a href="?${my_querydict.urlencode()}" class="bw-show_group_noauto" data-filters="ArtButton">Show user queries</a></li>
+	    % else:
+	      <%
+	        my_querydict = filter_params.copy()
+	        my_querydict['auto_query'] = 'on'
+	      %>
+	      <li><a href="?${my_querydict.urlencode()}" class="bw-show_group_auto" data-filters="ArtButton">Show auto actions</a></li>
+	    % endif
+    </div>
 </div>
-<div id="list_history" class="view">
-  ${comps.pagination(page)}
 
-  <div class="bw-show_group toolbar">
-      Show:
-    % if filter_params.get('user') == '_all':
-      <%
-        my_querydict = filter_params.copy()
-        my_querydict['user'] = request.user.username
-      %>
-      <a href="?${my_querydict.urlencode()}" class="bw-show_group_mine" data-filters="ArtButton">mine</a>
-    % else:
-      <%
-        my_querydict = filter_params.copy()
-        my_querydict['user'] = '_all'
-      %>
-      <a href="?${my_querydict.urlencode()}" class="bw-show_group_all" data-filters="ArtButton">everyone's</a>
-    % endif
 
-    % if filter_params.get('auto_query', None):
-      <%
-        my_querydict = filter_params.copy()
-        my_querydict['auto_query'] = ''
-      %>
-      <a href="?${my_querydict.urlencode()}" class="bw-show_group_noauto" data-filters="ArtButton">user queries</a>
-    % else:
-      <%
-        my_querydict = filter_params.copy()
-        my_querydict['auto_query'] = 'on'
-      %>
-      <a href="?${my_querydict.urlencode()}" class="bw-show_group_auto" data-filters="ArtButton">auto actions</a>
-    % endif
-  </div>
-
-  <h3 class="jframe-hidden">Query History:</h3>
-  <table data-filters="HtmlTable" class="selectable" cellpadding="0" cellspacing="0">
+<div class="content">
+  <table class="datatables">
     <thead>
       <tr>
         <th>Time</th>
@@ -133,6 +132,27 @@ ${wrappers.head("Beeswax: Query History", section='history')}
     % endfor
     </tbody>
   </table>
-
+ ${comps.pagination(page)}
 </div>
-${wrappers.foot()}
+<!-- <div>
+  <div class="bw-input-filter">
+    <input type="text" class="jframe-hidden" data-filters="OverText, ArtInput, FilterInput" data-art-input-type="search"
+      title="Filter by Name"
+      data-filter-elements="tbody tr" value=""/>
+  </div> -->
+</div>
+</div>
+
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".tabs").tabs();
+		$(".datatables").dataTable({
+			"bPaginate": false,
+		    "bLengthChange": false,
+			"bInfo": false,
+			"bFilter": false
+		});
+
+	});
+</script>
+${commonfooter()}

+ 9 - 3
apps/beeswax/src/beeswax/templates/load_table.mako

@@ -13,9 +13,14 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="util" file="util.mako" />
-${wrappers.head("Beeswax: Load Data into " + table)}
+${commonheader("Beeswax: Load Data into " + table, "beeswax", "100px")}
+${layout.menubar()}
+<div class="container-fluid">
   <h1>Load Data into <tt>${table}</tt></h1>
   <div class="prompt_popup">
     <form action="${action}" method="POST">
@@ -39,4 +44,5 @@ ${wrappers.head("Beeswax: Load Data into " + table)}
       <input type="submit">
     </form>
   </div>
-${wrappers.foot()}
+</div>
+${commonfooter()}

+ 175 - 131
apps/beeswax/src/beeswax/templates/my_queries.mako

@@ -15,141 +15,185 @@
 ## limitations under the License.
 <%!
 from django.template.defaultfilters import timesince
+from desktop.views import commonheader, commonfooter
 %>
 <%namespace name="comps" file="beeswax_components.mako" />
-<%namespace name="wrappers" file="header_footer.mako" />
+<%namespace name="layout" file="layout.mako" />
 <%!  from beeswax.views import collapse_whitespace %>
-${wrappers.head("Beeswax: My Queries", section='my queries')}
+${commonheader("Beeswax: My Queries", "beeswax", "100px")}
+${layout.menubar(section='my queries')}
 
-##
-## ----------------- Saved queries -------------------
-##
-<div id="my_queries" class="view">
-  <div data-filters="Tabs">
-    <ul class="toolbar bw-my_queries_tabs tabs clearfix">
-      <li><span>Recent Saved Queries</span></li>
-      <li><span>Recent Run Queries</span></li>
-    </ul>
+<div class="container-fluid">
+<h1>Beeswax: My Queries</h1>
+
+	<ul class="tabs">
+		<li class="active"><a href="#recentSavedQueries">Recent Saved Queries</a></li>
+		<li><a href="#recentRunQueries">Recent Run Queries</a></li>
+	</ul>
+	
 
-    <ul class="tab_sections jframe-clear">
-      <li>
-        <table data-filters="HtmlTable" class="selectable" cellpadding="0" cellspacing="0">
-          <thead>
-            <tr>
-              <th colspan="2">Name</th>
-              <th>Type</th>
-              <th colspan="2">Last Modified</th>
-            </tr>
-          </thead>
-          <tbody>
-          <%!
-            from beeswax import models
-          %>
-          % for design in q_page.object_list:
-            <tr data-dblclick-delegate="{'dblclick_loads':'.bw-query_edit, .bw-query_clone'}" class="jframe-no_select hue-help_links_small"
-            data-filters="ContextMenu"
-            data-context-menu-actions="[{'events':['contextmenu','click:relay(a.bw-options)'],'menu':'ul.context-menu'}]">
-              <td>
-                % if design.type == models.SavedQuery.REPORT:
-                  <a href="${ url('beeswax.views.edit_report', design_id=design.id) }">${design.name}</a>
-                % else:
-                  <a href="${ url('beeswax.views.execute_query', design_id=design.id) }">${design.name}</a>
-                % endif
+		<div class="tab-content">
+			<div class="active tab-pane" id="recentSavedQueries">
+	
+				 <table class="datatables">
+			          <thead>
+			            <tr>
+			              <th>Name</th>
+						  <th>Desc</th>
+			              <th>Type</th>
+			              <th>Last Modified</th>
+						  <th></th>
+			            </tr>
+			          </thead>
+			          <tbody>
+			          <%!
+			            from beeswax import models
+			          %>
+			          % for design in q_page.object_list:
+			            <tr>
+			              <td>
+			                % if design.type == models.SavedQuery.REPORT:
+			                  <a href="${ url('beeswax.views.edit_report', design_id=design.id) }">${design.name}</a>
+			                % else:
+			                  <a href="${ url('beeswax.views.execute_query', design_id=design.id) }">${design.name}</a>
+			                % endif
+			              </td>
+			              <td>
+			                % if design.desc:
+			                 <p>${design.desc}</p>
+			                % endif
+			              </td>
+			              <td>
+			                % if design.type == models.SavedQuery.REPORT:
+			                  Report
+			                % else:
+			                  Query
+			                % endif
+			              </td>
+			              <td>
+			                ${ timesince(design.mtime) } ago
+			              </td>
+			              <td>
+							<a class="btn small contextEnabler" data-menuid="${design.id}">Options</a>
+							<ul class="contextMenu" id="menu${design.id}">
+					             % if design.type == models.SavedQuery.REPORT:
+				                    <li><a href="${ url('beeswax.views.edit_report', design_id=design.id) }" title="Edit this report." class="contextItem">Edit</a></li>
+				                  % else:
+				                    <li><a href="${ url('beeswax.views.execute_query', design_id=design.id) }" title="Edit this query." class="contextItem">Edit</a></li>
+				                  % endif
+				                  <li><a href="javascript:void(0)" data-confirmation-url="${ url('beeswax.views.delete_design', design_id=design.id) }" title="Delete this query." class="contextItem confirmationModal">Delete</a></li>
+				                  <li><a href="${ url('beeswax.views.list_query_history') }?design_id=${design.id}" title="View the usage history of this query." class="contextItem">Usage History</a></li>
+				                  <li><a href="${ url('beeswax.views.clone_design', design_id=design.id) }" title="Copy this query." class="contextItem">Clone</a></li>
+							</ul>
+			              </td>
+			            </tr>
+			          % endfor
+			          </tbody>
+			        </table>
+			        % if q_page.number != q_page.num_pages():
+			          <a href="${ url('beeswax.views.list_designs') }?user=${request.user.username|u}" >View all my queries &raquo;</a>
+			        % endif
+			</div>
+			
+			<div class="tab-pane" id="recentRunQueries">
+				<table class="datatables">
+		          <thead>
+		            <tr>
+		              <th>Time</th>
+		              <th>Name</th>
+		              <th>Query</th>
+		              <th>State</th>
+		              <th>Result</th>
+		            </tr>
+		          </thead>
+		          <tbody>
+		          <%!
+		            from beeswax import models, views
+		          %>
+		          % for query in h_page.object_list:
+		            <%
+			      qcontext = ""
+			      try:
+				design = query.design
+				qcontext = views.make_query_context('design', design.id)
+			      except:
+				pass
+		            %>
+		            <tr >
+		              <td>${query.submission_date.strftime("%x %X")}</td>
+		              ## TODO (bc): Only showing HQL (not REPORT)
+		              <td><a href="${ url('beeswax.views.execute_query', design_id=design.id) }" >${design.name}</a></td>
+		              <td>
+		                <p>
+		                  % if len(query.query) > 100:
+		                    <code>${collapse_whitespace(query.query[:100])}...</code>
+		                  % else:
+		                    <code>${collapse_whitespace(query.query)}</code>
+		                  % endif
+		                </p>
+		              </td>
+		              <td>${models.QueryHistory.STATE[query.last_state]}</td>
+		              <td>
+		                % if qcontext and query.last_state != models.QueryHistory.STATE.expired.index:
+		                  <a href="${ url('beeswax.views.watch_query', id=query.id) }?context=${qcontext|u}">View</a>
+		                % else:
+		                  ~
+		                % endif
+		              </td>
+		            </tr>
+		          % endfor
+		          </tbody>
+		        </table>
+		        % if h_page.number != h_page.num_pages():
+		          <a href="${ url('beeswax.views.list_query_history') }">View my entire query history &raquo;</a>
+		        % endif
+			</div>
+
+</div>
 
-                <ul class="jframe-hidden context-menu">
-                  % if design.type == models.SavedQuery.REPORT:
-                    <li><a href="${ url('beeswax.views.edit_report', design_id=design.id) }" class="bw-query_edit frame_tip" title="Edit this report.">Edit</a></li>
-                  % else:
-                    <li><a href="${ url('beeswax.views.execute_query', design_id=design.id) }" class="bw-query_edit frame_tip" title="Edit this query.">Edit</a></li>
-                  % endif
-                  <li><a href="${ url('beeswax.views.delete_design', design_id=design.id) }" class="bw-query_delete frame_tip" title="Delete this query.">Delete</a></li>
-                  <li><a href="${ url('beeswax.views.list_query_history') }?design_id=${design.id}" class="bw-query_history frame_tip" title="View the usage history of this query.">Usage History</a></li>
-                  <li><a href="${ url('beeswax.views.clone_design', design_id=design.id) }" class="bw-query_clone frame_tip" title="Copy this query.">Clone</a></li>
-                </ul>
-              </td>
-              <td>
-                % if design.desc:
-                 <p class="jframe-inline" data-filters="InfoTip">${design.desc}</p>
-                % endif
-              </td>
-              <td>
-                % if design.type == models.SavedQuery.REPORT:
-                  Report
-                % else:
-                  Query
-                % endif
-              </td>
-              <td>
-                ${ timesince(design.mtime) } ago
-              </td>
-              <td>
-                <a class="bw-options">options</a>
-              </td>
-            </tr>
-          % endfor
-          </tbody>
-        </table>
-        % if q_page.number != q_page.num_pages():
-          <a href="${ url('beeswax.views.list_designs') }?user=${request.user.username|u}" class="bw-view_more">View all my queries &raquo;</a>
-        % endif
-      </li>
-      <li>
-        ##
-        ## ----------------- My history -------------------
-        ##
-        <table data-filters="HtmlTable" class="selectable" cellpadding="0" cellspacing="0">
-          <thead>
-            <tr>
-              <th>Time</th>
-              <th>Name</th>
-              <th>Query</th>
-              <th>State</th>
-              <th>Result</th>
-            </tr>
-          </thead>
-          <tbody>
-          <%!
-            from beeswax import models, views
-          %>
-          % for query in h_page.object_list:
-            <%
-	      qcontext = ""
-	      try:
-		design = query.design
-		qcontext = views.make_query_context('design', design.id)
-	      except:
-		pass
-            %>
-            <tr data-dblclick-delegate="{'dblclick_loads':'.bw-view_result'}" class="jframe-no_select hue-help_links_small">
-              <td>${query.submission_date.strftime("%x %X")}</td>
-              ## TODO (bc): Only showing HQL (not REPORT)
-              <td><a href="${ url('beeswax.views.execute_query', design_id=design.id) }" class="bw-view_query">${design.name}</a></td>
-              <td>
-                <p class="jframe-inline" data-filters="InfoTip">
-                  % if len(query.query) > 100:
-                    <code>${collapse_whitespace(query.query[:100])}...</code>
-                  % else:
-                    <code>${collapse_whitespace(query.query)}</code>
-                  % endif
-                </p>
-              </td>
-              <td>${models.QueryHistory.STATE[query.last_state]}</td>
-              <td class="bw-query_result">
-                % if qcontext and query.last_state != models.QueryHistory.STATE.expired.index:
-                  <a href="${ url('beeswax.views.watch_query', id=query.id) }?context=${qcontext|u}" class="bw-view_result" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16, 'top': 2}">View</a>
-                % else:
-                  ~
-                % endif
-              </td>
-            </tr>
-          % endfor
-          </tbody>
-        </table>
-        % if h_page.number != h_page.num_pages():
-          <a href="${ url('beeswax.views.list_query_history') }" class="bw-view_more">View my entire query history &raquo;</a>
-        % endif
-      </li>
-    </ul>
-  </div>
+<div id="deleteQuery" class="modal hide fade">
+	<form id="deleteQueryForm" action="" method="POST">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3 id="deleteQueryMessage">Confirm action</h3>
+	</div>
+	<div class="modal-footer">
+		<input type="submit" class="btn primary" value="Yes"/>
+		<a href="#" class="btn secondary hideModal">No</a>
+	</div>
+	</form>
 </div>
-${wrappers.foot()}
+</div>
+
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".tabs").tabs();
+		$(".datatables").dataTable({
+			"bPaginate": false,
+		    "bLengthChange": false,
+			"bInfo": false,
+			"bFilter": false
+		});
+		
+		
+		$(".contextEnabler").jHueContextMenu();
+		$("#deleteQuery").modal({
+			backdrop: "static",
+			keyboard: true
+		});
+		$(".confirmationModal").live("click", function(){
+			$.getJSON($(this).attr("data-confirmation-url"), function(data){
+				$("#deleteQueryForm").attr("action", data.url);
+				$("#deleteQueryMessage").text(data.title);
+			});
+			$("#deleteQuery").modal("show");
+		});
+		$(".hideModal").click(function(){
+			$("#deleteQuery").modal("hide");
+		});
+
+	});
+</script>
+
+
+${commonfooter()}

+ 9 - 3
apps/beeswax/src/beeswax/templates/parameterization.mako

@@ -13,9 +13,14 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
+<%!
+from desktop.views import commonheader, commonfooter
+%>
 <%namespace name="comps" file="beeswax_components.mako" />
-<%namespace name="wrappers" file="header_footer.mako" />
-${wrappers.head('Parameterize Hive Query')}
+<%namespace name="layout" file="layout.mako" />
+${commonheader("Parameterize Hive Query", "beeswax", "100px")}
+${layout.menubar()}
+<div class="container-fluid">
 <div class="prompt_popup">
 Please specify parameters for this query.
 <%
@@ -33,4 +38,5 @@ else:
 <input class="jframe-hidden" type="submit">
 </form>
 </div>
-${wrappers.foot()}
+</div>
+${commonfooter()}

+ 9 - 4
apps/beeswax/src/beeswax/templates/report_gen.mako

@@ -13,10 +13,14 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="util" file="util.mako" />
-${wrappers.head("Beeswax: Query Constructor", section='report generator')}
-
+${commonheader("Beeswax: Query Constructor", "beeswax", "100px")}
+${layout.menubar(section='report generator')}
+<div class="container-fluid">
 <h1>Report Generator</h1>
 % if design and not design.is_auto and design.name:
 <b>Working on saved query: ${design.name}</b>
@@ -113,4 +117,5 @@ Error: <b>${error_message}</b>
 ${log}
 </pre>
 % endif
-${wrappers.foot()}
+</div>
+${commonfooter()}

+ 9 - 4
apps/beeswax/src/beeswax/templates/save_results.mako

@@ -13,11 +13,15 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="comps" file="beeswax_components.mako" />
 <%namespace name="util" file="util.mako" />
-
-${wrappers.head("Beeswax: Query History", section='history')}
+${commonheader("Beeswax: Create table from file", "beeswax", "100px")}
+${layout.menubar(section='history')}
+<div class="container-fluid">
 % if error_msg:
 <h4>${error_msg}</h4>
 % endif
@@ -27,4 +31,5 @@ ${wrappers.head("Beeswax: Query History", section='history')}
   <input type="submit" name="save" value="Save"/>
   <input type="submit" name="cancel" value="Cancel"/>
 </form>
-${wrappers.foot()}
+</div>
+${commonfooter()}

+ 71 - 24
apps/beeswax/src/beeswax/templates/show_tables.mako

@@ -13,27 +13,30 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
-${wrappers.head("Beeswax: Table List", section='tables')}
-  <div class="toolbar">
-    <div class="bw-show_tables_subnav" data-filters="ArtButtonBar">
-      % if not examples_installed:
-        <a href="${ url('beeswax.views.install_examples') }" data-filters="ArtButton" class="bw-install_samples" data-icon-styles="{'width': 16, 'height': 16, 'top': 1}">install samples</a>
-      % endif
-      <a href="${ url('beeswax.create_table.index') }" data-filters="ArtButton" class="bw-new_table" data-icon-styles="{'width': 16, 'height': 16, 'top': 1}">new table</a>
-    </div>
-  </div>
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
+${commonheader("Beeswax: Table List", "beeswax", "100px")}
+${layout.menubar(section='tables')}
+<div class="container-fluid">
+<h1>Beeswax: Table List</h1>
 
-<div id="show_tables" class="view">
-  <h2 class="jframe-hidden">Tables</h2>
-  <div class="toolbar">
-    <div class="bw-input-filter">
-      <input type="text" class="jframe-hidden" data-filters="OverText, ArtInput, FilterInput" data-art-input-type="search"
-        title="Filter by Name"
-        data-filter-elements="td.bw-tables_table" data-filter-parents="tr" value=""/>
+<div class="sidebar withTitle">
+	<div class="well">
+		<h6>Actions</h6>
+		<ul>
+			% if not examples_installed:
+        	<li><a href="#" data-controls-modal="installSamples" data-backdrop="true" data-keyboard="true">Install samples</a></li>
+      		% endif
+      		<li><a href="${ url('beeswax.create_table.import_wizard')}">Create a new table from file</a></li>
+			<li><a href="${ url('beeswax.create_table.create_table')}">Create a new table manually</a></li>
+		</ul>
     </div>
-  </div>
-  <table data-filters="HtmlTable" class="selectable sortable" cellpadding="0" cellspacing="0">
+</div>
+
+<div class="content">
+  <table class="datatables">
     <thead>
       <tr>
         <th>Table Name</th>
@@ -42,15 +45,59 @@ ${wrappers.head("Beeswax: Table List", section='tables')}
     </thead>
     <tbody>
       % for table in tables:
-        <tr data-dblclick-delegate="{'dblclick_loads':'.bw-tables_table a'}" class="jframe-no_select">
-          <td class="bw-tables_table jframe-no_select">
+        <tr>
+          <td>
             <a href="${ url("beeswax.views.describe_table", table=table) }">${ table }</a>
-            <!-- <p class="jframe-inline" data-filters="HelpTip">TODO</p> -->
           </td>
-          <td class="bw-tables_browse"><a href="${ url("beeswax.views.read_table", table=table) }">Browse Data</a></td>
+          <td><a href="${ url("beeswax.views.read_table", table=table) }">Browse Data</a></td>
         </tr>
       % endfor
     </tbody>
   </table>
+	<div class="row">
+		<div class="span16">&nbsp;</div>
+	</div>
 </div>
-${wrappers.foot()}
+% if not examples_installed:
+<div id="installSamples" class="modal hide fade">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3>Install samples</h3>
+	</div>
+	<div class="modal-body">  
+	  <div id="installSamplesMessage" class="alert-message block-message warning">
+	        
+	  </div>
+	</div>
+	<div class="modal-footer">
+		<a href="#" id="installSamplesBtn" class="btn primary" value="Yes"/>
+		<a href="#" class="btn secondary hideModal">No</a>
+	</div>
+</div>
+% endif
+</div>
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".datatables").dataTable({
+			"bPaginate": false,
+		    "bLengthChange": false,
+			"bInfo": false,
+			"bFilter": false
+		});
+		% if not examples_installed:
+		$.getJSON("${ url('beeswax.views.install_examples') }",function(data){
+			$("#installSamplesMessage").text(data.title);
+		});
+		$(".hideModal").click(function(){
+			$(this).closest(".modal").modal("hide");
+		});
+		$("#installSamplesBtn").click(function(){
+			$.post("${ url('beeswax.views.install_examples') }", {submit:"Submit"}).error(function(){
+				$("#installSamplesMessage").removeClass("warning").addClass("error").text("There was an error processing your request.");
+			});
+		});
+		% endif
+	});
+</script>
+
+${commonfooter()}

+ 4 - 5
apps/beeswax/src/beeswax/templates/util.mako

@@ -56,17 +56,16 @@
   % if query_context:
     % if query_context[0] == 'table':
       <% tablename = query_context[1] %>
-      <h2>Table:
-      <a href="${ url('beeswax.views.describe_table', tablename) }" class="bw-query_link">${tablename}</a></h2>
+      <a href="${ url('beeswax.views.describe_table', tablename) }" class="bw-query_link">${tablename}</a>
     % elif query_context[0] == 'design':
       <% design = query_context[1] %>
       % if design.is_auto:
-        <h2><a href="${ url('beeswax.views.execute_query', design.id)}" class="bw-query_link">Unsaved Query</a></h2>
+		<a href="${ url('beeswax.views.execute_query', design.id)}" class="bw-query_link">Unsaved Query</a>
       % else:
-        <h2><a href="${ url('beeswax.views.execute_query', design.id)}" class="bw-query_link">${design.name}</a></h2>
+        <a href="${ url('beeswax.views.execute_query', design.id)}" class="bw-query_link">${design.name}</a>
       % endif
     % else:
-      <h2>Query Results</h2>
+      Query Results
     % endif
   % endif
 </%def>

+ 115 - 104
apps/beeswax/src/beeswax/templates/watch_results.mako

@@ -13,23 +13,44 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="util" file="util.mako" />
 <%namespace name="comps" file="beeswax_components.mako" />
-${wrappers.head("Beeswax: Query Results", section='query')}
-
-<div class="view resizable" id="watch_results" data-filters="SplitView">
-  <div class="left_col">
-    ${util.render_query_context(query_context)}
-      <dl class="jframe_padded">
-        % if download_urls:
-          ## Download results
-          <dt class="hue-dt_cap">Actions</dt>
-          <dd class="hue-dd_bottom bw-actions">
-            <ul>
-              <li><a target="_blank" href="${download_urls["csv"]}" class="bw-download_csv">Download as CSV</a>
-              <li><a target="_blank" href="${download_urls["xls"]}" class="bw-download_xls">Download as XLS</a>
-              <li data-filters="CollapsingElements"><a class="bw-save collapser jframe_ignore" href="${url('beeswax.views.save_results', query.id)}">Save</a>
+${commonheader("Beeswax: Query Results", "beeswax", "100px")}
+${layout.menubar(section='query')}
+<div class="container-fluid">
+<h1>Beeswax: Query Results: ${util.render_query_context(query_context)}</h1>
+<div class="sidebar withTitle">
+	<div class="well">
+		% if download_urls:
+		<h6>Downloads</h6>
+		<ul>
+			<li><a target="_blank" href="${download_urls["csv"]}" class="bw-download_csv">Download as CSV</a></li>
+			<li><a target="_blank" href="${download_urls["xls"]}" class="bw-download_xls">Download as XLS</a></li>
+			<li><a href="${url('beeswax.views.save_results', query.id)}">Save</a></li>
+		</ul>
+ 		% endif
+        <%
+          n_jobs = hadoop_jobs and len(hadoop_jobs) or 0
+          mr_jobs = (n_jobs == 1) and "MR Job" or "MR Jobs"
+        %>
+	 	% if n_jobs > 0:
+			<h6>${mr_jobs} (${n_jobs})</h6>
+	             
+			% for jobid in hadoop_jobs:
+			<a href="${url("jobbrowser.views.single_job", jobid=jobid)}" class="bw-hadoop_job">${jobid.replace("job_", "")}</a><br/>
+			% endfor
+		% else:
+			<h6>${mr_jobs}</h6>
+			<p class="bw-no_jobs">No Hadoop jobs were launched in running this query.</p>
+		% endif 
+	</div>
+</div>
+<div class="content">
+	
                 <div class="collapsible jframe-hidden bw-save_query_results" style="display:none" data-filters="Accordion"> 
                   <form action="${url('beeswax.views.save_results', query.id) }" method="POST">
                     ## Writing the save_target fields myself so I can match them to their respective text input fields.
@@ -55,94 +76,84 @@ ${wrappers.head("Beeswax: Query Results", section='query')}
                     <input type="submit" value="Save" name="save" data-filters="ArtButton"> 
                   </form>
                 </div>
-              </li>
-            </ul>
-          </dd>
-        % endif
-        <%
-          n_jobs = hadoop_jobs and len(hadoop_jobs) or 0
-          mr_jobs = (n_jobs == 1) and "MR Job" or "MR Jobs"
-        %>
-        <dt class="hue-dt_cap">${mr_jobs}</dt>
-        <dd class="hue-dd_bottom bw-actions">
-          <ul>
-            % if n_jobs > 0:
-              <h3 class="jframe-hidden">This query launched ${n_jobs} ${mr_jobs}:</h3>
-              <ul class="beeswax_hadoop_job_links">
-                % for jobid in hadoop_jobs:
-                <li><a href="${url("jobbrowser.views.single_job", jobid=jobid)}" target="JobBrowser" class="bw-hadoop_job">${jobid.replace("job_", "")}</a></li>
-                % endfor
-              </ul>
-            % else:
-              <p class="bw-no_jobs">No Hadoop jobs were launched in running this query.</p>
-            % endif 
-          </ul>
-        </dd>
-      </dl>
-  </div>
-  <div class="right_col">
-    <div data-filters="Tabs">
-        <ul class="toolbar bw-results_tabs tabs jframe-right clearfix">
-          <li><span>
-              % if error:
-                Error
-              % else:
-                Results
-              % endif
-            </span></li>
-          <li><span>Query</span></li>
-          <li><span>Log</span></li>
-        </ul>
 
-      <ul class="tab_sections jframe-clear">
-        <li>
-          % if error:
-            <div class="jframe-error jframe_padded">
-              <h3 class="jframe-hidden">Error!</h3> 
-              <pre>${error_message}</pre>
-            </div>
-          % else:
-            <div class="bw-result_nav toolbar">
-              % if has_more:
-                <a href="${ url('beeswax.views.view_results', query.id, next_row) }" title="Next page" class="bw-nextBlock">[next]</a>
-              % endif
-              % if start_row != 0:
-                <a href="${ url('beeswax.views.view_results', query.id, 0) }" title="Back to first row" class="bw-firstBlock">[top]</a>
-              % endif
-            </div>
-            % if expected_first_row != start_row:
-              <div class="bw-result_warning">Warning:</i> Page offset may have incremented since last view.</div>
-            % endif
-            <table data-filters="HtmlTable" cellpadding="0" cellspacing="0">
-              <thead>
-                <tr>
-                  <th>-</th>
-                  % for col in columns:
-                    <th>${col}</th>
-                  % endfor
-                </tr>
-              </thead>
-              <tbody>
-                % for i, row in enumerate(results):
-                <tr>
-                  <td>${start_row + i}</td>
-                  % for item in row:
-                    <td>${ item }</td>
-                  % endfor
-                </tr>
-                % endfor
-              </tbody>
-            </table>
-          % endif
-        </li>
-        <li class="jframe_padded">
-          <pre>${query.query}</pre>
-        </li>
-        <li class="jframe_padded">
-          <pre>${log}</pre>
-        </li>
-      </ul>
-    </div>
-  </div>
+				<ul class="tabs">
+					<li class="active"><a href="#results">
+		  			%if error:
+			            Error
+					%else:
+						Results
+					%endif
+					</a></li>
+					<li><a href="#query">Query</a></li>
+					<li><a href="#log">Log</a></li>
+				</ul>
+	
+				<div class="tab-content">
+					<div class="active tab-pane" id="results">
+					% if error:
+		            <div class="jframe-error jframe_padded">
+		              <h3 class="jframe-hidden">Error!</h3> 
+		              <pre>${error_message}</pre>
+		            </div>
+          			% else:
+            		<div class="bw-result_nav toolbar">
+		              % if has_more:
+		                <a href="${ url('beeswax.views.view_results', query.id, next_row) }" title="Next page" class="bw-nextBlock">[next]</a>
+		              % endif
+		              % if start_row != 0:
+		                <a href="${ url('beeswax.views.view_results', query.id, 0) }" title="Back to first row" class="bw-firstBlock">[top]</a>
+		              % endif
+		            </div>
+		            % if expected_first_row != start_row:
+		              <div class="bw-result_warning">Warning:</i> Page offset may have incremented since last view.</div>
+		            % endif
+            		<table class="resultTable" cellpadding="0" cellspacing="0">
+		              <thead>
+		                <tr>
+		                  <th>-</th>
+		                  % for col in columns:
+		                    <th>${col}</th>
+		                  % endfor
+		                </tr>
+		              </thead>
+		              <tbody>
+		                % for i, row in enumerate(results):
+		                <tr>
+		                  <td>${start_row + i}</td>
+		                  % for item in row:
+		                    <td>${ item }</td>
+		                  % endfor
+		                </tr>
+		                % endfor
+		              </tbody>
+		            </table>
+		          % endif
+				</div>
+				<div class="tab-pane" id="query">
+					
+						<pre>${query.query}</pre>
+					
+				</div>
+				<div class="tab-pane" id="log">
+					<pre>${log}</pre>
+				</div>
+			</div>
+
 </div>
-${wrappers.foot()}
+</div>
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".tabs").tabs();
+		$(".resultTable").dataTable({
+			"bPaginate": false,
+		    "bLengthChange": false,
+			"bInfo": false
+		});
+		$(".dataTables_wrapper").css("min-height","0");
+		$(".dataTables_filter").hide();
+
+	});
+</script>
+
+${commonfooter()}

+ 58 - 53
apps/beeswax/src/beeswax/templates/watch_wait.mako

@@ -13,62 +13,67 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+<%namespace name="layout" file="layout.mako" />
 <%namespace name="util" file="util.mako" />
-${wrappers.head("Beeswax: Waiting for query...", section='query')}
+${commonheader("Beeswax: Waiting for query...", "beeswax", "100px")}
+${layout.menubar(section='query')}
 
 <meta http-equiv="refresh" content="3;${url('beeswax.views.watch_query', query.id)}?${fwd_params}" />
+<div class="container-fluid">
+<h1>Beeswax: Waiting for query... ${util.render_query_context(query_context)}</h1>
+<div class="sidebar withTitle">
+	<div class="well">
+		% if download_urls:
+		<h6>Downloads</h6>
+		<ul>
+			<li><a target="_blank" href="${download_urls["csv"]}" class="bw-download_csv">Download as CSV</a></li>
+			<li><a target="_blank" href="${download_urls["xls"]}" class="bw-download_xls">Download as XLS</a></li>
+			<li><a class="bw-save collapser jframe_ignore" href="${url('beeswax.views.save_results', query.id)}">Save</a></li>
+		</ul>
+		%endif
+
+		<%
+          n_jobs = hadoop_jobs and len(hadoop_jobs) or 0
+          mr_jobs = (n_jobs == 1) and "MR Job" or "MR Jobs"
+        %>
+        
+	 	% if n_jobs > 0:
+			<h6>${mr_jobs} (${n_jobs})</h6>
+	             
+			% for jobid in hadoop_jobs:
+			<a href="${url("jobbrowser.views.single_job", jobid=jobid)}" class="bw-hadoop_job">${jobid.replace("job_", "")}</a><br/>
+			% endfor
+		% else:
+			<h6>${mr_jobs}</h6>
+			<p class="bw-no_jobs">No Hadoop jobs were launched in running this query.</p>
+		% endif 
+	</div>
+</div>
 
-<div class="view resizable" id="watch_wait" data-filters="SplitView">
-  <div class="left_col">
-    ${util.render_query_context(query_context)}
-    <dl class="jframe_padded">
-      % if download_urls:
-      <dt class="hue-dt_cap">Downloads</dt>
-      <dd class="hue-dd_bottom bw-actions">
-        <ul>
-          <li><a target="_blank" href="${download_urls["csv"]}" class="bw-download_csv">Download as CSV</a>
-          <li><a target="_blank" href="${download_urls["xls"]}" class="bw-download_xls">Download as XLS</a>
-        </ul>
-      </dd>
-      % endif
-    <%
-      n_jobs = hadoop_jobs and len(hadoop_jobs) or 0
-      mr_jobs = (n_jobs == 1) and "MR Job" or "MR Jobs"
-    %>
-    <dt class="hue-dt_cap">${mr_jobs}</dt>
-      <dd class="hue-dd_bottom bw-actions">
-        <ul data-single-partial-id="num_jobs">
-          % if n_jobs > 0:
-            <h3 class="jframe-hidden">This query launched ${n_jobs} ${mr_jobs}:</h3>
-            <ul class="beeswax_hadoop_job_links">
-              % for jobid in hadoop_jobs:
-              <li><a href="${url("jobbrowser.views.single_job", jobid=jobid)}" target="JobBrowser" class="bw-hadoop_job">${jobid.replace("job_", "")}</a></li>
-              % endfor
-            </ul>
-          % else:
-            <p class="bw-no_jobs">No Hadoop jobs were launched in running this query.</p>
-          % endif 
-        </ul>
-      </dd>
-    </dl>
-  </div>
-  <div class="right_col jframe_padded">
-    <div data-filters="Tabs">
-      <ul class="toolbar bw-results_tabs tabs jframe-right clearfix">
-        <li><span>Log</span></li>
-        <li><span>Query</span></li>
-      </ul>
 
-      <ul class="tab_sections jframe-clear">
-        <li>
-          <h3 class="jframe-hidden">Server Log</h3>
-          <pre data-single-partial-id="log">${log}</pre>
-        </li>
-        <li>
-          <pre>${query.query}</pre>
-        </li>
-      </ul>
-  </div>
+<div class="content">
+	<ul class="tabs">
+		<li class="active"><a href="#log">Log</a></li>
+		<li><a href="#query">Query</a></li>
+	</ul>
+  
+   	<div class="tab-content">
+		<div class="active tab-pane" id="log">
+			<pre>${log}</pre>
+		</div>
+		<div class="tab-pane" id="query">
+			<pre>${query.query}</pre>
+		</div>
+	</div>
 </div>
-${wrappers.foot()}
+</div>
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".tabs").tabs();
+	});
+</script>
+
+${commonfooter()}

+ 0 - 1183
apps/beeswax/static/css/beeswax.css

@@ -1,1183 +0,0 @@
-/* potential hue styles */
-div.beeswax dt.hue-dt_cap {
-	text-shadow: 1px 1px #666;
-	background: #999;
-	padding: 4px 8px;
-	border-radius: 2px 2px 0px 0px;
-	-moz-border-radius: 2px 2px 0px 0px;
-	-webkit-border-radius: 2px 2px 0px 0px;
-	text-align:right;
-	color: #fff;
-	font-size: 12px;
-	margin: 8px 0px 0px;
-}
-
-div.beeswax dd.hue-dd_bottom {
-	border: 1px solid #999;
-	border-radius: 0px 0px 2px 2px;
-	-moz-border-radius: 0px 0px 2px 2px;
-	-webkit-border-radius: 0px 0px 2px 2px;
-	padding: 8px;
-	font-size: 10px;
-	background: #f3f3f3;
-	overflow: auto;
-}
-/* global beeswax styles*/
-div.beeswax .beeswax_logo {
-	position: absolute;
-	top: 24px;
-	left: 14px;
-	z-index: 1;
-}
-div.beeswax .bw-nav {
-	position: relative;
-	top: 24px;
-	left: 80px;
-}
-div.beeswax a.bw-nav_icon {
-	padding: 6px 8px 6px 25px;
-	height: 25px;
-}
-div.beeswax a.bw-new_table_nav {
-	background: url(/static/art/icons/database_add.png) no-repeat;
-}
-div.beeswax a.bw-tables_nav {
-	background: url(/static/art/icons/table_multiple.png) no-repeat;
-}
-div.beeswax a.bw-my_queries_nav {
-	background: url(/static/art/led-icons/star_2.png) no-repeat;
-}
-div.beeswax a.bw-queries_nav {
-	background: url(/static/art/icons/application_form_edit.png) no-repeat;
-}
-div.beeswax a.bw-query_nav {
-	background: url(/static/art/icons/application_form_magnify.png) no-repeat;
-}
-div.beeswax a.bw-new_report_gen_nav {
-	background: url(/static/art/icons/layout_add.png) no-repeat;
-}
-div.beeswax a.bw-history_nav {
-	background: url(/static/art/led-icons/clock.png) no-repeat;
-}
-div.beeswax a.bw-config_nav {
-	background: url(/static/art/icons/cog.png) no-repeat;
-}
-div.beeswax a.jframe-refresh.large {
-	height: 25px;
-}
-div.beeswax .bw-nav li {
-	float: left;
-}
-div.beeswax .bw-actions ul {
-	margin-top: -8px;
-}
-div.beeswax .bw-actions ul li a {
-	margin-top: 8px;
-	color: #457396;
-	text-shadow: 1px 1px #d0e6f7;
-	border: 1px solid #6a8fab;
-	background-color: #9acef5;
-	display: block;
-	padding: 4px 4px 4px 25px;
-	border-radius: 5px;
-	-moz-border-radius: 5px;
-	-webkit-border-radius: 5px;
-}
-/* welcome screen */
-
-div.beeswax div.bw-welcome {
-	background: url(../art/icon_huge.png) no-repeat top left;
-	width: 520px;
-	height: 168px;
-	margin: 20px auto;
-	padding-left: 140px;
-}
-div.beeswax div.bw-welcome h2 {
-	font-size: 28px;
-	margin: 0px 0px 5px 17px;
-	position: relative;
-	padding-top: 10px;
-}
-div.beeswax div.bw-welcome p {
-	margin-left: 17px;
-}
-div.beeswax div.bw-welcome a {
-	float: left;
-	display: block;
-	width: 251px;
-	height: 75px;
-	overflow: hidden;
-	text-indent: -255px;
-	margin-top: 10px;
-}
-div.beeswax div.bw-welcome a.bw-import-button {
-	margin-left: 5px;
-	background: url(../art/import_data.png) no-repeat;
-}
-div.beeswax div.bw-welcome a.bw-load-sample-button {
-	background: url(../art/load_samples.png) no-repeat;
-}
-
-/* breadcrumb */
-div.beeswax ul[data-filters*=Breadcrumb] {
-	position: absolute;
-	top: 57px;
-	left: 80px;
-	margin: 0 auto;
-	z-index: 0;
-}
-div.beeswax ul[data-filters*=Breadcrumb] li {
-	float: left;
-	height: 23px;
-	background: url(../art/breadcrumb.png) top right;
-	position: relative;
-	margin-left: -16px;
-	padding-left: 12px;
-}
-div.beeswax ul[data-filters*=Breadcrumb] li.tabSelected {
-	background: url(../art/breadcrumb.png) right -23px;
-}
-div.beeswax ul[data-filters*=Breadcrumb] li.hue-bc-error {
-	background: url(../art/breadcrumb.png) right 23px;
-}
-div.beeswax ul[data-filters*=Breadcrumb] li:first-child {
-	margin-left: 0px;
-	border-radius: 4px;
-	-moz-border-radius: 4px;
-	-webkit-border-radius: 4px;
-}
-div.beeswax ul[data-filters*=Breadcrumb] li a {
-	line-height: 23px;
-	color: #000;
-	padding: 0px 16px 0px 8px;
-	text-shadow: 0px 1px #ccc;
-}
-div.beeswax ul[data-filters*=Breadcrumb] li a:hover {
-	text-decoration: none;
-}
-
-/* breadcrumb form*/
-div.beeswax div.hue-bc-section dt {
-	font-size: 18px;
-	font-weight: bold;
-}
-div.beeswax div.hue-bc-section {
-	background: url(../art/icon_huge.png) no-repeat;
-	min-height: 165px;
-	padding-left: 170px;
-	padding-top: 10px;
-	margin-bottom:40px;
-}
-div.beeswax div.hue-bc-section dl dt {
-	font-size: 16px;
-	margin-top: 4px;
-}
-div.beeswax div.hue-bc-section input {
-	font-size: 16px;
-	width: 250px;
-}
-div.beeswax div.hue-bc-section label.overTxtLabel {
-	font-size: 12px;
-	margin-top: 6px;
-}
-div.beeswax .hue-select-with-other input {
-	display: none;
-}
-div.beeswax .hue-select-with-other select {
-	font-size: 16px;
-	width: 250px;
-}
-
-/* multi-part form */
-div.beeswax a.hue-multipart-next, div.beeswax .bw-add_column button, div.beeswax input.bw-create_table_submit {
-	font-size: 16px;
-	font-weight: bold;
-	color: #457396;
-	text-shadow: 1px 1px #d0e6f7;
-	border: 2px solid #6a8fab;
-	background: #9acef5;
-	border-radius: 12px;
-	-moz-border-radius: 12px;
-	-webkit-border-radius: 12px;
-	padding: 2px 8px;
-	position: absolute;
-	right: 15px;
-	margin-top: 8px;
-}
-a.hue-multipart-next:hover, div.beeswax .bw-add_column button:hover, div.beeswax input.bw-create_table_submit:hover {
-	text-decoration: none;
-	color: #003f6f;
-	text-shadow: 1px 1px #d0e6f7;
-	border: 2px solid #003f6f;
-	background: #75bcf1;
-}
-/* create table form */
-div.beeswax dl.bw-table-setup .hue-help_link, div.beeswax div.bw-choose-file .hue-help_link {
-	position: relative;
-	top: -4px;
-	padding-left: 1px;
-}
-div.beeswax dl.bw-table-setup, div.beeswax div.bw-choose-file, div.beeswax div.bw-choose-delimiter {
-	width: 600px;
-	margin: 10px auto;
-}
-div.beeswax div.bw-define-columns {
-	width: 900px;
-	margin: 10px auto;
-}
-div.beeswax .bw-format input {
-	position: absolute;
-	top: -10000px;
-}
-div.beeswax .bw-format {
-	margin-top: 10px;
-}
-div.beeswax .bw-format dt label {
-	clear: both;
-	float: left;
-	width: 90px;
-	margin-right: 10px;
-	cursor: pointer;
-	position: relative;
-	z-index: 1;
-}
-
-div.beeswax .bw-format dd {
-	margin: 13px 0;
-}
-div.beeswax .bw-format .validation-advice {
-	position:absolute;
-	text-align:left;
-	text-shadow:none;
-	top:71px;
-	left: 0px;
-	width:400px;
-}
-div.beeswax ul.bw-config-data dl dt {
-	margin-top: 10px;
-}
-div.beeswax .bw-delim-options input {
-	margin: 5px 0;
-}
-div.beeswax .bw-file_formats input, div.beeswax .hue-bc-section input[type=checkbox] {
-	position: absolute;
-	top: -10000px;
-}
-div.beeswax .bw-file_formats ul {
-	margin: 10px 0 0;
-}
-div.beeswax .bw-file_formats li {
-	margin: 4px 0;
-	width: 200px;
-}
-div.beeswax .bw-file_formats label, div.beeswax .bw-format dt label, div.beeswax .bw-default_location label, div.beeswax .bw-partition_key label, div.beeswax .bw-import_data label, div.beeswax .bw-confirm_delim label, div.beeswax .bw-show_hive label {
-	user-select: none;
-	-moz-user-select: none;
-	-webkit-user-select: none;
-	border-radius: 5px;
-	-moz-border-radius: 5px;
-	-webkit-border-radius: 5px;
-	background: #9ACEF5 url(../art/checkback.png) 6px -29px no-repeat;
-	border: 1px solid #457396;
-	clear: both;
-	color: #457396;
-	display: block;
-	font-size: 16px;
-	font-weight: bold;
-	padding: 0 8px 0 24px;
-	text-shadow: 1px 1px #D0E6F7;
-	margin-right: 10px;
-	line-height: 29px;
-	cursor: pointer;
-	position: relative;
-	z-index: 1;
-}
-div.beeswax div.bw-confirm_delim label {
-	background: #9ACEF5;
-	padding:5px;
-	clear: none;
-}
-div.beeswax p.delimiter_confirmation {
-	background: lightYellow;
-	-moz-border-radius: 5px;
-	padding: 5px;
-	border: solid 1px black;
-	margin: 5px 0px;
-	font-weight: normal;
-}
-div.beeswax div.delimiter_preview_holder {
-	max-width: 600px;
-	height: auto;
-	float: left;
-	clear: both;
-	margin-top: 20px;
-	overflow-x: auto;
-	border: gray solid 1px;
-}
-div.beeswax table.delimiter_preview thead tr th {
-	background-color: white;
-	color: black;
-	font-weight: bold;
-	border: 2px solid black;
-	padding: 2px;
-}
-div.beeswax table.delimiter_preview tbody td {
-	border: 2px solid black;
-	padding: 2px;
-	background-color: white;
-	color: black;
-	font-weight: normal;
-} 
-div.beeswax .bw-select_delim dt {
-	padding: 5px 0px;
-}
-div.beeswax .bw-select_delim a.hue-help_link {
-	margin-bottom: 4px;
-}
-div.beeswax .bw-default_location label, div.beeswax .bw-import_data label, div.beeswax .bw-confirm_delim label, div.beeswax .bw-show_hive label {
-	float: left;
-}
-div.beeswax .bw-default_location, div.beeswax .bw-external_loc, div.beeswax .bw-import_data {
-	margin: 15px 0;
-}
-div.beeswax .bw-default_location a {
-	margin-top: 10px;
-}
-div.beeswax .bw-import_data a {
-	margin-top: 12px;
-}
-div.beeswax .bw-show_hive a {
-	margin-top: 8px;
-}
-div.beeswax .bw-file_formats label.hue-bw-selected, div.beeswax .bw-format dt.hue-bw-selected label, div.beeswax .bw-default_location .hue-bw-selected, div.beeswax .bw-partition_key label.hue-bw-selected,	div.beeswax .bw-show_hive label.hue-bw-selected, div.beeswax .bw-import_data label.hue-bw-selected {
-	color: #003f6f;
-	text-shadow: 1px 1px #d0e6f7;
-	border: 1px solid #003f6f;
-	background: #75bcf1 url(../art/checkback.png) 6px 8px no-repeat;
-}
-div.beeswax .bw-partition_key label.hue-bw-selected {
-	background: #75bcf1 url(../art/checkback.png) 6px 3px no-repeat;;
-}
-div.beeswax .bw-file_formats dt {
-	visibility: hidden;
-}
-div.beeswax .bw-external_loc {
-	clear: both;
-}
-
-/* define columns table styling */
-div.beeswax div.bw-define-columns td {
-	padding: 5px 5px 5px 10px;
-	border-right: 5px solid white;
-	margin-right: 2px;
-}
-
-div.beeswax table.data_table td {
-	white-space: nowrap;
-}
-
-div.beeswax div.bw-define-columns table tr:first-child, div.beeswax div.bw-define-columns table tr:first-child + tr {
-	background: white;
-}
-div.beeswax div.bw-define-columns table tr:first-child + tr {
-	margin-bottom: 10px;
-}
-div.beeswax div.bw-define-columns table tr:first-child td, div.beeswax div.bw-define-columns table tr:first-child + tr td {
-	border: solid black 1px;
-}
-div.beeswax div.bw-define-columns table tr:first-child + tr + tr {
-	background: white;
-	border: 1px solid white;
-}
-div.beeswax div.bw-define-columns td:last-child {
-	border: none;
-	margin: none;
-}
-div.beeswax div.bw-define-columns table.data_table dt label {
-	font-size: 12px;
-}
-div.beeswax div.bw-define-columns table.row_headers td.input_row_header {
-	padding-bottom: 15px;
-	padding-top: 16px;
-}
-
-
-div.beeswax div.bw-define-columns .row_headers {
-	font-weight: bold;
-	float: left;
-	width: 65px;
-	margin-right: 10px;
-}
-
-div.beeswax div.bw-define-columns input, div.beeswax div.bw-define-columns select {
-	background-color: #9ACEF5;
-	border: gray inset 1px;
-	width: 90px;
-}
-
-div.beeswax div.bw-define-columns table {
-	background: lightGray;
-	-moz-border-radius: 5px;
-	-webkit-border-radius: 5px;
-}
-
-div.beeswax div.table_holder {
-	width: 600px;
-	overflow-x: auto;
-	float: left;
-	margin-bottom: 10px;
-}
-div.beeswax div.bw-show_hive {
-	clear: both;
-}
-/* create table choice */
-div.beeswax ul.creation_choices {
-	margin: 20px auto;
-	width: 300px;
-	padding-left: 250px;
-}
-div.beeswax ul.creation_choices a {
-	float: left;
-	background: #9ACEF5;
-	color: black;
-	margin:10px;
-	padding: 10px;
-	-webkit-border-radius: 10px;
-	-moz-border-radius: 10px;
-	font-size: 16px;
-	text-shadow: 1px 1px #d0e6f7;
-	border: 2px solid black;
-	display: block;
-}
-div.beeswax ul.creation_choices a:hover {
-	text-decoration: none;
-	background: #51AFF5;
-}
-div.beeswax div.bw-create_table_choice {
-	width: 600px;
-	height: 220px;
-	margin: 0 auto;
-	background: url(../art/icon_huge.png) no-repeat 15% 100%;
-	position: relative;
-}
-div.beeswax h1 {
-	padding-top: 25px;
-}
-
-/* columns */
-/* headers */
-div.beeswax .bw-columns {
-	width: 430px;
-}
-div.beeswax .bw-columns p {
-	margin: 10px 0;
-}
-div.beeswax .bw-columns .bw-column_header input.bw-column_name {
-	border: 0px;
-	color: #457396;
-	padding: 4px 25px 4px 4px;
-	width: 360px;
-	cursor: pointer;
-	background: #9ACEF5;
-	border-radius: 5px;
-	-moz-border-radius: 5px;
-	-webkit-border-radius: 5px;
-}
-div.beeswax .bw-columns .bw-column_header input.bw-focused, div.beeswax .bw-columns .bw-filled input.bw-column_name, div.beeswax .bw-columns .bw-column_header input.bw-column_name:hover {
-	color: #003f6f;
-	background: #75bcf1;
-	font-weight: bold;
-}
-div.beeswax .bw-columns .bw-column_header label.overTxtLabel {
-	color: #457396;
-	margin-top: 0;
-}
-div.beeswax .bw-columns .bw-inactive a.hue-help_link {
-	display: none;
-}
-/* body */
-div.beeswax div.hue-bc-section .bw-column dt, div.beeswax div.hue-bc-section .bw-column input, div.beeswax div.hue-bc-section .bw-column label {
-	font-size: 12px;
-}
-div.beeswax div.hue-bc-section .bw-column .hue-help_link {
-	top: -2px;
-}
-div.beeswax .bw-array_type {
-	visibility: hidden;
-}
-div.beeswax .bw-col_type, div.beeswax .bw-array_type, div.beeswax .bw-map_key_type, div.beeswax .bw-map_value_type {
-	width: 172px;
-	margin-bottom: 12px;
-}
-div.beeswax .bw-map_data {
-	clear: both;
-	display: none;
-}
-div.beeswax .bw-column dl {
-	width: 350px;
-	margin: 0 auto;
-}
-div.beeswax .bw-column dl dd select {
-	width: 150px;
-}
-div.beeswax .bw-column .validation-advice {
-	background-color: #999;
-	background-position: 4px 50%;
-	margin-left: 4px;
-	padding: 5px 20px;
-	width: 337px;
-}
-div.beeswax .bw-inactive .validation-advice {
-	border-radius: 0 0 2px 2px;
-	-moz-border-radius:0 0 2px 2px;
-	-webkit-border-radius: 0 0 2px 2px;
-}
-div.beeswax .bw-column dt {
-	clear: both;
-	margin: 4px 0px;
-}
-div.beeswax dd.bw-column {
-	border-radius: 0 0 2px 2px;
-	-moz-border-radius:0 0 2px 2px;
-	-webkit-border-radius: 0 0 2px 2px;
-	background: #999;
-	margin-left:4px;
-	padding:0px 8px;
-	top:-5px;
-	width:361px;
-}
-div.beeswax .bw-partition_key label {
-	background: #9ACEF5 url(../art/checkback.png) 6px -34px no-repeat;
-	height:20px;
-	line-height:19px;
-	width:150px;
-	margin: 8px 0 !important;
-}
-div.beeswax .bw-partition_key a.hue-help_link {
-	left: 190px;
-	margin-top: 4px;
-	position: absolute;
-}
-div.beeswax .bw-add_column label {
-	display: none;
-}
-div.beeswax .bw-add_column button {
-	outline: none !important;
-	outline-style:none !important;
-	outline-width:0 !important;
-	padding: 0;
-	display: block;
-	left: 257px;
-	margin: 10px 0;
-	position: relative;
-	text-align: center;
-	width: 132px;
-}
-div.beeswax .bw-add_column button:hover {
-	text-decoration: none;
-}
-
-div.beeswax input.bw-create_table_submit {
-	position: relative;
-	left: 75px;
-}
-div.bw-remove_column {
-	position: absolute;
-	top: 5px;
-	width: 12px;
-	height: 12px;
-	left: 371px;
-}
-div.beeswax .bw-remove_column button {
-	border: none;
-	background: url("/static/art/close.png") no-repeat 0 -13px;
-	display: block;
-	width: 12px;
-	height: 12px;
-	overflow: hidden;
-	text-indent: -1000px;
-	cursor: pointer;
-}
-div.beeswax .bw-remove_column button:hover {
-		background: url(/static/art/close.png) no-repeat 0 0;
-}
-
-/* tables list */
-div.beeswax td.bw-tables_table {
-	background-image: url(/static/art/icons/table.png) !important;
-	background-repeat: no-repeat !important;
-	background-position: 8px 50% !important;
-	padding-left: 30px !important;
-}
-div.beeswax .show_tables td {
-	height: 25px;
-}
-div.beeswax .show_tables td a {
-	font-size: 14px;
-	display: block;
-}
-div.beeswax .show_tables td a:hover {
-	text-decoration: none;
-}
-div.beeswax td.bw-tables_browse {
-	background-image: url(/static/art/icons/application_go.png) !important;
-	background-repeat: no-repeat !important;
-	background-position: 8px 50% !important;
-	padding-left: 30px !important;
-	width: 100px;
-}
-div.beeswax .hue-help_links_small a.hue-help_link {
-/*	float: right;
-	font-size: 9px;
-	width: 10px;
-	height: 11px;
-	line-height: 11px;
-	top: 3px;
-	color: #457396
-*/}
-div.bw-show_tables_subnav {
-	left: 80px;
-	top: 60px;
-}
-div.beeswax a.bw-install_samples, div.beeswax a.bw-new_table {
-	background: url(/static/art/icons/bullet_add.png) no-repeat;
-	padding: 4px 8px 4px 20px;
-	height: 18px;
-}
-
-/* table page */
-div.beeswax .bw-col_table_wrapper, div.beeswax .bw-table_sample {
-}
-div.beeswax .describe_table .tabs {
-	margin: 10px 10px 0px 0px;
-}
-div.beeswax .bw-location_link a:hover {
-	text-decoration: none;
-}
-div.beeswax .bw-actions ul li a.bw-location_link {
-	background: #9acef5 url(/static/art/icons/folder.png) no-repeat 4px 1px;
-	display: block;
-	padding-left: 22px;
-}
-div.beeswax .bw-actions ul li a.bw-load_data {
-	background: #9acef5 url(/static/art/icons/table_row_insert.png) no-repeat 4px 50%;
-}
-div.beeswax .bw-actions ul li a.bw-browse_data {
-	background: #9acef5 url(/static/art/icons/application_view_detail.png) no-repeat 4px 50%;
-}
-div.beeswax .bw-actions ul li a.bw-drop_table {
-	background: #9acef5 url(/static/art/icons/table_delete.png) no-repeat 4px 50%;
-}
-div.beeswax .bw-actions ul li a.bw-hadoop_job {
-	background: #9acef5 url(/static/art/hadoop_job_16x16.gif) no-repeat 4px 50%;
-}
-div.beeswax .bw-actions ul li a:hover {
-	text-decoration: none;
-	color: #003f6f;
-	text-shadow: 1px 1px #d0e6f7;
-	border: 1px solid #003f6f;
-	background-color: #75bcf1;
-}
-
-div.beeswax a.hue-choose_file {
-	margin-top: 5px;
-	padding: 6px 10px 6px 25px;
-	height: 20px;
-	background: url(/static/art/icons/folder.png);
-	border: none !important;
-}
-
-div.beeswax input.bw-loadPath {
-	width: 90%;
-}
-
-div.beeswax .bw-dataNote {
-	background-color: lightYellow;
-	border: 1px solid lightGray;
-	-moz-border-radius: 5px;
-	-webkit-border-radius: 5px;
-	padding: 5px;
-	margin: 4px 0;
-}
-
-div.beeswax .bw-overwriteLabel {
-	padding: 3px 0px 0px 4px;
-	margin: 4px 0;
-}
-
-div.beeswax .bw-overwriteCheckbox {
-	margin-left: 3px;
-	margin-top: 2px;
-}
-
-div.beeswax .bw-pathLabel {
-	padding: 2px;
-}
-
-div.beeswax .bw-loadSubmit {
-	margin-top: 8px;
-	padding: 4px 8px;
-	height: 20px;
-}
-
-/* results page */
-div.beeswax .bw-result_warning {
-	font-weight: bold;
-	padding: 8px;
-	color: #900;
-	background: #fdd !important;
-}
-div.beeswax .bw-view_result {
-	padding: 5px 4px 3px 22px;
-	height: 20px;
-	background: url(/static/art/icons/magnifier.png);
-	margin: 2px 0;
-}
-div.beeswax .tabs li {
-	margin: 0px 2px;
-}
-div.beeswax .watch_results .bw-result_nav {
-	position: absolute;
-	top: 69px;
-	left: 498px;
-	width: 100px;
-}
-
-div.beeswax .watch_results .bw-result_nav a {
-	float: right;
-	text-indent: -500px;
-	overflow: hidden;
-	width: 16px;
-	height: 16px;
-	padding: 3px;
-	display: block;
-	padding: 0px;
-}
-div.beeswax .watch_results .bw-result_nav .bw-firstBlock {
-	background: transparent url(/static/art/icons/control_start.png) no-repeat scroll;
-}
-div.beeswax .watch_results .bw-result_nav .bw-nextBlock {
-	background: transparent url(/static/art/icons/control_play.png) no-repeat scroll;
-}
-div.beeswax .left_col h2 {
-	font-size: 10px;
-	padding: 8px;
-	color: #457396;
-	text-shadow: 1px 1px #d0e6f7;
-	border-bottom: 2px solid #6a8fab;
-	background: #9acef5;
-}
-div.beeswax .left_col h2 a.bw-query_link {
-	display: block;
-	padding-right: 22px;
-	line-height: 18px;
-	background: url(/static/art/icons/pencil.png) no-repeat right 50%;
-}
-div.beeswax .left_col h2 a.bw-query_link:hover {
-	text-decoration: none;
-	color: #003f6f;
-}
-div.beeswax .bw-no_jobs {
-	color: #666;
-	padding-top: 8px;
-}
-div.beeswax .bw-actions ul li a.bw-download_csv {
-	background: #9acef5 url(/static/art/led-icons/doc_excel_csv.png) no-repeat 4px 50%;
-}
-div.beeswax .bw-actions ul li a.bw-download_xls {
-	background: #9acef5 url(/static/art/led-icons/doc_excel_table.png) no-repeat 4px 50%;
-}
-div.beeswax .jframe-window-toolbar .tabs {
-	right: 7px;
-	position: absolute;
-	top: 69px;
-	margin: 0;
-}
-div.beeswax .bw-save_query_results input[type=radio] {
-	float: left;
-	clear: both;
-}
-div.beeswax .watch_results .bw-save_query_results [data-filters*=Accordion] .target {
-	clear: both;
-}
-div.beeswax .watch_results .bw-save_query_results {
-	padding: 5px;
-}
-div.beeswax .watch_results .bw-save_query_results div {
-	padding: 5px 0px;
-}
-div.beeswax .watch_results .bw-save_query_results label {
-	padding-left: 5px;
-}
-div.beeswax .watch_results .bw-save_query_results label.overTxtLabel {
-	padding: 0px;
-}
-div.beeswax .watch_results .bw-save_query_results input[type=text]{
-	margin-left: 17px;
-}
-div.beeswax .watch_results .bw-save_query_results a[data-filters*=ArtButton] {
-	margin-left: 17px;
-}
-div.beeswax .watch_results .bw-save_query_results div[data-filters*=ArtButton] {
-	margin-top: 5px;
-}
-div.beeswax .watch_results .bw-save_query_results a.hue-choose_file {
-	background: url(/static/art/icons/folder.png);
-}
-div.beeswax .bw-save {
-	background: #9acef5 url(/static/art/icons/525_floppy.gif) no-repeat 4px 50%;
-}
-/* query page */
-div.beeswax .bw-query_error {
-	width: 400px;
-	min-height: 100px;
-}
-div.beeswax .bw-results_log {
-	background: #fff;
-}
-div.beeswax .bw-query-field {
-	width: 100%;
-	margin: 0px auto;
-	border: none;
-	font-family: monaco, courier;
-	font-size: 12px;
-	color: #fff;
-	background: #333;
-	padding: 0;
-	outline:none
-}
-
-div.beeswax .bw-query dd.bw-query_bottom {
-	background: #333;
-	border: 1px solid #333;
-	padding: 0px 0px 0px 10px;
-}
-div.beeswax .bw-query div.validation-advice {
-	background-color: lightYellow;
-	background-position: 8px 50%;
-	bottom: 10px;
-	padding: 8px 8px 8px 26px;
-	position: absolute;
-	width: 90%;
-	border-radius: 8px;
-	-moz-border-radius: 8px;
-	-webkit-border-radius: 8px;
-}
-div.beeswax .bw-query .jframe-error {
-	background-color: lightYellow !important;
-}
-div.beeswax .bw-error_tab_msg {
-	padding-left: 22px;
-}
-div.beeswax .bw-query_save_buttons input, div.beeswax .bw-query_save_buttons a {
-	padding: 6px 7px 6px 25px;
-	height: 23px;
-}
-div.beeswax .query_edit_actions input.bw-query_save, div.beeswax .query_edit_actions input.bw-query_save_as {
-	padding: 6px 11px 6px 29px;
-	height: 23px;
-	background: url(/static/art/icons/525_floppy.gif);
-}
-div.beeswax .bw-query_save_buttons input.bw-query_execute {
-	padding: 6px 27px 6px 7px;
-	background: url(/static/art/led-icons/arrow_right.png);
-}
-div.beeswax .bw-query_save_buttons input.bw-query_explain {
-	padding: 6px 7px 6px 27px;
-	background: url(/static/art/icons/explain.gif);
-}
-div.beeswax .bw-query_save_buttons a.bw-query_new {
-	padding: 6px 7px 6px 27px;
-	background: url(/static/art/led-icons/add.png);
-}
-div.beeswax .query_edit_actions {
-	float: right;
-}
-div.beeswax .query_edit_actions li {
-	margin-left: 10px;
-}
-div.beeswax .bw-query_header label {
-	line-height: 20px;
-	float: left;
-	font-size: 14px;
-}
-div.beeswax .bw-query_header a.hue-help_link {
-	margin-left: 4px;
-}
-div.beeswax .bw-query_header {
-	padding: 4px 8px;
-	color: #003f6f;
-	text-shadow: 1px 1px #d0e6f7;
-	border-bottom: 2px solid #6a8fab;
-	background: #9acef5;
-	font-size: 12px;
-}
-div.beeswax .bw-query_save_buttons div {
-	float: left;
-}
-div.beeswax .bw-query_save_form {
-	display: none;
-}
-div.beeswax .bw-query_save_form * {
-	text-align: left;
-}
-div.beeswax .bw-query_save_form dt {
-	font-weight: bold;
-	margin-bottom: 4px;
-}
-div.beeswax .bw-query_save_form dd {
-	margin-bottom: 4px;
-}
-div.beeswax .bw-query_save_form input {
-	width: 240px;
-}
-div.beeswax .bw-query_settings {
-	min-width: 180px;
-}
-div.beeswax .bw-query_settings input, div.beeswax .bw-query_settings select {
-	width: 90%;
-	width: -moz-available;
-}
-div.beeswax .bw-query_settings a.hue-choose_file {
-	position: relative;
-	top: -1px;
-}
-div.beeswax .bw-query_settings .errorlist {
-	border: #999 solid;
-	border-width: 0 1px 1px;
-	padding: 4px;
-	background: lightyellow;
-}
-div.beeswax .bw-query_settings hr {
-	clear: both;
-	color: #333;
-	background-color: #333;
-	height: 1px;
-	border: none;
-	margin: 6px 0;
-}
-div.beeswax .bw-query_settings dt label {
-	background: #999;
-	border-radius: 4px 4px 0px 0px;
-	-moz-border-radius: 4px 4px 0px 0px;
-	-webkit-border-radius: 4px 4px 0px 0px;
-	padding: 2px 4px;
-}
-div.beeswax .bw-query_settings dd dl {
-	margin-top: -10px;
-	position: relative;
-}
-div.beeswax .bw-query_settings dd dt {
-	margin-top: 10px;
-}
-div.beeswax .bw-query_settings .bw-query_settings_delete {
-	position: absolute;
-	right: 0px;
-	top: -1px;
-	width: 12px;
-	height: 12px;
-}
-div.beeswax .bw-query_settings .bw-query_settings_delete button {
-	border: none;
-	text-indent: -10000px;
-	background: url(/static/art/close.png) no-repeat 0 0;
-	width: 12px;
-	height: 12px;
-	cursor: pointer;
-}
-div.beeswax .bw-query_settings .bw-query_settings_add {
-	height: 16px;
-}
-div.beeswax .bw-query_settings .bw-query_settings_add button {
-	border: none;
-	text-indent: -10000px;
-	background: url(/static/art/icons/add.png) no-repeat 0 0;
-	width: 16px;
-	height: 16px;
-	cursor: pointer;
-	position: absolute;
-	top: 4px;
-	right: -1px;
-}
-
-div.beeswax .hue-bw_parameters {
-	margin-top: 0px !important;
-}
-div.beeswax .hue-bw_parameters input {
-	width: auto;
-	margin-right: 10px;
-}
-/* saved queries */
-div.beeswax .bw-query_actions {
-	width: 90px;
-}
-div.beeswax .bw-query_actions a {
-	display: block;
-	float: left;
-	width: 16px;
-	height: 16px;
-	overflow: hidden;
-	text-indent: -300px;
-	margin-right: 5px;
-}
-div.beeswax .bw-query_edit {
-	background: url(/static/art/icons/page_edit.png) no-repeat;
-}
-div.beeswax .bw-query_delete {
-	background: url(/static/art/icons/page_delete.png) no-repeat;
-}
-div.beeswax .bw-query_history {
-	background: url(/static/art/icons/time.png) no-repeat;
-}
-div.beeswax .bw-query_clone {
-	background: url(/static/art/icons/page_copy.png) no-repeat;
-}
-div.beeswax div.bw-designs_toolbar {
-	position: absolute;
-	top: 60px;
-	left: 80px;
-}
-
-
-div.beeswax .bw-navigation a {
-	float: left;
-	text-indent: -500px;
-	overflow: hidden;
-	width: 16px;
-	height: 16px;
-	padding: 3px;
-	display: block;
-	padding: 0px;
-}
-div.beeswax .bw-navigation p {
-	color: #333;
-}
-div.beeswax .bw-navigation .bw-firstBlock {
-	background: transparent url(/static/art/icons/control_start.png) no-repeat scroll;
-}
-div.beeswax .bw-navigation .bw-prevBlock {
-	background: transparent url(/static/art/icons/control_previous.png) no-repeat scroll;
-}
-div.beeswax .bw-navigation .bw-nextBlock {
-	background: transparent url(/static/art/icons/control_play.png) no-repeat scroll;
-}
-div.beeswax .bw-navigation .bw-lastBlock {
-	background: transparent url(/static/art/icons/control_end.png) no-repeat scroll;
-}
-div.beeswax .bw-navigation .bw-nav_links {
-	position: absolute;
-	left: 381px;
-	top: 0px;
-	width: 220px;
-}
-div.beeswax .bw-navigation .bw-nav_links p {
-	float: left;
-	padding: 0 10px;
-}
-
-
-/* context menu */
-
-div.beeswax .context-menu {
-	border-radius: 2px;
-	-moz-border-radius: 2px;
-	-webkit-border-radius: 2px;
-	background: #fff;
-	border: solid #777;
-	border-width: 1px;
-	position: absolute;
-	z-index: 1;
-	display: none;
-	overflow: visible;
-}
-div.beeswax .context-menu * {
-	white-space: nowrap;
-} 
-div.beeswax .context-menu li {
-	border-bottom: 1px solid #ccc;
-	padding: 3px;
-}
-div.beeswax .context-menu li a {
-	padding-left: 20px;
-	display: block;
-	height: 18px;
-}
-div.beeswax table[data-filters*=HtmlTable] tr.table-tr-selected td .context-menu li a {
-	color: #000;
-	text-decoration: none;
-}
-div.beeswax .context-menu li:hover, div.beeswax .context-menu li:hover a {
-	text-decoration: none;
-	background-color: #3875D7 !important;
-	color: #fff !important;
-}
-div.beeswax .context-menu li:last-child {
-	border: none;
-}
-div.beeswax .bw-options {
-	background: url(/static/art/led-icons/ui_combo_box.png) no-repeat;
-	display: block;
-	width: 16px;
-	height: 16px;
-	text-indent: -500px;
-	overflow: hidden;
-	float: right;
-}
-
-/*
-	my queries
-*/
-div.beeswax .jframe-window-toolbar ul.bw-my_queries_tabs {
-	left: 77px;
-}
-div.beeswax .bw-view_more {
-	margin: 8px auto 0;
-	color: #457396;
-	text-shadow: 1px 1px #d0e6f7;
-	border: 1px solid #6a8fab;
-	background-color: #9acef5;
-	display: block;
-	padding: 4px 4px 4px 25px;
-	border-radius: 5px;
-	-moz-border-radius: 5px;
-	-webkit-border-radius: 5px;
-	text-align: center;
-	width: 200px;
-	font-size: 12px;
-}
-div.beeswax .bw-view_more:hover {
-	text-decoration: none;
-	color: #003f6f;
-	text-shadow: 1px 1px #d0e6f7;
-	border: 1px solid #003f6f;
-	background: #75bcf1;
-}
-div.beeswax .bw-query_settings_toggle {
-	padding: 8px 8px 8px 25px;
-	height: 25px;
-	background: url(/static/art/icons/cog.png) no-repeat;
-}
-
-/* history page */
-div.beeswax .list_history .bw-showing_msg {
-	display: none;
-}
-
-div.beeswax .list_history .bw-show_group {
-	position: absolute;
-	top: 60px;
-	left: 80px;
-}
-
-div.beeswax .list_history .bw-show_group a {
-	background:url("/static/art/icons/bullet_add.png") no-repeat scroll 0 0 transparent;
-	height:18px;
-	padding:4px 8px;
-}
-
-/* header */
-div.beeswax div.bw-input-filter {
-	position: absolute;
-	right: 16px;
-	top: 57px;
-}

+ 0 - 90
apps/filebrowser/src/filebrowser/plugin/toolbar.py

@@ -1,90 +0,0 @@
-#!/usr/bin/env python
-# Licensed to Cloudera, Inc. under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  Cloudera, Inc. licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""
-Interface to providing custom toolbars in the FileBrowser
-"""
-
-import logging
-
-LOG = logging.getLogger(__name__)
-
-class Toolbar(object):
-  """
-  All custom toolbars must derive from this class.
-  """
-  def display(self, context):
-    """
-    display(context) -> toolbar HTML
-
-    Return the HTML to display the toolbar. The HTML must contain one single
-    top-level <div> of class "toolbar".
-
-    ``context`` is a DisplayContext.
-
-    May return an empty string to hide the toolbar.
-    """
-    raise NotImplementedError
-
-  def get_app_name(self):
-    """
-    get_app_name() -> The name of the toolbar provider app.
-    """
-    raise NotImplementedError
-
-  def get_name(self):
-    """
-    get_name() -> The name of the toolbar, which is unique for the app.
-    """
-    raise NotImplementedError
-
-  def __str__(self):
-    return 'FileBrowser toolbar "%s" from %s' % (self.get_name(), self.get_app_name())
-
-
-class DisplayContext(object):
-  """Context object for displaying the Toolbar"""
-  def __init__(self, template, request, data):
-    self.template = template
-    self.request = request
-    self.data = data
-
-
-# Map of (app_name, name) -> toolbar obj
-_toolbars = { }
-
-def register(toolbar):
-  """Register a toolbar. Returns True/False."""
-  global _toolbars
-
-  key = (toolbar.get_app_name(), toolbar.get_name())
-  if _toolbars.has_key(key):
-    LOG.error('Failed to register %s: Already registered' % (toolbar,))
-    return False
-
-  _toolbars[key] = toolbar
-  return True
-
-
-def lookup(app_name, toolbar_name):
-  """lookup(app_name, toolbar_name) -> Toolbar or None"""
-  return _toolbars.get((app_name, toolbar_name))
-
-
-def all():
-  """all() -> [ all toolbars ]"""
-  return _toolbars.values()

+ 1249 - 0
apps/filebrowser/src/filebrowser/static/fileuploader.js

@@ -0,0 +1,1249 @@
+/**
+ * http://github.com/valums/file-uploader
+ * 
+ * Multiple file upload component with progress-bar, drag-and-drop. 
+ * © 2010 Andrew Valums ( andrew(at)valums.com ) 
+ * 
+ * Licensed under GNU GPL 2 or later and GNU LGPL 2 or later, see license.txt.
+ */    
+
+//
+// Helper functions
+//
+
+var qq = qq || {};
+
+/**
+ * Adds all missing properties from second obj to first obj
+ */ 
+qq.extend = function(first, second){
+    for (var prop in second){
+        first[prop] = second[prop];
+    }
+};  
+
+/**
+ * Searches for a given element in the array, returns -1 if it is not present.
+ * @param {Number} [from] The index at which to begin the search
+ */
+qq.indexOf = function(arr, elt, from){
+    if (arr.indexOf) return arr.indexOf(elt, from);
+    
+    from = from || 0;
+    var len = arr.length;    
+    
+    if (from < 0) from += len;  
+
+    for (; from < len; from++){  
+        if (from in arr && arr[from] === elt){  
+            return from;
+        }
+    }  
+    return -1;  
+}; 
+    
+qq.getUniqueId = (function(){
+    var id = 0;
+    return function(){ return id++; };
+})();
+
+//
+// Events
+
+qq.attach = function(element, type, fn){
+    if (element.addEventListener){
+        element.addEventListener(type, fn, false);
+    } else if (element.attachEvent){
+        element.attachEvent('on' + type, fn);
+    }
+};
+qq.detach = function(element, type, fn){
+    if (element.removeEventListener){
+        element.removeEventListener(type, fn, false);
+    } else if (element.attachEvent){
+        element.detachEvent('on' + type, fn);
+    }
+};
+
+qq.preventDefault = function(e){
+    if (e.preventDefault){
+        e.preventDefault();
+    } else{
+        e.returnValue = false;
+    }
+};
+
+//
+// Node manipulations
+
+/**
+ * Insert node a before node b.
+ */
+qq.insertBefore = function(a, b){
+    b.parentNode.insertBefore(a, b);
+};
+qq.remove = function(element){
+    element.parentNode.removeChild(element);
+};
+
+qq.contains = function(parent, descendant){       
+    // compareposition returns false in this case
+    if (parent == descendant) return true;
+    
+    if (parent.contains){
+        return parent.contains(descendant);
+    } else {
+        return !!(descendant.compareDocumentPosition(parent) & 8);
+    }
+};
+
+/**
+ * Creates and returns element from html string
+ * Uses innerHTML to create an element
+ */
+qq.toElement = (function(){
+    var div = document.createElement('div');
+    return function(html){
+        div.innerHTML = html;
+        var element = div.firstChild;
+        div.removeChild(element);
+        return element;
+    };
+})();
+
+//
+// Node properties and attributes
+
+/**
+ * Sets styles for an element.
+ * Fixes opacity in IE6-8.
+ */
+qq.css = function(element, styles){
+    if (styles.opacity != null){
+        if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){
+            styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
+        }
+    }
+    qq.extend(element.style, styles);
+};
+qq.hasClass = function(element, name){
+    var re = new RegExp('(^| )' + name + '( |$)');
+    return re.test(element.className);
+};
+qq.addClass = function(element, name){
+    if (!qq.hasClass(element, name)){
+        element.className += ' ' + name;
+    }
+};
+qq.removeClass = function(element, name){
+    var re = new RegExp('(^| )' + name + '( |$)');
+    element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
+};
+qq.setText = function(element, text){
+    element.innerText = text;
+    element.textContent = text;
+};
+
+//
+// Selecting elements
+
+qq.children = function(element){
+    var children = [],
+    child = element.firstChild;
+
+    while (child){
+        if (child.nodeType == 1){
+            children.push(child);
+        }
+        child = child.nextSibling;
+    }
+
+    return children;
+};
+
+qq.getByClass = function(element, className){
+    if (element.querySelectorAll){
+        return element.querySelectorAll('.' + className);
+    }
+
+    var result = [];
+    var candidates = element.getElementsByTagName("*");
+    var len = candidates.length;
+
+    for (var i = 0; i < len; i++){
+        if (qq.hasClass(candidates[i], className)){
+            result.push(candidates[i]);
+        }
+    }
+    return result;
+};
+
+/**
+ * obj2url() takes a json-object as argument and generates
+ * a querystring. pretty much like jQuery.param()
+ * 
+ * how to use:
+ *
+ *    `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
+ *
+ * will result in:
+ *
+ *    `http://any.url/upload?otherParam=value&a=b&c=d`
+ *
+ * @param  Object JSON-Object
+ * @param  String current querystring-part
+ * @return String encoded querystring
+ */
+qq.obj2url = function(obj, temp, prefixDone){
+    var uristrings = [],
+        prefix = '&',
+        add = function(nextObj, i){
+            var nextTemp = temp 
+                ? (/\[\]$/.test(temp)) // prevent double-encoding
+                   ? temp
+                   : temp+'['+i+']'
+                : i;
+            if ((nextTemp != 'undefined') && (i != 'undefined')) {  
+                uristrings.push(
+                    (typeof nextObj === 'object') 
+                        ? qq.obj2url(nextObj, nextTemp, true)
+                        : (Object.prototype.toString.call(nextObj) === '[object Function]')
+                            ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
+                            : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)                                                          
+                );
+            }
+        }; 
+
+    if (!prefixDone && temp) {
+      prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
+      uristrings.push(temp);
+      uristrings.push(qq.obj2url(obj));
+    } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) {
+        // we wont use a for-in-loop on an array (performance)
+        for (var i = 0, len = obj.length; i < len; ++i){
+            add(obj[i], i);
+        }
+    } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){
+        // for anything else but a scalar, we will use for-in-loop
+        for (var i in obj){
+            add(obj[i], i);
+        }
+    } else {
+        uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
+    }
+
+    return uristrings.join(prefix)
+                     .replace(/^&/, '')
+                     .replace(/%20/g, '+'); 
+};
+
+//
+//
+// Uploader Classes
+//
+//
+
+var qq = qq || {};
+    
+/**
+ * Creates upload button, validates upload, but doesn't create file list or dd. 
+ */
+qq.FileUploaderBasic = function(o){
+    this._options = {
+        // set to true to see the server response
+        debug: false,
+        action: '/server/upload',
+        params: {},
+        button: null,
+        multiple: true,
+        maxConnections: 3,
+        // validation        
+        allowedExtensions: [],               
+        sizeLimit: 0,   
+        minSizeLimit: 0,                             
+        // events
+        // return false to cancel submit
+        onSubmit: function(id, fileName){},
+        onProgress: function(id, fileName, loaded, total){},
+        onComplete: function(id, fileName, responseJSON){},
+        onCancel: function(id, fileName){},
+        // messages                
+        messages: {
+            typeError: "{file} has invalid extension. Only {extensions} are allowed.",
+            sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
+            minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
+            emptyError: "{file} is empty, please select files again without it.",
+            onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."            
+        },
+        showMessage: function(message){
+            alert(message);
+        }               
+    };
+    qq.extend(this._options, o);
+        
+    // number of files being uploaded
+    this._filesInProgress = 0;
+    this._handler = this._createUploadHandler(); 
+    
+    if (this._options.button){ 
+        this._button = this._createUploadButton(this._options.button);
+    }
+                        
+    this._preventLeaveInProgress();         
+};
+   
+qq.FileUploaderBasic.prototype = {
+    setParams: function(params){
+        this._options.params = params;
+    },
+    getInProgress: function(){
+        return this._filesInProgress;         
+    },
+    _createUploadButton: function(element){
+        var self = this;
+        
+        return new qq.UploadButton({
+            element: element,
+            multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(),
+            onChange: function(input){
+                self._onInputChange(input);
+            }        
+        });           
+    },    
+    _createUploadHandler: function(){
+        var self = this,
+            handlerClass;        
+        
+        if(qq.UploadHandlerXhr.isSupported()){           
+            handlerClass = 'UploadHandlerXhr';                        
+        } else {
+            handlerClass = 'UploadHandlerForm';
+        }
+
+        var handler = new qq[handlerClass]({
+            debug: this._options.debug,
+            action: this._options.action,         
+            maxConnections: this._options.maxConnections,   
+            onProgress: function(id, fileName, loaded, total){                
+                self._onProgress(id, fileName, loaded, total);
+                self._options.onProgress(id, fileName, loaded, total);                    
+            },            
+            onComplete: function(id, fileName, result){
+                self._onComplete(id, fileName, result);
+                self._options.onComplete(id, fileName, result);
+            },
+            onCancel: function(id, fileName){
+                self._onCancel(id, fileName);
+                self._options.onCancel(id, fileName);
+            }
+        });
+
+        return handler;
+    },    
+    _preventLeaveInProgress: function(){
+        var self = this;
+        
+        qq.attach(window, 'beforeunload', function(e){
+            if (!self._filesInProgress){return;}
+            
+            var e = e || window.event;
+            // for ie, ff
+            e.returnValue = self._options.messages.onLeave;
+            // for webkit
+            return self._options.messages.onLeave;             
+        });        
+    },    
+    _onSubmit: function(id, fileName){
+        this._filesInProgress++;  
+    },
+    _onProgress: function(id, fileName, loaded, total){        
+    },
+    _onComplete: function(id, fileName, result){
+        this._filesInProgress--;                 
+        if (result.error){
+            this._options.showMessage(result.error);
+        }             
+    },
+    _onCancel: function(id, fileName){
+        this._filesInProgress--;        
+    },
+    _onInputChange: function(input){
+        if (this._handler instanceof qq.UploadHandlerXhr){                
+            this._uploadFileList(input.files);                   
+        } else {             
+            if (this._validateFile(input)){                
+                this._uploadFile(input);                                    
+            }                      
+        }               
+        this._button.reset();   
+    },  
+    _uploadFileList: function(files){
+        for (var i=0; i<files.length; i++){
+            if ( !this._validateFile(files[i])){
+                return;
+            }            
+        }
+        
+        for (var i=0; i<files.length; i++){
+            this._uploadFile(files[i]);        
+        }        
+    },       
+    _uploadFile: function(fileContainer){      
+        var id = this._handler.add(fileContainer);
+        var fileName = this._handler.getName(id);
+        
+        if (this._options.onSubmit(id, fileName) !== false){
+            this._onSubmit(id, fileName);
+            this._handler.upload(id, this._options.params);
+        }
+    },      
+    _validateFile: function(file){
+        var name, size;
+        
+        if (file.value){
+            // it is a file input            
+            // get input value and remove path to normalize
+            name = file.value.replace(/.*(\/|\\)/, "");
+        } else {
+            // fix missing properties in Safari
+            name = file.fileName != null ? file.fileName : file.name;
+            size = file.fileSize != null ? file.fileSize : file.size;
+        }
+                    
+        if (! this._isAllowedExtension(name)){            
+            this._error('typeError', name);
+            return false;
+            
+        } else if (size === 0){            
+            this._error('emptyError', name);
+            return false;
+                                                     
+        } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){            
+            this._error('sizeError', name);
+            return false;
+                        
+        } else if (size && size < this._options.minSizeLimit){
+            this._error('minSizeError', name);
+            return false;            
+        }
+        
+        return true;                
+    },
+    _error: function(code, fileName){
+        var message = this._options.messages[code];        
+        function r(name, replacement){ message = message.replace(name, replacement); }
+        
+        r('{file}', this._formatFileName(fileName));        
+        r('{extensions}', this._options.allowedExtensions.join(', '));
+        r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
+        r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));
+        
+        this._options.showMessage(message);                
+    },
+    _formatFileName: function(name){
+        if (name.length > 33){
+            name = name.slice(0, 19) + '...' + name.slice(-13);    
+        }
+        return name;
+    },
+    _isAllowedExtension: function(fileName){
+        var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : '';
+        var allowed = this._options.allowedExtensions;
+        
+        if (!allowed.length){return true;}        
+        
+        for (var i=0; i<allowed.length; i++){
+            if (allowed[i].toLowerCase() == ext){ return true;}    
+        }
+        
+        return false;
+    },    
+    _formatSize: function(bytes){
+        var i = -1;                                    
+        do {
+            bytes = bytes / 1024;
+            i++;  
+        } while (bytes > 99);
+        
+        return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];          
+    }
+};
+    
+       
+/**
+ * Class that creates upload widget with drag-and-drop and file list
+ * @inherits qq.FileUploaderBasic
+ */
+qq.FileUploader = function(o){
+    // call parent constructor
+    qq.FileUploaderBasic.apply(this, arguments);
+    
+    // additional options    
+    qq.extend(this._options, {
+        element: null,
+        // if set, will be used instead of qq-upload-list in template
+        listElement: null,
+                
+        template: '<div class="qq-uploader">' + 
+                '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
+                '<div class="qq-upload-button">Upload a file</div>' +
+                '<ul class="qq-upload-list"></ul>' + 
+             '</div>',
+
+        // template for one item in file list
+        fileTemplate: '<li>' +
+                '<span class="qq-upload-file"></span>' +
+                '<span class="qq-upload-spinner"></span>' +
+                '<span class="qq-upload-size"></span>' +
+                '<a class="qq-upload-cancel" href="#">Cancel</a>' +
+                '<span class="qq-upload-failed-text">Failed</span>' +
+            '</li>',        
+        
+        classes: {
+            // used to get elements from templates
+            button: 'qq-upload-button',
+            drop: 'qq-upload-drop-area',
+            dropActive: 'qq-upload-drop-area-active',
+            list: 'qq-upload-list',
+                        
+            file: 'qq-upload-file',
+            spinner: 'qq-upload-spinner',
+            size: 'qq-upload-size',
+            cancel: 'qq-upload-cancel',
+
+            // added to list item when upload completes
+            // used in css to hide progress spinner
+            success: 'qq-upload-success',
+            fail: 'qq-upload-fail'
+        }
+    });
+    // overwrite options with user supplied
+
+    this._options.
+    qq.extend(this._options, o);       
+
+    this._element = this._options.element;
+    this._element.innerHTML = this._options.template;        
+    this._listElement = this._options.listElement || this._find(this._element, 'list');
+    
+    this._classes = this._options.classes;
+        
+    this._button = this._createUploadButton(this._find(this._element, 'button'));        
+    
+    this._bindCancelEvent();
+    this._setupDragDrop();
+};
+
+// inherit from Basic Uploader
+qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype);
+
+qq.extend(qq.FileUploader.prototype, {
+    /**
+     * Gets one of the elements listed in this._options.classes
+     **/
+    _find: function(parent, type){                                
+        var element = qq.getByClass(parent, this._options.classes[type])[0];        
+        if (!element){
+            throw new Error('element not found ' + type);
+        }
+        
+        return element;
+    },
+    _setupDragDrop: function(){
+        var self = this,
+            dropArea = this._find(this._element, 'drop');                        
+
+        var dz = new qq.UploadDropZone({
+            element: dropArea,
+            onEnter: function(e){
+                qq.addClass(dropArea, self._classes.dropActive);
+                e.stopPropagation();
+            },
+            onLeave: function(e){
+                e.stopPropagation();
+            },
+            onLeaveNotDescendants: function(e){
+                qq.removeClass(dropArea, self._classes.dropActive);  
+            },
+            onDrop: function(e){
+                dropArea.style.display = 'none';
+                qq.removeClass(dropArea, self._classes.dropActive);
+                self._uploadFileList(e.dataTransfer.files);    
+            }
+        });
+                
+        dropArea.style.display = 'none';
+
+        qq.attach(document, 'dragenter', function(e){     
+            if (!dz._isValidFileDrag(e)) return; 
+            
+            dropArea.style.display = 'block';            
+        });                 
+        qq.attach(document, 'dragleave', function(e){
+            if (!dz._isValidFileDrag(e)) return;            
+            
+            var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
+            // only fire when leaving document out
+            if ( ! relatedTarget || relatedTarget.nodeName == "HTML"){               
+                dropArea.style.display = 'none';                                            
+            }
+        });                
+    },
+    _onSubmit: function(id, fileName){
+        qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
+        this._addToList(id, fileName);  
+    },
+    _onProgress: function(id, fileName, loaded, total){
+        qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments);
+
+        var item = this._getItemByFileId(id);
+        var size = this._find(item, 'size');
+        size.style.display = 'inline';
+        
+        var text; 
+        if (loaded != total){
+            text = Math.round(loaded / total * 100) + '% from ' + this._formatSize(total);
+        } else {                                   
+            text = this._formatSize(total);
+        }          
+        
+        qq.setText(size, text);         
+    },
+    _onComplete: function(id, fileName, result){
+        qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);
+
+        // mark completed
+        var item = this._getItemByFileId(id);                
+        qq.remove(this._find(item, 'cancel'));
+        qq.remove(this._find(item, 'spinner'));
+        
+        if (result.success){
+            qq.addClass(item, this._classes.success);    
+        } else {
+            qq.addClass(item, this._classes.fail);
+        }         
+    },
+    _addToList: function(id, fileName){
+        var item = qq.toElement(this._options.fileTemplate);                
+        item.qqFileId = id;
+
+        var fileElement = this._find(item, 'file');        
+        qq.setText(fileElement, this._formatFileName(fileName));
+        this._find(item, 'size').style.display = 'none';        
+
+        this._listElement.appendChild(item);
+    },
+    _getItemByFileId: function(id){
+        var item = this._listElement.firstChild;        
+        
+        // there can't be txt nodes in dynamically created list
+        // and we can  use nextSibling
+        while (item){            
+            if (item.qqFileId == id) return item;            
+            item = item.nextSibling;
+        }          
+    },
+    /**
+     * delegate click event for cancel link 
+     **/
+    _bindCancelEvent: function(){
+        var self = this,
+            list = this._listElement;            
+        
+        qq.attach(list, 'click', function(e){            
+            e = e || window.event;
+            var target = e.target || e.srcElement;
+            
+            if (qq.hasClass(target, self._classes.cancel)){                
+                qq.preventDefault(e);
+               
+                var item = target.parentNode;
+                self._handler.cancel(item.qqFileId);
+                qq.remove(item);
+            }
+        });
+    }    
+});
+    
+qq.UploadDropZone = function(o){
+    this._options = {
+        element: null,  
+        onEnter: function(e){},
+        onLeave: function(e){},  
+        // is not fired when leaving element by hovering descendants   
+        onLeaveNotDescendants: function(e){},   
+        onDrop: function(e){}                       
+    };
+    qq.extend(this._options, o); 
+    
+    this._element = this._options.element;
+    
+    this._disableDropOutside();
+    this._attachEvents();   
+};
+
+qq.UploadDropZone.prototype = {
+    _disableDropOutside: function(e){
+        // run only once for all instances
+        if (!qq.UploadDropZone.dropOutsideDisabled ){
+
+            qq.attach(document, 'dragover', function(e){
+                if (e.dataTransfer){
+                    e.dataTransfer.dropEffect = 'none';
+                    e.preventDefault(); 
+                }           
+            });
+            
+            qq.UploadDropZone.dropOutsideDisabled = true; 
+        }        
+    },
+    _attachEvents: function(){
+        var self = this;              
+                  
+        qq.attach(self._element, 'dragover', function(e){
+            if (!self._isValidFileDrag(e)) return;
+            
+            var effect = e.dataTransfer.effectAllowed;
+            if (effect == 'move' || effect == 'linkMove'){
+                e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)    
+            } else {                    
+                e.dataTransfer.dropEffect = 'copy'; // for Chrome
+            }
+                                                     
+            e.stopPropagation();
+            e.preventDefault();                                                                    
+        });
+        
+        qq.attach(self._element, 'dragenter', function(e){
+            if (!self._isValidFileDrag(e)) return;
+                        
+            self._options.onEnter(e);
+        });
+        
+        qq.attach(self._element, 'dragleave', function(e){
+            if (!self._isValidFileDrag(e)) return;
+            
+            self._options.onLeave(e);
+            
+            var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);                      
+            // do not fire when moving a mouse over a descendant
+            if (qq.contains(this, relatedTarget)) return;
+                        
+            self._options.onLeaveNotDescendants(e); 
+        });
+                
+        qq.attach(self._element, 'drop', function(e){
+            if (!self._isValidFileDrag(e)) return;
+            
+            e.preventDefault();
+            self._options.onDrop(e);
+        });          
+    },
+    _isValidFileDrag: function(e){
+        var dt = e.dataTransfer,
+            // do not check dt.types.contains in webkit, because it crashes safari 4            
+            isWebkit = navigator.userAgent.indexOf("AppleWebKit") > -1;                        
+
+        // dt.effectAllowed is none in Safari 5
+        // dt.types.contains check is for firefox            
+        return dt && dt.effectAllowed != 'none' && 
+            (dt.files || (!isWebkit && dt.types.contains && dt.types.contains('Files')));
+        
+    }        
+}; 
+
+qq.UploadButton = function(o){
+    this._options = {
+        element: null,  
+        // if set to true adds multiple attribute to file input      
+        multiple: false,
+        // name attribute of file input
+        name: 'file',
+        onChange: function(input){},
+        hoverClass: 'qq-upload-button-hover',
+        focusClass: 'qq-upload-button-focus'                       
+    };
+    
+    qq.extend(this._options, o);
+        
+    this._element = this._options.element;
+    
+    // make button suitable container for input
+    qq.css(this._element, {
+        position: 'relative',
+        overflow: 'hidden',
+        // Make sure browse button is in the right side
+        // in Internet Explorer
+        direction: 'ltr'
+    });   
+    
+    this._input = this._createInput();
+};
+
+qq.UploadButton.prototype = {
+    /* returns file input element */    
+    getInput: function(){
+        return this._input;
+    },
+    /* cleans/recreates the file input */
+    reset: function(){
+        if (this._input.parentNode){
+            qq.remove(this._input);    
+        }                
+        
+        qq.removeClass(this._element, this._options.focusClass);
+        this._input = this._createInput();
+    },    
+    _createInput: function(){                
+        var input = document.createElement("input");
+        
+        if (this._options.multiple){
+            input.setAttribute("multiple", "multiple");
+        }
+                
+        input.setAttribute("type", "file");
+        input.setAttribute("name", this._options.name);
+        
+        qq.css(input, {
+            position: 'absolute',
+            // in Opera only 'browse' button
+            // is clickable and it is located at
+            // the right side of the input
+            right: 0,
+            top: 0,
+            fontFamily: 'Arial',
+            // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118
+            fontSize: '118px',
+            margin: 0,
+            padding: 0,
+            cursor: 'pointer',
+            opacity: 0
+        });
+        
+        this._element.appendChild(input);
+
+        var self = this;
+        qq.attach(input, 'change', function(){
+            self._options.onChange(input);
+        });
+                
+        qq.attach(input, 'mouseover', function(){
+            qq.addClass(self._element, self._options.hoverClass);
+        });
+        qq.attach(input, 'mouseout', function(){
+            qq.removeClass(self._element, self._options.hoverClass);
+        });
+        qq.attach(input, 'focus', function(){
+            qq.addClass(self._element, self._options.focusClass);
+        });
+        qq.attach(input, 'blur', function(){
+            qq.removeClass(self._element, self._options.focusClass);
+        });
+
+        // IE and Opera, unfortunately have 2 tab stops on file input
+        // which is unacceptable in our case, disable keyboard access
+        if (window.attachEvent){
+            // it is IE or Opera
+            input.setAttribute('tabIndex', "-1");
+        }
+
+        return input;            
+    }        
+};
+
+/**
+ * Class for uploading files, uploading itself is handled by child classes
+ */
+qq.UploadHandlerAbstract = function(o){
+    this._options = {
+        debug: false,
+        action: '/upload.php',
+        // maximum number of concurrent uploads        
+        maxConnections: 999,
+        onProgress: function(id, fileName, loaded, total){},
+        onComplete: function(id, fileName, response){},
+        onCancel: function(id, fileName){}
+    };
+    qq.extend(this._options, o);    
+    
+    this._queue = [];
+    // params for files in queue
+    this._params = [];
+};
+qq.UploadHandlerAbstract.prototype = {
+    log: function(str){
+        if (this._options.debug && window.console) console.log('[uploader] ' + str);        
+    },
+    /**
+     * Adds file or file input to the queue
+     * @returns id
+     **/    
+    add: function(file){},
+    /**
+     * Sends the file identified by id and additional query params to the server
+     */
+    upload: function(id, params){
+        var len = this._queue.push(id);
+
+        var copy = {};        
+        qq.extend(copy, params);
+        this._params[id] = copy;        
+                
+        // if too many active uploads, wait...
+        if (len <= this._options.maxConnections){               
+            this._upload(id, this._params[id]);
+        }
+    },
+    /**
+     * Cancels file upload by id
+     */
+    cancel: function(id){
+        this._cancel(id);
+        this._dequeue(id);
+    },
+    /**
+     * Cancells all uploads
+     */
+    cancelAll: function(){
+        for (var i=0; i<this._queue.length; i++){
+            this._cancel(this._queue[i]);
+        }
+        this._queue = [];
+    },
+    /**
+     * Returns name of the file identified by id
+     */
+    getName: function(id){},
+    /**
+     * Returns size of the file identified by id
+     */          
+    getSize: function(id){},
+    /**
+     * Returns id of files being uploaded or
+     * waiting for their turn
+     */
+    getQueue: function(){
+        return this._queue;
+    },
+    /**
+     * Actual upload method
+     */
+    _upload: function(id){},
+    /**
+     * Actual cancel method
+     */
+    _cancel: function(id){},     
+    /**
+     * Removes element from queue, starts upload of next
+     */
+    _dequeue: function(id){
+        var i = qq.indexOf(this._queue, id);
+        this._queue.splice(i, 1);
+                
+        var max = this._options.maxConnections;
+        
+        if (this._queue.length >= max && i < max){
+            var nextId = this._queue[max-1];
+            this._upload(nextId, this._params[nextId]);
+        }
+    }        
+};
+
+/**
+ * Class for uploading files using form and iframe
+ * @inherits qq.UploadHandlerAbstract
+ */
+qq.UploadHandlerForm = function(o){
+    qq.UploadHandlerAbstract.apply(this, arguments);
+       
+    this._inputs = {};
+};
+// @inherits qq.UploadHandlerAbstract
+qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype);
+
+qq.extend(qq.UploadHandlerForm.prototype, {
+    add: function(fileInput){
+        fileInput.setAttribute('name', 'qqfile');
+        var id = 'qq-upload-handler-iframe' + qq.getUniqueId();       
+        
+        this._inputs[id] = fileInput;
+        
+        // remove file input from DOM
+        if (fileInput.parentNode){
+            qq.remove(fileInput);
+        }
+                
+        return id;
+    },
+    getName: function(id){
+        // get input value and remove path to normalize
+        return this._inputs[id].value.replace(/.*(\/|\\)/, "");
+    },    
+    _cancel: function(id){
+        this._options.onCancel(id, this.getName(id));
+        
+        delete this._inputs[id];        
+
+        var iframe = document.getElementById(id);
+        if (iframe){
+            // to cancel request set src to something else
+            // we use src="javascript:false;" because it doesn't
+            // trigger ie6 prompt on https
+            iframe.setAttribute('src', 'javascript:false;');
+
+            qq.remove(iframe);
+        }
+    },     
+    _upload: function(id, params){                        
+        var input = this._inputs[id];
+        
+        if (!input){
+            throw new Error('file with passed id was not added, or already uploaded or cancelled');
+        }                
+
+        var fileName = this.getName(id);
+                
+        var iframe = this._createIframe(id);
+        var form = this._createForm(iframe, params);
+        form.appendChild(input);
+
+        var self = this;
+        this._attachLoadEvent(iframe, function(){                                 
+            self.log('iframe loaded');
+            
+            var response = self._getIframeContentJSON(iframe);
+
+            self._options.onComplete(id, fileName, response);
+            self._dequeue(id);
+            
+            delete self._inputs[id];
+            // timeout added to fix busy state in FF3.6
+            setTimeout(function(){
+                qq.remove(iframe);
+            }, 1);
+        });
+
+        form.submit();        
+        qq.remove(form);        
+        
+        return id;
+    }, 
+    _attachLoadEvent: function(iframe, callback){
+        qq.attach(iframe, 'load', function(){
+            // when we remove iframe from dom
+            // the request stops, but in IE load
+            // event fires
+            if (!iframe.parentNode){
+                return;
+            }
+
+            // fixing Opera 10.53
+            if (iframe.contentDocument &&
+                iframe.contentDocument.body &&
+                iframe.contentDocument.body.innerHTML == "false"){
+                // In Opera event is fired second time
+                // when body.innerHTML changed from false
+                // to server response approx. after 1 sec
+                // when we upload file with iframe
+                return;
+            }
+
+            callback();
+        });
+    },
+    /**
+     * Returns json object received by iframe from server.
+     */
+    _getIframeContentJSON: function(iframe){
+        // iframe.contentWindow.document - for IE<7
+        var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
+            response;
+        
+        this.log("converting iframe's innerHTML to JSON");
+        this.log("innerHTML = " + doc.body.innerHTML);
+                        
+        try {
+            response = eval("(" + doc.body.innerHTML + ")");
+        } catch(err){
+            response = {};
+        }        
+
+        return response;
+    },
+    /**
+     * Creates iframe with unique name
+     */
+    _createIframe: function(id){
+        // We can't use following code as the name attribute
+        // won't be properly registered in IE6, and new window
+        // on form submit will open
+        // var iframe = document.createElement('iframe');
+        // iframe.setAttribute('name', id);
+
+        var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />');
+        // src="javascript:false;" removes ie6 prompt on https
+
+        iframe.setAttribute('id', id);
+
+        iframe.style.display = 'none';
+        document.body.appendChild(iframe);
+
+        return iframe;
+    },
+    /**
+     * Creates form, that will be submitted to iframe
+     */
+    _createForm: function(iframe, params){
+        // We can't use the following code in IE6
+        // var form = document.createElement('form');
+        // form.setAttribute('method', 'post');
+        // form.setAttribute('enctype', 'multipart/form-data');
+        // Because in this case file won't be attached to request
+        var form = qq.toElement('<form method="post" enctype="multipart/form-data"></form>');
+
+        var queryString = qq.obj2url(params, this._options.action);
+
+        form.setAttribute('action', queryString);
+        form.setAttribute('target', iframe.name);
+        form.style.display = 'none';
+        document.body.appendChild(form);
+
+        return form;
+    }
+});
+
+/**
+ * Class for uploading files using xhr
+ * @inherits qq.UploadHandlerAbstract
+ */
+qq.UploadHandlerXhr = function(o){
+    qq.UploadHandlerAbstract.apply(this, arguments);
+
+    this._files = [];
+    this._xhrs = [];
+    
+    // current loaded size in bytes for each file 
+    this._loaded = [];
+};
+
+// static method
+qq.UploadHandlerXhr.isSupported = function(){
+    var input = document.createElement('input');
+    input.type = 'file';        
+    
+    return (
+        'multiple' in input &&
+        typeof File != "undefined" &&
+        typeof (new XMLHttpRequest()).upload != "undefined" );       
+};
+
+// @inherits qq.UploadHandlerAbstract
+qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype)
+
+qq.extend(qq.UploadHandlerXhr.prototype, {
+    /**
+     * Adds file to the queue
+     * Returns id to use with upload, cancel
+     **/    
+    add: function(file){
+        if (!(file instanceof File)){
+            throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
+        }
+                
+        return this._files.push(file) - 1;        
+    },
+    getName: function(id){        
+        var file = this._files[id];
+        // fix missing name in Safari 4
+        return file.fileName != null ? file.fileName : file.name;       
+    },
+    getSize: function(id){
+        var file = this._files[id];
+        return file.fileSize != null ? file.fileSize : file.size;
+    },    
+    /**
+     * Returns uploaded bytes for file identified by id 
+     */    
+    getLoaded: function(id){
+        return this._loaded[id] || 0; 
+    },
+    /**
+     * Sends the file identified by id and additional query params to the server
+     * @param {Object} params name-value string pairs
+     */    
+    _upload: function(id, params){
+        var file = this._files[id],
+            name = this.getName(id),
+            size = this.getSize(id);
+                
+        this._loaded[id] = 0;
+                                
+        var xhr = this._xhrs[id] = new XMLHttpRequest();
+        var self = this;
+                                        
+        xhr.upload.onprogress = function(e){
+            if (e.lengthComputable){
+                self._loaded[id] = e.loaded;
+                self._options.onProgress(id, name, e.loaded, e.total);
+            }
+        };
+
+        xhr.onreadystatechange = function(){            
+            if (xhr.readyState == 4){
+                self._onComplete(id, xhr);                    
+            }
+        };
+
+        // build query string
+        params = params || {};
+        params['qqfile'] = name;
+        var queryString = qq.obj2url(params, this._options.action);
+
+        xhr.open("POST", queryString, true);
+        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+        xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
+        xhr.setRequestHeader("Content-Type", "application/octet-stream");
+        xhr.send(file);
+    },
+    _onComplete: function(id, xhr){
+        // the request was aborted/cancelled
+        if (!this._files[id]) return;
+        
+        var name = this.getName(id);
+        var size = this.getSize(id);
+        
+        this._options.onProgress(id, name, size, size);
+                
+        if (xhr.status == 200){
+            this.log("xhr - server response received");
+            this.log("responseText = " + xhr.responseText);
+                        
+            var response;
+                    
+            try {
+                response = eval("(" + xhr.responseText + ")");
+            } catch(err){
+                response = {};
+            }
+            
+            this._options.onComplete(id, name, response);
+                        
+        } else {                   
+            this._options.onComplete(id, name, {});
+        }
+                
+        this._files[id] = null;
+        this._xhrs[id] = null;    
+        this._dequeue(id);                    
+    },
+    _cancel: function(id){
+        this._options.onCancel(id, this.getName(id));
+        
+        this._files[id] = null;
+        
+        if (this._xhrs[id]){
+            this._xhrs[id].abort();
+            this._xhrs[id] = null;                                   
+        }
+    }
+});

+ 45 - 46
apps/filebrowser/src/filebrowser/templates/chmod.mako

@@ -14,50 +14,49 @@
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
 <%namespace name="edit" file="editor_components.mako" />
-<%namespace name="comps" file="fb_components.mako" />
-${comps.header('Change Permissions: ' + path.split('/')[-1])}
 
-<div class="prompt_popup">
-<form action="/filebrowser/chmod?next=${next|u}" method="POST" enctype="multipart/form-data">
-  <h4 class="jframe-hidden">Change Permissions: ${path}</h4>
-  <dl>
-    ${edit.render_field(form["path"], hidden=True)}
-    <table class="fb-chmod">
-      <thead>
-        <tr>
-          <th class="fb-empty"></th>
-          <th>User</th>
-          <th>Group</th>
-          <th>Other</th>
-        </tr>
-      </thead>
-      <tbody>
-        <tr>
-          <td class="fb-label">Read</td>
-          <td>${edit.render_field(form["user_read"], tag="checkbox", button_text=" ", notitle=True)}</td>
-          <td>${edit.render_field(form["group_read"], tag="checkbox", button_text=" ", notitle=True)}</td>
-          <td>${edit.render_field(form["other_read"], tag="checkbox", button_text=" ", notitle=True)}</td>
-        </tr>
-        <tr>
-          <td class="fb-label">Write</td>
-          <td>${edit.render_field(form["user_write"], tag="checkbox", button_text=" ", notitle=True)}</td>
-          <td>${edit.render_field(form["group_write"], tag="checkbox", button_text=" ", notitle=True)}</td>
-          <td>${edit.render_field(form["other_write"], tag="checkbox", button_text=" ", notitle=True)}</td>
-        </tr>
-        <tr>
-          <td class="fb-label">Execute</td>
-          <td>${edit.render_field(form["user_execute"], tag="checkbox", button_text=" ", notitle=True)}</td>
-          <td>${edit.render_field(form["group_execute"], tag="checkbox", button_text=" ", notitle=True)}</td>
-          <td>${edit.render_field(form["other_execute"], tag="checkbox", button_text=" ", notitle=True)}</td>
-        </tr>
-      </tbody>
-    </table>
-  </dl>
-  <input class="jframe-hidden" type="submit" value="Submit" />
-</form>
-</div>
-
-<div class="jframe-hidden">Go back to where you were: <a href="${next|u}">${next}</a>.</div>
-
-
-${comps.footer()}
+<form action="/filebrowser/chmod?next=${next|u}" method="POST" enctype="multipart/form-data"
+      class="form-stacked form-padding-fix">
+    <div class="modal-header">
+        <a href="#" class="close">&times;</a>
+        <h3>Change Permissions: ${path}</h3>
+    </div>
+    <div class="change-owner-modal-body clearfix" >
+        ${edit.render_field(form["path"], hidden=True)}
+        <table class="zebra-striped"
+               style="background-color: #ffffff;">
+            <thead>
+            <tr>
+                <th></th>
+                <th>User</th>
+                <th>Group</th>
+                <th>Other</th>
+            </tr>
+            </thead>
+            <tbody>
+            <tr>
+                <td>Read</td>
+                <td>${edit.render_field(form["user_read"], tag="checkbox", button_text=" ", notitle=True)}</td>
+                <td>${edit.render_field(form["group_read"], tag="checkbox", button_text=" ", notitle=True)}</td>
+                <td>${edit.render_field(form["other_read"], tag="checkbox", button_text=" ", notitle=True)}</td>
+            </tr>
+            <tr>
+                <td>Write</td>
+                <td>${edit.render_field(form["user_write"], tag="checkbox", button_text=" ", notitle=True)}</td>
+                <td>${edit.render_field(form["group_write"], tag="checkbox", button_text=" ", notitle=True)}</td>
+                <td>${edit.render_field(form["other_write"], tag="checkbox", button_text=" ", notitle=True)}</td>
+            </tr>
+            <tr>
+                <td>Execute</td>
+                <td>${edit.render_field(form["user_execute"], tag="checkbox", button_text=" ", notitle=True)}</td>
+                <td>${edit.render_field(form["group_execute"], tag="checkbox", button_text=" ", notitle=True)}</td>
+                <td>${edit.render_field(form["other_execute"], tag="checkbox", button_text=" ", notitle=True)}</td>
+            </tr>
+            </tbody>
+        </table>
+    </div>
+    <div class="modal-footer" style="padding-top: 10px;">
+        <input class="btn primary" type="submit" value="Submit"/>
+        <a class="btn" onclick="$('#changePermissionModal').modal('hide');">Cancel</a>
+    </div>
+</form>

+ 3 - 9
apps/filebrowser/src/filebrowser/templates/chooser.mako

@@ -13,18 +13,12 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="comps" file="fb_components.mako" />
 <%namespace name="dir" file="listdir_components.mako" />
-<html>
-  <head>
-    <title>${path}</title>
-  </head>
-  <body>
-    <div class="toolbar">
+
       <div class="fb-actions" data-filters="ArtButtonBar">
         <a class="fb-upload" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height' : 16}" href="${url('filebrowser.views.upload')}?dest=${path|u}&next=${current_request_path|u}">Upload Files</a>
         <a class="fb-mkdir" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16}" href="${url('filebrowser.views.mkdir')}?path=${path|u}&next=${current_request_path|u}">New Directory</a>
       </div>
-    </div>
+
     ${dir.list_table_chooser(files, path_enc, current_request_path)}
-${comps.footer()}
+

+ 32 - 30
apps/filebrowser/src/filebrowser/templates/chown.mako

@@ -14,8 +14,6 @@
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
 <%namespace name="edit" file="editor_components.mako" />
-<%namespace name="comps" file="fb_components.mako" />
-${comps.header('Change Owner / Group: ' + path.split('/')[-1])}
 <%! from desktop.lib.django_util import extract_field_data %>
 
 <%
@@ -56,36 +54,40 @@ ${comps.header('Change Owner / Group: ' + path.split('/')[-1])}
       % endif
     % endif
 </%def>
+<form action="/filebrowser/chown?next=${next|u}" method="POST" enctype="multipart/form-data" class="form-stacked form-padding-fix">
+    <div class="modal-header">
+        <a href="#" class="close">&times;</a>
+        <h3>Change Owner / Group: ${path}</h3>
+    </div>
+    <div class="change-owner-modal-body clearfix" >
+        <div class="alert-message block-message info">Note: Only the Hadoop superuser, on this FS "${extra_params['superuser']}", may change the owner of a file.</div>
+        <div style="padding-left: 15px; padding-bottom: 10px;">
+            ${edit.render_field(form["path"], hidden=True)}
 
-<div class="prompt_popup">
-<form action="/filebrowser/chown?next=${next|u}" method="POST" enctype="multipart/form-data">
-  <h4 class="jframe-hidden">Change Owner / Group: ${path}</h4>
-  <dl class="fb-side-by-side">
-    ${edit.render_field(form["path"], hidden=True)}
+            <label>User</label>
 
-    <dt><label>User</label></dt>
-    <dd data-filters="${select_filter}">
-      % if is_superuser:
-        ${ selection("user", form.all_users, extract_field_data(form["user"]), "user_other") }
-      % else:
-        ${ selection("user", [extract_field_data(form['user'])], extract_field_data(form["user"])) }
-      % endif
-    </dd>
-    <dt><label>Group</label></dt>
-    <dd data-filters="${select_filter}">
-      % if is_superuser:
-        ${ selection("group", form.all_groups, extract_field_data(form["group"]), "group_other") }
-      % else:
-        ${ selection("group", [group for group in form.all_groups if group in extra_params['current_user'].get_groups()], extract_field_data(form["group"])) }
-      % endif
-    </dd>
-  </dl>
-  <input class="jframe-hidden" type="submit" value="Submit" />
-</form>
-<p>Note: Only the Hadoop superuser, on this FS "${extra_params['superuser']}", may change the owner of a file.</p>
-</div>
+            % if is_superuser:
+            ${ selection("user", form.all_users, extract_field_data(form["user"]), "user_other") }
+            % else:
+            ${ selection("user", [extract_field_data(form['user'])], extract_field_data(form["user"])) }
+            % endif
 
-<div class="jframe-hidden">Go back to where you were: <a href="${next|u}">${next}</a>.</div>
+            <label>Group</label>
+
+            % if is_superuser:
+            ${ selection("group", form.all_groups, extract_field_data(form["group"]), "group_other") }
+            % else:
+            ${ selection("group", [group for group in form.all_groups if group in extra_params['current_user'].get_groups()], extract_field_data(form["group"])) }
+            % endif
+        </div>
+
+
+    </div>
+    <div class="modal-footer" style="padding-top: 10px;">
+        <input class="btn primary" type="submit" value="Submit" />
+        <a class="btn" onclick="$('#changeOwnerModal').modal('hide');">Cancel</a>
+    </div>
+</form>
 
 
-${comps.footer()}
+<!--<div class="alert-message info modal-footer">Note: Only the Hadoop superuser, on this FS "${extra_params['superuser']}", may change the owner of a file.</div>-->

+ 66 - 51
apps/filebrowser/src/filebrowser/templates/display.mako

@@ -24,104 +24,113 @@
   dirname_enc = urlencode(view['dirname'])
   base_url = url('filebrowser.views.view', path=path_enc)
 %>
-<html>
-<head><title>${truncate(filename)} :: File Viewer</title></head>
-<body>
+<%namespace name="wrappers" file="header_footer.mako" />
+${wrappers.head(truncate(filename)+' :: File Viewer', show_upload=False, show_new_directory=False, show_side_bar=False)}
   <div class="toolbar">
-    <div class="fv-path draggable" data-filters="FitText">${path}</div>
 
-    <div class="fv-actions" data-filters="ArtButtonBar">
+
+    <div>
       % if view['mode'] == "binary":
-        <a class="fv-viewText" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16}" href="${base_url}?offset=${view['offset']}&length=${view['length']}&mode=text&compression=${view['compression']}">View As Text</a>
+        <a class="btn" href="${base_url}?offset=${view['offset']}&length=${view['length']}&mode=text&compression=${view['compression']}">View As Text</a>
       % endif
 
       % if view['mode'] == "text":
-        <a class="fv-viewBinary" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16}" href="${base_url}?offset=${view['offset']}&length=${view['length']}&mode=binary&compression=${view['compression']}">View As Binary</a>
+        <a class="btn" href="${base_url}?offset=${view['offset']}&length=${view['length']}&mode=binary&compression=${view['compression']}">View As Binary</a>
       % endif
 
       % if view['compression'] != "gzip" and path.endswith('.gz'):
-        <a class="fv-viewGzip" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16}" href="${base_url}?offset=0&length=2000&mode=${view['mode']}&compression=gzip">Preview As Gzip</a>
+        <a class="btn" href="${base_url}?offset=0&length=2000&mode=${view['mode']}&compression=gzip">Preview As Gzip</a>
       % endif
 
       % if view['compression'] != "avro" and path.endswith('.avro'):
-        <a class="fv-viewAvro" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16}" href="${base_url}?offset=0&length=2000&mode=${view['mode']}&compression=avro">Preview As Avro</a>
+        <a class="btn" href="${base_url}?offset=0&length=2000&mode=${view['mode']}&compression=avro">Preview As Avro</a>
       % endif
 
       % if view['compression'] and view['compression'] != "none":
-        <a class="fv-viewGzip" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16}" href="${base_url}?offset=0&length=2000&mode=${view['mode']}&compression=none">Stop preview</a>
+        <a class="btn" href="${base_url}?offset=0&length=2000&mode=${view['mode']}&compression=none">Stop preview</a>
       % endif
 
       % if editable and view['compression'] == "none":
-        <a class="fv-editFile" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16}" href="${url('filebrowser.views.edit', path=path_enc)}" target="FileEditor">Edit File</a>
+        <a class="btn" href="${url('filebrowser.views.edit', path=path_enc)}">Edit File</a>
       % endif
-       <a class="fv-download" data-filters="ArtButton" target="_blank" data-icon-styles="{'width': 16, 'height': 16}" href="${url('filebrowser.views.download', path=path_enc)}">Download</a>
-       <a class="fv-viewLocation" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16}" href="${url('filebrowser.views.view', path=dirname_enc)}" target="FileBrowser">View File Location</a>
-       <a class="jframe-refresh large" data-filters="ArtButton">Refresh</a>
+       <a class="btn" href="${url('filebrowser.views.download', path=path_enc)}">Download</a>
+       <a class="btn" href="${url('filebrowser.views.view', path=dirname_enc)}">View File Location</a>
+       <a id="refreshBtn" class="btn">Refresh</a>
     </div>
   </div>
-  <div class="fv-navhead">
+  <div>
     % if not view['compression'] or view['compression'] in ("none", "avro"):
       <div class="fv-navStatus">
-        <form data-filters="SubmitOnChange" class="fv-changeBytesForm" action="${url('filebrowser.views.view', path=path_enc)}" method="GET">
-          <span class="fv-bold">Viewing Bytes:</span><a class="fv-editBytes jframe-inline" title="Enter Bytes"></a>
+        <form action="${url('filebrowser.views.view', path=path_enc)}" method="GET">
+          <span>Viewing Bytes:</span><a title="Enter Bytes"></a>
           <input name="begin" value="${view['offset'] + 1}"/>
           -
           <input value="${view['end']}" name="end"/> of
-          <span class="fv-bold totalBytes">${stats['size']}</span>
-          <span class="fv-stepInfo">(${view['length']} B block size)</span>
+          <span>${stats['size']}</span>
+          <span>(${view['length']} B block size)</span>
           % if view['mode']:
             <input type="hidden" name="mode" value="${view['mode']}"/><br/>
           % endif
         </form>
       </div>
-      <div class="fv-navigation">
+      <div class="pagination">
         <%
           base_url = url('filebrowser.views.view', path=path_enc)
           if view['offset'] == 0:
-              first = "style=visibility:hidden"
-              prev = "style=visibility:hidden"
+              first_class = "prev disabled"
+              prev_class = "disabled"
+              first_href = ""
+              prev_href = ""
           else:
-              first = "href=%s?offset=0&length=%d&compression=none title=1 - %d" %(base_url, view['length'], min(view['length'], stats['size']))
-              prev =  "href=%s?offset=%d&length=%d&compression=none title=%d - %d" %(base_url, max(0, view['offset']-view['length']), view['length'], max(0, view['offset']-view['length']) + 1, min(max(0, view['offset'] - view['length']) + view['length'], stats['size']))
+              first_class = "prev"
+              prev_class = ""
+              first_href = "href=%s?offset=0&length=%d&compression=none title=1 - %d" %(base_url, view['length'], min(view['length'], stats['size']))
+              prev_href =  "href=%s?offset=%d&length=%d&compression=none title=%d - %d" %(base_url, max(0, view['offset']-view['length']), view['length'], max(0, view['offset']-view['length']) + 1, min(max(0, view['offset'] - view['length']) + view['length'], stats['size']))
           if view['offset'] + view['length'] >= stats['size']:
-              next = "style=visibility:hidden"
-              last = "style=visibility:hidden"
+              next_class = "disabled"
+              last_class = "next disabled"
+              next_href = ""
+              last_href = ""
           else:
-              next = "href=%s?offset=%d&length=%d&compression=none title=%d - %d" %(base_url, view['offset'] + view['length'], view['length'], view['offset'] + view['length'] + 1, view['offset'] + (2 * view['length']))
-              last =  "href=%s?offset=%d&length=%d&compression=none title=%d - %d" %(base_url, stats['size']-(stats['size'] % view['length']), view['length'], stats['size']-(stats['size'] % view['length']) + 1, stats['size'])
+              next_class = ""
+              last_class = "next"
+              next_href = "href=%s?offset=%d&length=%d&compression=none title=%d - %d" %(base_url, view['offset'] + view['length'], view['length'], view['offset'] + view['length'] + 1, view['offset'] + (2 * view['length']))
+              last_href =  "href=%s?offset=%d&length=%d&compression=none title=%d - %d" %(base_url, stats['size']-(stats['size'] % view['length']), view['length'], stats['size']-(stats['size'] % view['length']) + 1, stats['size'])
         %>
         ###DEFINE REL
-        <a class="jframe-inline fv-firstBlock" data-filters="PointyTip" ${first}>First Block</a>
-        <a class="jframe-inline fv-prevBlock" data-filters="PointyTip" ${prev}>Previous Block</a>
-        <a class="jframe-inline fv-nextBlock" data-filters="PointyTip" ${next}>Next Block</a>
-        <a class="jframe-inline fv-lastBlock" data-filters="PointyTip" ${last}>Last Block</a>
+        <ul>
+            <li class="${first_class}"><a ${first_href}>First Block</a></li>
+            <li class="${prev_class}"><a ${prev_href}>Previous Block</a></li>
+            <li class="${next_class}"><a ${next_href}>Next Block</a></li>
+            <li class="${last_class}"><a ${last_href}>Last Block</a></li>
+        </ul>
       </div>
     % endif
   </div>
-  <div class="resizable" data-filters="SplitView" data-split-offset-y="36">
-    <div class="left_col jframe_padded">
-      <dl class="fv-fileInfo">
-        <dt>Last Modified</dt>
-        <dd>${date(datetime.datetime.fromtimestamp(stats['mtime']))} ${time(datetime.datetime.fromtimestamp(stats['mtime']))}</dd>
-        <dt>User</dt>
-        <dd>${stats['user']}<dd>
-        <dt>Group</dt>
-        <dd>${stats['group']}</dd>
-        <dt>Size</dt>
-        <dd>${stats['size']|filesizeformat}<dd>
+  <div class="container-fluid">
+    <div class="sidebar">
+      <div class="well">
+        <h5>Last Modified</h5>
+        ${date(datetime.datetime.fromtimestamp(stats['mtime']))} ${time(datetime.datetime.fromtimestamp(stats['mtime']))}
+        <h5>User</h5>
+        ${stats['user']}
+        <h5>Group</h5>
+        ${stats['group']}
+        <h5>Size</h5>
+        ${stats['size']|filesizeformat}
         ## Could convert this to "rw-rw-r--" form.
-        <dt>Mode</dt>
-        <dd>${stringformat(stats['mode'], "o")}</dd>
+        <h5>Mode</h5>
+        ${stringformat(stats['mode'], "o")}
         ## Could increase accuracy here depending on how long ago this was
-      </dl>
+      </div>
     </div>
-    <div class="right_col">
+    <div class="content">
     %if 'contents' in view:
       % if view['masked_binary_data']:
-      <div class="fv-binaryWarning">Warning: some binary data has been masked out with '&#xfffd'.</div>
+      <div class="alert-message warning">Warning: some binary data has been masked out with '&#xfffd'.</div>
       % endif
     % endif
-      <div class="jframe_padded">
+      <div>
       % if 'contents' in view:
              <div><pre><code>${view['contents']|escape}</code></pre></div>
       % else:
@@ -150,6 +159,12 @@
       </div>
     </div>
   </div>
-</body>
-</html>
 
+	<script type="text/javascript" charset="utf-8">
+		$(document).ready(function(){
+			$("#refreshBtn").click(function(){
+				window.location.reload();
+			});
+		});
+	</script>
+${wrappers.foot()}

+ 78 - 23
apps/filebrowser/src/filebrowser/templates/edit.mako

@@ -22,17 +22,20 @@
   path_enc = urlencode(path)
   dirname_enc = urlencode(dirname)
 %>
-<html>
-<head><title>${truncate(filename)} :: File Editor</title></head>
-<body>
-<div class="toolbar">
-  <div class="fe-path">${truncate(path, 91)}</div>
-  <div class="fe-buttons" data-filters="ArtButtonBar">
-    <a class="fe-viewLocation" data-filters="ArtButton" data-icon-styles="{'width': 16, 'height': 16}" href="${url('filebrowser.views.view', path=dirname_enc)}" target="FileBrowser">View Location</a>
-  </div>
-</div>
+<%namespace name="wrappers" file="header_footer.mako" />
+${wrappers.head(truncate(filename)+' :: File Viewer', show_upload=False, show_new_directory=False, show_side_bar=False)}
+
+
+<h1>${truncate(path, 91)}</h1>
+<div class="well" >
+    <form class="form-stacked" method="post" action="${url('filebrowser.views.save_file')}">
+    <div class="toolbar">
+		<a class="btn" href="${url('filebrowser.views.view', path=dirname_enc)}">View Location</a>
+	</div>
+	<br/>
+
 % if form.errors:
-  <div class="alert_popup">
+  <div class="alert-message">
     % for field in form:
       % if len(field.errors):
        ${unicode(field.errors) | n}
@@ -40,17 +43,69 @@
     % endfor
   </div>
 % endif
-<form class="fe-editForm noReset" method="post" action="${url('filebrowser.views.save_file')}">
-    ${edit.render_field(form["path"], hidden=True, notitle=True)}
-    ${edit.render_field(form["encoding"], hidden=True, notitle=True)}
-    <h2 class="jframe-hidden">${form["contents"].label_tag() | n}</h2>
-    <div class="fe-divResize" data-filters="SizeTo" data-size-to-width="100%" data-size-to-height="100%">${edit.render_field(form["contents"], tag="textarea", notitle=True, attrs=dict(
-      data_filters="SizeTo, PostEditor",
-      data_size_to_width="-20",
-      data_size_to_height="100%")) | n}</div>
-    <input class="jframe-hidden" type="submit" name="save" value="saveAs">
-    <input class="jframe-hidden" type="submit" name="save" value="save">
-</form>
-</body>
-</html>
+        ${edit.render_field(form["path"], hidden=True, notitle=True)}
+        ${edit.render_field(form["encoding"], hidden=True, notitle=True)}
+        
+        <div style="width: 100%; height: 100%;">${edit.render_field(form["contents"], tag="textarea", notitle=True, attrs=dict(
+          style="width:100%; height:400px;")) | n}</div>
+        <input class="btn primary" type="submit" name="save" value="Save">
+        <a id="saveAsBtn" class="btn">Save As</a>
+    </form>
+</div>
+
+
+<div id="saveAsModal" class="modal hide fade">
+    <form id="saveAsForm" action="${url('filebrowser.views.save_file')}" method="POST" class="form-stacked form-padding-fix">
+    <div class="modal-header">
+        <a href="#" class="close">&times;</a>
+        <h3>Save As</h3>
+    </div>
+    <div class="modal-body">
+		${edit.render_field(form["path"], notitle=True, klass="xlarge")}
+		<span class="help-block">Please enter the location where you'd like to save the file.</span>
+    </div>
+    <div class="modal-footer">
+        <div id="saveAsNameRequiredAlert" class="alert-message error hide" style="position: absolute; left: 10;">
+            <p><strong>Sorry, name is required.</strong>
+        </div>
+		${edit.render_field(form["contents"], hidden=True)}
+		${edit.render_field(form["encoding"], hidden=True)}
+        <input type="submit" value="Save" class="btn primary" />
+        <a id="cancelSaveAsBtn" class="btn">Cancel</a>
+    </div>
+    </form>
+</div>
+
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$("#saveAsBtn").click(function(){
+			$("#saveAsModal").modal({
+				backdrop: "static",
+				keyboard: true,
+				show: true
+			})
+		});
+		
+		
+		$("#cancelSaveAsBtn").click(function(){
+			$("#saveAsModal").modal("hide");
+		});
+		
+		$("#saveAsForm").submit(function() {
+			if ($.trim($("#saveAsForm").find("input[name='path']").val()) == ""){
+				$("#saveAsForm").find("input[name='path']").addClass("fieldError");
+				$("#saveAsNameRequiredAlert").show();
+				return false;
+			}
+			return true;
+		});
+		
+		$("#saveAsForm").find("input[name='path']").focus(function(){
+			$(this).removeClass("fieldError");
+			$("#saveAsNameRequiredAlert").hide();
+		});
+	});
+</script>
+
+${wrappers.foot()}
 

+ 19 - 11
apps/filebrowser/src/filebrowser/templates/editor_components.mako

@@ -52,7 +52,7 @@
     attrs = {}
   if not render_default:
     attrs.setdefault('type', 'text')
-    
+
   if data_filters:
     attrs.data_filters = data_filters
   
@@ -70,11 +70,14 @@
     title_classes.append("jframe-hidden")
   titlecls = ' '.join(title_classes)
 %>
-  % if field.is_hidden:
-    ${unicode(field) | n}
-  % else:
-    <dt class="${titlecls}" ${make_attr_str(dt_attrs) | n}>${field.label_tag() | n}</dt>
-    <dd class="${cls}" ${make_attr_str(dd_attrs) | n}>
+
+    % if not hidden:
+    <div class="clearfix">
+
+        ${field.label_tag() | n}
+
+    <div class="input">
+    % endif
       % if render_default:
         ${unicode(field) | n}
       % else:
@@ -84,19 +87,24 @@
           <button name="${field.html_name | n}" ${make_attr_str(attrs) | n} value="${value}"/>${button_text or field.name or ''}</button>
         % elif tag == 'checkbox':
           <input type="checkbox" name="${field.html_name | n}" ${make_attr_str(attrs) | n} ${value and "CHECKED" or ""}/>${button_text or field.name or ''}</input>
+        % elif hidden:
+          <input type="hidden" name="${field.html_name | n}" ${make_attr_str(attrs) | n} value="${extract_field_data(field)}"></input>
         % else:
-          <${tag} name="${field.html_name | n}" value="${extract_field_data(field) or ''}" ${make_attr_str(attrs) | n} />
+          <${tag} name="${field.html_name | n}" value="${extract_field_data(field) or ''}" class="${cls}" ${make_attr_str(attrs) | n}/>
         % endif
       % endif
       % if help:
         <p class="jframe-inline" data-filters="HelpTip" ${make_attr_str(help_attrs) | n}>${help}</p>
       % endif
-    </dd>
+
+    % if not hidden:
+    </div>
+    </div>
+    % endif
     % if len(field.errors):
-      <dd class="beeswax_error jframe-error">
+      <div class="beeswax_error jframe-error">
          ${unicode(field.errors) | n}
-       </dd>
+      </div>
     % endif
-  % endif
 </%def>
 

+ 15 - 9
apps/filebrowser/src/filebrowser/templates/fileop.mako

@@ -18,15 +18,21 @@ import datetime
 from django.template.defaultfilters import urlencode, escape, stringformat, date, filesizeformat, time
 %>
 
-<html>
-<head><title>File Operation</title></head>
-<body>
-<h1>${form.op}</h1>
+<%namespace name="wrappers" file="header_footer.mako" />
+
+${wrappers.head('File Operation', show_side_bar=False)}
+
 ## Not sure if enctype breaks anything if used for things other than file upload.
-<form action="" method="POST" enctype="multipart/form-data">
+
+<div class="well">
+<form action="" method="POST" enctype="multipart/form-data" class="form-stacked">
+<h1>${form.op}</h1>
 ${form.as_p()|n}
-<input type="submit" value="Submit" />
-Go back to where you were: <a href="${urlencode(next)}">${next}</a>.
+<div>
+<input type="submit" value="Submit" class="btn primary" />
+<a href="${urlencode(next)}" class="btn">Cancel</a>
+</div>
 </form>
-</body>
-</html>
+</div>
+
+${wrappers.foot()}

+ 121 - 0
apps/filebrowser/src/filebrowser/templates/header_footer.mako

@@ -0,0 +1,121 @@
+## Licensed to Cloudera, Inc. under one
+## or more contributor license agreements.  See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership.  Cloudera, Inc. licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##
+##     http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+##
+##
+## no spaces in this method please; we're declaring a CSS class, and ART uses this value for stuff, and it splits on spaces, and
+## multiple spaces and line breaks cause issues
+<%!
+import datetime
+import hashlib
+from django.template.defaultfilters import urlencode, escape
+%>
+<%!
+def is_selected(section, matcher):
+  if section == matcher:
+    return "selected"
+  else:
+    return ""
+%>
+
+<%!
+def is_home(path):
+    if path == "/":
+        return "selected"
+    else:
+        return ""
+%>
+
+<%def name="head(title='File Browser', section='', path='', current_request_path=False, toolbar=True, cwd_set=True, show_upload=False, show_new_directory=False, show_side_bar=True)">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+	<meta name="viewport" content="width=device-width user-scalable=no initial-scale=1" />
+	<meta name="apple-mobile-web-app-capable" content="yes" />
+	<title>${title}</title>
+	<link rel="stylesheet" href="/static/ext/css/bootstrap.min.css" type="text/css" media="screen" title="no title" charset="utf-8" />
+	<link rel="stylesheet" href="/static/css/jhue.css" type="text/css" media="screen" title="no title" charset="utf-8" />
+
+	<style type="text/css">
+      body {
+        padding-top: 60px;
+      }
+    </style>
+	<script src="/static/ext/js/jquery/jquery-1.7.min.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/js/Source/jHue/jquery.showusername.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/js/Source/jHue/jquery.contextmenu.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/ext/js/jquery/plugins/jquery.simpleplaceholder.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/ext/js/jquery/plugins/jquery.dataTables.1.8.2.min.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/ext/js/bootstrap-tabs.js" type="text/javascript" charset="utf-8"></script>
+    <script src="/static/ext/js/bootstrap-modal.js" type="text/javascript" charset="utf-8"></script>
+    <script src="/static/ext/js/bootstrap-dropdown.js" type="text/javascript" charset="utf-8"></script>
+
+	<script type="text/javascript" charset="utf-8">
+		$(document).ready(function(){
+			$("#username").showUsername();
+			$("input:text[placeholder]").simplePlaceholder();
+			$(".submitter").keydown(function(e){
+				if (e.keyCode==13){
+					$(this).closest("form").submit();
+				}
+			}).change(function(){
+				$(this).closest("form").submit();
+			});
+		});
+	</script>
+
+</head>
+<body>
+	<div class="topbar">
+		<div class="topbar-inner">
+			<div class="container-fluid">
+				<a class="brand" href="#">jHue</a>
+				<ul class="nav">
+					<li><a href="/beeswax">Beeswax</a></li>
+
+					<li class="active"><a href="/filebrowser/">File Browser</a></li>
+					<li><a href="/jobsub/">Job Designer</a></li>
+					<li><a href="/jobbrowser/jobs/">Job Browser</a></li>
+					<li><a href="/useradmin/">User Admin</a></li>
+					<li><a href="/shell/">Shell</a></li>
+					<li><a href="/help/">Help</a></li>
+					<li><a href="/about/">About</a></li>
+				</ul>
+				<p class="pull-right">Logged in as <strong><span id="username">xxx</span></strong> - <a href="/accounts/logout">Sign out</a></p>
+			</div>
+		</div>
+	</div>
+
+	<div class="container-fluid">
+		<h1>${title}</h1>
+		% if breadcrumbs:
+			<ul class="breadcrumb">
+				% for breadcrumb_item in breadcrumbs:
+				<li><a href="/filebrowser/view${breadcrumb_item['url']}">${breadcrumb_item['label']}</a> <span class="divider">/</span></li>
+				% endfor
+			</ul>
+
+	    %endif
+</%def>
+
+<%def name="foot()">
+	</div>
+</body>
+</html>
+</%def>

+ 16 - 6
apps/filebrowser/src/filebrowser/templates/listdir.mako

@@ -16,13 +16,23 @@
 <%!
 import datetime
 from django.template.defaultfilters import escape, stringformat, date, time
+from desktop.views import commonheader, commonfooter
 %>
-<%namespace name="comps" file="fb_components.mako" />
+
 <%namespace name="dir" file="listdir_components.mako" />
-${comps.header(path, current_request_path, cwd_set=cwd_set, show_upload=show_upload)}
 
-  <div id="dirlist" class="view">
-    <h1 class="jframe-hidden">${path|escape}</h1>
+${commonheader('File Browser', 'filebrowser')}
+<div class="container-fluid">
+	<h1>File Browser</h1>
+	% if breadcrumbs:
+		<ul class="breadcrumb">
+			% for breadcrumb_item in breadcrumbs:
+			<li><a href="/filebrowser/view${breadcrumb_item['url']}">${breadcrumb_item['label']}</a> <span class="divider">/</span></li>
+			% endfor
+		</ul>
+	%endif
+    <div id="dirlist" class="view">
     ${dir.list_table_browser(files, path_enc, current_request_path, cwd_set)}
-  </div>
-${comps.footer()}
+    </div>
+</div>
+${commonfooter()}

+ 383 - 45
apps/filebrowser/src/filebrowser/templates/listdir_components.mako

@@ -15,7 +15,8 @@
 ## limitations under the License.
 <%!
 import datetime
-from django.template.defaultfilters import urlencode, stringformat, filesizeformat, date, time
+import hashlib
+from django.template.defaultfilters import urlencode, stringformat, filesizeformat, date, time, escape
 from desktop.lib.django_util import reverse_with_get
 %>
 
@@ -40,7 +41,23 @@ from desktop.lib.django_util import reverse_with_get
   else:
     optional_fit_text = ''
   %>
-  <table data-filters="HtmlTable" class="fb-file-list selectable ${optional_sortable}" cellpadding="0" cellspacing="0">
+  <script src="/static/ext/js/fileuploader.js" type="text/javascript" charset="utf-8"></script>
+  <link rel="stylesheet" href="/static/ext/css/fileuploader.css" type="text/css" media="screen" title="no title" charset="utf-8" />
+  <style type="text/css">
+    .form-padding-fix{
+        display: inline;
+        padding: 0;
+        margin: 0;
+    }
+  </style>
+  <div class="well">
+		Filter by name: <input id="filterInput"/> <a href="#" id="clearFilterBtn" class="btn">Clear</a>
+		<p class="pull-right">
+			<a href="#" class="btn upload-link">Upload files</a>
+			<a href="#" class="btn create-directory-link">New directory</a>
+		</p>
+  </div>
+  <table class="datatables">
     <thead>
       <tr>
         % if cwd_set:
@@ -52,7 +69,8 @@ from desktop.lib.django_util import reverse_with_get
         <th>User</th>
         <th>Group</th>
         <th>Permissions</th>
-        <th colspan="2">Date</th>
+        <th>Date</th>
+        <th></th>
       </tr>
     </thead>
     <tbody>
@@ -71,41 +89,17 @@ from desktop.lib.django_util import reverse_with_get
         %>
   ## Since path is in unicode, Django and Mako handle url encoding and
   ## iri encoding correctly for us.
+
         <% path = file['path'] %>
-        <tr class="jframe-no_select fb-item-row ${cls}"
-         data-filters="ContextMenu"
-         data-context-menu-actions="[{'events':['contextmenu','click:relay(.fb-item-options)'],'menu':'ul.context-menu'}]"
-         data-dblclick-delegate= "{'dblclick_loads':'a.fb-item'}" data-filedata="{'path':'${path}','type':'${file['type']|u}'}">
-          <td class="fb-name">
-            <div class="fb-name-container">
+        <tr class="file-row" file-name="${display_name}">
+          <td>
+            <div>
               % if "dir" == file['type']:
-                <a ${optional_fit_text | n} class="fb-item fb-dir jframe_ignore" href="${url('filebrowser.views.'+view, path=urlencode(path))}?file_filter=${file_filter}">${display_name}</a>
+                <h5><a ${optional_fit_text | n} href="${url('filebrowser.views.'+view, path=urlencode(path))}?file_filter=${file_filter}">${display_name}</a></h5>
               % else:
-                <a ${optional_fit_text | n} class="fb-item fb-file jframe_ignore" target="FileViewer" href="${url('filebrowser.views.'+view, path=urlencode(path))}?file_filter=${file_filter}">${display_name}</a>
-              % endif
-              % if ".." != file['name']:
-                <ul class="fb-item-actions context-menu">
-                  % if "dir" == file['type']:
-                    <li class="fb-rmdir-container"><a class="fb-rmdir confirm_unencode_and_post" alt="Are you sure you want to delete this directory and its contents?" href="${reverse_with_get('filebrowser.views.rmdir', get=dict(path=path,next=current_request_path))}">Delete</a></li>
-                    <li class="fb-rmtree-container"><a class="fb-rmtree confirm_unencode_and_post fb-default-rm" alt="Are you sure you want to delete ${display_name} and its contents?" href="${reverse_with_get('filebrowser.views.rmtree', get=dict(path=path,next=current_request_path))}"">Delete</a></li>
-                  % else:
-                    <li><a class="fb-viewfile" href="${url('filebrowser.views.view', path=urlencode(path))}" target="FileViewer">View File</a></li>
-                    <li><a class="fb-editfile" href="${url('filebrowser.views.edit', path=urlencode(path))}" target="FileEditor">Edit File</a></li>
-                    <li><a class="fb-downloadfile" href="${url('filebrowser.views.download', path=urlencode(path))}" target="_blank">Download File</a></li>
-                    <li class="fb-rm-container"><a class="fb-rm fb-default-rm confirm_unencode_and_post" alt="Are you sure you want to delete ${display_name}?" href="${reverse_with_get('filebrowser.views.remove', get=dict(path=path, next=current_request_path))}">Delete</a></li>
-                  % endif
-                  <li class="fb-rename-container"><a class="fb-rename" href="${reverse_with_get('filebrowser.views.rename',get=dict(src_path=path,next=current_request_path))}">Rename</a></li>
-                  <li class="fb-chown-container"><a class="fb-chown" href="${reverse_with_get('filebrowser.views.chown',get=dict(path=path,user=file['stats']['user'],group=file['stats']['group'],next=current_request_path))}">Change Owner / Group</a></li>
-                  <li class="fb-chmod-container"><a class="fb-chmod" href="${reverse_with_get('filebrowser.views.chmod',get=dict(path=path,mode=stringformat(file['stats']['mode'], "o"),next=current_request_path))}">Change Permissions</a></li>
-                  <%
-                    if "dir" == file['type']:
-                      cls = "fb-move-dir"
-                    else:
-                      cls = "fb-move-file"
-                  %>
-                  <li><a class="fb-move ${cls}" href="${reverse_with_get('filebrowser.views.move',get=dict(src_path=path,mode=stringformat(file['stats']['mode'], "o"),next=current_request_path))}">Move</a></li>
-              </ul>
+                <h5><a ${optional_fit_text | n} href="${url('filebrowser.views.'+view, path=urlencode(path))}?file_filter=${file_filter}">${display_name}</a></h5>
               % endif
+
             </div>
           </td>
           <%
@@ -114,24 +108,368 @@ from desktop.lib.django_util import reverse_with_get
             else:
               sortValue = file['stats']['size']
           %>
-          <td class="fb-filesize">
+          <td>
             % if "dir" == file['type']:
-              <span data-sort-numeric="${sortValue}">~</span>
+              <span>~</span>
             % else:
-              <span data-sort-numeric="${sortValue}">${file['stats']['size']|filesizeformat}</span>
+              <span>${file['stats']['size']|filesizeformat}</span>
             % endif
           </td>
-          <td class="fb-user">${file['stats']['user']}</td>
-          <td class="fb-group">${file['stats']['group']}</td>
-          <td class="fb-perm">${file['rwx']}</td>
-          <td class="fb-date"><span data-sort-numeric="${file['stats']['mtime']}">${date(datetime.datetime.fromtimestamp(file['stats']['mtime']))} ${time(datetime.datetime.fromtimestamp(file['stats']['mtime']))}</span></td>
-          <td class="fb-option-links">
-            % if ".." != file['name']:
-              <a class="fb-item-options">options</a>
-            % endif
+          <td>${file['stats']['user']}</td>
+          <td>${file['stats']['group']}</td>
+          <td>${file['rwx']}</td>
+          <td><span>${date(datetime.datetime.fromtimestamp(file['stats']['mtime']))} ${time(datetime.datetime.fromtimestamp(file['stats']['mtime']))}</span></td>
+          <td>
+             % if ".." != file['name']:
+				<%
+				m = hashlib.md5()
+				m.update(path)
+				%>
+				<a class="btn small contextEnabler" data-menuid="${urlencode(m.hexdigest())}">Options</a>
+				<ul class="contextMenu" id="menu${urlencode(m.hexdigest())}">
+                % if "dir" == file['type']:
+                  <li><a class="contextItem delete" delete-type="rmdir" file-to-delete="${path}" data-backdrop="static" data-keyboard="true">Delete</a></li>
+                  <li><a class="contextItem delete" delete-type="rmtree" file-to-delete="${path}" data-backdrop="static" data-keyboard="true">Delete Recursively</a></li>
+                % else:
+                  <li><a class="contextItem delete" delete-type="remove" file-to-delete="${path}" data-backdrop="static" data-keyboard="true">Delete</a></li>
+                  <li><a class="contextItem" href="${url('filebrowser.views.view', path=urlencode(path))}">View File</a></li>
+                  <li><a class="contextItem" href="${url('filebrowser.views.edit', path=urlencode(path))}">Edit File</a></li>
+                  <li><a class="contextItem" href="${url('filebrowser.views.download', path=urlencode(path))}" target="_blank">Download File</a></li>
+
+                % endif
+                <li><a class="contextItem rename" file-to-rename="${path}">Rename</a></li>
+                <li><a class="contextItem" onclick="openChownWindow('${path}','${file['stats']['user']}','${file['stats']['group']}','${current_request_path}')">Change Owner / Group</a></li>
+
+                <li><a class="contextItem" onclick="openChmodWindow('${path}','${stringformat(file['stats']['mode'], "o")}','${current_request_path}')">Change Permissions</a></li>
+                <li><a class="contextItem" onclick="openMoveModal('${path}','${stringformat(file['stats']['mode'], "o")}', '${current_request_path}')">Move</a></li>
+				</ul>
+              % endif
           </td>
         </tr>
       % endfor
     </tbody>
   </table>
+
+<!-- delete modal -->
+<div id="deleteModal" class="modal hide fade">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3>Please Confirm</h3>
+    </div>
+    <div class="modal-body">
+        <p>Are you sure you want to delete this file?</p>
+    </div>
+    <div class="modal-footer">
+        <form id="deleteForm" action="" method="POST" enctype="multipart/form-data" class="form-stacked">
+			<input type="submit" value="Yes" class="btn primary" />
+			<a id="cancelDeleteBtn" class="btn">No</a>
+        	<input id="fileToDeleteInput" type="hidden" name="path" />
+        </form>
+    </div>
+</div>
+
+<!-- rename modal -->
+<div id="renameModal" class="modal hide fade">
+    <form id="renameForm" action="/filebrowser/rename?next=${current_request_path}" method="POST" enctype="multipart/form-data" class="form-stacked form-padding-fix">
+    <div class="modal-header">
+        <a href="#" class="close">&times;</a>
+        <h3>Renaming: <span id="renameFileName">file name</span></h3>
+    </div>
+    <div class="modal-body">
+        <div class="clearfix">
+            <label>New name</label>
+            <div class="input">
+                <input id="newNameInput" name="dest_path" value="" type="text" class="xlarge"/>
+            </div>
+        </div>
+    </div>
+    <div class="modal-footer">
+        <div id="renameNameRequiredAlert" class="alert-message error hide" style="position: absolute; left: 10;">
+            <p><strong>Sorry, name is required.</strong>
+        </div>
+
+        <input id="renameSrcPath" type="hidden" name="src_path" type="text">
+        <input type="submit" value="Submit" class="btn primary" />
+        <a id="cancelRenameBtn" class="btn">Cancel</a>
+    </div>
+    </form>
+</div>
+
+<!-- upload modal -->
+<div id="uploadModal" class="modal hide fade">
+    <form id="uploadForm" action="/filebrowser/rename?next=${current_request_path}" method="POST" enctype="multipart/form-data" class="form-stacked form-padding-fix">
+    <div class="modal-header">
+        <a href="#" class="close">&times;</a>
+        <h3>Uploading to: <span id="uploadDirName">${current_dir_path}</span></h3>
+    </div>
+    <div class="modal-body">
+        <form action="/filebrowser/upload?next=${current_dir_path}" method="POST" enctype="multipart/form-data" class="form-stacked">
+			<div id="fileUploader">
+		<noscript>
+			<p>Please enable JavaScript to use file uploader.</p>
+			<!-- or put a simple form for upload here -->
+		</noscript>
+	</div>
+        </form>
+
+    </div>
+    <div class="modal-footer">
+
+    </div>
+    </form>
+</div>
+
+
+<!-- create directory modal -->
+<div id="createDirectoryModal" class="modal hide fade">
+    <form id="createDirectoryForm" action="/filebrowser/mkdir?next=${current_request_path}" method="POST" enctype="multipart/form-data" class="form-stacked form-padding-fix">
+    <div class="modal-header">
+        <a href="#" class="close">&times;</a>
+        <h3>Create Directory</h3>
+    </div>
+    <div class="modal-body">
+        <div class="clearfix">
+            <label>Directory Name</label>
+            <div class="input">
+                <input id="newDirectoryNameInput" name="name" value="" type="text" class="xlarge"/>
+                <input type="hidden" name="path" type="text" value="${current_dir_path}"/>
+            </div>
+        </div>
+
+    </div>
+    <div class="modal-footer">
+         <div id="directoryNameRequiredAlert" class="alert-message error hide" style="position: absolute; left: 10;">
+            <p><strong>Sorry, directory name is required.</strong>
+        </div>
+        <input class="btn primary" type="submit" value="Submit" />
+        <a id="cancelCreateDirectoryBtn" class="btn" href="#">Cancel</a>
+    </div>
+    </form>
+</div>
+
+
+<div id="changeOwnerModal" class="modal hide fade">
+</div>
+
+<div id="changePermissionModal" class="modal hide fade">
+</div>
+
+<div id="moveModal" class="modal hide fade">
+</div>
+
+<script type="text/javascript" charset="utf-8">
+    // ajax modal windows
+    function openChownWindow(path, user, group, next){
+        $.ajax({
+            url: "/filebrowser/chown",
+            data: {"path":path, "user":user, "group" : group, "next" : next},
+            beforeSend: function(xhr){
+                xhr.setRequestHeader("X-Requested-With", "Hue");
+            },
+            dataType: "html",
+            success: function(data){
+                $("#changeOwnerModal").html(data);
+                $("#changeOwnerModal").modal({
+					backdrop: "static",
+					keyboard: true,
+					show: true
+				});
+            }
+        });
+    }
+
+    function openChmodWindow(path, mode, next){
+
+        $.ajax({
+            url: "/filebrowser/chmod",
+            data: {"path":path, "mode":mode, "next" : next},
+            beforeSend: function(xhr){
+                xhr.setRequestHeader("X-Requested-With", "Hue");
+            },
+            dataType: "html",
+            success: function(data){
+                $("#changePermissionModal").html(data);
+                $("#changePermissionModal").modal({
+					backdrop: "static",
+					keyboard: true,
+					show: true
+				});
+            }
+        });
+    }
+
+    function openMoveModal(src_path, mode, next){
+
+        $.ajax({
+            url: "/filebrowser/move",
+            data: {"src_path":src_path, "mode":mode, "next" : next},
+            beforeSend: function(xhr){
+                xhr.setRequestHeader("X-Requested-With", "Hue");
+            },
+            dataType: "html",
+            success: function(data){
+                $("#moveModal").html(data);
+                $("#moveModal").modal({
+					backdrop: "static",
+					keyboard: true,
+					show: true
+				});
+            }
+        });
+    }
+    //uploader
+    var num_of_pending_uploads = 0;
+    function createUploader(){
+        var uploader = new qq.FileUploader({
+            element: document.getElementById("fileUploader"),
+            action: "/filebrowser/upload",
+            params:{
+                dest: "${current_dir_path}",
+                fileFieldLabel: "hdfs_file"
+            },
+            onComplete:function(id, fileName, responseJSON){
+                num_of_pending_uploads--;
+                if(num_of_pending_uploads == 0){
+                    window.location = "/filebrowser/view${current_dir_path}";
+                }
+            },
+            onSubmit:function(id, fileName, responseJSON){
+                num_of_pending_uploads++;
+            },
+            debug: true
+        });
+    }
+
+    // in your app create uploader as soon as the DOM is ready
+    // don"t wait for the window to load
+    window.onload = createUploader;
+
+	$(document).ready(function(){
+		$(".datatables").dataTable({
+			"bPaginate": false,
+		    "bLengthChange": false,
+		    "bFilter": false,
+			"bInfo": false
+		});
+	});
+
+    //delete handlers
+    $(".delete").live("click", function(e){
+        $("#fileToDeleteInput").attr("value", $(e.target).attr("file-to-delete"));
+        $("#deleteForm").attr("action", "/filebrowser/" + $(e.target).attr("delete-type") + "?next=" + encodeURI("${current_request_path}") + "&path=" + encodeURI("${path}"));
+        $("#deleteModal").modal({
+			backdrop: "static",
+			keyboard: true,
+			show: true
+		});
+    });
+
+    $("#cancelDeleteBtn").click(function(){
+        $("#deleteModal").modal("hide");
+    });
+
+    //rename handlers
+    $(".rename").live("click",function(eventObject){
+        $("#renameSrcPath").attr("value", $(eventObject.target).attr("file-to-rename"));
+        $("#renameFileName").text($(eventObject.target).attr("file-to-rename"));
+        $("#renameModal").modal({
+			backdrop: "static",
+			keyboard: true,
+			show: true
+		});
+    });
+
+    $("#cancelRenameBtn").click(function(){
+        $("#renameModal").modal("hide");
+    });
+
+    $("#renameForm").submit(function(){
+        if($("#newNameInput").val() == ""){
+            $("#renameNameRequiredAlert").show();
+			$("#newNameInput").addClass("fieldError");
+            return false;
+        }
+    });
+
+	$("#newNameInput").focus(function(){
+		$("#renameNameRequiredAlert").hide();
+		$("#newNameInput").removeClass("fieldError");
+	});
+	
+	$("#moveForm").live("submit", function(){
+		console.log("submit");
+		if ($.trim($("#moveForm").find("input[name='dest_path']").val()) == ""){
+			$("#moveNameRequiredAlert").show();
+			$("#moveForm").find("input[name='dest_path']").addClass("fieldError");
+			return false;
+		}
+		return true;
+	});
+	
+	$("#moveForm").find("input[name='dest_path']").live("focus", function(){
+		$("#moveNameRequiredAlert").hide();
+		$("#moveForm").find("input[name='dest_path']").removeClass("fieldError");
+	});
+	
+
+    //upload handlers
+    $(".upload-link").click(function(){
+        $("#uploadModal").modal({
+			backdrop: "static",
+			keyboard: true,
+			show: true
+		});
+    });
+
+    //create directory handlers
+    $(".create-directory-link").click(function(){
+        $("#createDirectoryModal").modal({
+			backdrop: "static",
+			keyboard: true,
+			show: true
+		});
+    });
+    $("#cancelCreateDirectoryBtn").click(function(){
+        $("#createDirectoryModal").modal("hide");
+    });
+    $("#createDirectoryForm").submit(function(){
+		if ($.trim($("#newDirectoryNameInput").val())==""){
+			$("#directoryNameRequiredAlert").show();
+			$("#newDirectoryNameInput").addClass("fieldError");
+			return false;
+		}
+		return true;
+    });
+	$("#newDirectoryNameInput").focus(function(){
+		$("#newDirectoryNameInput").removeClass("fieldError");
+		$("#directoryNameRequiredAlert").hide();
+	});
+	
+
+    //filter handlers
+    $("#filterInput").keyup(function(){
+        $.each($(".file-row"), function(index, value) {
+
+          if($(value).attr("file-name").toLowerCase().indexOf($("#filterInput").val().toLowerCase()) == -1 && $("#filterInput").val() != ""){
+            $(value).hide(250);
+          }else{
+            $(value).show(250);
+          }
+        });
+
+    });
+
+    $("#clearFilterBtn").click(function(){
+        $("#filterInput").val("");
+        $.each($(".file-row"), function(index, value) {
+            $(value).show(250);
+        });
+    });
+
+	$(".contextEnabler").jHueContextMenu();
+
+
+
+</script>
+
 </%def>

+ 14 - 14
apps/filebrowser/src/filebrowser/templates/mkdir.mako

@@ -14,22 +14,22 @@
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
 <%namespace name="edit" file="editor_components.mako" />
-<%namespace name="comps" file="fb_components.mako" />
-${comps.header('Create Directory')}
+<%namespace name="wrappers" file="header_footer.mako" />
+${wrappers.head('Create Directory', 'new directory', show_upload=False, show_side_bar=False)}
 
+<div class="well">
 
-<div class="prompt_popup">
-<form action="/filebrowser/mkdir?next=${next|u}" method="POST" enctype="multipart/form-data">
-  <h4 class="jframe-hidden">Create Directory}</h4>
-  <dl>
-    ${edit.render_field(form["path"], hidden=True)}
-    ${edit.render_field(form["name"])}
-  </dl>
-  <input class="jframe-hidden" type="submit" value="Submit" />
-</form>
-</div>
+    <form action="/filebrowser/mkdir?next=${next|u}" method="POST" enctype="multipart/form-data" class="form-stacked">
+        <h1>Create Directory</h1>
+        ${edit.render_field(form["name"])}
+        ${edit.render_field(form["path"], hidden=True)}
 
-<div class="jframe-hidden">Go back to where you were: <a href="${next|u}">${next}</a>.</div>
+        <input class="btn primary" type="submit" value="Submit" />
+        <a class="btn" href="${next|u}">Cancel</a>
+        
+    </form>
+</div>
+<!--<div class="jframe-hidden">Go back to where you were: <a href="${next|u}">${next}</a>.</div>-->
 
 
-${comps.footer()}
+${wrappers.foot()}

+ 19 - 18
apps/filebrowser/src/filebrowser/templates/move.mako

@@ -14,22 +14,23 @@
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
 <%namespace name="edit" file="editor_components.mako" />
-<%namespace name="comps" file="fb_components.mako" />
-${comps.header('Move: ' + src_path.split('/')[-1])}
 
-
-<div class="prompt_popup">
-<form action="/filebrowser/move?next=${next|u}" method="POST" enctype="multipart/form-data">
-  <h4 class="jframe-hidden">Move: ${src_path}</h4>
-  <dl>
-    ${edit.render_field(form["src_path"], hidden=True)}
-    ${edit.render_field(form["dest_path"], notitle=True)}
-  </dl>
-  <input class="jframe-hidden" type="submit" value="Submit" />
-</form>
-</div>
-
-<div class="jframe-hidden">Go back to where you were: <a href="${next|u}">${next}</a>.</div>
-
-
-${comps.footer()}
+<form id="moveForm" action="/filebrowser/move?next=${next|u}" method="POST" enctype="multipart/form-data" class="form-stacked form-padding-fix">
+    <div class="modal-header">
+        <a href="#" class="close">&times;</a>
+        <h3>Move: ${src_path}</h3>
+    </div>
+    <div class="change-owner-modal-body clearfix" >
+        <div style="padding-left: 15px;">
+        ${edit.render_field(form["src_path"], hidden=True)}
+        ${edit.render_field(form["dest_path"], notitle=True, klass="xlarge")}
+        </div>
+    </div>
+    <div class="modal-footer">
+		<div id="moveNameRequiredAlert" class="alert-message error hide" style="position: absolute; left: 10;">
+        	<p><strong>Sorry, name is required.</strong>
+    	</div>
+        <input class="btn primary" type="submit" value="Submit"/>
+        <a class="btn" onclick="$('#moveModal').modal('hide');">Cancel</a>
+    </div>
+</form>

+ 14 - 14
apps/filebrowser/src/filebrowser/templates/rename.mako

@@ -14,22 +14,22 @@
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
 <%namespace name="edit" file="editor_components.mako" />
-<%namespace name="comps" file="fb_components.mako" />
-${comps.header('Rename: ' + src_path.split('/')[-1])}
+<%namespace name="wrappers" file="header_footer.mako" />
+${wrappers.head('Rename: ' + src_path.split('/')[-1], show_side_bar=False)}
 
 
-<div class="prompt_popup">
-<form action="/filebrowser/rename?next=${next|u}" method="POST" enctype="multipart/form-data">
-  <h4 class="jframe-hidden">Renaming: ${src_path}</h4>
-  <dl>
-    ${edit.render_field(form["src_path"], hidden=True)}
-    ${edit.render_field(form["dest_path"], notitle=True)}
-  </dl>
-  <input class="jframe-hidden" type="submit" value="Submit" />
-</form>
-</div>
 
-<div class="jframe-hidden">Go back to where you were: <a href="${next|u}">${next}</a>.</div>
+  <div class="well">
+      <form action="/filebrowser/rename?next=${next|u}" method="POST" enctype="multipart/form-data" class="form-stacked">
+      <h1>Renaming: ${src_path}</h1>
 
+    ${edit.render_field(form["src_path"], hidden=True)}
+    ${edit.render_field(form["dest_path"], notitle=True)}
+      <div>
+        <input class="btn primary" type="submit" value="Submit" />
+        <a class="btn" href="${next|u}">Cancel</a>
+      </div>
+     </form>
+  </div>
 
-${comps.footer()}
+${wrappers.foot()}

+ 41 - 14
apps/filebrowser/src/filebrowser/templates/upload.mako

@@ -14,21 +14,48 @@
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
 <%namespace name="edit" file="editor_components.mako" />
-<%namespace name="comps" file="fb_components.mako" />
-${comps.header('Upload Files')}
+<%namespace name="wrappers" file="header_footer.mako" />
+${wrappers.head('Upload Files', 'upload', show_new_directory=False, show_side_bar=False)}
+<script src="/static/ext/js/fileuploader.js" type="text/javascript" charset="utf-8"></script>
+<link rel="stylesheet" href="/static/ext/css/fileuploader.css" type="text/css" media="screen" title="no title" charset="utf-8" />        
 
-<div class="prompt_popup">
-<form action="/filebrowser/upload?next=${next|u}" method="POST" enctype="multipart/form-data">
-  <h4 class="jframe-hidden">Upload Files</h4>
-  <dl>
-    ${edit.render_field(form["dest"], hidden=True)}
-    ${edit.render_field(form["hdfs_file"], render_default=True, notitle=True)}
-  </dl>
-  <input class="jframe-hidden" type="submit" value="Submit" />
-</form>
-</div>
 
-<div class="jframe-hidden">Go back to where you were: <a href="${next|u}">${next}</a>.</div>
 
 
-${comps.footer()}
+
+      <div class="well">
+          <form action="/filebrowser/upload?next=${next|u}" method="POST" enctype="multipart/form-data" class="form-stacked">
+          <h1>Upload Files</h1>
+         <div id="file-uploader">
+		<noscript>
+			<p>Please enable JavaScript to use file uploader.</p>
+			<!-- or put a simple form for upload here -->
+		</noscript>
+	</div>
+        </form>
+      </div>
+
+    <!--<span class="alert-message block-message info">Go back to where you were: <a href="/filebrowser/view${next}">${next}</a>.</span>-->
+
+ <script>
+        function createUploader(){
+            var uploader = new qq.FileUploader({
+                element: document.getElementById('file-uploader'),
+                action: '/filebrowser/upload',
+                params:{
+                    dest: '${next}',
+                    fileFieldLabel: 'hdfs_file'
+                },
+                onComplete:function(id, fileName, responseJSON){
+                    window.location = "/filebrowser/view${next}";
+                },
+                debug: true
+            });
+        }
+
+        // in your app create uploader as soon as the DOM is ready
+        // don't wait for the window to load
+        window.onload = createUploader;
+    </script>            
+
+${wrappers.foot()}

+ 3 - 5
apps/filebrowser/src/filebrowser/templates/upload_done.mako

@@ -17,11 +17,9 @@
 import datetime
 from django.template.defaultfilters import urlencode
 %>
-<html>
-<head><title>${path} - Upload Complete</title></head>
-<body>
+<%namespace name="wrappers" file="header_footer.mako" />
+${wrappers.head('${path} - Upload Complete', 'upload', show_new_directory=False)}
 <% path_enc = urlencode(path) %>
 View uploaded file: <a href="${url('filebrowser.views.view', path=path_enc)}">${path}</a>.<br>
 Go back to where you were: <a href="${next|urlencode}">${next}</a>.
-</body>
-</html>
+${wrappers.foot()}

+ 727 - 658
apps/filebrowser/src/filebrowser/views.py

@@ -39,19 +39,18 @@ from gzip import GzipFile
 from avro import datafile, io
 
 from desktop.lib import i18n
-from desktop.lib.django_util import make_absolute, render_json
+from desktop.lib.django_util import make_absolute, render, render_json
 from desktop.lib.django_util import PopupException, format_preserving_redirect
 from filebrowser.lib.rwx import filetype, rwx
 from filebrowser.lib import xxd
-from filebrowser.forms import RenameForm, UploadForm, MkDirForm, RmDirForm, RmTreeForm, \
+from filebrowser.forms import RenameForm, UploadForm, MkDirForm, RmDirForm, RmTreeForm,\
     RemoveForm, ChmodForm, ChownForm, EditorForm
 from hadoop.fs import normpath
-from filebrowser.plugin.views import render_with_toolbars
 
 
-DEFAULT_CHUNK_SIZE_BYTES = 1024*4 # 4KB
-MAX_CHUNK_SIZE_BYTES = 1024*1024 # 1MB
-DOWNLOAD_CHUNK_SIZE = 32*1024 # 32KB
+DEFAULT_CHUNK_SIZE_BYTES = 1024 * 4 # 4KB
+MAX_CHUNK_SIZE_BYTES = 1024 * 1024 # 1MB
+DOWNLOAD_CHUNK_SIZE = 32 * 1024 # 32KB
 
 # Defaults for "xxd"-style output.
 # Sentences refer to groups of bytes printed together, within a line.
@@ -59,749 +58,819 @@ BYTES_PER_LINE = 16
 BYTES_PER_SENTENCE = 2
 
 # The maximum size the file editor will allow you to edit
-MAX_FILEEDITOR_SIZE = 256*1024
+MAX_FILEEDITOR_SIZE = 256 * 1024
 
 logger = logging.getLogger(__name__)
 
 def _unquote_path(path):
-  """Normalizes paths."""
-  return urllib.unquote(path)
+    """Normalizes paths."""
+    return urllib.unquote(path)
+
 
 def _file_reader(fh):
-  """Generator that reads a file, chunk-by-chunk."""
-  while True:
-    chunk = fh.read(DOWNLOAD_CHUNK_SIZE)
-    if chunk == '':
-      fh.close()
-      break
-    yield chunk
+    """Generator that reads a file, chunk-by-chunk."""
+    while True:
+        chunk = fh.read(DOWNLOAD_CHUNK_SIZE)
+        if chunk == '':
+            fh.close()
+            break
+        yield chunk
+
 
 def download(request, path):
-  """
-  Downloads a file.
-
-  This is inspired by django.views.static.serve.
-  """
-  path = _unquote_path(path)
-  if not request.fs.exists(path):
-    raise Http404("File not found: %s" % escape(path))
-  if not request.fs.isfile(path):
-    raise PopupException("'%s' is not a file" % (path,))
-
-  mimetype = mimetypes.guess_type(path)[0] or 'application/octet-stream'
-  stats = request.fs.stats(path)
-  mtime = stats['mtime']
-  size = stats['size']
-  if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), mtime, size):
-    return HttpResponseNotModified()
-  # TODO(philip): Ideally a with statement would protect from leaks,
-  # but tricky to do here.
-  fh = request.fs.open(path)
-
-  response = HttpResponse(_file_reader(fh), mimetype=mimetype)
-  response["Last-Modified"] = http_date(stats['mtime'])
-  response["Content-Length"] = stats['size']
-  response["Content-Disposition"] = "attachment"
-  return response
+    """
+    Downloads a file.
+
+    This is inspired by django.views.static.serve.
+    """
+    path = _unquote_path(path)
+    if not request.fs.exists(path):
+        raise Http404("File not found: %s" % escape(path))
+    if not request.fs.isfile(path):
+        raise PopupException("'%s' is not a file" % (path,))
+
+    mimetype = mimetypes.guess_type(path)[0] or 'application/octet-stream'
+    stats = request.fs.stats(path)
+    mtime = stats['mtime']
+    size = stats['size']
+    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), mtime, size):
+        return HttpResponseNotModified()
+        # TODO(philip): Ideally a with statement would protect from leaks,
+    # but tricky to do here.
+    fh = request.fs.open(path)
 
-def view(request, path):
-  """Dispatches viewing of a path to either index() or fileview(), depending on type."""
+    response = HttpResponse(_file_reader(fh), mimetype=mimetype)
+    response["Last-Modified"] = http_date(stats['mtime'])
+    response["Content-Length"] = stats['size']
+    response["Content-Disposition"] = "attachment"
+    return response
 
-  # default_to_home is set in bootstrap.js
-  home_dir_path = request.user.get_home_directory()
-  if request.GET.get('default_to_home') and request.fs.isdir(home_dir_path):
-    return format_preserving_redirect(request, urlresolvers.reverse(view, kwargs=dict(path=home_dir_path)))
 
-  if request.fs.isdir(path):
-    return listdir(request, path)
-  elif request.fs.isfile(path):
-    return display(request, path)
-  else:
-    raise Http404("File not found: %s" % escape(path))
+def view(request, path):
+    """Dispatches viewing of a path to either index() or fileview(), depending on type."""
 
-def edit(request, path, form=None):
-  """Shows an edit form for the given path. Path does not necessarily have to exist."""
+    # default_to_home is set in bootstrap.js
+    home_dir_path = request.user.get_home_directory()
+    if request.GET.get('default_to_home') and request.fs.isdir(home_dir_path):
+        return format_preserving_redirect(request, urlresolvers.reverse(view, kwargs=dict(path=home_dir_path)))
 
-  try:
-    stats = request.fs.stats(path)
-  except IOError, ioe:
-    # A file not found is OK, otherwise re-raise
-    if ioe.errno == errno.ENOENT:
-      stats = None
+    if request.fs.isdir(path):
+        return listdir(request, path, False)
+    elif request.fs.isfile(path):
+        return display(request, path)
     else:
-      raise
+        raise Http404("File not found: %s" % escape(path))
 
-  # Can't edit a directory
-  if stats and stats['mode'] & stat_module.S_IFDIR:
-    raise PopupException("Cannot edit a directory: %s" % (path,))
 
-  # Maximum size of edit
-  if stats and stats['size'] > MAX_FILEEDITOR_SIZE:
-    raise PopupException("File too big to edit: %s" % (path,))
+def edit(request, path, form=None):
+    """Shows an edit form for the given path. Path does not necessarily have to exist."""
 
-  if not form:
-    encoding = request.REQUEST.get('encoding') or i18n.get_site_encoding()
-    if stats:
-      f = request.fs.open(path)
-      try:
-        try:
-          current_contents = unicode(f.read(), encoding)
-        except UnicodeDecodeError:
-          raise PopupException("File is not encoded in %s; cannot be edited: %s" % (encoding, path))
-      finally:
-        f.close()
-    else:
-      current_contents = u""
+    try:
+        stats = request.fs.stats(path)
+    except IOError, ioe:
+        # A file not found is OK, otherwise re-raise
+        if ioe.errno == errno.ENOENT:
+            stats = None
+        else:
+            raise
+
+    # Can't edit a directory
+    if stats and stats['mode'] & stat_module.S_IFDIR:
+        raise PopupException("Cannot edit a directory: %s" % (path,))
+
+    # Maximum size of edit
+    if stats and stats['size'] > MAX_FILEEDITOR_SIZE:
+        raise PopupException("File too big to edit: %s" % (path,))
+
+    if not form:
+        encoding = request.REQUEST.get('encoding') or i18n.get_site_encoding()
+        if stats:
+            f = request.fs.open(path)
+            try:
+                try:
+                    current_contents = unicode(f.read(), encoding)
+                except UnicodeDecodeError:
+                    raise PopupException("File is not encoded in %s; cannot be edited: %s" % (encoding, path))
+            finally:
+                f.close()
+        else:
+            current_contents = u""
 
-    form = EditorForm(dict(path=path, contents=current_contents, encoding=encoding))
+        form = EditorForm(dict(path=path, contents=current_contents, encoding=encoding))
 
-  data = dict(
-    exists=(stats is not None),
-    form=form,
-    path=path,
-    filename=os.path.basename(path),
-    dirname=os.path.dirname(path))
-  return render_with_toolbars("edit.mako", request, data)
+    data = dict(
+        exists=(stats is not None),
+        form=form,
+        path=path,
+        filename=os.path.basename(path),
+        dirname=os.path.dirname(path))
+    return render("edit.mako", request, data)
 
-def save_file(request):
-  """
-  The POST endpoint to save a file in the file editor.
 
-  Does the save and then redirects back to the edit page.
-  """
-  form = EditorForm(request.POST)
-  is_valid = form.is_valid()
-  path = form.cleaned_data.get('path')
+def save_file(request):
+    """
+    The POST endpoint to save a file in the file editor.
+
+    Does the save and then redirects back to the edit page.
+    """
+    form = EditorForm(request.POST)
+    is_valid = form.is_valid()
+    path = form.cleaned_data.get('path')
+
+    if request.POST.get('save') == "Save As":
+        if not is_valid:
+            return edit(request, path, form=form)
+        else:
+            data = dict(form=form)
+            return render("saveas.mako", request, data)
 
-  if request.POST.get('save') == "saveAs":
+    if not path:
+        raise PopupException("No path specified")
     if not is_valid:
-      return edit(request, path, form=form)
+        return edit(request, path, form=form)
+
+    if request.fs.exists(path):
+        _do_overwrite_save(request.fs, path,
+                           form.cleaned_data['contents'],
+                           form.cleaned_data['encoding'])
     else:
-      data = dict(form = form)
-      return render_with_toolbars("saveas.mako", request, data)
-
-  if not path:
-    raise PopupException("No path specified")
-  if not is_valid:
-    return edit(request, path, form=form)
-
-  if request.fs.exists(path):
-    _do_overwrite_save(request.fs, path,
-                       form.cleaned_data['contents'],
-                       form.cleaned_data['encoding'])
-  else:
-    _do_newfile_save(request.fs, path,
-                     form.cleaned_data['contents'],
-                     form.cleaned_data['encoding'])
-
-  request.flash.put('Saved %s.' % os.path.basename(path))
-  """ Changing path to reflect the request path of the JFrame that will actually be returned."""
-  request.path = urlresolvers.reverse("filebrowser.views.edit", kwargs=dict(path=path))
-  return edit(request, path, form)
+        _do_newfile_save(request.fs, path,
+                         form.cleaned_data['contents'],
+                         form.cleaned_data['encoding'])
+
+    request.flash.put('Saved %s.' % os.path.basename(path))
+    """ Changing path to reflect the request path of the JFrame that will actually be returned."""
+    request.path = urlresolvers.reverse("filebrowser.views.edit", kwargs=dict(path=path))
+    return edit(request, path, form)
+
 
 def _do_overwrite_save(fs, path, data, encoding):
-  """
-  Atomically (best-effort) save the specified data to the given path
-  on the filesystem.
-
-  TODO(todd) should this be in some fsutil.py?
-  """
-  # TODO(todd) Should probably do an advisory permissions check here to
-  # see if we're likely to fail (eg make sure we own the file
-  # and can write to the dir)
-
-  # First write somewhat-kinda-atomically to a staging file
-  # so that if we fail, we don't clobber the old one
-  path_dest = path + "._hue_new"
-
-  new_file = fs.open(path_dest, "w")
-  try:
+    """
+    Atomically (best-effort) save the specified data to the given path
+    on the filesystem.
+
+    TODO(todd) should this be in some fsutil.py?
+    """
+    # TODO(todd) Should probably do an advisory permissions check here to
+    # see if we're likely to fail (eg make sure we own the file
+    # and can write to the dir)
+
+    # First write somewhat-kinda-atomically to a staging file
+    # so that if we fail, we don't clobber the old one
+    path_dest = path + "._hue_new"
+
+    new_file = fs.open(path_dest, "w")
     try:
-      new_file.write(data.encode(encoding))
-      logging.info("Wrote to " + path_dest)
-    finally:
-      new_file.close()
-  except Exception, e:
-    # An error occurred in writing, we should clean up
-    # the tmp file if it exists, before re-raising
+        try:
+            new_file.write(data.encode(encoding))
+            logging.info("Wrote to " + path_dest)
+        finally:
+            new_file.close()
+    except Exception, e:
+        # An error occurred in writing, we should clean up
+        # the tmp file if it exists, before re-raising
+        try:
+            fs.remove(path_dest)
+        except:
+            pass
+        raise e
+
+    # Try to match the permissions and ownership of the old file
+    cur_stats = fs.stats(path)
     try:
-      fs.remove(path_dest)
+        fs.chmod(path_dest, cur_stats['mode'])
     except:
-      pass
-    raise e
-
-  # Try to match the permissions and ownership of the old file
-  cur_stats = fs.stats(path)
-  try:
-    fs.chmod(path_dest, cur_stats['mode'])
-  except:
-    logging.warn("Could not chmod new file %s to match old file %s" % (
-        path_dest, path), exc_info=True)
-    # but not the end of the world - keep going
-
-  try:
-    fs.chown(path_dest, cur_stats['user'], cur_stats['group'])
-  except:
-    logging.warn("Could not chown new file %s to match old file %s" % (
-        path_dest, path), exc_info=True)
-    # but not the end of the world - keep going
-
-  # Now delete the old - nothing we can do here to recover
-  fs.remove(path)
-
-  # Now move the new one into place
-  # If this fails, then we have no reason to assume
-  # we can do anything to recover, since we know the
-  # destination shouldn't already exist (we just deleted it above)
-  fs.rename(path_dest, path)
+        logging.warn("Could not chmod new file %s to match old file %s" % (
+            path_dest, path), exc_info=True)
+        # but not the end of the world - keep going
+
+    try:
+        fs.chown(path_dest, cur_stats['user'], cur_stats['group'])
+    except:
+        logging.warn("Could not chown new file %s to match old file %s" % (
+            path_dest, path), exc_info=True)
+        # but not the end of the world - keep going
+
+    # Now delete the old - nothing we can do here to recover
+    fs.remove(path)
+
+    # Now move the new one into place
+    # If this fails, then we have no reason to assume
+    # we can do anything to recover, since we know the
+    # destination shouldn't already exist (we just deleted it above)
+    fs.rename(path_dest, path)
 
 
 def _do_newfile_save(fs, path, data, encoding):
-  """
-  Save data to the path 'path' on the filesystem 'fs'.
-
-  There must not be a pre-existing file at that path.
-  """
-  new_file = fs.open(path, "w")
-  try:
-    new_file.write(data.encode(encoding))
-  finally:
-    new_file.close()
-
-
-def listdir(request, path):
-  """
-  Implements directory listing (or index).
-
-  Intended to be called via view().
-  """
-  path = _unquote_path(path)
-  if not request.fs.isdir(path):
-    raise PopupException("Not a directory: %s" % (path,))
-
-  file_filter = request.REQUEST.get('file_filter', 'any')
-
-  assert file_filter in ['any', 'file', 'dir']
-
-  home_dir_path = request.user.get_home_directory()
-  data = {
-    'path': path,
-    'file_filter': file_filter,
-    # These could also be put in automatically via
-    # http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request,
-    # but manually seems cleaner, since we only need it here.
-    'current_request_path': request.path,
-    'home_directory': request.fs.isdir(home_dir_path) and home_dir_path or None,
-    'cwd_set': True,
-    'show_upload': (request.REQUEST.get('show_upload') == 'false' and (False,) or (True,))[0]
-  }
-
-  stats = request.fs.listdir_stats(path)
-
-  # Include parent dir, unless at filesystem root.
-  if normpath(path) != posixpath.sep:
-    parent_stat = request.fs.stats(posixpath.join(path, ".."))
-    # The 'path' field would be absolute, but we want its basename to be
-    # actually '..' for display purposes. Encode it since _massage_stats expects byte strings.
-    parent_stat['path'] = posixpath.join(path, "..")
-    stats.insert(0, parent_stat)
-
-  data['files'] = [_massage_stats(request, stat) for stat in stats]
-  return render_with_toolbars('listdir.mako', request, data)
+    """
+    Save data to the path 'path' on the filesystem 'fs'.
+
+    There must not be a pre-existing file at that path.
+    """
+    new_file = fs.open(path, "w")
+    try:
+        new_file.write(data.encode(encoding))
+    finally:
+        new_file.close()
+
+
+def parse_breadcrumbs(path):
+    breadcrumbs_parts = path.split('/')
+    i = 1
+    breadcrumbs = [{'url': '', 'label': 'my home'}]
+    while (i < len(breadcrumbs_parts)):
+        breadcrumb_url = breadcrumbs[i - 1]['url'] + '/' + breadcrumbs_parts[i]
+        if breadcrumb_url != '/':
+            breadcrumbs.append({'url': breadcrumb_url, 'label': breadcrumbs_parts[i]})
+        i = i + 1
+    return breadcrumbs
+
+
+def listdir(request, path, chooser):
+    """
+    Implements directory listing (or index).
+
+    Intended to be called via view().
+    """
+    path = _unquote_path(path)
+    if not request.fs.isdir(path):
+        raise PopupException("Not a directory: %s" % (path,))
+
+    file_filter = request.REQUEST.get('file_filter', 'any')
+
+    assert file_filter in ['any', 'file', 'dir']
+
+    home_dir_path = request.user.get_home_directory()
+
+
+    breadcrumbs = parse_breadcrumbs(path)
+    
+    data = {
+        'path': path,
+        'file_filter': file_filter,
+        'breadcrumbs': breadcrumbs,
+        'current_dir_path': path,
+        # These could also be put in automatically via
+        # http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request,
+        # but manually seems cleaner, since we only need it here.
+        'current_request_path': request.path,
+        'home_directory': request.fs.isdir(home_dir_path) and home_dir_path or None,
+        'cwd_set': True,
+        'show_upload': (request.REQUEST.get('show_upload') == 'false' and (False,) or (True,))[0]
+    }
+
+    stats = request.fs.listdir_stats(path)
+
+    # Include parent dir, unless at filesystem root.
+    if normpath(path) != posixpath.sep:
+        parent_stat = request.fs.stats(posixpath.join(path, ".."))
+        # The 'path' field would be absolute, but we want its basename to be
+        # actually '..' for display purposes. Encode it since _massage_stats expects byte strings.
+        parent_stat['path'] = posixpath.join(path, "..")
+        stats.insert(0, parent_stat)
+
+    data['files'] = [_massage_stats(request, stat) for stat in stats]
+    if chooser:
+        return render('chooser.mako', request, data)
+    else:
+        return render('listdir.mako', request, data)
+
 
 def chooser(request, path):
-  """
-  Returns the html to JFrame that will display a file prompt.
-  """
-  return view(request, path)
+    """
+    Returns the html to JFrame that will display a file prompt.
+    """
+    """return view(request, path)"""
+
+    """Dispatches viewing of a path to either index() or fileview(), depending on type."""
+
+    # default_to_home is set in bootstrap.js
+    home_dir_path = request.user.get_home_directory()
+    if request.GET.get('default_to_home') and request.fs.isdir(home_dir_path):
+        return format_preserving_redirect(request, urlresolvers.reverse(view, kwargs=dict(path=home_dir_path)))
+
+    if request.fs.isdir(path):
+        return listdir(request, path, True)
+    elif request.fs.isfile(path):
+        return display(request, path)
+    else:
+        raise Http404("File not found: %s" % escape(path))
+
 
 def _massage_stats(request, stats):
-  """
-  Massage a stats record as returned by the filesystem implementation
-  into the format that the views would like it in.
-  """
-  path = stats['path']
-  normalized = normpath(path)
-  return {
-    'path': normalized,
-    'name': posixpath.basename(path),
-    'stats': stats,
-    'type': filetype(stats['mode']),
-    'rwx': rwx(stats['mode']),
-    'url': make_absolute(request, "view", dict(path=urlquote(normalized))),
-  }
+    """
+    Massage a stats record as returned by the filesystem implementation
+    into the format that the views would like it in.
+    """
+    path = stats['path']
+    normalized = normpath(path)
+    return {
+        'path': normalized,
+        'name': posixpath.basename(path),
+        'stats': stats,
+        'type': filetype(stats['mode']),
+        'rwx': rwx(stats['mode']),
+        'url': make_absolute(request, "view", dict(path=urlquote(normalized))),
+        }
+
 
 def stat(request, path):
-  """
-  Returns just the generic stats of a file.
-
-  Intended for use via AJAX (and hence doesn't provide
-  an HTML view).
-  """
-  path = _unquote_path(path)
-  if not request.fs.exists(path):
-    raise Http404("File not found: %s" % escape(path))
-  stats = request.fs.stats(path)
-  return render_json(_massage_stats(request, stats))
+    """
+    Returns just the generic stats of a file.
+
+    Intended for use via AJAX (and hence doesn't provide
+    an HTML view).
+    """
+    path = _unquote_path(path)
+    if not request.fs.exists(path):
+        raise Http404("File not found: %s" % escape(path))
+    stats = request.fs.stats(path)
+    return render_json(_massage_stats(request, stats))
+
 
 def display(request, path):
-  """
-  Implements displaying part of a file.
-
-  GET arguments are length, offset, mode, compression and encoding
-  with reasonable defaults chosen.
-
-  Note that display by length and offset are on bytes, not on characters.
-
-  TODO(philip): Could easily built-in file type detection
-  (perhaps using something similar to file(1)), as well
-  as more advanced binary-file viewing capability (de-serialize
-  sequence files, decompress gzipped text files, etc.).
-  There exists a python-magic package to interface with libmagic.
-  """
-  path = _unquote_path(path)
-  if not request.fs.isfile(path):
-    raise PopupException("Not a file: '%s'" % (path,))
-
-  stats = request.fs.stats(path)
-  encoding = request.GET.get('encoding') or i18n.get_site_encoding()
-
-  # I'm mixing URL-based parameters and traditional
-  # HTTP GET parameters, since URL-based parameters
-  # can't naturally be optional.
-
-  # Need to deal with possibility that length is not present
-  # because the offset came in via the toolbar manual byte entry.
-  end = request.GET.get("end")
-  if end:
-    end = int(end)
-  begin = request.GET.get("begin", 1)
-  if begin:
-    # Subtract one to zero index for file read
-    begin = int(begin) - 1
-  if end:
-    offset = begin
-    length = end - begin
-    if begin >= end:
-      raise PopupException("First byte to display must be before last byte to display.")
-  else:
-    length = int(request.GET.get("length", DEFAULT_CHUNK_SIZE_BYTES))
-    # Display first block by default.
-    offset = int(request.GET.get("offset", 0))
-
-  mode = request.GET.get("mode")
-  compression = request.GET.get("compression")
-
-  if mode and mode not in ["binary", "text"]:
-    raise PopupException("Mode must be one of 'binary' or 'text'.")
-  if offset < 0:
-    raise PopupException("Offset may not be less than zero.")
-  if length < 0:
-    raise PopupException("Length may not be less than zero.")
-  if length > MAX_CHUNK_SIZE_BYTES:
-    raise PopupException("Cannot request chunks greater than %d bytes" % MAX_CHUNK_SIZE_BYTES)
-
-  # Do not decompress in binary mode.
-  if mode == 'binary':
-    compression = 'none'
-  # Read out based on meta.
-  compression, offset, length, contents = \
+    """
+    Implements displaying part of a file.
+
+    GET arguments are length, offset, mode, compression and encoding
+    with reasonable defaults chosen.
+
+    Note that display by length and offset are on bytes, not on characters.
+
+    TODO(philip): Could easily built-in file type detection
+    (perhaps using something similar to file(1)), as well
+    as more advanced binary-file viewing capability (de-serialize
+    sequence files, decompress gzipped text files, etc.).
+    There exists a python-magic package to interface with libmagic.
+    """
+    path = _unquote_path(path)
+    if not request.fs.isfile(path):
+        raise PopupException("Not a file: '%s'" % (path,))
+
+    stats = request.fs.stats(path)
+    encoding = request.GET.get('encoding') or i18n.get_site_encoding()
+
+    # I'm mixing URL-based parameters and traditional
+    # HTTP GET parameters, since URL-based parameters
+    # can't naturally be optional.
+
+    # Need to deal with possibility that length is not present
+    # because the offset came in via the toolbar manual byte entry.
+    end = request.GET.get("end")
+    if end:
+        end = int(end)
+    begin = request.GET.get("begin", 1)
+    if begin:
+        # Subtract one to zero index for file read
+        begin = int(begin) - 1
+    if end:
+        offset = begin
+        length = end - begin
+        if begin >= end:
+            raise PopupException("First byte to display must be before last byte to display.")
+    else:
+        length = int(request.GET.get("length", DEFAULT_CHUNK_SIZE_BYTES))
+        # Display first block by default.
+        offset = int(request.GET.get("offset", 0))
+
+    mode = request.GET.get("mode")
+    compression = request.GET.get("compression")
+
+    if mode and mode not in ["binary", "text"]:
+        raise PopupException("Mode must be one of 'binary' or 'text'.")
+    if offset < 0:
+        raise PopupException("Offset may not be less than zero.")
+    if length < 0:
+        raise PopupException("Length may not be less than zero.")
+    if length > MAX_CHUNK_SIZE_BYTES:
+        raise PopupException("Cannot request chunks greater than %d bytes" % MAX_CHUNK_SIZE_BYTES)
+
+    # Do not decompress in binary mode.
+    if mode == 'binary':
+        compression = 'none'
+        # Read out based on meta.
+    compression, offset, length, contents =\
     read_contents(compression, path, request.fs, offset, length)
 
-  # Get contents as string for text mode, or at least try
-  uni_contents = None
-  if not mode or mode == 'text':
-    uni_contents = unicode(contents, encoding, errors='replace')
-    is_binary = uni_contents.find(i18n.REPLACEMENT_CHAR) != -1
-    # Auto-detect mode
-    if not mode:
-      mode = is_binary and 'binary' or 'text'
-
-  # Get contents as bytes
-  if mode == "binary":
-    xxd_out = list(xxd.xxd(offset, contents, BYTES_PER_LINE, BYTES_PER_SENTENCE))
-
-  dirname = posixpath.dirname(path)
-  # Start with index-like data:
-  data = _massage_stats(request, request.fs.stats(path))
-  # And add a view structure:
-  data["success"] = True
-  data["view"] = {
-    'offset': offset,
-    'length': length,
-    'end': offset + len(contents),
-    'dirname': dirname,
-    'mode': mode,
-    'compression': compression,
-    'size': stats['size']
-  }
-  data["filename"] = os.path.basename(path)
-  data["editable"] = stats['size'] < MAX_FILEEDITOR_SIZE
-  if mode == "binary":
-    # This might be the wrong thing for ?format=json; doing the
-    # xxd'ing in javascript might be more compact, or sending a less
-    # intermediate representation...
-    logger.debug("xxd: " + str(xxd_out))
-    data['view']['xxd'] = xxd_out
-    data['view']['masked_binary_data'] =  False
-  else:
-    data['view']['contents'] = uni_contents
-    data['view']['masked_binary_data'] = is_binary
-
-  return render_with_toolbars("display.mako", request, data)
+    # Get contents as string for text mode, or at least try
+    uni_contents = None
+    if not mode or mode == 'text':
+        uni_contents = unicode(contents, encoding, errors='replace')
+        is_binary = uni_contents.find(i18n.REPLACEMENT_CHAR) != -1
+        # Auto-detect mode
+        if not mode:
+            mode = is_binary and 'binary' or 'text'
+
+    # Get contents as bytes
+    if mode == "binary":
+        xxd_out = list(xxd.xxd(offset, contents, BYTES_PER_LINE, BYTES_PER_SENTENCE))
+
+    dirname = posixpath.dirname(path)
+    # Start with index-like data:
+    data = _massage_stats(request, request.fs.stats(path))
+    # And add a view structure:
+    data["success"] = True
+    data["view"] = {
+        'offset': offset,
+        'length': length,
+        'end': offset + len(contents),
+        'dirname': dirname,
+        'mode': mode,
+        'compression': compression,
+        'size': stats['size']
+    }
+    data["filename"] = os.path.basename(path)
+    data["editable"] = stats['size'] < MAX_FILEEDITOR_SIZE
+    if mode == "binary":
+        # This might be the wrong thing for ?format=json; doing the
+        # xxd'ing in javascript might be more compact, or sending a less
+        # intermediate representation...
+        logger.debug("xxd: " + str(xxd_out))
+        data['view']['xxd'] = xxd_out
+        data['view']['masked_binary_data'] = False
+    else:
+        data['view']['contents'] = uni_contents
+        data['view']['masked_binary_data'] = is_binary
+
+    data['breadcrumbs'] = parse_breadcrumbs(path)
+
+    return render("display.mako", request, data)
+
 
 def read_contents(codec_type, path, fs, offset, length):
-  """
-  Reads contents of a passed path, by appropriately decoding the data.
-  Arguments:
-     codec_type - The type of codec to use to decode. (Auto-detected if None).
-     path - The path of the file to read.
-     fs - The FileSystem instance to use to read.
-     offset - Offset to seek to before read begins.
-     length - Amount of bytes to read after offset.
-     Returns: A tuple of codec_type, offset, length and contents read.
-  """
-  # Auto codec detection for [gzip, avro, none]
-  # Only done when codec_type is unset
-  if not codec_type:
-    if path.endswith('.gz') and detect_gzip(fs.open(path).read(2)):
-      codec_type = 'gzip'
-      offset = 0
-    elif path.endswith('.avro') and detect_avro(fs.open(path).read(3)):
-      codec_type = 'avro'
-    else:
-      codec_type = 'none'
+    """
+    Reads contents of a passed path, by appropriately decoding the data.
+    Arguments:
+       codec_type - The type of codec to use to decode. (Auto-detected if None).
+       path - The path of the file to read.
+       fs - The FileSystem instance to use to read.
+       offset - Offset to seek to before read begins.
+       length - Amount of bytes to read after offset.
+       Returns: A tuple of codec_type, offset, length and contents read.
+    """
+    # Auto codec detection for [gzip, avro, none]
+    # Only done when codec_type is unset
+    if not codec_type:
+        if path.endswith('.gz') and detect_gzip(fs.open(path).read(2)):
+            codec_type = 'gzip'
+            offset = 0
+        elif path.endswith('.avro') and detect_avro(fs.open(path).read(3)):
+            codec_type = 'avro'
+        else:
+            codec_type = 'none'
 
-  f = fs.open(path)
-  contents = ''
+    f = fs.open(path)
+    contents = ''
 
-  if codec_type == 'gzip':
-    contents = _read_gzip(fs, path, offset, length)
-  elif codec_type == 'avro':
-    contents = _read_avro(fs, path, offset, length)
-  else:
-    # for 'none' type.
-    contents = _read_simple(fs, path, offset, length)
+    if codec_type == 'gzip':
+        contents = _read_gzip(fs, path, offset, length)
+    elif codec_type == 'avro':
+        contents = _read_avro(fs, path, offset, length)
+    else:
+        # for 'none' type.
+        contents = _read_simple(fs, path, offset, length)
+
+    return (codec_type, offset, length, contents)
 
-  return (codec_type, offset, length, contents)
 
 def _read_avro(fs, path, offset, length):
-  contents = ''
-  try:
-    fhandle = fs.open(path)
+    contents = ''
     try:
-      fhandle.seek(offset)
-      data_file_reader = datafile.DataFileReader(fhandle, io.DatumReader())
-      contents_list = []
-      read_start = fhandle.tell()
-      # Iterate over the entire sought file.
-      for datum in data_file_reader:
-        read_length = fhandle.tell() - read_start
-        if read_length > length and len(contents_list) > 0:
-          break
-        else:
-          datum_str = str(datum) + "\n"
-          contents_list.append(datum_str)
-      data_file_reader.close()
-      contents = "".join(contents_list)
-    except:
-      logging.warn("Could not read avro file at %s" % path, exc_info=True)
-      raise PopupException("Failed to read Avro file")
-  finally:
-    fhandle.close()
-  return contents
+        fhandle = fs.open(path)
+        try:
+            fhandle.seek(offset)
+            data_file_reader = datafile.DataFileReader(fhandle, io.DatumReader())
+            contents_list = []
+            read_start = fhandle.tell()
+            # Iterate over the entire sought file.
+            for datum in data_file_reader:
+                read_length = fhandle.tell() - read_start
+                if read_length > length and len(contents_list) > 0:
+                    break
+                else:
+                    datum_str = str(datum) + "\n"
+                    contents_list.append(datum_str)
+            data_file_reader.close()
+            contents = "".join(contents_list)
+        except:
+            logging.warn("Could not read avro file at %s" % path, exc_info=True)
+            raise PopupException("Failed to read Avro file")
+    finally:
+        fhandle.close()
+    return contents
+
 
 def _read_gzip(fs, path, offset, length):
-  contents = ''
-  if offset and offset != 0:
-    raise PopupException("We don't support offset and gzip Compression")
-  try:
-    fhandle = fs.open(path)
+    contents = ''
+    if offset and offset != 0:
+        raise PopupException("We don't support offset and gzip Compression")
     try:
-      contents = GzipFile('', 'r', 0, StringIO(fhandle.read())).read(length)
-    except:
-      logging.warn("Could not decompress file at %s" % path, exc_info=True)
-      raise PopupException("Failed to decompress file")
-  finally:
-    fhandle.close()
-  return contents
+        fhandle = fs.open(path)
+        try:
+            contents = GzipFile('', 'r', 0, StringIO(fhandle.read())).read(length)
+        except:
+            logging.warn("Could not decompress file at %s" % path, exc_info=True)
+            raise PopupException("Failed to decompress file")
+    finally:
+        fhandle.close()
+    return contents
+
 
 def _read_simple(fs, path, offset, length):
-  contents = ''
-  try:
-    fhandle = fs.open(path)
+    contents = ''
     try:
-      fhandle.seek(offset)
-      contents = fhandle.read(length)
-    except:
-      logging.warn("Could not read file at %s" % path, exc_info=True)
-      raise PopupException("Failed to read file")
-  finally:
-    fhandle.close()
-  return contents
+        fhandle = fs.open(path)
+        try:
+            fhandle.seek(offset)
+            contents = fhandle.read(length)
+        except:
+            logging.warn("Could not read file at %s" % path, exc_info=True)
+            raise PopupException("Failed to read file")
+    finally:
+        fhandle.close()
+    return contents
+
 
 def detect_gzip(contents):
-  '''This is a silly small function which checks to see if the file is Gzip'''
-  return contents[:2] == '\x1f\x8b'
+    '''This is a silly small function which checks to see if the file is Gzip'''
+    return contents[:2] == '\x1f\x8b'
+
 
 def detect_avro(contents):
-  '''This is a silly small function which checks to see if the file is Avro'''
-  # Check if the first three bytes are 'O', 'b' and 'j'
-  return contents[:3] == '\x4F\x62\x6A'
+    '''This is a silly small function which checks to see if the file is Avro'''
+    # Check if the first three bytes are 'O', 'b' and 'j'
+    return contents[:3] == '\x4F\x62\x6A'
+
 
 def _calculate_navigation(offset, length, size):
-  """
-  List of (offset, length, string) tuples for suggested navigation through the file.
-  If offset is -1, then this option is already "selected".  (Whereas None would
-  be the natural pythonic way, Django's template syntax doesn't let us test
-  against None (since its truth value is the same as 0).)
-
-  By all means this logic ought to be in the template, but the template
-  language is too limiting.
-  """
-  if offset == 0:
-    first, prev = (-1, None, "First Block"), (-1, None, "Previous Block")
-  else:
-    first, prev = (0, length, "First Block"), (max(0, offset - length), length, "Previous Block")
-
-  if offset + length >= size:
-    next, last = (-1, None, "Next Block"), (-1, None, "Last Block")
-  else:
-    # 1-off Reasoning: if length is the same as size, you want to start at 0.
-    next, last = (offset + length, length, "Next Block"), (max(0, size - length), length, "Last Block")
-
-  return first, prev, next, last
+    """
+    List of (offset, length, string) tuples for suggested navigation through the file.
+    If offset is -1, then this option is already "selected".  (Whereas None would
+    be the natural pythonic way, Django's template syntax doesn't let us test
+    against None (since its truth value is the same as 0).)
+
+    By all means this logic ought to be in the template, but the template
+    language is too limiting.
+    """
+    if offset == 0:
+        first, prev = (-1, None, "First Block"), (-1, None, "Previous Block")
+    else:
+        first, prev = (0, length, "First Block"), (max(0, offset - length), length, "Previous Block")
+
+    if offset + length >= size:
+        next, last = (-1, None, "Next Block"), (-1, None, "Last Block")
+    else:
+        # 1-off Reasoning: if length is the same as size, you want to start at 0.
+        next, last = (offset + length, length, "Next Block"), (max(0, size - length), length, "Last Block")
+
+    return first, prev, next, last
+
 
 def generic_op(form_class, request, op, parameter_names, piggyback=None, template="fileop.mako", extra_params=None):
-  """
-  Generic implementation for several operations.
-
-  @param form_class form to instantiate
-  @param request incoming request, used for parameters
-  @param op callable with the filesystem operation
-  @param parameter_names list of form parameters that are extracted and then passed to op
-  @param piggyback list of form parameters whose file stats to look up after the operation
-  @param extra_params dictionary of extra parameters to send to the template for rendering
-  """
-  # Use next for non-ajax requests, when available.
-  next = request.GET.get("next")
-  if next is None:
-    next = request.POST.get("next")
-
-  ret = dict({
-    'next':next
-  })
-
-  if extra_params is not None:
-    ret['extra_params'] = extra_params
-
-  for p in parameter_names:
-    val = request.REQUEST.get(p)
-    if val:
-      ret[p] = val
-
-  if request.method == 'POST':
-    form = form_class(request.POST)
-    # TODO(philip): How best to do error handling?  fs will throw
-    # an arbitrary-ish exception (typically file not found or maybe permission
-    # denied), and this needs to be coaxed into an HTTP error.
-    ret['form'] = form
-    if form.is_valid():
-      args = [ form.cleaned_data[p] for p in parameter_names ]
-      op(*args)
-      if next:
-        logging.debug("Next: %s" % next)
-        # Doesn't need to be quoted: quoting is done by HttpResponseRedirect.
-        return format_preserving_redirect(request, next)
-      ret["success"] = True
-      try:
-        if piggyback:
-          piggy_path = form.cleaned_data[piggyback]
-          ret["result"] = _massage_stats(request, request.fs.stats(piggy_path))
-      except Exception, e:
-        # Hard to report these more naturally here.  These happen either
-        # because of a bug in the piggy-back code or because of a
-        # race condition.
-        logger.exception("Exception while processing piggyback data")
-        ret["result_error"] = True
-
-      return render_with_toolbars(template, request, ret)
-  else:
-    # Initial parameters may be specified with get
-    initial_values = {}
+    """
+    Generic implementation for several operations.
+
+    @param form_class form to instantiate
+    @param request incoming request, used for parameters
+    @param op callable with the filesystem operation
+    @param parameter_names list of form parameters that are extracted and then passed to op
+    @param piggyback list of form parameters whose file stats to look up after the operation
+    @param extra_params dictionary of extra parameters to send to the template for rendering
+    """
+    # Use next for non-ajax requests, when available.
+    next = request.GET.get("next")
+    if next is None:
+        next = request.POST.get("next")
+
+    ret = dict({
+        'next': next
+    })
+
+    if extra_params is not None:
+        ret['extra_params'] = extra_params
+
     for p in parameter_names:
-      val = request.GET.get(p)
-      if val:
-        initial_values[p] = val
-    form = form_class(initial=initial_values)
-    ret['form'] = form
-  return render_with_toolbars(template, request, ret)
+        val = request.REQUEST.get(p)
+        if val:
+            ret[p] = val
+
+    if request.method == 'POST':
+        form = form_class(request.POST)
+        # TODO(philip): How best to do error handling?  fs will throw
+        # an arbitrary-ish exception (typically file not found or maybe permission
+        # denied), and this needs to be coaxed into an HTTP error.
+        ret['form'] = form
+        if form.is_valid():
+            args = [form.cleaned_data[p] for p in parameter_names]
+            op(*args)
+            if next:
+                logging.debug("Next: %s" % next)
+                # Doesn't need to be quoted: quoting is done by HttpResponseRedirect.
+                return format_preserving_redirect(request, next)
+            ret["success"] = True
+            try:
+                if piggyback:
+                    piggy_path = form.cleaned_data[piggyback]
+                    ret["result"] = _massage_stats(request, request.fs.stats(piggy_path))
+            except Exception, e:
+                # Hard to report these more naturally here.  These happen either
+                # because of a bug in the piggy-back code or because of a
+                # race condition.
+                logger.exception("Exception while processing piggyback data")
+                ret["result_error"] = True
+
+            return render(template, request, ret)
+    else:
+        # Initial parameters may be specified with get
+        initial_values = {}
+        for p in parameter_names:
+            val = request.GET.get(p)
+            if val:
+                initial_values[p] = val
+        form = form_class(initial=initial_values)
+        ret['form'] = form
+    return render(template, request, ret)
+
 
 def move(request):
-  return generic_op(RenameForm, request, request.fs.rename, ["src_path", "dest_path"], None, template="move.mako")
+    return generic_op(RenameForm, request, request.fs.rename, ["src_path", "dest_path"], None, template="move.mako")
+
 
 def rename(request):
-  def smart_rename(src_path, dest_path):
-    """If dest_path doesn't have a directory specified, use same dir."""
-    if "/" not in dest_path:
-      src_dir = os.path.dirname(src_path)
-      dest_path = os.path.join(src_dir, dest_path)
-    request.fs.rename(src_path, dest_path)
-  return generic_op(RenameForm, request, smart_rename, ["src_path", "dest_path"], None, template="rename.mako")
+    def smart_rename(src_path, dest_path):
+        """If dest_path doesn't have a directory specified, use same dir."""
+        if "/" not in dest_path:
+            src_dir = os.path.dirname(src_path)
+            dest_path = os.path.join(src_dir, dest_path)
+        request.fs.rename(src_path, dest_path)
+
+    return generic_op(RenameForm, request, smart_rename, ["src_path", "dest_path"], None, template="rename.mako")
+
 
 def mkdir(request):
-  def smart_mkdir(path, name):
-    request.fs.mkdir(os.path.join(path, name))
-  return generic_op(MkDirForm, request, smart_mkdir, ["path", "name"], "path", template="mkdir.mako")
+    def smart_mkdir(path, name):
+        request.fs.mkdir(os.path.join(path, name))
+
+    return generic_op(MkDirForm, request, smart_mkdir, ["path", "name"], "path", template="mkdir.mako")
+
 
 def remove(request):
-  return generic_op(RemoveForm, request, request.fs.remove, ["path"], None)
+    return generic_op(RemoveForm, request, request.fs.remove, ["path"], None)
+
 
 def rmdir(request):
-  return generic_op(RmDirForm, request, request.fs.rmdir, ["path"], None)
+    return generic_op(RmDirForm, request, request.fs.rmdir, ["path"], None)
+
 
 def rmtree(request):
-  return generic_op(RmTreeForm, request, request.fs.rmtree, ["path"], None)
+    return generic_op(RmTreeForm, request, request.fs.rmtree, ["path"], None)
+
 
 def chmod(request):
-  # mode here is abused: on input, it's a string, but when retrieved,
-  # it's an int.
-  return generic_op(ChmodForm, request, request.fs.chmod, ["path", "mode"], "path", template="chmod.mako")
+    # mode here is abused: on input, it's a string, but when retrieved,
+    # it's an int.
+    return generic_op(ChmodForm, request, request.fs.chmod, ["path", "mode"], "path", template="chmod.mako")
+
 
 def chown(request):
-  # This is a bit clever: generic_op takes an argument (here, args), indicating
-  # which POST parameters to pick out and pass to the given function.
-  # We update that mapping based on whether or not the user selected "other".
-  args = [ "path", "user", "group" ]
-  if request.POST.get("user") == "__other__":
-    args[1] = "user_other"
-  if request.POST.get("group") == "__other__":
-    args[2] = "group_other"
-
-  return generic_op(ChownForm, request, request.fs.chown, args, "path", template="chown.mako",
-    extra_params=dict(current_user=request.user, superuser=request.fs.superuser))
+    # This is a bit clever: generic_op takes an argument (here, args), indicating
+    # which POST parameters to pick out and pass to the given function.
+    # We update that mapping based on whether or not the user selected "other".
+    args = ["path", "user", "group"]
+    if request.POST.get("user") == "__other__":
+        args[1] = "user_other"
+    if request.POST.get("group") == "__other__":
+        args[2] = "group_other"
+
+    return generic_op(ChownForm, request, request.fs.chown, args, "path", template="chown.mako",
+                      extra_params=dict(current_user=request.user, superuser=request.fs.superuser))
+
 
 def upload_flash(request):
-  """
-  Our flash uploader is bad at handling errors, so, instead
-  of using the regular exception-handling, we use a
-  special signifier.
-  """
-  try:
-    r = upload(request)
-    if r.status_code == 200:
-      return HttpResponse("{}", content_type="application/json")
-    else:
-      raise Exception("Unknown error")
-  except Exception, e:
-    return HttpResponse(simplejson.dumps(dict(error=unicode(e))),
-                        content_type="application/json")
+    """
+    Our flash uploader is bad at handling errors, so, instead
+    of using the regular exception-handling, we use a
+    special signifier.
+    """
+    try:
+        r = upload(request)
+        if r.status_code == 200:
+            return HttpResponse("{}", content_type="application/json")
+        else:
+            raise Exception("Unknown error")
+    except Exception, e:
+        return HttpResponse(simplejson.dumps(dict(error=unicode(e))),
+                            content_type="application/json")
+
 
 def upload(request):
-  """
-  A wrapper around the actual upload view function to clean up the
-  temporary file afterwards.
-  """
-  try:
-    return _upload(request)
-  finally:
-    if request.method == 'POST':
-      try:
-        upload_file = request.FILES['hdfs_file']
-        upload_file.remove()
-      except KeyError:
-        pass
+    """
+    A wrapper around the actual upload view function to clean up the
+    temporary file afterwards.
+    """
+    try:
+        return _upload(request)
+    finally:
+        if request.method == 'POST':
+            try:
+                upload_file = request.FILES['hdfs_file']
+                upload_file.remove()
+            except KeyError:
+                pass
+
 
 def _upload(request):
-  """
-  Handles file uploads. The uploaded file is stored in HDFS. We just
-  need to rename it to the right path.
-  """
-  if request.method == 'POST':
-    form = UploadForm(request.POST, request.FILES)
-    if not form.is_valid():
-      logger.error("Error in upload form: %s" % (form.errors,))
+    """
+    Handles file uploads. The uploaded file is stored in HDFS. We just
+    need to rename it to the right path.
+    """
+    if request.method == 'POST':
+        form = UploadForm(request.POST, request.FILES)
+        if not form.is_valid():
+            logger.error("Error in upload form: %s" % (form.errors,))
+        else:
+            uploaded_file = request.FILES['hdfs_file']
+            dest = form.cleaned_data["dest"]
+            if request.fs.isdir(dest):
+                assert posixpath.sep not in uploaded_file.name
+                dest = request.fs.join(dest, uploaded_file.name)
+
+            # Temp file is created by superuser. Chown the file.
+            tmp_file = uploaded_file.get_temp_path()
+            username = request.user.username
+            try:
+                try:
+                    request.fs.setuser(request.fs.superuser)
+                    request.fs.chmod(tmp_file, 0644)
+                    request.fs.chown(tmp_file, username, username)
+                except IOError, ex:
+                    msg = 'Failed to chown uploaded file ("%s") as superuser %s' %\
+                          (tmp_file, request.fs.superuser)
+                    logger.exception(msg)
+                    raise PopupException(msg, detail=str(ex))
+            finally:
+                request.fs.setuser(username)
+
+            # Move the file to where it belongs
+            try:
+                request.fs.rename(uploaded_file.get_temp_path(), dest)
+            except IOError, ex:
+                raise PopupException(
+                    'Failed to rename uploaded temporary file ("%s") to "%s": %s' %
+                    (tmp_file, dest, ex))
+
+            dest_stats = request.fs.stats(dest)
+            return render('upload_done.mako', request, {
+                # status is used by "fancy uploader"
+                'status': 1,
+                'path': dest,
+                'result': _massage_stats(request, dest_stats),
+                'next': request.GET.get("next")
+            })
     else:
-      uploaded_file = request.FILES['hdfs_file']
-      dest = form.cleaned_data["dest"]
-      if request.fs.isdir(dest):
-        assert posixpath.sep not in uploaded_file.name
-        dest = request.fs.join(dest, uploaded_file.name)
-
-      # Temp file is created by superuser. Chown the file.
-      tmp_file = uploaded_file.get_temp_path()
-      username = request.user.username
-      try:
-        try:
-          request.fs.setuser(request.fs.superuser)
-          request.fs.chmod(tmp_file, 0644)
-          request.fs.chown(tmp_file, username, username)
-        except IOError, ex:
-          msg = 'Failed to chown uploaded file ("%s") as superuser %s' % \
-                (tmp_file, request.fs.superuser)
-          logger.exception(msg)
-          raise PopupException(msg, detail=str(ex))
-      finally:
-        request.fs.setuser(username)
-
-      # Move the file to where it belongs
-      try:
-        request.fs.rename(uploaded_file.get_temp_path(), dest)
-      except IOError, ex:
-        raise PopupException(
-            'Failed to rename uploaded temporary file ("%s") to "%s": %s' %
-            (tmp_file, dest, ex))
-
-      dest_stats = request.fs.stats(dest)
-      return render_with_toolbars('upload_done.mako', request, {
-          # status is used by "fancy uploader"
-          'status': 1,
-          'path': dest,
-          'result': _massage_stats(request, dest_stats),
-          'next': request.GET.get("next")
-      })
-  else:
-    dest = request.GET.get("dest")
-    initial_values = {}
-    if dest:
-      initial_values["dest"] = dest
-    form = UploadForm(initial=initial_values)
-  return render_with_toolbars('upload.mako', request,
-                              {'form': form, 'next': request.REQUEST.get("dest")})
+        dest = request.GET.get("dest")
+        initial_values = {}
+        if dest:
+            initial_values["dest"] = dest
+        form = UploadForm(initial=initial_values)
+    return render('upload.mako', request,
+            {'form': form, 'next': request.REQUEST.get("dest")})
+
 
 def status(request):
-  status = request.fs.status()
-  data = {
-    # Beware: "messages" is special in the context browser.
-    'msgs': status.get_messages(),
-    'health': status.get_health(),
-    'datanode_report': status.get_datanode_report(),
-    'name': request.fs.name
-  }
-  return render_with_toolbars("status.mako", request, data)
+    status = request.fs.status()
+    data = {
+        # Beware: "messages" is special in the context browser.
+        'msgs': status.get_messages(),
+        'health': status.get_health(),
+        'datanode_report': status.get_datanode_report(),
+        'name': request.fs.name
+    }
+    return render("status.mako", request, data)
+
 
 def location_to_url(request, location, strict=True):
-  """
-  If possible, returns a file browser URL to the location.
-  Location is a URI, if strict is True.
-
-  Python doesn't seem to have a readily-available URI-comparison
-  library, so this is quite hacky.
-  """
-  if location is None:
-    return None
-  split_path = request.fs.urlsplit(location)
-  if strict and not split_path[1]:
-    # No netloc, not full url
-    return None
-  return urlresolvers.reverse("filebrowser.views.view", kwargs=dict(path=split_path[2]))
+    """
+    If possible, returns a file browser URL to the location.
+    Location is a URI, if strict is True.
+
+    Python doesn't seem to have a readily-available URI-comparison
+    library, so this is quite hacky.
+    """
+    if location is None:
+      return None
+    split_path = request.fs.urlsplit(location)
+    if strict and not split_path[1]:
+      # No netloc, not full url
+      return None
+    return urlresolvers.reverse("filebrowser.views.view", kwargs=dict(path=split_path[2]))
 
 def truncate(toTruncate, charsToKeep=50):
-  """
-  Returns a string truncated to 'charsToKeep' length plus ellipses.
-  """
-  if len(toTruncate) > charsToKeep:
-    truncated = toTruncate[:charsToKeep] + "..."
-    return truncated
-  else:
-    return toTruncate
+    """
+    Returns a string truncated to 'charsToKeep' length plus ellipses.
+    """
+    if len(toTruncate) > charsToKeep:
+        truncated = toTruncate[:charsToKeep] + "..."
+        return truncated
+    else:
+        return toTruncate

+ 8 - 13
apps/useradmin/src/useradmin/templates/header_footer.mako → apps/hello/src/hello/templates/hello.mako

@@ -13,18 +13,13 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%def name="head(title='Hue Users')">
-<html>
-	<head>
-		<title>${title}</title>
-	</head>
-	<body class="hue-shared">
-	<div class="toolbar">
-	  <a href="/useradmin/"><img src="/useradmin/static/art/useradmin-logo.png" width="33" height="33" alt="Hue User Admin" class="useradmin_logo"></a>
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+${commonheader("Hi there!", "hello")}
+
+	<div class="container-fluid">
+		<h1>${greeting}</h1>
 	</div>
-</%def>
 
-<%def name="foot()">
-	</body>
-</html>
-</%def>
+${commonfooter()}

+ 2 - 2
apps/hello/src/hello/views.py

@@ -22,7 +22,7 @@ from hello import conf
 
 def hello(request):
   # Use render from django_util so that ?format=json works.
-  return render("hello.html", request, {"greeting": conf.GREETING.get()})
+  return render("hello.mako", request, {"greeting": conf.GREETING.get()})
 
 def goodbye(request):
-  return render("hello.html", request, {"greeting": "goodbye"})
+  return render("hello.mako", request, {"greeting": "goodbye"})

+ 19 - 22
apps/help/src/help/templates/display.mako

@@ -13,25 +13,22 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<html>
-<head>
-  <title>${title}</title>
-</head>
-<body>
-  <div class="resizable" data-filters="SplitView">
-    <div class="left_col">
-      <div class="jframe_padded">
-        <h2>Index</h2>
-        <ul>
-          % for app in apps:
-            <li><a href="${url("help.views.view", app=app.name, path="/")}">${app.nice_name}</a></li>
-          % endfor
-        </ul>
-      </div>
-    </div>
-    <div class="right_col">
-      <div class="jframe_padded">${content|n}</div>
-    </div>
-  </div>
-</body>
-</html>
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+${commonheader("jHue Help", "help", "100px")}
+	<div class="menubar">
+		<div class="menubar-inner">
+			<div class="container-fluid">
+				<ul class="nav">
+					% for app in apps:
+				        <li><a href="${url("help.views.view", app=app.name, path="/")}">${app.nice_name}</a></li>
+				      % endfor
+				</ul>
+			</div>
+		</div>
+	</div>
+	<div class="container-fluid">
+		${content|n}
+	</div>
+${commonfooter()}

+ 8 - 4
apps/jobbrowser/src/jobbrowser/templates/attempt.mako

@@ -13,10 +13,14 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
+<%!
+  from desktop.views import commonheader, commonfooter
+%>
 <%namespace name="comps" file="jobbrowser_components.mako" />
 
-  ${comps.header("Task Attempt: " + attempt.attemptId + ":: Job Browser")}
-
+${commonheader("Task Attempt: " + attempt.attemptId + ":: Job Browser", "jobbrowser")}
+<div class="container-fluid">
+	<h1>Task Attempt: ${attempt.attemptId} :: Job Browser</h1>
     <div id="job_browser_job" class="view jframe_padded">
       <div class="jtv_meta_top clearfix">
         <dl>
@@ -142,5 +146,5 @@ ${ line | h,trim }
           </li>
         </ul>
       </div>
-
-    ${comps.footer()}
+</div>
+${commonfooter()}

+ 224 - 145
apps/jobbrowser/src/jobbrowser/templates/job.mako

@@ -19,23 +19,26 @@
   from filebrowser.views import location_to_url
   import os
   import re
+  from desktop.views import commonheader, commonfooter
 %>
 
 <%def name="task_table(tasks)">
-  <table data-filters="HtmlTable" class="selectable sortable" cellpadding="0" cellspacing="0">
+  <table class="taskTable">
     <thead>
       <tr>
         <th>Tasks</th>
-        <th colspan="2">Type</th>
+        <th>Type</th>
+		<th>&nbsp;</th>
       </tr>
     </thead>
     <tbody>
       % for task in tasks:
-        <tr data-dblclick-delegate="{'dblclick_loads':'.view_task'}">
-          <td class="task_table_id">${task.taskId_short}</td>
-          <td class="task_table_type">${task.taskType}</td>
-          <td class="jtask_view_col"><a class="frame_tip jtask_view jt_slide_right view_task" title="View this task"
-                 href="${ url('jobbrowser.views.single_task', jobid=job.jobId, taskid=task.taskId) }">View</a></td>
+        <tr>
+			<td>${task.taskId_short}</td>
+			<td>${task.taskType}</td>
+          	<td>
+				<a title="View this task" href="${ url('jobbrowser.views.single_task', jobid=job.jobId, taskid=task.taskId) }">View</a>
+			</td>
         </tr>
       % endfor
     </tbody>
@@ -73,147 +76,223 @@
         </tr>
     % endfor
 </%def>
-
-  ${comps.header("Job: " + job.jobId + " :: Job Browser")}
+${commonheader("Job: " + job.jobId + " - Job Browser", "jobbrowser")}
+<div class="container-fluid">
+	<h1>Job: ${job.jobId} - Job Browser</h1>
+	<div class="sidebar withTitle">
+		<div class="well">
+			<h6>Job ID</h6>
+			${job.jobId}
+			
+			<h6>User</h6>
+			${job.user}
+			
+			<h6>Status</h6>
+			% if job.status.lower() == 'running' or job.status.lower() == 'pending':
+				<span class="label warning">${job.status.lower()}</span>
+			% elif job.status.lower() == 'succeeded':
+				<span class="label success">${job.status.lower()}</span>
+			% else:
+				<span class="label">${job.status.lower()}</span>
+			% endif
+			
+			% if job.status.lower() == 'running' or job.status.lower() == 'pending':
+	        <h6>Kill Job</h6>
+			<a href="${url('jobbrowser.views.kill_job', jobid=job.jobId)}" title="Kill this job">Kill this job</a>
+	        % endif
+			
+			
+			<h6>Output</h6>
+			<%
+	            output_dir = job.conf_keys.get('mapredOutputDir', "")
+	            location_url = location_to_url(request, output_dir)
+	            basename = os.path.basename(output_dir)
+	            dir_name = basename.split('/')[-1]
+	          %>
+	          % if location_url != None:
+	            <a href="${location_url}" title="${output_dir}">${dir_name}</a>
+	          % else:
+	            ${dir_name}
+	          % endif
+		</div>
+	</div>
     
-    <div id="job_browser_job" class="view jframe_padded">
-      <div class="jtv_meta_top clearfix">
-        <dl>
-          <dt>Job ID</dt>
-          <dd>${job.jobId}</dd>
-          <dt>User</dt>
-          <dd>${job.user}</dd>
-        </dl>
-        <dl>
-          <dt>Status</dt>
-          <dd>${job.status.lower()}</dd>
-          <dt>Output</dt>
-          <dd>
-          <%
-            output_dir = job.conf_keys.get('mapredOutputDir', "")
-            location_url = location_to_url(request, output_dir)
-            basename = os.path.basename(output_dir)
-            dir_name = basename.split('/')[-1]
-          %>
-          % if location_url != None:
-            <a class="jt-output_dir" href="${location_url}" title="${output_dir}" target="FileBrowser">${dir_name}</a>
-          % else:
-            ${dir_name}
-          % endif
-          <dd>
-        </dl>
-        % if job.status.lower() == 'running' or job.status.lower() == 'pending':
-        <dl>
-          <dt>Kill Job:</dt>
-          <dd>
-          <a href="${url('jobbrowser.views.kill_job', jobid=job.jobId)}" class="frame_tip jt_kill confirm_unencode_and_post" title="Kill this job">kill</a>
-          </dd>
-        </dl>
-        % endif
+    <div class="content">
+		<ul class="tabs">
+			<li class="active"><a href="#tasks">Tasks</a></li>
+			<li><a href="#metadata">Metadata</a></li>
+			<li><a href="#counters">Counters</a></li>
+		</ul>
+
+		<div class="tab-content">
+			<div class="tab-pane active" id="tasks">
+				<dl>
+	                <dt>Maps:</dt>
+	                <dd>${comps.mr_graph_maps(job)}</dd>
+	                <dt>Reduces:</dt>
+	                <dd>${comps.mr_graph_reduces(job, right_border=True)}</dd>
+	              </dl>
+	            %if failed_tasks:
+	            <div>
+	              <h3>
+	                <a href="${url('jobbrowser.views.tasks', jobid=job.jobId)}?taskstate=failed">View Failed Tasks &raquo;</a>
+	                Failed Tasks
+	              </h3>
+	              <div class="jt_task_list_container">
+	                ${task_table(failed_tasks)}
+	              </div>
+	            </div>
+	            %endif
+	            <div>
+					<a style="float:right;margin-right:10px" href="${url('jobbrowser.views.tasks', jobid=job.jobId)}">View All Tasks &raquo;</a>
+	              <h3>
+	                Recent Tasks
+	              </h3>
+	              <div class="jt_task_list_container">
+	                ${task_table(recent_tasks)}
+	              </div>
+	            </div>
+	
+			</div>
+			<div id="metadata" class="tab-pane">
+				<div class="toolbar">
+					<form>
+						<b>Filter metadata:</b>
+						<ul>
+							<li>
+								<input type="text" id="metadataFilter" title="Text Filter" placeholder="Text Filter"/>
+							</li>
+						</ul>
+					</form>
+		        </div>
+				 <table id="metadataTable">
+		              <thead>
+		                <th>Name</th>
+		                <th>Value</th>
+		              </thead>
+		              <tbody>
+		                <tr>
+		                  <td>ID</td>
+		                  <td>${job.jobId}</td>
+		                </tr>
+		                <tr>
+		                  <td>User</td>
+		                  <td>${job.user}</td>
+		                </tr>
+		                <tr>
+		                  <td>Maps</td>
+		                  <td>${job.finishedMaps} of ${job.desiredMaps}</td>
+		                </tr>
+		                <tr>
+		                  <td>Reduces</td>
+		                  <td>${job.finishedReduces} of ${job.desiredReduces}</td>
+		                </tr>
+		                <tr>
+		                  <td>Started</td>
+		                  <td>${job.startTimeFormatted}</td>
+		                </tr>
+		                <tr>
+		                  <td>Ended</td>
+		                  <td>${job.finishTimeFormatted}</td>
+		                </tr>
+		                <tr>
+		                  <td>Duration</td>
+		                  <td>${job.duration}</td>
+		                </tr>
+		                <tr>
+		                  <td>Status</td>
+		                  <td>${job.status}</td>
+		                </tr>
+		                ${rows_for_conf_vars(job.conf_keys)}
+		             
+		              </tbody>
+		            </table>
+					<h3>Raw configuration:</h3>
+				 <table id="rawConfigurationTable">
+		              <thead>
+		                <th>Name</th>
+		                <th>Value</th>
+		              </thead>
+		              <tbody>
+
+		              % for key, value in sorted(job.full_job_conf.items()):
+		                <tr>
+		                  <td width="20%">${key}</td>
+		                  <td>
+							<div class="wordbreak">
+								${value}
+							</div>
+						  </td>
+		                </tr>
+		              % endfor
+		              </tbody>
+		            </table>
 
-      </div>
+			</div>
+			<div id="counters" class="tab-pane">
+				${comps.job_counters(job.counters)}
+			</div>
+		</div>
+	</div>
+</div>
+		<script type="text/javascript" charset="utf-8">
+			$(document).ready(function(){
+				$(".tabs").tabs();
+				$(".taskTable").dataTable({
+					"bPaginate": false,
+				    "bLengthChange": false,
+					"bInfo": false,
+					"bAutoWidth": false,
+					"aoColumns": [ 
+						{ "sWidth": "40%" },
+						{ "sWidth": "40%" },
+						{ "sWidth": "20%" }
+					]
+				});
+				var _metadataTable = $("#metadataTable").dataTable({
+					"bPaginate": false,
+				    "bLengthChange": false,
+					"bInfo": false,
+					"bAutoWidth": false,
+					"aoColumns": [ 
+						{ "sWidth": "30%" },
+						{ "sWidth": "70%" }
+					]
+				});
+				var _rawConfigurationTable = $("#rawConfigurationTable").dataTable({
+					"bPaginate": false,
+				    "bLengthChange": false,
+					"bInfo": false,
+					"bAutoWidth": false,
+					"aoColumns": [ 
+						{ "sWidth": "30%" },
+						{ "sWidth": "70%" }
+					]
+				});
+				
+				$("#metadataFilter").keydown(function(){
+					_metadataTable.fnFilter($(this).val());
+					_rawConfigurationTable.fnFilter($(this).val());
+				});
+				
+				$(".jobCountersTable").dataTable({
+					"bPaginate": false,
+				    "bLengthChange": false,
+					"bInfo": false,
+					"bAutoWidth": false,
+					"aoColumns": [ 
+						{ "sWidth": "40%" },
+						{ "sWidth": "20%" },
+						{ "sWidth": "20%" },
+						{ "sWidth": "20%" }
+					]
+				});
 
-      <div data-filters="Tabs">
-        <ul class="tabs jtv_tabs jframe-right clearfix">
-          <li><span>Tasks</span></li>
-          <li><span>Metadata</span></li>
-          <li><span>Counters</span></li>
-        </ul>
+				$(".dataTables_wrapper").css("min-height","0");
+				$(".dataTables_filter").hide();
 
-        <ul class="tab_sections jframe-clear">
-          <li>
-            <div class="jt_mr_display">
-              <dl class="jtv_graph">
-                <dt>Maps:</dt>
-                <dd>${comps.mr_graph_maps(job)}</dd>
-                <dt>Reduces:</dt>
-                <dd>${comps.mr_graph_reduces(job, right_border=True)}</dd>
-              </dl>
-            </div>
-            <% 
-            task_table_size = '100%'
-            if failed_tasks:
-              task_table_size = '49%' 
-            %>
-            %if failed_tasks:
-            <div class="jt_task_list jt_failed_tasks jframe-inline" style="width: ${task_table_size};">
-              <h3>
-                <a class="jframe-right" href="${url('jobbrowser.views.tasks', jobid=job.jobId)}?taskstate=failed">view failed tasks &raquo;</a>
-                Failed Tasks
-              </h3>
-              <div class="jt_task_list_container">
-                ${task_table(failed_tasks)}
-              </div>
-            </div>
-            %endif
-            <div class="jt_task_list jt_recent_tasks jframe-inline" style="width: ${task_table_size}">
-              <h3>
-                <a class="jframe-right" href="${url('jobbrowser.views.tasks', jobid=job.jobId)}">View All Tasks &raquo;</a>
-                Recent Tasks
-              </h3>
-              <div class="jt_task_list_container">
-                ${task_table(recent_tasks)}
-              </div>
-            </div>
-            
-          </li>
-          <li>
-            <table data-filters="HtmlTable" class="jt_meta_table sortable" cellpadding="0" cellspacing="0">
-              <thead>
-                <th>Name</th>
-                <th>Value</th>
-              </thead>
-              <tbody>
-                <tr>
-                  <td>ID</td>
-                  <td>${job.jobId}</td>
-                </tr>
-                <tr>
-                  <td>User</td>
-                  <td>${job.user}</td>
-                </tr>
-                <tr>
-                  <td>Maps</td>
-                  <td>${job.finishedMaps} of ${job.desiredMaps}</td>
-                </tr>
-                <tr>
-                  <td>Reduces</td>
-                  <td>${job.finishedReduces} of ${job.desiredReduces}</td>
-                </tr>
-                <tr>
-                  <td>Started</td>
-                  <td>${job.startTimeFormatted}</td>
-                </tr>
-                <tr>
-                  <td>Ended</td>
-                  <td>${job.finishTimeFormatted}</td>
-                </tr>
-                <tr>
-                  <td>Duration</td>
-                  <td>${job.duration}</td>
-                </tr>
-                <tr>
-                  <td>Status</td>
-                  <td>${job.status}</td>
-                </tr>
-                ${rows_for_conf_vars(job.conf_keys)}
-              <tr>
-                <td colspan="2" class="jt-raw_delimiter">Raw Configuration:</td>
-              </tr>
-              % for key, value in sorted(job.full_job_conf.items()):
-                <tr>
-                  <td>${key}</td>
-                  <td>${value}</td>
-                </tr>
-              % endfor
-              </tbody>
-            </table>
-          </li>
-          <li>
-            ${comps.job_counters(job.counters)}
-          </li>
-        </ul>
-      </div>
+			});
+		</script>
 
 
-    ${comps.footer()}
+${commonfooter()}

+ 43 - 63
apps/jobbrowser/src/jobbrowser/templates/jobbrowser_components.mako

@@ -14,50 +14,29 @@
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
 
-<%def name="header(title, toolbar=True)">
-  <html>
-    <head>
-      <title>${title}</title>
-    </head>
-    <body>
-      % if toolbar: 
-      <div class="toolbar">
-        <a href="/jobbrowser/jobs/"><img src="/jobbrowser/static/art/icon_large.png" class="jt_icon"/></a>
-      </div>
-      % endif
-</%def>
-
-<%def name="footer()">
-    </body>
-  </html>
-</%def>
-
-
 <%def name="task_counters(counters)">
 <%
   from jobbrowser.views import format_counter_name
 %>
-    <table data-filters="HtmlTable" class="jt_counter_table">
-      <thead>
-         <tr>
-           <th class="jt_counter_display_name">Counter Name</th>
-           <th class="jt_counter_total">Value</th>   
-        </tr>
-      </thead>
-      <tbody>
-      % for group in counters.groups:
-        <tr>
-          <td colspan="4" class="jt_counter_group_name">${format_counter_name(group.displayName)}</td>
-        </tr>
-      % for name, counter in sorted(group.counters.iteritems()):
-       <tr>
-          <td class="jt_counter_display_name">${format_counter_name(counter.displayName)}</td>
-          <td class="jt_counter_total">${counter.value}</td>
-        </tr>
-      % endfor
-      % endfor
+	% for group in counters.groups:
+		<h3>${format_counter_name(group.displayName)}</h3>
+	    <table class="taskCountersTable">
+	      <thead>
+	         <tr>
+	           <th>Counter Name</th>
+	           <th>Value</th>   
+	        </tr>
+	      </thead>
+	      <tbody>
+	      % for name, counter in sorted(group.counters.iteritems()):
+	       <tr>
+	          <td class="jt_counter_display_name">${format_counter_name(counter.displayName)}</td>
+	          <td class="jt_counter_total">${counter.value}</td>
+	        </tr>
+	      % endfor
       </tbody>
      </table>
+      % endfor
 </%def>
 
 <%def name="job_counters(counters)">
@@ -65,36 +44,37 @@
   from jobbrowser.views import format_counter_name
 %>
 
-    <table data-filters="HtmlTable" class="jt_counter_table">
+	% for group in counters.itervalues():
+      <h3>${format_counter_name(group['displayName'])}</h3>
+	  <table class="jobCountersTable">
       <thead>
          <tr>
-           <th class="jt_counter_display_name">Name</th>
-           <th class="jt_counter_maps_total">Maps Total</th>
-           <th class="jt_counter_reduces_total">Reduces Total</th>
-           <th class="jt_counter_total">Total</th>   
+           <th>Name</th>
+           <th>Maps Total</th>
+           <th>Reduces Total</th>
+           <th>Total</th>   
         </tr>
       </thead>
       <tbody>
-      % for group in counters.itervalues():
-        <tr>
-          <td colspan="4" class="jt_counter_group_name">${format_counter_name(group['displayName'])}</td>
-        </tr>
-      % for name, counter in sorted(group['counters'].iteritems()):
-      <%
-        map_count = counter.get('map', 0)
-        reduce_count = counter.get('reduce', 0)
-        job_count = counter.get('job', 0)
-      %>
-       <tr>
-          <td class="jt_counter_display_name">${format_counter_name(counter.get('displayName', 'n/a'))}</td>
-          <td class="jt_counter_maps_total">${map_count}</td>
-          <td class="jt_counter_reduces_total">${reduce_count}</td>
-          <td class="jt_counter_total">${map_count + reduce_count + job_count}</td>
-        </tr>
-      % endfor
-      % endfor
-      </tbody>
-     </table>
+		 % for name, counter in sorted(group['counters'].iteritems()):
+	      <%
+	        map_count = counter.get('map', 0)
+	        reduce_count = counter.get('reduce', 0)
+	        job_count = counter.get('job', 0)
+	      %>
+	       <tr>
+	          <td>${format_counter_name(counter.get('displayName', 'n/a'))}</td>
+	          <td>${map_count}</td>
+	          <td>${reduce_count}</td>
+	          <td>${map_count + reduce_count + job_count}</td>
+	        </tr>
+	      % endfor
+			</tbody>
+	     </table>
+	% endfor
+    
+
+   
 </%def>
 
 <%def name="mr_graph(job)">

+ 113 - 94
apps/jobbrowser/src/jobbrowser/templates/jobs.mako

@@ -17,6 +17,7 @@
   from jobbrowser.views import get_state_link
   from desktop import appmanager
   from django.template.defaultfilters import urlencode
+  from desktop.views import commonheader, commonfooter
 %>
 <%namespace name="comps" file="jobbrowser_components.mako" />
 <%def name="get_state(option, state)">
@@ -25,99 +26,117 @@
 %   endif
 </%def>
 
-    % if len(jobs) > 0 or filtered:
-      ${comps.header("Job Browser", toolbar=False)}
-      <div id="job_browser_list" class="view">
-        <h1 class="jframe-hidden">Jobs</h1>
-        <div class="toolbar">
-          <a href="/jobbrowser/jobs/"><img src="/jobbrowser/static/art/icon_large.png" class="jt_icon"/></a>
-          <ul class="jt_filters">
-            <form class="jt_filter_form" data-filters="SubmitOnChange" method="get" action="/jobbrowser/jobs/">
-              <li class="jframe-inline"><b>Filter Jobs:</b></li>
-              <li class="jframe-inline">
-                <select name="state">
-                  <option value="all" ${get_state('all', state_filter)}>All States</option>
-                  <option value="running" ${get_state('running', state_filter)}>Running</option>
-                  <option value="completed" ${get_state('completed', state_filter)}>Completed</option>
-                  <option value="failed" ${get_state('failed', state_filter)}>Failed</option>
-                  <option value="killed" ${get_state('killed', state_filter)}>Killed</option>
-                </select>
-              </li>
-              <li class="jframe-inline">
-                <input type="text" class="jt_filter" data-filters="OverText, ArtInput" data-art-input-type="search" name="user" title="User Name Filter" value="${user_filter}"/>
-              </li>
-              <li class="jframe-inline">
-                <input type="text" class="jt_filter" data-filters="OverText, ArtInput" data-art-input-type="search" name="text" title="Text Filter" value="${text_filter}"/>
-              </li>
-            </form>
-          </ul>
-        </div>
-    
-    
-        <table data-filters="HtmlTable" class="selectable sortable" cellpadding="0" cellspacing="0">
-          <thead>
-            <tr>
-              <th>Name / Id</th>
-              <th>Status</th>
-              <th>User</th>
-              <th>Maps/Reduces</th>
-              <th>Queue</th>
-              <th>Priority</th>
-              <th>Duration</th>
-              <th colspan="3">Date</th>
-            </tr>
-          </thead>
 
-          <tbody>
-            % if len(jobs) == 0:
-              <tr>
-                <td colspan="10">There were no jobs that match your search criteria.</td>
-              </tr>
-            % endif
-            % for job in jobs:
-            <tr data-dblclick-delegate="{'dblclick_loads':'.view_this_job'}">
-              <td>${job.jobName}
-                  <div class="jt_jobid">${job.jobId_short}</div>
-              </td>
-              <td><a href="${url('jobbrowser.views.jobs')}?${get_state_link(request, 'state', job.status.lower())}"
-                    title="Show only ${job.status.lower()} jobs"
-                    class="frame_tip status_link ${job.status.lower()}">${job.status.lower()}</a></td>
-              <td><a href="${url('jobbrowser.views.jobs')}?${get_state_link(request, 'user', job.user.lower())}"
-                    title="Show only ${job.user.lower()} jobs"
-                    class="frame_tip user_link ${job.user.lower()}">${job.user}</a></td>
-              <td class="jt_mrs">
 
-                ${comps.mr_graph(job)}
-              
-              </td>
-              <td>${job.queueName}</td>
-              <td>${job.priority.lower()}</td>
-              <td>${job.durationFormatted}</td>
-              <td>${job.startTimeFormatted}</td>
-              <td>
-                % if job.status.lower() == 'running' or job.status.lower() == 'pending':
-                  % if request.user.is_superuser or request.user.username == job.user:
-                    <a href="${url('jobbrowser.views.kill_job', jobid=job.jobId)}?next=${request.get_full_path()|urlencode}" class="frame_tip jt_kill confirm_unencode_and_post" title="Kill this job">kill</a>
-                  % endif
-                % endif
-              </td>
-              <td><a href="${url('jobbrowser.views.single_job', jobid=job.jobId)}" class="frame_tip jt_view jt_slide_right view_this_job" title="View this job">view</a></td>
-            </tr>
-            % endfor
-          </tbody>
-        </table>
-      % else:
-        ${comps.header("Job Browser", toolbar=True)}
-        <div class="jt-welcome">
-          <h2>Welcome to the Job Browser</h2>
-          <p>There aren't any jobs running. Let's fix that.</p>
-          <a href="/jobsub/list/" target="JobSub" class='jt-jobdesigner-button'>Launch the Job Designer</a>
-          % if "beeswax" in appmanager.DESKTOP_APPS:
-            <a href="/beeswax/" target="Beeswax" class='jt-beeswax-button'>Launch Beeswax</a>
-          % endif
-        </div>
-      % endif
-      <div class="jt-show_trackers">
-        <a href="/jobbrowser/trackers">view all task trackers &raquo;</a>
-      </div>
-    ${comps.footer()}
+% if len(jobs) > 0 or filtered:
+${commonheader("Job Browser", "jobbrowser")}
+<div class="container-fluid">
+<h1>Job Browser</h1>
+<div class="well">
+	<form action="/jobbrowser/jobs" method="GET">
+		<b>Filter jobs:</b>
+		
+				<select name="state" class="submitter">
+					<option value="all" ${get_state('all', state_filter)}>All States</option>
+					<option value="running" ${get_state('running', state_filter)}>Running</option>
+					<option value="completed" ${get_state('completed', state_filter)}>Completed</option>
+					<option value="failed" ${get_state('failed', state_filter)}>Failed</option>
+					<option value="killed" ${get_state('killed', state_filter)}>Killed</option>
+				</select>
+		
+				<input type="text" name="user" title="User Name Filter" value="${user_filter}" placeholder="User Name Filter" class="submitter"/>
+			
+				<input type="text" name="text" title="Text Filter" value="${text_filter}" placeholder="Text Filter" class="submitter"/>
+			
+	</form>
+</div>
+
+
+% if len(jobs) == 0:
+<p>There were no jobs that match your search criteria.</p>
+% else:
+<table class="datatables">
+	<thead>
+		<tr>
+			<th>Name / Id</th>
+			<th>Status</th>
+			<th>User</th>
+			<th>Maps/Reduces</th>
+			<th>Queue</th>
+			<th>Priority</th>
+			<th>Duration</th>
+			<th>Date</th>
+			<th></th>
+		</tr>
+	</thead>
+	<tbody>
+		% for job in jobs:
+		<tr>
+			<td>${job.jobName}
+				<div class="jobbrowser_jobid_short">${job.jobId_short}</div>
+			</td>
+			<td>
+				<a href="${url('jobbrowser.views.jobs')}?${get_state_link(request, 'state', job.status.lower())}" title="Show only ${job.status.lower()} jobs">${job.status.lower()}</a>
+			</td>
+			<td>
+				<a href="${url('jobbrowser.views.jobs')}?${get_state_link(request, 'user', job.user.lower())}" title="Show only ${job.user.lower()} jobs">${job.user}</a>
+			</td>
+			<td class="jt_mrs">
+				${comps.mr_graph(job)}
+			</td>
+			<td>${job.queueName}</td>
+			<td>${job.priority.lower()}</td>
+			<td>${job.durationFormatted}</td>
+			<td>${job.startTimeFormatted}</td>
+			<td>
+				% if job.status.lower() == 'running' or job.status.lower() == 'pending':
+				% if request.user.is_superuser or request.user.username == job.user:
+				<a href="${url('jobbrowser.views.kill_job', jobid=job.jobId)}?next=${request.get_full_path()|urlencode}" title="Kill this job">Kill</a> -
+				% endif
+				% endif
+				<a href="${url('jobbrowser.views.single_job', jobid=job.jobId)}" title="View this job">View</a></td>
+			</tr>
+			% endfor
+		</tbody>
+	</table>
+	% endif
+
+
+
+	% else:
+	${commonheader("Job Browser", "jobbrowser")}
+	<div class="container-fluid">
+	<h1>Welcome to the Job Browser</h1>
+	<div>
+		<p>There aren't any jobs running. Let's fix that.</p>
+		<a href="/jobsub/list/">Launch the Job Designer</a>
+		% if "beeswax" in appmanager.DESKTOP_APPS:
+		or <a href="/beeswax/">Launch Beeswax</a>
+		% endif
+	</div>
+	% endif
+</div>
+	<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		$(".datatables").dataTable({
+			"bPaginate": false,
+			"bLengthChange": false,
+			"bFilter": false,
+			"bInfo": false,
+			"aoColumns": [
+			null,
+			null,
+			null,
+			null,
+			null,
+			null,
+			null,
+			null,
+			{"bSortable":false}
+			]
+		});
+	});
+	</script>
+
+
+${commonfooter()}

+ 160 - 112
apps/jobbrowser/src/jobbrowser/templates/task.mako

@@ -13,123 +13,171 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
+<%!
+  from desktop.views import commonheader, commonfooter
+%>
 <%namespace name="comps" file="jobbrowser_components.mako" />
 
-  ${comps.header("Job Task: " + task.taskId + ":: Job Browser")}
+  ${commonheader("Job Task: " + task.taskId + "- Job Browser", "jobbrowser")}
+	<div class="container-fluid">
+	<h1>Job Task: ${task.taskId} - Job Browser</h1>
 
-    <div id="job_browser_job" class="view jframe_padded">
-      <div class="jtv_meta_top clearfix">
-        <dl>
-          <dt>Task ID</dt>
-          <dd>${task.taskId_short}</dd>
-          <dt>Job</dt>
-          <td><a href="${url('jobbrowser.views.single_job', jobid=joblnk.jobId)}" class="frame_tip jt_view" title="View this job">${joblnk.jobId_short}</a></td>
-        </dl>
-        <dl>
-          <dt>Status</dt>
-          <dd>${task.state.lower()}</dd>
-        </dl>
-      </div>
+	<div class="sidebar withTitle">
+		<div class="well">
+			<h6>Task ID</h6>
+			${task.taskId_short}
+			
+			<h6>Job</h6>
+			<a href="${url('jobbrowser.views.single_job', jobid=joblnk.jobId)}" class="frame_tip jt_view" title="View this job">${joblnk.jobId_short}</a>
+			
+			<h6>Status</h6>
+			% if task.state.lower() == 'running' or task.state.lower() == 'pending':
+				<span class="label warning">${task.state.lower()}</span>
+			% elif task.state.lower() == 'succeeded':
+				<span class="label success">${task.state.lower()}</span>
+			% else:
+				<span class="label">${task.state.lower()}</span>
+			% endif
+		</div>
+	</div>
+	
+	<div class="content">
+		
 
-      <div data-filters="Tabs">
-        <ul class="tabs jtv_tabs jframe-right clearfix">
-          <li><span>Attempts</span></li>
-          <li><span>Metadata</span></li>
-          <li><span>Counters</span></li>
-        </ul>
+		<ul class="tabs">
+			<li class="active"><a href="#attempts">Attempts</a></li>
+			<li><a href="#metadata">Metadata</a></li>
+			<li><a href="#counters">Counters</a></li>
+		</ul>
 
-        <ul class="tab_sections jframe-clear">
-          <li>
-            <table border="0" cellpadding="0" cellspacing="0" data-filters="HtmlTable" class="jt_meta_table sortable selectable">
-              <thead>
-                <tr>
-                 <th>Attempt ID</th>
-                 <th>Progress</th>
-                 <th>State</th>
-                 <th>Task Tracker</th>
-                 <th>Start Time</th>
-                 <th>End Time</th>
-                 <th>Output Size</th>
-                 <th>Phase</th>
-                 <th>Shuffle Finish</th>
-                 <th>Sort Finish</th>
-                 <th>Map Finish</th>
-                 <th>View</th>
-                </tr>
-              </thead>
-              <tbody>
-                % for attempt in task.attempts:
-                 <tr data-dblclick-delegate="{'dblclick_loads':'.view_attempt'}">
-                   <td>${attempt.attemptId_short}</td>
-                   <td>${"%d" % (attempt.progress * 100)}%</td>
-                   <td><span class="status_link ${attempt.state}">${attempt.state}</span></td>
-                   <td><a href="/jobbrowser/trackers/${attempt.taskTrackerId}" class="task_tracker_link">${attempt.taskTrackerId}</a></td>
-                   <td>${attempt.startTimeFormatted}</td>
-                   <td>${attempt.finishTimeFormatted}</td>
-                   <td>${attempt.outputSize}</td>
-                   <td>${attempt.phase}</td>
-                   <td>${attempt.shuffleFinishTimeFormatted}</td>
-                   <td>${attempt.sortFinishTimeFormatted}</td>
-                   <td>${attempt.mapFinishTimeFormatted}</td>
-                   <td><a class="frame_tip jtask_view jt_slide_right view_attempt" title="View this attempt"
-                          href="${ url('jobbrowser.views.single_task_attempt', jobid=joblnk.jobId, taskid=task.taskId, attemptid=attempt.attemptId) }"></a></td>
-                 </tr>
-                % endfor
-              </tbody>
-            </table>
-          </li>
-          <li>
-            <table data-filters="HtmlTable" class="jt_meta_table sortable" cellpadding="0" cellspacing="0">
-              <thead>
-                <th>Name</th>
-                <th>Value</th>
-              </thead>
-              <tbody>
-                <tr>
-                  <td>Task id</td>
-                  <td>${task.taskId}</td>
-                </tr>
-                <tr>
-                  <td>Type</td>
-                  <td>${task.taskType}</td>
-                </tr>
-                <tr>
-                  <td>JobId</td>
-                  <td><a href="${url('jobbrowser.views.single_job', jobid=joblnk.jobId)}" class="frame_tip jt_view" title="View this job">${joblnk.jobId}</a></td>
-                </tr>
-                <tr>
-                  <td>State</td>
-                  <td>${task.state}</td>
-                </tr>
-                <tr>
-                  <td>Status</td>
-                  <td>${task.mostRecentState}</td>
-                </tr>
-                <tr>
-                  <td>Start Time</td>
-                  <td>${task.startTimeFormatted}</td>
-                </tr>
-                <tr>
-                  <td>Execution Start Time</td>
-                  <td>${task.execStartTimeFormatted}</td>
-                </tr>
-                <tr>
-                  <td>Execution Finish Time</td>
-                  <td>${task.execFinishTimeFormatted}</td>
-                </tr>
-                <tr>
-                  <td>Progress</td>
-                  <td>${"%d" % (task.progress * 100)}%</td>
-                </tr>
-              </tbody>
-            </table>
+		<div class="tab-content">
+			<div class="tab-pane active" id="attempts">
+				<table id="attemptsTable">
+	              <thead>
+	                <tr>
+	                 <th>Attempt ID</th>
+	                 <th>Progress</th>
+	                 <th>State</th>
+	                 <th>Task Tracker</th>
+	                 <th>Start Time</th>
+	                 <th>End Time</th>
+	                 <th>Output Size</th>
+	                 <th>Phase</th>
+	                 <th>Shuffle Finish</th>
+	                 <th>Sort Finish</th>
+	                 <th>Map Finish</th>
+	                 <th>View</th>
+	                </tr>
+	              </thead>
+	              <tbody>
+	                % for attempt in task.attempts:
+	                 <tr data-dblclick-delegate="{'dblclick_loads':'.view_attempt'}">
+	                   <td>${attempt.attemptId_short}</td>
+	                   <td>${"%d" % (attempt.progress * 100)}%</td>
+	                   <td><span class="status_link ${attempt.state}">${attempt.state}</span></td>
+	                   <td><a href="/jobbrowser/trackers/${attempt.taskTrackerId}" class="task_tracker_link">${attempt.taskTrackerId}</a></td>
+	                   <td>${attempt.startTimeFormatted}</td>
+	                   <td>${attempt.finishTimeFormatted}</td>
+	                   <td>${attempt.outputSize}</td>
+	                   <td>${attempt.phase}</td>
+	                   <td>${attempt.shuffleFinishTimeFormatted}</td>
+	                   <td>${attempt.sortFinishTimeFormatted}</td>
+	                   <td>${attempt.mapFinishTimeFormatted}</td>
+	                   <td><a class="frame_tip jtask_view jt_slide_right view_attempt" title="View this attempt"
+	                          href="${ url('jobbrowser.views.single_task_attempt', jobid=joblnk.jobId, taskid=task.taskId, attemptid=attempt.attemptId) }"></a></td>
+	                 </tr>
+	                % endfor
+	              </tbody>
+	            </table>
+			</div>
+			<div id="metadata" class="tab-pane">
+				<table id="metadataTable">
+	              <thead>
+	                <th>Name</th>
+	                <th>Value</th>
+	              </thead>
+	              <tbody>
+	                <tr>
+	                  <td>Task id</td>
+	                  <td>${task.taskId}</td>
+	                </tr>
+	                <tr>
+	                  <td>Type</td>
+	                  <td>${task.taskType}</td>
+	                </tr>
+	                <tr>
+	                  <td>JobId</td>
+	                  <td><a href="${url('jobbrowser.views.single_job', jobid=joblnk.jobId)}" class="frame_tip jt_view" title="View this job">${joblnk.jobId}</a></td>
+	                </tr>
+	                <tr>
+	                  <td>State</td>
+	                  <td>${task.state}</td>
+	                </tr>
+	                <tr>
+	                  <td>Status</td>
+	                  <td>${task.mostRecentState}</td>
+	                </tr>
+	                <tr>
+	                  <td>Start Time</td>
+	                  <td>${task.startTimeFormatted}</td>
+	                </tr>
+	                <tr>
+	                  <td>Execution Start Time</td>
+	                  <td>${task.execStartTimeFormatted}</td>
+	                </tr>
+	                <tr>
+	                  <td>Execution Finish Time</td>
+	                  <td>${task.execFinishTimeFormatted}</td>
+	                </tr>
+	                <tr>
+	                  <td>Progress</td>
+	                  <td>${"%d" % (task.progress * 100)}%</td>
+	                </tr>
+	              </tbody>
+	            </table>
+			</div>
+			<div id="counters" class="tab-pane">
+				${comps.task_counters(task.counters)}
+			</div>
+		</div>
+	</div>	
+		<script type="text/javascript" charset="utf-8">
+			$(document).ready(function(){
+				$(".tabs").tabs();
+				$("#attemptsTable").dataTable({
+					"bPaginate": false,
+				    "bLengthChange": false,
+					"bInfo": false,
+					"bFilter": false
+				});
+				$("#metadataTable").dataTable({
+					"bPaginate": false,
+				    "bLengthChange": false,
+					"bInfo": false,
+					"bAutoWidth": false,
+					"bFilter": false,
+					"aoColumns": [ 
+						{ "sWidth": "30%" },
+						{ "sWidth": "70%" }
+					]
+				});
+				
+				$(".taskCountersTable").dataTable({
+					"bPaginate": false,
+				    "bLengthChange": false,
+					"bInfo": false,
+					"bAutoWidth": false,
+					"aoColumns": [ 
+						{ "sWidth": "30%" },
+						{ "sWidth": "70%" }
+					]
+				});
 
-          </li>
-          <li>
-            ${comps.task_counters(task.counters)}
-          </li>
-        </ul>
-      </div>
+				$(".dataTables_wrapper").css("min-height","0");
+				$(".dataTables_filter").hide();
 
+			});
+		</script>
+     
 
-    ${comps.footer()}
+    ${commonfooter()}

+ 87 - 97
apps/jobbrowser/src/jobbrowser/templates/tasks.mako

@@ -15,111 +15,101 @@
 ## limitations under the License.
 <%
   from jobbrowser.views import get_state_link
+  from desktop.views import commonheader, commonfooter
 %>
 
 <%namespace name="comps" file="jobbrowser_components.mako" />
 
-  ${comps.header("Task View: Job: " + jobid, toolbar=False)}
+  ${commonheader("Task View: Job: " + jobid + " - Job Browser", "jobbrowser")}
   <%def name="selected(val, state)">
   %   if val is not None and state is not None and val in state:
         selected="true"
   %   endif
   </%def>
-  <%def name="pageref(num)">
-    href="?page=${num}&${filter_params}"
-  </%def>
-  <%def name="prevpage()">
-    ${pageref(page.previous_page_number())}
-  </%def>
-  <%def name="nextpage()">
-    ${pageref(page.next_page_number())}
-  </%def>
-  <%def name="toppage()">
-    ${pageref(1)}
-  </%def>
-  <%def name="bottompage()">
-    ${pageref(page.num_pages())}
-  </%def>
+	<div class="container-fluid">
+	<h1>Task View: Job:  ${jobid}</h1>
+	<div class="well">
+		<div class="">
+		
+				<form method="get" action="/jobbrowser/jobs/${jobid}/tasks">
+					<b>Filter tasks:</b>
+				
+						<select name="taskstate" class="submitter">
+							<option value="">All states</option>
+							<option value="succeeded" ${selected('succeeded', taskstate)}>succeeded</option>
+							<option value="running" ${selected('running', taskstate)}>running</option>
+							<option value="failed" ${selected('failed', taskstate)}>failed</option>
+							<option value="killed" ${selected('killed', taskstate)}>killed</option>
+							<option value="pending" ${selected('pending', taskstate)}>pending</option>
+						</select>
+				
+				
+						<select name="tasktype" class="submitter">
+							<option value="">All types</option>
+							<option value="map" ${selected('map', tasktype)}>maps</option>
+							<option value="reduce" ${selected('reduce', tasktype)}>reduces</option>
+							<option value="job_cleanup" ${selected('job_cleanup', tasktype)}>cleanups</option>
+							<option value="job_setup" ${selected('job_setup', tasktype)}>setups</option>
+						</select>
+				
+				
+						<input type="text" name="tasktext"  class="submitter" title="Text filter" placeholder="Text Filter"
+						% if tasktext:
+						value="${tasktext}"
+						% endif
+						/>
+				
+				</form>
+		
+		</div>
+	</div>
+
+
+	% if len(page.object_list) == 0:
+	<p>There were no tasks that match your search criteria.</p>
+	% else:
 
+	<table class="datatables">
+		<thead>
+			<tr>
+				<th>Task ID</th>
+				<th>Type</th>
+				<th>Progress</th>
+				<th>Status</th>
+				<th>State</th>
+				<th>Start Time</th>
+				<th>End Time</th>
+				<th>View Attempts</th>
+			</tr>
+		</thead>
+		<tbody>
+			%for t in page.object_list:
+			<tr data-dblclick-delegate="{'dblclick_loads':'.view_task'}">
+				<td>${t.taskId_short}</td>
+				<td>${t.taskType}</td>
+				<td>${"%d" % (t.progress * 100)}%</td>
+				<td><a href="${url('jobbrowser.views.tasks', jobid=jobid)}?${get_state_link(request, 'taskstate', t.state.lower())}"
+					title="Show only ${t.state.lower()} tasks"
+					class="${t.state.lower()}">${t.state.lower()}</a></td>
+					<td>${t.mostRecentState}</td>
+					<td>${t.execStartTimeFormatted}</td>
+					<td>${t.execFinishTimeFormatted}</td>
+					<td><a href="/jobbrowser/jobs/${jobid}/tasks/${t.taskId}" class="view_task jt_slide_right">Attempts</a></td>
+				</tr>
+				%endfor
+		</tbody>
+	</table>
+	%endif
+	</div>
+	<script type="text/javascript" charset="utf-8">
+		$(document).ready(function(){
+			$(".datatables").dataTable({
+				"bPaginate": false,
+			    "bLengthChange": false,
+			    "bFilter": false,
+				"bInfo": false,
+			});
+		});
+	</script>
 
-  <div id="job_browser_task_list" class="view">
-    <h1 class="jframe-hidden">Tasks for Job ${jobid}</h1>
-    <div class="toolbar">
-      <a href="/jobbrowser/jobs/"><img src="/jobbrowser/static/art/icon_large.png" class="jt_icon"/></a>
-      <ul class="jt_filters">
-        <form class="jtv_filter_form" data-filters="SubmitOnChange" method="get" action="/jobbrowser/jobs/${jobid}/tasks">
-          <li class="jframe-inline">
-            <select name="taskstate">
-              <option value="">All states</option>
-              <option value="succeeded" ${selected('succeeded', taskstate)}>succeeded</option>
-              <option value="running" ${selected('running', taskstate)}>running</option>
-              <option value="failed" ${selected('failed', taskstate)}>failed</option>
-              <option value="killed" ${selected('killed', taskstate)}>killed</option>
-              <option value="pending" ${selected('pending', taskstate)}>pending</option>
-            </select>
-          </li>
-          <li class="jframe-inline">
-            <select name="tasktype">
-              <option value="">All types</option>
-              <option value="map" ${selected('map', tasktype)}>maps</option>
-              <option value="reduce" ${selected('reduce', tasktype)}>reduces</option>
-              <option value="job_cleanup" ${selected('job_cleanup', tasktype)}>cleanups</option>
-              <option value="job_setup" ${selected('job_setup', tasktype)}>setups</option>
-            </select>
-          </li>
-          <li class="jframe-inline">
-            <input type="text" name="tasktext" class="jtv_filter" data-filters="OverText, ArtInput" data-art-input-type="search" title="text filter"
-              % if tasktext:
-                value="${tasktext}"
-              % endif
-            />
-          </li>
-        </form>
-      </ul>
-    </div>
-    <div data-filters="SizeTo" data-size-to-height="-30" style="overflow: auto">
-      ## Use fit-text because the task state can be a very long string
-      <table data-filters="HtmlTable" class="selectable" data-fit-text="td" cellpadding="0" cellspacing="0">
-        <thead>
-           <tr>
-             <th>Task ID</th>
-             <th>Type</th>
-             <th>Progress</th>
-             <th>Status</th>
-             <th>State</th>
-             <th>Start Time</th>
-             <th>End Time</th>
-             <th>View Attempts</th>
-          </tr>
-        </thead>
-        <tbody>
-          %for t in page.object_list:
-           <tr data-dblclick-delegate="{'dblclick_loads':'.view_task'}">
-              <td>${t.taskId_short}</td>
-              <td>${t.taskType}</td>
-              <td>${"%d" % (t.progress * 100)}%</td>
-              <td><a href="${url('jobbrowser.views.tasks', jobid=jobid)}?${get_state_link(request, 'taskstate', t.state.lower())}"
-                    title="Show only ${t.state.lower()} tasks"
-                    class="frame_tip status_link ${t.state.lower()}">${t.state.lower()}</a></td>
-              <td>${t.mostRecentState}</td>
-              <td>${t.execStartTimeFormatted}</td>
-              <td>${t.execFinishTimeFormatted}</td>
-              <td><a href="/jobbrowser/jobs/${jobid}/tasks/${t.taskId}" class="view_task jt_slide_right">Attempts</a></td>
-           </tr>
-          %endfor
-        </tbody>
-      </table>
-    </div>
-    <div class="jtv-pagination">
-      <div class="jtv-pagination_count jframe-inline">
-        Showing ${page.start_index()} to ${page.end_index()} of ${page.total_count()} tasks
-      </div>
-      <div class="jtv_offset_controls">
-        <a title="Beginning of File" class="jtv_offset_begin" ${toppage()}>Beginning of File</a>
-        <a title="Previous Block" class="jtv_offset_previous" ${prevpage()}>Previous Block</a>
-        <div class="jtv_nav_pages">page <span class="jtv_page">${page.number} of ${page.num_pages()}</span></div>
-        <a title="Next Block" class="jtv_offset_next" ${nextpage()}>Next Block</a>
-        <a title="End of File" class="jtv_offset_end" ${bottompage()}>End of File</a>
-      </div>
-    </div>
-  ${comps.footer()}
+  ${commonfooter()}

+ 42 - 36
apps/jobbrowser/src/jobbrowser/templates/tasktracker.mako

@@ -13,42 +13,48 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
+<%!
+  from desktop.views import commonheader, commonfooter
+%>
 <%namespace name="comps" file="jobbrowser_components.mako" />
-${comps.header("Tracker " + tracker.trackerId + " :: Job Browser")}
-<div id="job_browser_tracker" class="view">
-  <h1>Tracker at ${ tracker.host } on port ${ tracker.httpPort }</h1>
-  <div class="jframe_padded">
-    <dl class="tracker_meta">
-      <dt>ID</dt>
-      <dd>${ tracker.trackerId }</dd>
-      <dt>Last heard from at</dt>
-      <dd>${ tracker.lastSeenFormatted }.</dd>
-    </dl>
-  </div>
-    <h2>Memory Metrics</h2>
-  <div class="jframe_padded">
-    <dl class="tracker_meta">
-      <dt>Total virtual memory:</dt>
-      <dd>${tracker.totalVirtualMemory }</dd>
-      <dt>Total physical memory: </dt>
-      <dd>${tracker.totalPhysicalMemory }</dd>
-      <dt>Available space: </dt>
-      <dd>${tracker.availableSpace}</dd>
-    </dl>
-  </div>
 
-    <h2>Map and Reduce</h2>
-  <div class="jframe_padded">
-    <dl class="tracker_meta">
-      <dt>Map count:</dt>
-      <dd>${tracker.mapCount}</dd>
-      <dt>Reduce count:</dt>
-      <dd>${tracker.reduceCount}</dd>
-      <dt>Max map tasks:</dt>
-      <dd>${tracker.maxMapTasks}</dd>
-      <dt>Max reduce tasks:</dt>
-      <dd>${tracker.maxReduceTasks}</dd>
-    </dl>
-  </div>
+${commonheader("Tracker " + tracker.trackerId + " - Job Browser", "jobbrowser")}
+<div class="container-fluid">
+	<h1>Tracker at ${ tracker.host } on port ${ tracker.httpPort }</h1>
+	<div>
+		<dl>
+			<dt>ID</dt>
+			<dd>${ tracker.trackerId }</dd>
+			<dt>Last heard from at</dt>
+			<dd>${ tracker.lastSeenFormatted }.</dd>
+		</dl>
+	</div>
+	
+	<h2>Memory Metrics</h2>
+	<div>
+		<dl>
+			<dt>Total virtual memory:</dt>
+			<dd>${tracker.totalVirtualMemory }</dd>
+			<dt>Total physical memory: </dt>
+			<dd>${tracker.totalPhysicalMemory }</dd>
+			<dt>Available space: </dt>
+			<dd>${tracker.availableSpace}</dd>
+		</dl>
+	</div>
+
+	<h2>Map and Reduce</h2>
+	<div>
+		<dl>
+			<dt>Map count:</dt>
+			<dd>${tracker.mapCount}</dd>
+			<dt>Reduce count:</dt>
+			<dd>${tracker.reduceCount}</dd>
+			<dt>Max map tasks:</dt>
+			<dd>${tracker.maxMapTasks}</dd>
+			<dt>Max reduce tasks:</dt>
+			<dd>${tracker.maxReduceTasks}</dd>
+		</dl>
+	</div>
 </div>
-${comps.footer()}
+
+${commonfooter()}

+ 51 - 35
apps/jobbrowser/src/jobbrowser/templates/tasktrackers.mako

@@ -13,39 +13,55 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
+<%!
+  from desktop.views import commonheader, commonfooter
+%>
 <%namespace name="comps" file="jobbrowser_components.mako" />
-${comps.header("Task Trackers :: Job Browser")}
-  <h1 class="jframe-hidden">Task Trackers :: Job Browser</h1>
-  <table border="0" cellpadding="0" cellspacing="0" data-filters="HtmlTable" class="sortable">
-    <thead>
-      <tr>
-       <th>Name</th>
-       <th>Host</th>
-       <th>Port</th>
-       <th>Last Seen</th>
-       <th>Available Space</th>
-       <th>Failure Count</th>
-       <th>Map Count</th>
-       <th>Reduce Count</th>
-       <th>Max Map Tasks</th>
-       <th>Max Reduce Tasks</th>
-      </tr>
-    </thead>
-    <tbody>
-      % for t in trackers:
-      <tr>
-        <td><a href="/jobbrowser/trackers/${t.trackerId}">${t.trackerId}</a></td>
-        <td>${t.host}</td>
-        <td>${t.httpPort}</td>
-        <td>${t.lastSeenFormatted}</td>
-        <td>${t.availableSpace}</td>
-        <td>${t.failureCount}</td>
-        <td>${t.mapCount}</td>
-        <td>${t.reduceCount}</td>
-        <td>${t.maxMapTasks}</td>
-        <td>${t.maxReduceTasks}</td>
-      </tr>
-      % endfor
-    </tbody>
-  </table>
-${comps.footer()}
+${commonheader("Task Trackers - Job Browser", "jobbrowser")}
+<div class="container-fluid">
+<table class="datatables">
+	<thead>
+		<tr>
+			<th>Name</th>
+			<th>Host</th>
+			<th>Port</th>
+			<th>Last Seen</th>
+			<th>Available Space</th>
+			<th>Failure Count</th>
+			<th>Map Count</th>
+			<th>Reduce Count</th>
+			<th>Max Map Tasks</th>
+			<th>Max Reduce Tasks</th>
+		</tr>
+	</thead>
+	<tbody>
+		% for t in trackers:
+		<tr>
+			<td><a href="/jobbrowser/trackers/${t.trackerId}">${t.trackerId}</a></td>
+			<td>${t.host}</td>
+			<td>${t.httpPort}</td>
+			<td>${t.lastSeenFormatted}</td>
+			<td>${t.availableSpace}</td>
+			<td>${t.failureCount}</td>
+			<td>${t.mapCount}</td>
+			<td>${t.reduceCount}</td>
+			<td>${t.maxMapTasks}</td>
+			<td>${t.maxReduceTasks}</td>
+		</tr>
+		% endfor
+	</tbody>
+</table>
+<div id="trackerDialog"></div>
+</div>
+<script type="text/javascript" charset="utf-8">
+$(document).ready(function(){
+	$(".datatables").dataTable({
+		"bPaginate": false,
+		"bLengthChange": false,
+		"bFilter": false,
+		"bInfo": false				
+	});
+});
+</script>
+
+${commonfooter()}

+ 5 - 0
apps/jobsub/babel.cfg

@@ -0,0 +1,5 @@
+[python: src/jobsub/**.py]
+[django: src/jobsub/templates/**.html]
+
+[extractors]
+django = babeldjango.extract:extract_django

+ 23 - 0
apps/jobsub/src/jobsub/locale/django.pot

@@ -0,0 +1,23 @@
+# Translations template for PROJECT.
+# Copyright (C) 2012 ORGANIZATION
+# This file is distributed under the same license as the PROJECT project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2012.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: PROJECT VERSION\n"
+"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
+"POT-Creation-Date: 2012-01-27 15:00+0100\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: LANGUAGE <LL@li.org>\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 0.9.6\n"
+
+#: src/jobsub/templates/layout.html:74
+msgid "'Shell'"
+msgstr ""
+

BIN
apps/jobsub/src/jobsub/locale/en_US/LC_MESSAGES/django.mo


+ 23 - 0
apps/jobsub/src/jobsub/locale/en_US/LC_MESSAGES/django.po

@@ -0,0 +1,23 @@
+# English (United States) translations for PROJECT.
+# Copyright (C) 2012 ORGANIZATION
+# This file is distributed under the same license as the PROJECT project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2012.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: PROJECT VERSION\n"
+"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
+"POT-Creation-Date: 2012-01-27 15:00+0100\n"
+"PO-Revision-Date: 2012-01-27 15:00+0100\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: en_US <LL@li.org>\n"
+"Plural-Forms: nplurals=2; plural=(n != 1)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 0.9.6\n"
+
+#: src/jobsub/templates/layout.html:74
+msgid "'Shella'"
+msgstr ""
+

BIN
apps/jobsub/src/jobsub/locale/it/LC_MESSAGES/django.mo


+ 23 - 0
apps/jobsub/src/jobsub/locale/it/LC_MESSAGES/django.po

@@ -0,0 +1,23 @@
+# Italian translations for PROJECT.
+# Copyright (C) 2012 ORGANIZATION
+# This file is distributed under the same license as the PROJECT project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2012.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: PROJECT VERSION\n"
+"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
+"POT-Creation-Date: 2012-01-27 15:00+0100\n"
+"PO-Revision-Date: 2012-01-27 15:00+0100\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: it <LL@li.org>\n"
+"Plural-Forms: nplurals=2; plural=(n != 1)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 0.9.6\n"
+
+#: src/jobsub/templates/layout.html:74
+msgid "'Terminale'"
+msgstr ""
+

+ 4 - 3
apps/jobsub/src/jobsub/templates/confirm.html

@@ -19,10 +19,11 @@ limitations under the License.
 {% block title %}{{ title }}{% endblock %}
 {% block content %}
 <div class="prompt_popup">
-	<h1>Are you sure?</h1>
+	<h1>Please confirm</h1>
 	<form action="{{ url }}" method="POST">
-		{{title}}
-		<input type="submit" value="Yes" class="jframe-hidden">
+		<h3 style="display: inline;">{{title}}</h3>
+		<input type="submit" value="Yes" class="btn danger">
+        <a href="/jobsub/" class="btn">No</a>
 	</form>
 </div>
 {% endblock %}

+ 55 - 47
apps/jobsub/src/jobsub/templates/edit.html

@@ -8,7 +8,7 @@ to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
-    http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,56 +17,64 @@ See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
 {% block title %}Job Design Editor{% endblock %}
+{% block nav %}
+<li><a href="{% url jobsub.views.list_designs %}" class="selected">Job List</a></li>
+<li><a href="{% url jobsub.views.watch %}">History</a></li>
+{% endblock %}
+
 {% block content %}
-<div id="jobsub_edit" class="view jobsub_col_wrapper" data-filters="SplitView">
-	<div class="jobsub_left_col left_col">
-		{% include "types.html" %}
-	</div>
-	<div class="jobsub_right_col right_col clearfix jframe_padded">
-
-		<h1>Job Design Editor</h1>
-
-		{% if message %}
-		<div align="center" class="jframe-error">{{message}}</div>
-		{% endif %}
-
-		<h2>Job Design Editor: {{form.name}} Job</h2>
-		<form method="POST" action="{{ edit_url }}" enctype="multipart/form-data">
-
-			<div class="jobsub_edit_tip">
-				<p><b>Tip</b>:
-					Job Designs allow you to rudimentarily parameterize your jobs by using variables.
-					At submission time, you'll be prompted to specify the values of any variables 
-					of the form <i>$variable_name</i>.
-					<!--
-					TODO(philip): Put this in if the file chooser is hooked up.
-
-					The following variables are treated specially, prompting a "file chooser"
-					tool.
-
-					<dl class="jobsub_notes clearfix">
-					<dt><tt>$input</tt></dt><dd>Input for your job.</dd>
-					<dt><tt>$output</tt></dt><dd>Output directory (must not already exist) for your job.</dd>
-					</dl>
-					-->
-			</div>
+    <div class="sidebar">
+		<div class="well">
+        	{% include "types.html" %}
+		</div>
+    </div>
+    <div class="content">
+		<h1>Job Design Editor: {{form.name}} Job</h1>
+        {% if message %}
+        <div>{{message}}</div>
+        {% endif %}
+		<div class="alert-message block-message info">
+		    <b>Tip</b>:
+		    Job Designs allow you to rudimentarily parameterize your jobs by using variables.
+		    At submission time, you'll be prompted to specify the values of any variables
+		    of the form <i>$variable_name</i>.
+		    <!--
+		                     TODO(philip): Put this in if the file chooser is hooked up.
+
+		                     The following variables are treated specially, prompting a "file chooser"
+		                     tool.
+
+		                     <dl class="jobsub_notes clearfix">
+		                     <dt><tt>$input</tt></dt><dd>Input for your job.</dd>
+		                     <dt><tt>$output</tt></dt><dd>Output directory (must not already exist) for your job.</dd>
+		                     </dl>
+		                     -->
+		</div>
+
+        <form method="POST" action="{{ edit_url }}" enctype="multipart/form-data" class="form-stacked">
+
+            <input type="hidden" name="type" value="{{ form.type_str }}"/>
 
+            <label>{{ metadata_form.name.html_name }}</label>
+            {{ metadata_form.name|safe }}
 
-			<input type="hidden" name="type" value="{{ form.type_str }}"/>
-			<dl class="jobsub_meta clearfix">
-				<dt>{{ metadata_form.name.html_name }}</dt>
-				<dd>{{ metadata_form.name|safe }}</dd>
+            <label>{{ metadata_form.description.html_name }}</label>
+            {{ metadata_form.description|safe }}
 
-				<dt>{{ metadata_form.description.html_name }}</dt>
-				<dd>{{ metadata_form.description|safe }}</dd>
 
-			</dl>
-			{{ form.render_edit }}
-			<div class="jobsub_edit_save">
-					<input type="submit" name="submit" value="Save" class="hue-submit"/>
-					<label><input type="checkbox" name="save_submit"/> Submit upon save.</label>
+            {{ form.render_edit }}
+			
+			<div class="actions">
+                <input type="submit" name="submit" value="Save" class="btn primary"/>
+                <input type="checkbox" name="save_submit"/> Submit upon save.
+                <a href="/jobsub/" class="btn">Cancel</a>
 			</div>
-		</form>
-	</div>
-</div>
+
+
+        </form>
+
+
+    </div>
+
+
 {% endblock %}

+ 19 - 18
apps/jobsub/src/jobsub/templates/forms/basic_parameterization.html

@@ -7,7 +7,7 @@ to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
-    http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
@@ -15,24 +15,25 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
-<dl class="clearfix">
+<div>
 {% for field in form %}
-  <dt>{{ field.label }}</dt>
-  <dd>
-      <div>
-        {{ field|safe }}
-      </div>
-      {% if field.help_text %}
-      <p>
-        {{ field.help_text|safe}}
-      </p>
-      {% endif %}
+<label>{{ field.label }}</label>
 
-      <div class="jobsub_errors">{{ field.errors }}</div>
+<div>
+    {{ field|safe }}
+</div>
+{% if field.help_text %}
+<div>
+    {{ field.help_text|safe}}
+</div>
+{% endif %}
+{% if field.errors %}
+<div class="alert-message">{{ field.errors }}</div>
+{% endif %}
+
+{% ifequal field.label "Output" %}
+<!-- Filechoose would go here; also for "Input" -->
+{% endifequal %}
 
-      {% ifequal field.label "Output" %}
-      <!-- Filechoose would go here; also for "Input" -->
-      {% endifequal %}
-  </dd>
 {% endfor %}
-</dl>
+</div>

+ 29 - 27
apps/jobsub/src/jobsub/templates/forms/jar.html

@@ -7,7 +7,7 @@ to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
-    http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,29 +16,31 @@ See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
 {# Currently very generic form for jar submission #}
-<dl class="jobsub_basic clearfix">
-
-	<dt>{{ form.jarfile.label }}</dt>
-	<dd class="jobsub_file">
-			<div class="jobsub_input">
-				{{ form.jarfile|safe }}
-			</div>
-			<p>
-				{{ form.jarfile.help_text|safe}}
-			</p>
-			<div class="jobsub_errors">{{ form.jarfile.errors }}</div>
-	</dd>
-
-	<dt>{{ form.arguments.label }}</dt>
-	<dd class="jobsub_paths">
-		<div class="jobsub_input">
-			{{ form.arguments|safe }}
-			<a class="hue-choose_file" data-filters="ArtButton" data-chooseFor="jarfile">...</a>
-		</div>
-		<p>
-			{{ form.arguments.help_text|safe}}
-		</p>
-		<div class="jobsub_errors">{{ form.arguments.errors }}</div>
-	</dd>
-
-</dl>
+
+
+<label>{{ form.jarfile.label }}</label>
+<div>
+    <div class="jobsub_input">
+        {{ form.jarfile|safe }}
+    </div>
+    <p>
+        {{ form.jarfile.help_text|safe}}
+    </p>
+
+    <div class="jobsub_errors">{{ form.jarfile.errors }}</div>
+</div>
+
+<label>{{ form.arguments.label }}</label>
+<div>
+    <div class="jobsub_input">
+        {{ form.arguments|safe }}
+        <a class="btn">...</a>
+    </div>
+    <p>
+        {{ form.arguments.help_text|safe}}
+    </p>
+
+    <div class="jobsub_errors">{{ form.arguments.errors }}</div>
+</div>
+
+

+ 213 - 183
apps/jobsub/src/jobsub/templates/forms/streaming.html

@@ -7,7 +7,7 @@ to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
-    http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
@@ -15,186 +15,216 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
-	<dl class="jobsub_basic clearfix">
-
-		<dt>{{ form.input.label }}</dt>
-		<dd class="jobsub_multiinput jobsub_paths">
-				<div class="jobsub_input">
-					{{ form.input|safe }}
-				</div>
-				<p>
-					{{ form.input.help_text }}
-				</p>
-				<div class="jobsub_errors">
-				{{ form.input.errors }}
-				</div>
-		</dd>
-
-		<dt>{{ form.output.label }}</dt>
-		<dd class="jobsub_paths">
-			<div class="jobsub_input">
-				{{ form.output|safe }}
-			</div>
-			<p>
-				{{ form.output.help_text|safe}}
-			</p>
-			<div class="jobsub_errors">{{ form.output.errors }}</div>
-		</dd>
-
-		<dt>{{ form.mapper_cmd.label }}</dt>
-		<dd>
-			<div class="jobsub_input">
-				{{ form.mapper_cmd|safe }}
-			</div>
-			<p>
-				{{ form.mapper_cmd.help_text|safe}}
-			</p>
-				<div class="jobsub_errors">{{ form.mapper_cmd.errors }}</div>
-		</dd>
-
-		<dt>{{ form.reducer_cmd.label }}</dt>
-		<dd>
-			<div class="jobsub_input">
-				{{ form.reducer_cmd|safe }}
-				
-			</div>
-			<p>
-				{{ form.reducer_cmd.help_text|safe}}
-			</p>
-			<div class="jobsub_errors">{{ form.reducer_cmd.errors }}</div>
-		</dd>
-			
-		<dt>{{ form.num_reduce_tasks.label }}</dt>
-		<dd>
-			<div class="jobsub_input">
-				{{ form.num_reduce_tasks|safe }}
-			</div>
-			<p>
-				{{ form.num_reduce_tasks.help_text|safe}}
-			</p>
-			<div class="jobsub_errors">{{ form.num_reduce_tasks.errors }}</div>
-		</dd>
-
-		<dt>{{ form.cache_files.label }}</dt>
-		<dd class="jobsub_multiinput jobsub_paths">
-			<div class="jobsub_input">
-				{{ form.cache_files|safe }}
-				
-			</div>
-			<p>
-				{{ form.cache_files.help_text|safe}}
-			</p>
-			<div class="jobsub_errors">{{ form.cache_files.errors }}</div>
-		</dd>
-
-	</dl>
-
-	<div data-filters="CollapsingElements">
-          <dl class="jobsub_toggler clearfix">
-                  <dt></dt>
-                  <dd>
-                          <a class="jobsub_toggle_advanced collapser">Show Advanced Options</a>
-                  </dd>
-          </dl>
-          <dl class="jobsub_advanced clearfix collapsible">
-                  <dt>{{ form.mapper_class.label }}</dt>
-                  <dd>
-                          <div class="jobsub_input">
-                                  {{ form.mapper_class|safe }}
-                          </div>
-                          <p>
-                                  {{ form.mapper_class.help_text|safe}}
-                          </p>
-                          <div class="jobsub_errors">{{ form.mapper_class.errors }}</div>
-                  </dd>
-
-                  <dt>{{ form.combiner_class.label }}</dt>
-                  <dd>
-                          <div class="jobsub_input">
-                                  {{ form.combiner_class|safe }}
-                          </div>
-                          <p>
-                                  {{ form.combiner_class.help_text|safe}}
-                          </p>
-                          <div class="jobsub_errors">{{ form.jobsub_input.errors }}</div>
-                  </dd>
-
-                  <dt>{{ form.reducer_class.label }}</dt>
-                  <dd>
-                          <div class="jobsub_input">
-                                  {{ form.reducer_class|safe }}
-                          </div>
-                          <p>
-                                  {{ form.reducer_class.help_text|safe}}
-                          </p>
-                          <div class="jobsub_errors">{{ form.reducer_class.errors }}</div>
-                  </dd>
-
-                  <dt>{{ form.inputformat_class.label }}</dt>
-                  <dd>
-                          <div class="jobsub_input">
-                                  {{ form.inputformat_class|safe }}
-                          </div>
-                          <p>
-                                  {{ form.inputformat_class.help_text|safe}}
-                          </p>
-                          <div class="jobsub_errors">{{ form.inputformat_class.errors }}</div>
-                  </dd>
-
-                  <dt>{{ form.outputformat_class.label }}</dt>
-                  <dd>
-                          <div class="jobsub_input">
-                                  {{ form.outputformat_class|safe }}
-                          </div>
-                          <p>
-                                  {{ form.outputformat_class.help_text|safe}}
-                          </p>
-                          <div class="jobsub_errors">{{ form.outputformat_class.errors }}</div>
-                  </dd>
-
-                  <dt>{{ form.partitioner_class.label }}</dt>
-                  <dd>
-                          <div class="jobsub_input">
-                                  {{ form.partitioner_class|safe }}
-                          </div>
-                          <p>
-                                  {{ form.partitioner_class.help_text|safe}}
-                          </p>
-                          <div class="jobsub_errors">{{ form.partitioner_class.errors }}</div>
-                  </dd>
-
-                  <dt>{{ form.inputreader.label }}</dt>
-                  <dd>
-                          <div class="jobsub_input">
-                                  {{ form.inputreader|safe }}
-                          </div>
-                          <p>
-                                  {{ form.inputreader.help_text|safe}}
-                          </p>
-                          <div class="jobsub_errors">{{ form.inputreader.errors }}</div>
-                  </dd>
-
-                  <dt>{{ form.cache_archives.label }}</dt>
-                  <dd>
-                          <div class="jobsub_input">
-                                  {{ form.cache_archives|safe }}
-                          </div>
-                          <p>
-                                  {{ form.cache_archives.help_text|safe }}
-                          </p>
-                          <div class="jobsub_errors">{{ form.cache_archives.errors }}</div>
-                  </dd>
-
-                  <dt>{{ form.hadoop_properties.label }}</dt>
-                  <dd>
-                          <div class="jobsub_input">
-                                  {{ form.hadoop_properties|safe }}
-                          </div>
-                          <p>
-                                  {{ form.hadoop_properties.help_text|safe}}
-                          </p>
-                          <div class="jobsub_errors">{{ form.hadoop_properties.errors }}</div>
-                  </dd>
-
-          </dl>
+
+
+<label>{{ form.input.label }}</label>
+<div class="jobsub_multiinput jobsub_paths">
+    <div class="jobsub_input">
+        {{ form.input|safe }}
+    </div>
+    <p>
+        {{ form.input.help_text }}
+    </p>
+
+    <div class="jobsub_errors">
+        {{ form.input.errors }}
+    </div>
+</div>
+
+<label>{{ form.output.label }}</label>
+<div class="jobsub_paths">
+    <div class="jobsub_input">
+        {{ form.output|safe }}
+    </div>
+    <p>
+        {{ form.output.help_text|safe}}
+    </p>
+
+    <div class="jobsub_errors">{{ form.output.errors }}</div>
+</div>
+
+<label>{{ form.mapper_cmd.label }}</label>
+<div>
+    <div class="jobsub_input">
+        {{ form.mapper_cmd|safe }}
+    </div>
+    <p>
+        {{ form.mapper_cmd.help_text|safe}}
+    </p>
+
+    <div class="jobsub_errors">{{ form.mapper_cmd.errors }}</div>
+</div>
+
+<label>{{ form.reducer_cmd.label }}</label>
+<div>
+    <div class="jobsub_input">
+        {{ form.reducer_cmd|safe }}
+
+    </div>
+    <p>
+        {{ form.reducer_cmd.help_text|safe}}
+    </p>
+
+    <div class="jobsub_errors">{{ form.reducer_cmd.errors }}</div>
+</div>
+
+<label>{{ form.num_reduce_tasks.label }}</label>
+<div>
+    <div class="jobsub_input">
+        {{ form.num_reduce_tasks|safe }}
+    </div>
+    <p>
+        {{ form.num_reduce_tasks.help_text|safe}}
+    </p>
+
+    <div class="jobsub_errors">{{ form.num_reduce_tasks.errors }}</div>
+</div>
+
+<label>{{ form.cache_files.label }}</label>
+<div class="jobsub_multiinput jobsub_paths">
+    <div class="jobsub_input">
+        {{ form.cache_files|safe }}
+
+    </div>
+    <p>
+        {{ form.cache_files.help_text|safe}}
+    </p>
+
+    <div class="jobsub_errors">{{ form.cache_files.errors }}</div>
+</div>
+
+
+<a class="jobsub_toggle_advanced btn">Show Advanced Options</a>
+
+
+<div class="advanced_options" style="visibility: collapse; display: none;">
+    <label>{{ form.mapper_class.label }}</label>
+
+    <div>
+        <div class="jobsub_input">
+            {{ form.mapper_class|safe }}
+        </div>
+        <p>
+            {{ form.mapper_class.help_text|safe}}
+        </p>
+
+        <div class="jobsub_errors">{{ form.mapper_class.errors }}</div>
+    </div>
+
+    <label>{{ form.combiner_class.label }}</label>
+
+    <div>
+        <div class="jobsub_input">
+            {{ form.combiner_class|safe }}
+        </div>
+        <p>
+            {{ form.combiner_class.help_text|safe}}
+        </p>
+
+        <div class="jobsub_errors">{{ form.jobsub_input.errors }}</div>
+    </div>
+
+    <label>{{ form.reducer_class.label }}</label>
+
+    <div>
+        <div class="jobsub_input">
+            {{ form.reducer_class|safe }}
+        </div>
+        <p>
+            {{ form.reducer_class.help_text|safe}}
+        </p>
+
+        <div class="jobsub_errors">{{ form.reducer_class.errors }}</div>
+    </div>
+
+    <label>{{ form.inputformat_class.label }}</label>
+
+    <div>
+        <div class="jobsub_input">
+            {{ form.inputformat_class|safe }}
+        </div>
+        <p>
+            {{ form.inputformat_class.help_text|safe}}
+        </p>
+
+        <div class="jobsub_errors">{{ form.inputformat_class.errors }}</div>
+    </div>
+
+    <label>{{ form.outputformat_class.label }}</label>
+
+    <div>
+        <div class="jobsub_input">
+            {{ form.outputformat_class|safe }}
+        </div>
+        <p>
+            {{ form.outputformat_class.help_text|safe}}
+        </p>
+
+        <div class="jobsub_errors">{{ form.outputformat_class.errors }}</div>
+    </div>
+
+    <label>{{ form.partitioner_class.label }}</label>
+
+    <div>
+        <div class="jobsub_input">
+            {{ form.partitioner_class|safe }}
+        </div>
+        <p>
+            {{ form.partitioner_class.help_text|safe}}
+        </p>
+
+        <div class="jobsub_errors">{{ form.partitioner_class.errors }}</div>
+    </div>
+
+    <label>{{ form.inputreader.label }}</label>
+
+    <div>
+        <div class="jobsub_input">
+            {{ form.inputreader|safe }}
+        </div>
+        <p>
+            {{ form.inputreader.help_text|safe}}
+        </p>
+
+        <div class="jobsub_errors">{{ form.inputreader.errors }}</div>
+    </div>
+
+    <label>{{ form.cache_archives.label }}</label>
+
+    <div>
+        <div class="jobsub_input">
+            {{ form.cache_archives|safe }}
+        </div>
+        <p>
+            {{ form.cache_archives.help_text|safe }}
+        </p>
+
+        <div class="jobsub_errors">{{ form.cache_archives.errors }}</div>
+    </div>
+
+    <label>{{ form.hadoop_properties.label }}</label>
+
+    <div>
+        <div class="jobsub_input">
+            {{ form.hadoop_properties|safe }}
         </div>
+        <p>
+            {{ form.hadoop_properties.help_text|safe}}
+        </p>
+
+        <div class="jobsub_errors">{{ form.hadoop_properties.errors }}</div>
+    </div>
+
+</div>
+
+<script type="text/javascript">
+    $('.jobsub_toggle_advanced').click(function() {
+        if ($('.advanced_options').css('visibility') == 'collapse'){
+            $('.advanced_options').css('visibility', 'visible').css('display', 'block');
+            $('.jobsub_toggle_advanced').html('Hide Advanced Options');
+        }else{
+            $('.advanced_options').css('visibility', 'collapse').css('display', 'none');
+            $('.jobsub_toggle_advanced').html('Show Advanced Options');
+        }
+    });
+</script>

+ 76 - 11
apps/jobsub/src/jobsub/templates/layout.html

@@ -15,17 +15,82 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-	<head>
-		<title>{% block title %}{% endblock %} :: Job Designer :: </title>
-		{%block head %}{% endblock %}
-	</head>
-	<body class="hue-shared">
-		<div class="toolbar">
-			<a class="jobsub_joblist" href="{% url jobsub.views.list_designs %}">Job List</a>
-			<a class="jobsub_history" href="{% url jobsub.views.watch %}">History</a>
+{% load babel %}
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+	<title>{% block title %}{% endblock %} - Job Designer</title>
+	{%block head %}{% endblock %}
+	<link rel="stylesheet" href="/static/ext/css/bootstrap.min.css" type="text/css" media="screen" title="no title" charset="utf-8" />
+	<link rel="stylesheet" href="/static/css/jhue.css" type="text/css" media="screen" title="no title" charset="utf-8" />
+	
+	<style type="text/css">
+      body {
+        padding-top: 100px;
+      }
+    </style>
+	<script src="/static/ext/js/jquery/jquery-1.7.min.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/js/Source/jHue/jquery.showusername.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/js/Source/jHue/jquery.contextmenu.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/ext/js/jquery/plugins/jquery.simpleplaceholder.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/ext/js/jquery/plugins/jquery.dataTables.1.8.2.min.js" type="text/javascript" charset="utf-8"></script>
+	<script src="/static/ext/js/bootstrap-tabs.js" type="text/javascript" charset="utf-8"></script>	
+	<script src="/static/ext/js/bootstrap-dropdown.js" type="text/javascript" charset="utf-8"></script>	
+	<script src="/static/ext/js/bootstrap-modal.js" type="text/javascript" charset="utf-8"></script>	
+	<script src="/static/ext/js/bootstrap-twipsy.js" type="text/javascript" charset="utf-8"></script>	
+	<script src="/static/ext/js/bootstrap-popover.js" type="text/javascript" charset="utf-8"></script>	
+	
+
+	<script type="text/javascript" charset="utf-8">
+		$(document).ready(function(){
+			$("#username").showUsername();
+			$("input:text[placeholder]").simplePlaceholder();
+			$(".submitter").keydown(function(e){
+				if (e.keyCode==13){
+					$(this).closest("form").submit();
+				}
+			}).change(function(){
+				$(this).closest("form").submit();
+			});
+		});
+	</script>
+	
+</head>
+<body>
+	<div class="topbar">
+		<div class="topbar-inner">
+			<div class="container-fluid">
+				<a class="brand" href="#">jHue</a>
+				<ul class="nav">
+					<li><a href="/beeswax">Beeswax</a></li>
+					<li><a href="/filebrowser/">File Browser</a></li>
+					<li class="active"><a href="/jobsub/">Job Designer</a></li>
+					<li><a href="/jobbrowser/jobs/">Job Browser</a></li>
+					<li><a href="/useradmin/">User Admin</a></li>
+					<li><a href="/shell/">{{_('Shell')}}</a></li>
+					<li><a href="/help/">Help</a></li>
+					<li><a href="/about/">About</a></li>
+				</ul>
+				<p class="pull-right">Logged in as <strong><span id="username">xxx</span></strong> - <a href="/accounts/logout">Sign out</a></p>
+			</div>
+		</div>
+	</div>
+	<div class="menubar">
+		<div class="menubar-inner">
+			<div class="container-fluid">
+				<ul class="nav">
+					{%block nav %}{% endblock %}
+				</ul>
+			</div>
 		</div>
+	</div>
+	
+	<div class="container-fluid">
 		{% block content %}{% endblock %}
-	</body>
+	</div>
+</body>
 </html>

+ 101 - 54
apps/jobsub/src/jobsub/templates/list.html

@@ -8,7 +8,7 @@ to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
-    http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,58 +17,105 @@ See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
 {% block title %}Job Design List{% endblock %}
+{% block nav %}
+<li><a href="{% url jobsub.views.list_designs %}" class="selected">Job List</a></li>
+<li><a href="{% url jobsub.views.watch %}">History</a></li>
+{% endblock %}
 {% block content %}
-<div id="jobsub_joblist jobsub_col_wrapper" class="view" data-filters="SplitView">
-  <h1>Job Designer: Job Designs</h1>
-  <div class="jobsub_left_col left_col">
-    {% include "types.html" %}
-  </div>
-  <div class="jobsub_right_col right_col">
-    <div class="jobsub_topsection clearfix">
-      <form class="jobsub_filter" data-filters="SubmitOnChange" action="{% url jobsub.list %}" method="get">
-        <span class="filter_text">Filter By Owner:</span>
-        <input data-filters="ArtInput, OverText" data-art-input-type="search" name="owner" alt="Filter By Owner" value="{{ owner }}"/>
-        <input data-filters="ArtInput, OverText" data-art-input-type="search" name="name" alt="Filter By Name" value="{{ name }}"/>
-        <input class="submit" type="submit"/>
-      </form>
-    </div>
-  
-    <table data-filters="HtmlTable" class="selectable sortable" cellpadding="0" cellspacing="0">
-      <thead>
-        <tr>
-          <th>Owner</th>
-          <th>Name</th>
-          <th colspan="2">Last Modified</th>
-        </tr>
-      </thead>
-      <tbody>
-    {% for jobdesign in jobdesigns %}
-        <tr 
-          {% ifequal saved jobdesign.id %} class="jobsub_saved"{% endifequal %}
-          data-filters="ContextMenu"
-          data-context-menu-actions="[{'events':['contextmenu','click:relay(.item-options)'],'menu':'ul.context-menu'}]"
-          data-dblclick-delegate= "{'dblclick_loads':'a.run'}">
-          <td>
-            {{ jobdesign.owner.username }}
-            <ul class="context-menu">
-              <li><a title="Launch job with this design" class="run frame_tip" href="{{ jobdesign.submit_url }}">Submit to Cluster</a></li>
-              <li><a title="Copy design" class="copy frame_tip" href="{{ jobdesign.clone_url }}">Copy</a></li>
-              <li><a title="Edit this design" class="edit frame_tip" href="{{ jobdesign.edit_url }}">Edit</a></li>
-              <li><a title="Delete this design" alt="Are you sure you want to delete this design?" class="delete frame_tip" href="{{ jobdesign.delete_url }}">Delete</a></li>
-            </ul>
-          </td>
-          <td>{{ jobdesign.name }}</td>
-          <td>
-            <span class="jobsub_actual_date" style="display: none">{{ jobdesign.last_modified|date:"U" }}</span>
-            {{ jobdesign.last_modified|timesince }} ago
-          </td>
-          <td>
-            <a class="item-options">options</a>
-          </td>
-        </tr>
-    {% endfor %}
-      </tbody>
-    </table>
-  </div>
-</div>
+        <div class="sidebar">
+			<div class="well">
+            {% include "types.html" %}
+			</div>
+        </div>
+
+        <div class="content">
+			<h1>Job Designer: Job Designs</h1>
+            <form action="{% url jobsub.list %}" method="get">
+                <div class="well">
+                    <span>Filter By Owner:</span>
+                    <input name="owner" alt="Filter By Owner"
+                           value="{{ owner }}"/>
+                    <span>Filter By Name:</span>
+                    <input name="name" alt="Filter By Name"
+                           value="{{ name }}"/>
+                    <input class="btn primary" type="submit"/>
+
+                </div>
+            </form>
+
+            <table class="datatables" cellpadding="0" cellspacing="0">
+                <thead>
+                <tr>
+                    <th>Owner</th>
+                    <th>Name</th>
+                    <th>Last Modified</th>
+                    <th></th>
+                </tr>
+                </thead>
+                <tbody>
+                {% for jobdesign in jobdesigns %}
+                <tr>
+                <td>
+                    {{ jobdesign.owner.username }}
+
+
+                </td>
+                <td>{{ jobdesign.name }}</td>
+                <td>
+                    <span style="display: none">{{ jobdesign.last_modified|date:"U" }}</span>
+                    {{ jobdesign.last_modified|timesince }} ago
+                </td>
+                <td>
+					<a class="btn small contextEnabler" data-menuid="{{ jobdesign.id }}">Options</a>
+					<ul class="contextMenu" id="menu{{ jobdesign.id }}">
+                    	<li><a title="Launch job with this design" class="contextItem" href="{{ jobdesign.submit_url }}">Submit to Cluster</a></li>
+                    	<li><a title="Copy design" class="contextItem" href="{{ jobdesign.clone_url }}">Copy</a></li>
+                    	<li><a title="Edit this design" class="contextItem" href="{{ jobdesign.edit_url }}">Edit</a></li>
+                    	<li><a title="Delete this design" alt="Are you sure you want to delete this design?" class="contextItem confirmationModal" data-confirmation-url="{{ jobdesign.delete_url }}">Delete</a></li>
+                </td>
+                </tr>
+                {% endfor %}
+                </tbody>
+            </table>
+        </div>
+
+
+		<div id="deleteDesign" class="modal hide fade">
+			<form id="deleteDesignForm" action="" method="POST">
+			<div class="modal-header">
+				<a href="#" class="close">&times;</a>
+				<h3 id="deleteDesignMessage">Confirm action</h3>
+			</div>
+			<div class="modal-footer">
+				<input type="submit" class="btn danger" value="Yes"/>
+				<a href="#" class="btn secondary hideModal">No</a>
+			</div>
+			</form>
+		</div>
+<script type="text/javascript" charset="utf-8">
+    $(document).ready(function() {
+        $(".datatables").dataTable({
+            "bPaginate": false,
+            "bLengthChange": false,
+            "bFilter": false,
+            "bInfo": false
+        });
+		$(".contextEnabler").jHueContextMenu();
+		$("#deleteDesign").modal({
+			backdrop: "static",
+			keyboard: true
+		});
+		$(".confirmationModal").live("click", function(){
+			var _this = $(this);
+			$.getJSON(_this.attr("data-confirmation-url"), function(data){
+				$("#deleteDesignForm").attr("action", data.url);
+				$("#deleteDesignMessage").text(_this.attr("alt"));
+			});
+			$("#deleteDesign").modal("show");
+		});
+		$(".hideModal").click(function(){
+			$("#deleteDesign").modal("hide");
+		});
+    });
+</script>
 {% endblock %}

+ 25 - 23
apps/jobsub/src/jobsub/templates/parameterize.html

@@ -8,7 +8,7 @@ to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
-    http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,28 +17,30 @@ See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
 {% block title %}Submit Job: {{ job_design.name }}{% endblock %}
+{% block nav %}
+<li><a href="{% url jobsub.views.list_designs %}" class="selected">Job List</a></li>
+<li><a href="{% url jobsub.views.watch %}">History</a></li>
+{% endblock %}
+
 {% block content %}
-	<div class="prompt_popup">
-		<h1 class="jframe-hidden">Submit Job: {{ job_design.name }} </h1>
-		<div class="jobsub_parameterize" id="view">
-			<dl class="jobsub_parameterize_description clearfix">
-				<dt>Job Name</dt>
-				<dd>{{ job_design.name }}</dd>
-				{% if job_design.description %}
-				<dt>Description</dt>
-				<dd>{{ job_design.description }}</dd>
-				{% endif %}
-			</dl>
-			
-			<form action="{% url jobsub.views.submit_design job_design.id %}" method="POST" enctype="multipart/form-data">
-			{{ form.render_parameterization }}
-			<dl class="jframe-hidden">
-				<dt>&nbsp;</dt>
-				<dd class="jobsub_edit_save">
-					<input type="submit" name="submitter" value="Start Job" class="hue-submit"/>
-				</dd>
-			</dl>
-			</form>
-		</div>
+<div class="sidebar">
+	<div class="well">
+		<h6>Job Name</h6>
+        <span>{{ job_design.name }}</span>
+        {% if job_design.description %}
+        <h6>Description</h6>
+        <span>{{ job_design.description }}</span>
+        {% endif %}
 	</div>
+</div>
+<div class="content">
+	<h1>Submit Job: {{ job_design.name }} </h1>
+	<form class="form-stacked" action="{% url jobsub.views.submit_design job_design.id %}" method="POST" enctype="multipart/form-data">
+		{{ form.render_parameterization }}
+        <div class="actions">
+            <input type="submit" name="submitter" value="Start Job" class="btn primary"/>
+            <a href="/jobsub/" class="btn">Cancel</a>
+        </div>
+	</form>
+</div>
 {% endblock %}

+ 27 - 25
apps/jobsub/src/jobsub/templates/scripteditor.html

@@ -1,3 +1,4 @@
+{% extends "layout.html" %}
 {% comment %}
 Licensed to Cloudera, Inc. under one
 or more contributor license agreements.  See the NOTICE file
@@ -7,7 +8,7 @@ to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
-    http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
@@ -15,27 +16,28 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
-<title>
-Script Editor
-</title>
-</head>
-<body>
-{% if error %}
-<b>Error!</b> {{ error }}
-{% endif %}
-{% if message %}
-<b>{{ message }}</b>
-{% endif %}
-<form action="" method="POST" enctype="multipart/form-data">
-{{ templates.non_field_errors }}
-{{ template.as_p }}
-<input type="submit" name="load" value="Load Template" />
-{{ editor.non_field_errors }}
-{{ editor.as_p }}
-<input type="submit" name="save" value="Save" />
-</form>
-</body>
-</html>
+{% block title %}Script editor{% endblock %}
+{% block nav %}
+<li><a href="{% url jobsub.views.list_designs %}" class="selected">Job List</a></li>
+<li><a href="{% url jobsub.views.watch %}">History</a></li>
+{% endblock %}
+
+{% block content %}
+
+	{% if error %}
+		<h1>Error!</h1> 
+		<div class="alert-message block-message error">{{ error }}</div>
+	{% endif %}
+	{% if message %}
+		<div class="alert-message block-message info">{{ message }}</div>
+	{% endif %}
+	<form action="" method="POST" enctype="multipart/form-data">
+		{{ templates.non_field_errors }}
+		{{ template.as_p }}
+		<input type="submit" name="load" value="Load Template" />
+		{{ editor.non_field_errors }}
+		{{ editor.as_p }}
+		<input type="submit" name="save" value="Save" class="btn primary" />
+	</form>
+	
+{% endblock %}

+ 2 - 2
apps/jobsub/src/jobsub/templates/types.html

@@ -15,8 +15,8 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 {% endcomment %}
-<h2>Create a Job Design</h2>
-<ul class="jobsub_new">
+<h4>Create a Job Design</h4>
+<ul>
 	{% for type, newurl in newlinks %}
 		<li><a href="{{ newurl }}" class="jframe_target(.jobsub_right_col)">{{ type|capfirst }}</a></li>
 	{% endfor %}

+ 58 - 32
apps/jobsub/src/jobsub/templates/watch.html

@@ -8,7 +8,7 @@ to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
-    http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
@@ -18,37 +18,63 @@ limitations under the License.
 {% endcomment %}
 {% block title %}Job History{% endblock %}
 {% block head %}
-  <meta http-equiv="refresh" content="5" />
+<meta http-equiv="refresh" content="5"/>
+{% endblock %}
+{% block nav %}
+<li><a href="{% url jobsub.views.list_designs %}">Job List</a></li>
+<li><a href="{% url jobsub.views.watch %}" class="selected">History</a></li>
 {% endblock %}
 {% block content %}
-  <div id="jobsub_history" class="view">
-    <h1>Recently Launched Jobs</h1>
-    <table data-filters="HtmlTable" class="selectable sortable">
-      <thead>
-        <tr>
-          <th>Owner</th>
-          <th>Name</th>
-          <th>Submitted</th>
-          <th colspan=2>Last known state</th>
-        </tr>
-      </thead>
-      <tbody>
-        {% for submission in submissions %}
-          <tr data-dblclick-delegate= "{'dblclick_loads':'a'}">
-            <td>{{ submission.owner }}</td>
-            <td>{{ submission.name }}</td>
-            <td>
-              <span class="jobsub_actual_date" style="display: none">{{ submission.submission_date|date:"U" }}</span>
-              {{ submission.submission_date|timesince }} ago
-            </td>
-            <td>{{ submission.last_seen_state_as_string }}</td>
-            <td><a href="{{ submission.watch_url }}" class="jobsub_watch">watch progress</a></td>
-          </tr>
-        {% endfor %}
-      </tbody>
-    </table>
-    {% if more %}
-      <a href="/jobsub/watch/?offset={{ offset }}&limit={{ limit|add:"20" }}" class="jobsub_more">See more</a>
-    {% endif %}
-  </div>
+
+<h1>Recently Launched Jobs</h1>
+<table class="datatables">
+    <thead>
+    <tr>
+        <th>Owner</th>
+        <th>Name</th>
+        <th>Submitted</th>
+        <th>Last known state</th>
+        <th></th>
+    </tr>
+    </thead>
+    <tbody>
+    {% for submission in submissions %}
+    <tr>
+        <td>{{ submission.owner }}</td>
+        <td>{{ submission.name }}</td>
+        <td>
+            <span class="jobsub_actual_date" style="display: none">{{ submission.submission_date|date:"U" }}</span>
+            {{ submission.submission_date|timesince }} ago
+        </td>
+
+        <td>
+        {%if submission.last_seen_state_as_string == "SUCCESS" %}
+            <span class="label success">{{ submission.last_seen_state_as_string }}</span>
+        {% else %}
+        {%if submission.last_seen_state_as_string == "ERROR" %}
+            <span class="label important">{{ submission.last_seen_state_as_string }}</span>
+        {%else %}
+            <span class="label">{{ submission.last_seen_state_as_string }}</span>
+        {% endif %}{% endif %}
+        </td>
+        <td><a href="{{ submission.watch_url }}" class="btn">Watch Progress</a></td>
+    </tr>
+    {% endfor %}
+    </tbody>
+</table>
+{% if more %}
+<a href="/jobsub/watch/?offset={{ offset }}&limit={{ limit|add:"20" }}" class="jobsub_more">See more</a>
+{% endif %}
+
+<script type="text/javascript" charset="utf-8">
+    $(document).ready(function() {
+        $(".datatables").dataTable({
+            "bPaginate": false,
+            "bLengthChange": false,
+            "bFilter": false,
+            "bInfo": false
+        });
+    });
+</script>
+
 {% endblock %}

+ 25 - 18
apps/jobsub/src/jobsub/templates/watch_submission.html

@@ -19,34 +19,41 @@ limitations under the License.
 {% block title %}Job - {{ submission.name }}{% endblock %}
 {% block head %}
 	{% if not completed %}
-		<meta http-equiv="refresh" content="10" />
+		<meta http-equiv="refresh" content="5" />
 	{% endif %}
 {% endblock %}
+{% block nav %}
+<li><a href="{% url jobsub.views.list_designs %}" class="selected">Job List</a></li>
+<li><a href="{% url jobsub.views.watch %}">History</a></li>
+{% endblock %}
 {% block content %}
-	<div id="jobsub_output" class="view">
-		<h1>Job - {{ submission.name }}</h1>
-		<b class="state{% if completed %} complete {% endif %}" data-single-partial-id="0">
+	<div class="sidebar">
+		<div class="well">
+			<h6>Status</h6>
 			{% if completed %}
-				status: finished
+				<span class="label success">Finished</span>
 			{% else %}
-				status: running
-				<input type="hidden" value="5" class="autorefresh">
-				<span class="jobsub_autorefresh_note">note: this view will auto refresh in <span class="sec_to_autorefresh"></span> seconds</span>
+				<span class="label warning">Running</span>
+				<span class="help-block">note: this view will auto refresh every 5 seconds</span>
 			{% endif %}
-		</b>
-		<div class="jframe_padded" data-filters="SizeTo" data-size-to-height="-74">
-			<h2 class="jobsub_output_links_header">Launched Jobs</h2>
-			<ul class="jobsub_output_links" data-single-partial-id="1">
+			<br/><br/>
+			<h6>Launched Jobs</h6>
+			<ul>
 				{% for j in jobs %}
-					<li><a href="{% url single_job jobid=j %}" target="JobBrowser">{{ j }}</a>
+				<li><a href="{% url single_job jobid=j %}">{{ j }}</a>
 				{% endfor %}
 			</ul>
+		</div>
+	</div>
+	
+	<div class="content">
+		<h1>Job - {{ submission.name }}</h1>		
 
-			<h2 class="jobsub_output_stout_header">Last 10KB of stdout:</h2>
-			<pre class="jobsub_output_stout" data-single-partial-id="2">{{ job_data.stdout_tail }}</pre>
+		<h2>Last 10KB of stdout:</h2>
+		<pre>{{ job_data.stdout_tail }}</pre>
 
-			<h2 class="jobsub_output_sterr_header">Last 10KB of stderr:</h2>
-			<pre class="jobsub_output_sterr" data-single-partial-id="3">{{ job_data.stderr_tail }}</pre>
-		</div>
+		<h2>Last 10KB of stderr:</h2>
+		<pre>{{ job_data.stderr_tail }}</pre>
 	</div>
+		
 {% endblock %}

+ 31 - 17
apps/shell/src/shell/templates/failed_to_create.mako

@@ -1,19 +1,33 @@
-<%namespace name="shared" file="shared_components.mako" />
+## Licensed to Cloudera, Inc. under one
+## or more contributor license agreements.  See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership.  Cloudera, Inc. licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##
+##     http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+<%!
+from desktop.views import commonheader, commonfooter
+%>
 
-${shared.header("Hue Shell", False)}
-
-## use double hashes for a mako template comment
-
-## this id in the div below ("index") is stripped by Hue.JFrame
-## and passed along as the "view" argument in its onLoad event
-
-## the class 'jframe_padded' will give the contents of your window a standard padding
-<div id="index" class="view jframe_padded">
-Failed to create a shell of the given type. The possible reasons for this are:
-1. The system is out of PTYs.
-2. The system cannot create more subprocesses.
-3. You do not have permission to create shells of this type.
-4. There is no shell with that name.
-5. There is no Unix user account for you.
+${commonheader("Hue Shell", "shell")}
+<div class="container-fluid">
+<div>
+	Failed to create a shell of the given type. The possible reasons for this are:
+	<ol>
+		<li>The system is out of PTYs.</li>
+		<li>The system cannot create more subprocesses.</li>
+		<li>You do not have permission to create shells of this type.</li>
+		<li>There is no shell with that name.</li>
+		<li>There is no Unix user account for you.</li>
+	</ol>
+</div>
 </div>
-${shared.footer()}
+${commonfooter()}

+ 239 - 22
apps/shell/src/shell/templates/index.mako

@@ -1,30 +1,247 @@
-<%namespace name="shared" file="shared_components.mako" />
+## Licensed to Cloudera, Inc. under one
+## or more contributor license agreements.  See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership.  Cloudera, Inc. licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##
+##     http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+<%!
+from desktop.views import commonheader, commonfooter
+%>
 
-${shared.header("Hue Shell", True, shells)}
+% if shells:
+	${commonheader("Hue Shell", "shell", "100px")}
+% else:
+	${commonheader("Hue Shell", "shell")}
+% endif
 
-## use double hashes for a mako template comment
 
-## this id in the div below ("index") is stripped by Hue.JFrame
-## and passed along as the "view" argument in its onLoad event
+% if shells:
+<div class="menubar">
+	<div class="menubar-inner">
+		<div class="container-fluid">
+			<ul class="nav">
+			% if len(shells) == 1:
+				% if shells[0]["exists"]:
+					<li><a href="${url('shell.views.create')}?keyName=${shells[0]["keyName"]}" class="${shells[0]["keyName"]}">${shells[0]["niceName"]}</a></li>
+				% else: 
+					<li><a href="#" class="disabled">${shells[0]["niceName"]}</a></li>
+				% endif
+			% else:
+				% if shells[0]["exists"]:
+					<li><a href="${url('shell.views.create')}?keyName=${shells[0]["keyName"]}" class="${shells[0]["keyName"]}">${shells[0]["niceName"]}</a></li>
+				% else:
+					<li><a href="#" class="disabled">${shells[0]["niceName"]}</a></li>
+				% endif
+				% for item in shells[1:-1]:
+					% if item["exists"]:
+						<li><a href="${url('shell.views.create')}?keyName=${item["keyName"]}" class="${item["keyName"]}">${item["niceName"]}</a></li>
+					% else:
+						<li><a href="#" class="disabled">${item["niceName"]}</a></li>
+					% endif
+				% endfor
+				% if shells[-1]["exists"]:
+					<li><a href="${url('shell.views.create')}?keyName=${shells[-1]["keyName"]}" class="${shells[-1]["keyName"]}">${shells[-1]["niceName"]}</a></li>
+				% else:
+					<li><a href="#" class="disabled">${shells[-1]["niceName"]}</a></li>
+				% endif
+			% endif
+			</ul>
+		</div>
+	</div>
+</div>
+% endif
+
+
+<div class="container-fluid">
 
-## the class 'jframe_padded' will give the contents of your window a standard padding
-<div id="index" class="view jframe_padded shell_container">
   % if shell_id:
-    <span class="shell_id hidden">${shell_id}</span>
+	<style type="text/css" media="screen">
+		body {
+			background-color: #333;
+		}
+		.shell {
+			background-color:#333;
+			color:#EEE;
+			font-family: monospace;
+			font-size: 14px;
+		}
+		#shellOutput {
+			/*position:absolute;
+			left:0;
+			top:-20px;*/
+			padding:0;
+			width:100%;
+		}
+		#shellInput {
+			border:0;
+			margin:0;
+			margin-top:10px;
+			margin-bottom:10px;
+			padding:0;
+			box-shadow:none;
+			
+
+		}
+		#shellInput:focus {
+			box-shadow:none;
+			border:0;
+		}
+		#shellContent {
+
+		}
+	</style>
+	<div id="shellOutput" class="shell">
+		<span id="shellContent"></span>
+		<input type="text" id="shellInput" class="shell" />
+	</div>
+	<span id="shell_id" class="hidden">${shell_id}</span>
   % else:
-    <div>
-      <ul>
-        % for item in shells:
-          <li>
-          % if item["exists"]:
-            <a class="round Button menu_button">${item["niceName"]}</a><span class="hidden">${item["keyName"]}</span>
-          % else:
-            <a class="round Button disabled">${item["niceName"]}</a>
-          % endif
-          </li>
-        % endfor
-      </ul>
-    </div>
+	<div>
+		<h3>Please select one of the available shells from the toolbar above.</h3>
+	</div>
   % endif
+
+
+<script type="text/javascript" charset="utf-8">
+	$(document).ready(function(){
+		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
+		for (var i=0;i<hashes.length;i++){
+			if (hashes[i].indexOf("keyName")>-1){
+				$("."+hashes[i].split("=")[1]).addClass("selected");
+			}
+		}
+		
+		var hueInstanceID = function() {
+			var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
+			var lastIndex = chars.length - 1;
+			var stringLength = 128;
+			var randomString = "";
+			for (var i = 0; i < stringLength; i++) {
+				var randomIndex = Math.floor(Math.random()*lastIndex);
+				randomString += chars.substring(randomIndex, randomIndex+1);
+			}
+			return randomString;
+		}();
+		
+		if ($("#shell_id").length){
+		
+			var shell = {};
+			shell.id = $("#shell_id").text();
+			shell.get = function(offset){
+				var _shell = this;
+				$.ajax({
+					type: "POST",
+					url: "/shell/retrieve_output",
+					data: {
+						numPairs: 1,
+						offset1: offset,
+						shellId1: _shell.id
+					},
+					beforeSend: function(xhr){ 
+						xhr.setRequestHeader("X-Request", "JSON");
+						xhr.setRequestHeader("Hue-Instance-ID", hueInstanceID);
+					},
+					success: function(data, status, xhr){
+						if (status == "success"){
+							if (data.periodicResponse){
+								shell.get(offset);
+							}
+							else {
+								var _out = data[_shell.id].output;
+								_out = _out.replace(/>/g, '&gt;');
+								_out = _out.replace(/</g, '&lt;');
+								_out = _out.replace(/\n/g, '<br />');
+								$("#shellContent").html($("#shellContent").html()+_out);
+								if (_out.indexOf("Disconnected!")>-1){
+									window.setTimeout(function(){
+										$.ajax({
+											type: "POST",
+											url: "/shell/kill_shell",
+											data: {
+												shellId: _shell.id
+											},
+											beforeSend: function(xhr){ 
+												xhr.setRequestHeader("X-Request", "JSON");
+											},
+											success: function(data, status, xhr){
+												location.href = "/shell/";
+											}
+										});
+									},500);
+								}
+								$("html").animate({ scrollTop: $(document).height() }, "fast");
+								_shell.get(data[_shell.id].nextOffset);
+							}
+						}
+					}
+				});
+			};
+			shell.send = function(command){
+				var _shell = this;
+				$.ajax({
+					type: "POST",
+					url: "/shell/process_command",
+					data: {
+						lineToSend: command,
+						shellId: _shell.id
+					},
+					beforeSend: function(xhr){ 
+						xhr.setRequestHeader("X-Request", "JSON");
+					},
+					success: function(data, status, xhr){
+						if (status == "success"){
+							if (command == "quit"){
+								window.setTimeout(function(){
+									$.ajax({
+										type: "POST",
+										url: "/shell/kill_shell",
+										data: {
+											shellId: _shell.id
+										},
+										beforeSend: function(xhr){ 
+											xhr.setRequestHeader("X-Request", "JSON");
+										},
+										success: function(data, status, xhr){
+											location.href = "/shell/";
+										}
+									});
+								},500);
+							}
+						}
+					}
+				});
+			};
+		
+			shell.get(0);
+		
+			$("#shellInput").val("");
+			$("#shellInput").focus();
+		
+			$("#shellInput").blur(function(){
+				window.setTimeout(function(){
+					$("#shellInput").focus();
+				}, 50);
+			});
+			$("#shellInput").keydown(function(e){
+				if ((e.keyCode ? e.keyCode : e.which) == 13){
+					shell.send($(this).val());
+					$(this).val("");
+				}
+			});
+		
+		}
+				
+		
+	});
+</script>
 </div>
-${shared.footer()}
+${commonfooter()}

+ 26 - 14
apps/shell/src/shell/templates/no_such_user.mako

@@ -1,16 +1,28 @@
-<%namespace name="shared" file="shared_components.mako" />
+## Licensed to Cloudera, Inc. under one
+## or more contributor license agreements.  See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership.  Cloudera, Inc. licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##
+##     http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+<%!
+from desktop.views import commonheader, commonfooter
+%>
 
-${shared.header("Hue Shell", False)}
-
-## use double hashes for a mako template comment
-
-## this id in the div below ("index") is stripped by Hue.JFrame
-## and passed along as the "view" argument in its onLoad event
-
-## the class 'jframe_padded' will give the contents of your window a standard padding
-<div id="index" class="view jframe_padded">
-The Shell app requires a Unix user account for every user of Hue on the remote webserver.
-Please ask your admin to create a user account for you on the remote webserver as
-described in the Shell documentation.
+${commonheader("Hue Shell", "shell")}
+<div class="container-fluid">
+<div>
+	The Shell app requires a Unix user account for every user of Hue on the remote webserver.
+	Please ask your admin to create a user account for you on the remote webserver as
+	described in the Shell documentation.
+</div>
 </div>
-${shared.footer()}
+${commonfooter()}

+ 24 - 13
apps/shell/src/shell/templates/not_running_spawning.mako

@@ -1,15 +1,26 @@
-<%namespace name="shared" file="shared_components.mako" />
+## Licensed to Cloudera, Inc. under one
+## or more contributor license agreements.  See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership.  Cloudera, Inc. licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##
+##     http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+<%!
+from desktop.views import commonheader, commonfooter
+%>
 
-${shared.header("Hue Shell", False)}
-
-## use double hashes for a mako template comment
-
-## this id in the div below ("index") is stripped by Hue.JFrame
-## and passed along as the "view" argument in its onLoad event
-
-## the class 'jframe_padded' will give the contents of your window a standard padding
-<div id="index" class="view jframe_padded">
-The webserver currently running Hue does not support the Shell app. Please contact your
-administrator.
+${commonheader("Hue Shell", "shell")}
+<div class="container-fluid">
+<div>
+	<h3>The webserver currently running Hue does not support the Shell app. Please contact your administrator.</h3>
+</div>
 </div>
-${shared.footer()}
+${commonfooter()}

+ 0 - 49
apps/shell/src/shell/templates/shared_components.mako

@@ -1,49 +0,0 @@
-<%!
-import datetime
-from django.template.defaultfilters import urlencode, escape
-%>
-<%def name="header(title='Hue Shell', toolbar=True, shells=[])">
-  <!DOCTYPE html>
-  <html>
-    <head>
-      <title>${title}</title>
-    </head>
-    <body>
-      <div class="toolbar">
-        <a href="${url('shell.views.index')}"><img src="/shell/static/art/shell.png" class="shell_icon"/></a>
-        % if toolbar and shells:
-          <div class="nav_menu">
-          % if len(shells) == 1:
-            % if shells[0]["exists"]:
-              <a target="Shell" class="nav_button Button round" href="${url('shell.views.create')}?keyName=${shells[0]["keyName"]}">${shells[0]["niceName"]}</a>
-            % else:
-              <a class="nav_button Button round disabled">${shells[0]["niceName"]}</a>
-            % endif
-          % else:
-            % if shells[0]["exists"]:
-              <a target="Shell" class="nav_button Button roundLeft" href="${url('shell.views.create')}?keyName=${shells[0]["keyName"]}">${shells[0]["niceName"]}</a>
-            % else:
-              <a class="nav_button Button roundLeft disabled">${shells[0]["niceName"]}</a>
-            % endif
-            % for item in shells[1:-1]:
-              % if item["exists"]:
-                <a target="Shell" class="nav_button Button" href="${url('shell.views.create')}?keyName=${item["keyName"]}">${item["niceName"]}</a>
-              % else:
-                <a class="nav_button Button disabled">${item["niceName"]}</a>
-              % endif
-            % endfor
-            % if shells[-1]["exists"]:
-              <a target="Shell" class="nav_button Button roundRight" href="${url('shell.views.create')}?keyName=${shells[-1]["keyName"]}">${shells[-1]["niceName"]}</a>
-            % else:
-              <a class="nav_button Button roundRight disabled">${shells[-1]["niceName"]}</a>
-            % endif
-          % endif
-          </div>
-        % endif
-      </div>
-</%def>
-
-<%def name="footer()">
-    </body>
-  </html>
-</%def>

+ 2 - 0
apps/useradmin/babel.cfg

@@ -0,0 +1,2 @@
+[python: src/useradmin/**.py]
+[mako: src/useradmin/templates/**.mako]

+ 39 - 0
apps/useradmin/src/useradmin/locale/django.pot

@@ -0,0 +1,39 @@
+# Translations template for PROJECT.
+# Copyright (C) 2012 ORGANIZATION
+# This file is distributed under the same license as the PROJECT project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2012.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: PROJECT VERSION\n"
+"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
+"POT-Creation-Date: 2012-01-30 16:44-0800\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: LANGUAGE <LL@li.org>\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 0.9.6\n"
+
+#: src/useradmin/templates/list_users.mako:31
+msgid "Username"
+msgstr ""
+
+#: src/useradmin/templates/list_users.mako:32
+msgid "First Name"
+msgstr ""
+
+#: src/useradmin/templates/list_users.mako:33
+msgid "Last Name"
+msgstr ""
+
+#: src/useradmin/templates/list_users.mako:34
+msgid "E-mail"
+msgstr ""
+
+#: src/useradmin/templates/list_users.mako:35
+msgid "Last Login"
+msgstr ""
+

+ 39 - 0
apps/useradmin/src/useradmin/locale/en_US/LC_MESSAGES/django.po

@@ -0,0 +1,39 @@
+# English (United States) translations for PROJECT.
+# Copyright (C) 2012 ORGANIZATION
+# This file is distributed under the same license as the PROJECT project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2012.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: PROJECT VERSION\n"
+"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
+"POT-Creation-Date: 2012-01-30 16:44-0800\n"
+"PO-Revision-Date: 2012-01-30 16:58-0800\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: en_US <LL@li.org>\n"
+"Plural-Forms: nplurals=2; plural=(n != 1)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 0.9.6\n"
+
+#: src/useradmin/templates/list_users.mako:31
+msgid "Username"
+msgstr "--Username"
+
+#: src/useradmin/templates/list_users.mako:32
+msgid "First Name"
+msgstr "--First Name"
+
+#: src/useradmin/templates/list_users.mako:33
+msgid "Last Name"
+msgstr "--Last Name"
+
+#: src/useradmin/templates/list_users.mako:34
+msgid "E-mail"
+msgstr "--E-mail"
+
+#: src/useradmin/templates/list_users.mako:35
+msgid "Last Login"
+msgstr ""
+

+ 40 - 0
apps/useradmin/src/useradmin/locale/it/LC_MESSAGES/django.po

@@ -0,0 +1,40 @@
+# Italian translations for PROJECT.
+# Copyright (C) 2012 ORGANIZATION
+# This file is distributed under the same license as the PROJECT project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2012.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: PROJECT VERSION\n"
+"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
+"POT-Creation-Date: 2012-01-30 16:44-0800\n"
+"PO-Revision-Date: 2012-01-30 15:40-0800\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: it <LL@li.org>\n"
+"Plural-Forms: nplurals=2; plural=(n != 1)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 0.9.6\n"
+
+#: src/useradmin/templates/list_users.mako:31
+msgid "Username"
+msgstr ""
+
+#: src/useradmin/templates/list_users.mako:32
+msgid "First Name"
+msgstr "New FIRST Nome"
+
+#: src/useradmin/templates/list_users.mako:33
+#, fuzzy
+msgid "Last Name"
+msgstr "New FIRST Nome"
+
+#: src/useradmin/templates/list_users.mako:34
+msgid "E-mail"
+msgstr ""
+
+#: src/useradmin/templates/list_users.mako:35
+msgid "Last Login"
+msgstr ""
+

+ 12 - 8
apps/useradmin/src/useradmin/templates/confirm.mako

@@ -13,11 +13,15 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
-${wrappers.head(title)}
-<h1>Confirm</h1>
-<form action="${path}" method="POST">
-${title}
-<input type="submit" value="Yes">
-</form>
-${wrappers.foot()}
+<%!
+from desktop.views import commonheader, commonfooter
+%>
+${commonheader(title, "useradmin")}
+<div class="container-fluid">
+	<h1>Confirm</h1>
+	<form action="${path}" method="POST">
+		${title}
+		<input type="submit" value="Yes">
+	</form>
+</div>
+${commonfooter()}

+ 38 - 35
apps/useradmin/src/useradmin/templates/edit_user.mako

@@ -13,43 +13,46 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
 <% import urllib %>
-
+<div class="container-fluid">
   % if username:
-    ${wrappers.head('Edit User: ' + username + ' -- Hue Users')}
+	${commonheader('Edit User: ' + username + ' -- Hue Users', "useradmin")}
+	<h1>Edit User: ${username} -- Hue Users</h1>
   % else:
-    ${wrappers.head('Create User -- Hue Users')}
+    ${commonheader('Create User -- Hue Users', "useradmin")}
+    <h1>Create User -- Hue Users</h1>
   % endif
-
-
-    <div id="useradmin_edituser" class="view">
-    <h1>
-      % if username:
-        Edit User: ${username}
-      % else:
-        Create User 
-      % endif
-    </h1>
-    <form action="${urllib.quote(action)}" method="POST" class="jframe_padded">
-      <dl>
+	<form action="${urllib.quote(action)}" method="POST" class="jframe_padded">
+		<fieldset>
+			<legend> 
+			  % if username:
+		        Edit User: ${username}
+		      % else:
+		        Create User 
+		      % endif
+			</legend>
         <%def name="render_field(field)">
-          <dt>${field.label_tag() | n}</dt>
-          <dd>${unicode(field) | n}</dd>
-          % if len(field.errors):
-            <dt>&nbsp;</dt>
-            <dd class="jframe-error validation-advice">
-               ${unicode(field.errors) | n}
-             </dd>
-           % endif
-        </%def>
-        % for field in form:
-	  ${render_field(field)}
-        % endfor
-        <dt>&nbsp;</dt>
-        <dd class="save">
-          <input type="submit" value="Save"/>
-        </dd>
-      </dl>
-    </form>
-${wrappers.foot()}
+			<div class="clearfix">
+				${field.label_tag() | n}
+				<div class="input">
+					${unicode(field) | n}
+				</div>
+				% if len(field.errors):
+					${unicode(field.errors) | n}
+				% endif
+			</div>
+		</%def>
+          
+		% for field in form:
+			${render_field(field)}
+		% endfor
+        </fieldset>
+		<div class="actions">
+			<input type="submit" value="Save" class="btn primary"/>
+		</div>
+	</form>
+</div>
+${commonfooter()}

+ 92 - 18
apps/useradmin/src/useradmin/templates/list_users.mako

@@ -13,42 +13,116 @@
 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ## See the License for the specific language governing permissions and
 ## limitations under the License.
-<%namespace name="wrappers" file="header_footer.mako" />
+<%!
+from desktop.views import commonheader, commonfooter
+%>
 <% import urllib %>
+<% from django.utils.translation import ugettext, ungettext, get_language, activate %>
+<% _ = ugettext %>
 
-${wrappers.head()}
-    <div id="useradmin_userlist" class="view">
-      <table data-filters="HtmlTable" class="sortable" cellpadding="0" cellspacing="0">
+${commonheader("Hue Users", "useradmin")}
+<div class="container-fluid">
+	<h1>Hue Users</h1>
+	<div class="well">
+			Filter by name: <input id="filterInput"/> <a href="#" id="clearFilterBtn" class="btn">Clear</a>
+			<p class="pull-right">
+				<a href="${ url('useradmin.views.edit_user') }" class="btn">Add user</a>
+			</p>
+	</div>
+      <table class="datatables">
         <thead>
           <tr>
-            <th>Username</th>
-            <th>First Name</th>
-            <th>Last Name</th>
-            <th>E-mail</th>
-            <th colspan="2">Last Login</th>
+            <th>${_('Username')}</th>
+            <th>${_('First Name')}</th>
+            <th>${_('Last Name')}</th>
+            <th>${_('E-mail')}</th>
+            <th>${_('Last Login')}</th>
+			<th>&nbsp;</th>
           </tr>
         </head>
         <tbody>
         % for user in users:
-          <tr>
+          <tr class="userRow" data-search="${user.username}${user.first_name}${user.last_name}${user.email}">
             <td>${user.username}</td>
             <td>${user.first_name}</td>
             <td>${user.last_name}</td>
             <td>${user.email}</td>
             <td>
-              <span class="jframe-hidden">
-                ${int(user.last_login.strftime("%s"))}
-              </span>
               ${user.last_login.strftime('%c')}
             </td>
             <td>
-              <a title="Edit ${user.username}" class="edit frame_tip" href="${ url('useradmin.views.edit_user', username=urllib.quote(user.username)) }">Edit</a>
-              <a title="Delete ${user.username}" class="delete frame_tip confirm_unencode_and_post" alt="Are you sure you want to delete ${user.username}?" href="${ url('useradmin.views.delete_user', username=urllib.quote_plus(user.username)) }">Delete</a>
+              <a title="Edit ${user.username}" class="btn small" href="${ url('useradmin.views.edit_user', username=urllib.quote(user.username)) }">Edit</a>
+              <a title="Delete ${user.username}" class="btn small confirmationModal" alt="Are you sure you want to delete ${user.username}?" href="javascript:void(0)" data-confirmation-url="${ url('useradmin.views.delete_user', username=urllib.quote_plus(user.username)) }">Delete</a>
             </td>
           </tr>
         % endfor
         </tbody>
       </table>
-      <a class="useradmin_add_user" href="${ url('useradmin.views.edit_user') }">Add User</a>
-    </div>
-${wrappers.foot()}
+
+
+
+<div id="deleteUser" class="modal hide fade">
+	<form id="deleteUserForm" action="" method="POST">
+	<div class="modal-header">
+		<a href="#" class="close">&times;</a>
+		<h3 id="deleteUserMessage">Confirm action</h3>
+	</div>
+	<div class="modal-footer">
+		<input type="submit" class="btn primary" value="Yes"/>
+		<a href="#" class="btn secondary hideModal">No</a>
+	</div>
+	</form>
+</div>
+</div>   
+
+	<script type="text/javascript" charset="utf-8">
+		$(document).ready(function(){
+			$(".datatables").dataTable({
+				"bPaginate": false,
+			    "bLengthChange": false,
+				"bInfo": false,
+				"bFilter": false
+			});
+			$(".dataTables_wrapper").css("min-height","0");
+			$(".dataTables_filter").hide();
+
+			$("#deleteUser").modal({
+				backdrop: "static",
+				keyboard: true
+			});
+			$(".confirmationModal").click(function(){
+				var _this = $(this);
+				$.getJSON(_this.attr("data-confirmation-url"), function(data){
+					$("#deleteUserForm").attr("action", data.path);
+					$("#deleteUserMessage").text(_this.attr("alt"));
+				});
+				$("#deleteUser").modal("show");
+			});
+			$(".hideModal").click(function(){
+				$("#deleteUser").modal("hide");
+			});
+			
+			$("#filterInput").keyup(function(){
+		        $.each($(".userRow"), function(index, value) {
+
+		          if($(value).attr("data-search").toLowerCase().indexOf($("#filterInput").val().toLowerCase()) == -1 && $("#filterInput").val() != ""){
+		            $(value).hide(250);
+		          }else{
+		            $(value).show(250);
+		          }
+		        });
+
+		    });
+
+		    $("#clearFilterBtn").click(function(){
+		        $("#filterInput").val("");
+		        $.each($(".file-row"), function(index, value) {
+		            $(value).show(250);
+		        });
+		    });
+		   
+
+		});
+	</script>
+
+${commonfooter()}

+ 10 - 2
apps/useradmin/static/css/useradmin.css

@@ -1,3 +1,11 @@
+// css Added here for convenience before merge -- FIXME
+
+.hidden {
+    display: none;
+}
+
+// end of convenience section
+
 .useradmin .jframe-window-toolbar {
 	position: absolute;
 }
@@ -39,13 +47,13 @@
 	margin: 8px;
 	padding-left: 26px;
 }
-.useradmin_userlist a.useradmin_add_user:hover {
+#useradmin_userlist a.useradmin_add_user:hover {
 	text-decoration: none;
 	background: #ddd url('../art/line_icons.png') no-repeat 4px -88px;
 	color: #333;
 	border: 1px solid #333;
 }
-.useradmin_edituser .view {
+#useradmin_edituser .view {
 	background: #eee;
 }
 .useradmin_edituser dt {

+ 28 - 0
desktop/core/ext-py/Babel-0.9.6/COPYING

@@ -0,0 +1,28 @@
+Copyright (C) 2007 Edgewall Software
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+ 1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+ 3. The name of the author may not be used to endorse or promote
+    products derived from this software without specific prior
+    written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
+IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 181 - 0
desktop/core/ext-py/Babel-0.9.6/ChangeLog

@@ -0,0 +1,181 @@
+Version 0.9.6
+http://svn.edgewall.org/repos/babel/tags/0.9.6/
+(Mar 17 2011, from branches/stable/0.9.x)
+
+ * Backport r493-494: documentation typo fixes.
+ * Make the CLDR import script work with Python 2.7.
+ * Fix various typos.
+ * Fixed Python 2.3 compatibility (ticket #146, #233).
+ * Sort output of list-locales.
+ * Make the POT-Creation-Date of the catalog being updated equal to
+   POT-Creation-Date of the template used to update (ticket #148).
+ * Use a more explicit error message if no option or argument (command) is
+   passed to pybabel (ticket #81).
+ * Keep the PO-Revision-Date if it is not the default value (ticket #148).
+ * Make --no-wrap work by reworking --width's default and mimic xgettext's
+   behaviour of always wrapping comments (ticket #145).
+ * Fixed negative offset handling of Catalog._set_mime_headers (ticket #165).
+ * Add --project and --version options for commandline (ticket #173).
+ * Add a __ne__() method to the Local class.
+ * Explicitly sort instead of using sorted() and don't assume ordering
+   (Python 2.3 and Jython compatibility).
+ * Removed ValueError raising for string formatting message checkers if the
+   string does not contain any string formattings (ticket #150).
+ * Fix Serbian plural forms (ticket #213).
+ * Small speed improvement in format_date() (ticket #216).
+ * Fix number formatting for locales where CLDR specifies alt or draft 
+   items (ticket #217)
+ * Fix bad check in format_time (ticket #257, reported with patch and tests by 
+   jomae)
+ * Fix so frontend.CommandLineInterface.run does not accumulate logging 
+   handlers (#227, reported with initial patch by dfraser)
+ * Fix exception if environment contains an invalid locale setting (#200)
+
+
+Version 0.9.5
+http://svn.edgewall.org/repos/babel/tags/0.9.5/
+(Apr 6 2010, from branches/stable/0.9.x)
+
+ * Fixed the case where messages containing square brackets would break with
+   an unpack error.
+ * Backport of r467: Fuzzy matching regarding plurals should *NOT* be checked
+   against len(message.id)  because this is always 2, instead, it's should be
+   checked against catalog.num_plurals (ticket #212).
+
+
+Version 0.9.4
+http://svn.edgewall.org/repos/babel/tags/0.9.4/
+(Aug 25 2008, from branches/stable/0.9.x)
+
+ * Currency symbol definitions that is defined with choice patterns in the
+   CLDR data are no longer imported, so the symbol code will be used instead.
+ * Fixed quarter support in date formatting.
+ * Fixed a serious memory leak that was introduces by the support for CLDR
+   aliases in 0.9.3 (ticket #128).
+ * Locale modifiers such as "@euro" are now stripped from locale identifiers
+   when parsing (ticket #136).
+ * The system locales "C" and "POSIX" are now treated as aliases for
+   "en_US_POSIX", for which the CLDR provides the appropriate data. Thanks to
+   Manlio Perillo for the suggestion.
+ * Fixed JavaScript extraction for regular expression literals (ticket #138)
+   and concatenated strings.
+ * The `Translation` class in `babel.support` can now manage catalogs with
+   different message domains, and exposes the family of `d*gettext` functions
+   (ticket #137).
+
+
+Version 0.9.3
+http://svn.edgewall.org/repos/babel/tags/0.9.3/
+(Jul 9 2008, from branches/stable/0.9.x)
+
+ * Fixed invalid message extraction methods causing an UnboundLocalError.
+ * Extraction method specification can now use a dot instead of the colon to
+   separate module and function name (ticket #105).
+ * Fixed message catalog compilation for locales with more than two plural
+   forms (ticket #95).
+ * Fixed compilation of message catalogs for locales with more than two plural
+   forms where the translations were empty (ticket #97).
+ * The stripping of the comment tags in comments is optional now and
+   is done for each line in a comment.
+ * Added a JavaScript message extractor.
+ * Updated to CLDR 1.6.
+ * Fixed timezone calculations when formatting datetime and time values.
+ * Added a `get_plural` function into the plurals module that returns the
+   correct plural forms for a locale as tuple.
+ * Added support for alias definitions in the CLDR data files, meaning that
+   the chance for items missing in certain locales should be greatly reduced
+   (ticket #68).
+
+
+Version 0.9.2
+http://svn.edgewall.org/repos/babel/tags/0.9.2/
+(Feb 4 2008, from branches/stable/0.9.x)
+
+ * Fixed catalogs' charset values not being recognized (ticket #66).
+ * Numerous improvements to the default plural forms.
+ * Fixed fuzzy matching when updating message catalogs (ticket #82).
+ * Fixed bug in catalog updating, that in some cases pulled in translations
+   from different catalogs based on the same template.
+ * Location lines in PO files do no longer get wrapped at hyphens in file
+   names (ticket #79).
+ * Fixed division by zero error in catalog compilation on empty catalogs
+   (ticket #60).
+
+
+Version 0.9.1
+http://svn.edgewall.org/repos/babel/tags/0.9.1/
+(Sep 7 2007, from branches/stable/0.9.x)
+
+ * Fixed catalog updating when a message is merged that was previously simple
+   but now has a plural form, for example by moving from `gettext` to
+   `ngettext`, or vice versa.
+ * Fixed time formatting for 12 am and 12 pm.
+ * Fixed output encoding of the `pybabel --list-locales` command.
+ * MO files are now written in binary mode on windows (ticket #61).
+
+
+Version 0.9
+http://svn.edgewall.org/repos/babel/tags/0.9.0/
+(Aug 20 2007, from branches/stable/0.9.x)
+
+ * The `new_catalog` distutils command has been renamed to `init_catalog` for
+   consistency with the command-line frontend.
+ * Added compilation of message catalogs to MO files (ticket #21).
+ * Added updating of message catalogs from POT files (ticket #22).
+ * Support for significant digits in number formatting.
+ * Apply proper "banker's rounding" in number formatting in a cross-platform
+   manner.
+ * The number formatting functions now also work with numbers represented by
+   Python `Decimal` objects (ticket #53).
+ * Added extensible infrastructure for validating translation catalogs.
+ * Fixed the extractor not filtering out messages that didn't validate against
+   the keyword's specification (ticket #39).
+ * Fixed the extractor raising an exception when encountering an empty string
+   msgid. It now emits a warning to stderr.
+ * Numerous Python message extractor fixes: it now handles nested function
+   calls within a gettext function call correctly, uses the correct line number
+   for multi-line function calls, and other small fixes (tickets #38 and #39).
+ * Improved support for detecting Python string formatting fields in message
+   strings (ticket #57).
+ * CLDR upgraded to the 1.5 release.
+ * Improved timezone formatting.
+ * Implemented scientific number formatting.
+ * Added mechanism to lookup locales by alias, for cases where browsers insist
+   on including only the language code in the `Accept-Language` header, and
+   sometimes even the incorrect language code.
+
+
+Version 0.8.1
+http://svn.edgewall.org/repos/babel/tags/0.8.1/
+(Jul 2 2007, from branches/stable/0.8.x)
+
+ * `default_locale()` would fail when the value of the `LANGUAGE` environment
+   variable contained multiple language codes separated by colon, as is
+   explicitly allowed by the GNU gettext tools. As the `default_locale()`
+   function is called at the module level in some modules, this bug would
+   completely break importing these modules on systems where `LANGUAGE` is set
+   that way.
+ * The character set specified in PO template files is now respected when
+   creating new catalog files based on that template. This allows the use of
+   characters outside the ASCII range in POT files (ticket #17).
+ * The default ordering of messages in generated POT files, which is based on
+   the order those messages are found when walking the source tree, is no
+   longer subject to differences between platforms; directory and file names
+   are now always sorted alphabetically.
+ * The Python message extractor now respects the special encoding comment to be
+   able to handle files containing non-ASCII characters (ticket #23).
+ * Added 'N_' (gettext noop) to the extractor's default keywords.
+ * Made locale string parsing more robust, and also take the script part into
+   account (ticket #27).
+ * Added a function to list all locales for which locale data is available.
+ * Added a command-line option to the `pybabel` command which prints out all
+   available locales (ticket #24).
+ * The name of the command-line script has been changed from just `babel` to
+   `pybabel` to avoid a conflict with the OpenBabel project (ticket #34).
+
+
+Version 0.8
+http://svn.edgewall.org/repos/babel/tags/0.8.0/
+(Jun 20 2007, from branches/stable/0.8.x)
+
+ * First public release

+ 39 - 0
desktop/core/ext-py/Babel-0.9.6/INSTALL.txt

@@ -0,0 +1,39 @@
+Installing Babel
+================
+
+Prerequisites
+-------------
+
+ * Python 2.3 or later (2.4 or later is recommended)
+ * Optional: setuptools 0.6b1 or later
+ * Optional: pytz (strongly recommended for real time-zone support, mandatory 
+   to run the automated test suite)
+
+
+Installation
+------------
+
+Once you've downloaded and unpacked a Babel source release, enter the
+directory where the archive was unpacked, and run:
+
+  $ python setup.py install
+
+Note that you may need administrator/root privileges for this step, as
+this command will by default attempt to install Babel to the Python
+site-packages directory on your system.
+
+For advanced options, please refer to the easy_install and/or the distutils
+documentation:
+
+  http://peak.telecommunity.com/DevCenter/EasyInstall
+  http://docs.python.org/inst/inst.html
+
+
+Support
+-------
+
+If you encounter any problems with Babel, please don't hesitate to ask
+questions on the Babel mailing list or IRC channel:
+
+  http://babel.edgewall.org/wiki/MailingList
+  http://babel.edgewall.org/wiki/IrcChannel

+ 4 - 0
desktop/core/ext-py/Babel-0.9.6/MANIFEST.in

@@ -0,0 +1,4 @@
+include babel/global.dat
+include babel/localedata/*.dat
+include doc/api/*.*
+include doc/*.html

+ 18 - 0
desktop/core/ext-py/Babel-0.9.6/PKG-INFO

@@ -0,0 +1,18 @@
+Metadata-Version: 1.0
+Name: Babel
+Version: 0.9.6
+Summary: Internationalization utilities
+Home-page: http://babel.edgewall.org/
+Author: Edgewall Software
+Author-email: info@edgewall.org
+License: BSD
+Download-URL: http://babel.edgewall.org/wiki/Download
+Description: A collection of tools for internationalizing Python applications.
+Platform: UNKNOWN
+Classifier: Development Status :: 4 - Beta
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Software Development :: Libraries :: Python Modules

+ 12 - 0
desktop/core/ext-py/Babel-0.9.6/README.txt

@@ -0,0 +1,12 @@
+About Babel
+===========
+
+Babel is a Python library that provides an integrated collection of
+utilities that assist with internationalizing and localizing Python
+applications (in particular web-based applications.)
+
+Details can be found in the HTML files in the `doc` folder.
+
+For more information please visit the Babel web site:
+
+  <http://babel.edgewall.org/>

+ 39 - 0
desktop/core/ext-py/Babel-0.9.6/babel/__init__.py

@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007-2008 Edgewall Software
+# All rights reserved.
+#
+# This software is licensed as described in the file COPYING, which
+# you should have received as part of this distribution. The terms
+# are also available at http://babel.edgewall.org/wiki/License.
+#
+# This software consists of voluntary contributions made by many
+# individuals. For the exact contribution history, see the revision
+# history and logs, available at http://babel.edgewall.org/log/.
+
+"""Integrated collection of utilities that assist in internationalizing and
+localizing applications.
+
+This package is basically composed of two major parts:
+
+ * tools to build and work with ``gettext`` message catalogs
+ * a Python interface to the CLDR (Common Locale Data Repository), providing
+   access to various locale display names, localized number and date
+   formatting, etc.
+
+:see: http://www.gnu.org/software/gettext/
+:see: http://docs.python.org/lib/module-gettext.html
+:see: http://www.unicode.org/cldr/
+"""
+
+from babel.core import *
+
+__docformat__ = 'restructuredtext en'
+try:
+    from pkg_resources import get_distribution, ResolutionError
+    try:
+        __version__ = get_distribution('Babel').version
+    except ResolutionError:
+        __version__ = None # unknown
+except ImportError:
+    __version__ = None # unknown

+ 790 - 0
desktop/core/ext-py/Babel-0.9.6/babel/core.py

@@ -0,0 +1,790 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007 Edgewall Software
+# All rights reserved.
+#
+# This software is licensed as described in the file COPYING, which
+# you should have received as part of this distribution. The terms
+# are also available at http://babel.edgewall.org/wiki/License.
+#
+# This software consists of voluntary contributions made by many
+# individuals. For the exact contribution history, see the revision
+# history and logs, available at http://babel.edgewall.org/log/.
+
+"""Core locale representation and locale data access."""
+
+import os
+import pickle
+
+from babel import localedata
+
+__all__ = ['UnknownLocaleError', 'Locale', 'default_locale', 'negotiate_locale',
+           'parse_locale']
+__docformat__ = 'restructuredtext en'
+
+_global_data = None
+
+def get_global(key):
+    """Return the dictionary for the given key in the global data.
+    
+    The global data is stored in the ``babel/global.dat`` file and contains
+    information independent of individual locales.
+    
+    >>> get_global('zone_aliases')['UTC']
+    'Etc/GMT'
+    >>> get_global('zone_territories')['Europe/Berlin']
+    'DE'
+    
+    :param key: the data key
+    :return: the dictionary found in the global data under the given key
+    :rtype: `dict`
+    :since: version 0.9
+    """
+    global _global_data
+    if _global_data is None:
+        dirname = os.path.join(os.path.dirname(__file__))
+        filename = os.path.join(dirname, 'global.dat')
+        fileobj = open(filename, 'rb')
+        try:
+            _global_data = pickle.load(fileobj)
+        finally:
+            fileobj.close()
+    return _global_data.get(key, {})
+
+
+LOCALE_ALIASES = {
+    'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ', 
+    'da': 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es': 'es_ES', 
+    'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES', 
+    'he': 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it': 'it_IT', 
+    'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV', 
+    'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL', 
+    'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI', 
+    'sv': 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA'
+}
+
+
+class UnknownLocaleError(Exception):
+    """Exception thrown when a locale is requested for which no locale data
+    is available.
+    """
+
+    def __init__(self, identifier):
+        """Create the exception.
+        
+        :param identifier: the identifier string of the unsupported locale
+        """
+        Exception.__init__(self, 'unknown locale %r' % identifier)
+        self.identifier = identifier
+
+
+class Locale(object):
+    """Representation of a specific locale.
+    
+    >>> locale = Locale('en', 'US')
+    >>> repr(locale)
+    '<Locale "en_US">'
+    >>> locale.display_name
+    u'English (United States)'
+    
+    A `Locale` object can also be instantiated from a raw locale string:
+    
+    >>> locale = Locale.parse('en-US', sep='-')
+    >>> repr(locale)
+    '<Locale "en_US">'
+    
+    `Locale` objects provide access to a collection of locale data, such as
+    territory and language names, number and date format patterns, and more:
+    
+    >>> locale.number_symbols['decimal']
+    u'.'
+    
+    If a locale is requested for which no locale data is available, an
+    `UnknownLocaleError` is raised:
+    
+    >>> Locale.parse('en_DE')
+    Traceback (most recent call last):
+        ...
+    UnknownLocaleError: unknown locale 'en_DE'
+    
+    :see: `IETF RFC 3066 <http://www.ietf.org/rfc/rfc3066.txt>`_
+    """
+
+    def __init__(self, language, territory=None, script=None, variant=None):
+        """Initialize the locale object from the given identifier components.
+        
+        >>> locale = Locale('en', 'US')
+        >>> locale.language
+        'en'
+        >>> locale.territory
+        'US'
+        
+        :param language: the language code
+        :param territory: the territory (country or region) code
+        :param script: the script code
+        :param variant: the variant code
+        :raise `UnknownLocaleError`: if no locale data is available for the
+                                     requested locale
+        """
+        self.language = language
+        self.territory = territory
+        self.script = script
+        self.variant = variant
+        self.__data = None
+
+        identifier = str(self)
+        if not localedata.exists(identifier):
+            raise UnknownLocaleError(identifier)
+
+    def default(cls, category=None, aliases=LOCALE_ALIASES):
+        """Return the system default locale for the specified category.
+        
+        >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']:
+        ...     os.environ[name] = ''
+        >>> os.environ['LANG'] = 'fr_FR.UTF-8'
+        >>> Locale.default('LC_MESSAGES')
+        <Locale "fr_FR">
+
+        :param category: one of the ``LC_XXX`` environment variable names
+        :param aliases: a dictionary of aliases for locale identifiers
+        :return: the value of the variable, or any of the fallbacks
+                 (``LANGUAGE``, ``LC_ALL``, ``LC_CTYPE``, and ``LANG``)
+        :rtype: `Locale`
+        :see: `default_locale`
+        """
+        return cls(default_locale(category, aliases=aliases))
+    default = classmethod(default)
+
+    def negotiate(cls, preferred, available, sep='_', aliases=LOCALE_ALIASES):
+        """Find the best match between available and requested locale strings.
+        
+        >>> Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
+        <Locale "de_DE">
+        >>> Locale.negotiate(['de_DE', 'en_US'], ['en', 'de'])
+        <Locale "de">
+        >>> Locale.negotiate(['de_DE', 'de'], ['en_US'])
+        
+        You can specify the character used in the locale identifiers to separate
+        the differnet components. This separator is applied to both lists. Also,
+        case is ignored in the comparison:
+        
+        >>> Locale.negotiate(['de-DE', 'de'], ['en-us', 'de-de'], sep='-')
+        <Locale "de_DE">
+        
+        :param preferred: the list of locale identifers preferred by the user
+        :param available: the list of locale identifiers available
+        :param aliases: a dictionary of aliases for locale identifiers
+        :return: the `Locale` object for the best match, or `None` if no match
+                 was found
+        :rtype: `Locale`
+        :see: `negotiate_locale`
+        """
+        identifier = negotiate_locale(preferred, available, sep=sep,
+                                      aliases=aliases)
+        if identifier:
+            return Locale.parse(identifier, sep=sep)
+    negotiate = classmethod(negotiate)
+
+    def parse(cls, identifier, sep='_'):
+        """Create a `Locale` instance for the given locale identifier.
+        
+        >>> l = Locale.parse('de-DE', sep='-')
+        >>> l.display_name
+        u'Deutsch (Deutschland)'
+        
+        If the `identifier` parameter is not a string, but actually a `Locale`
+        object, that object is returned:
+        
+        >>> Locale.parse(l)
+        <Locale "de_DE">
+        
+        :param identifier: the locale identifier string
+        :param sep: optional component separator
+        :return: a corresponding `Locale` instance
+        :rtype: `Locale`
+        :raise `ValueError`: if the string does not appear to be a valid locale
+                             identifier
+        :raise `UnknownLocaleError`: if no locale data is available for the
+                                     requested locale
+        :see: `parse_locale`
+        """
+        if isinstance(identifier, basestring):
+            return cls(*parse_locale(identifier, sep=sep))
+        return identifier
+    parse = classmethod(parse)
+
+    def __eq__(self, other):
+        return str(self) == str(other)
+
+    def __ne__(self, other):
+        return not self.__eq__(other)
+
+    def __repr__(self):
+        return '<Locale "%s">' % str(self)
+
+    def __str__(self):
+        return '_'.join(filter(None, [self.language, self.script,
+                                      self.territory, self.variant]))
+
+    def _data(self):
+        if self.__data is None:
+            self.__data = localedata.LocaleDataDict(localedata.load(str(self)))
+        return self.__data
+    _data = property(_data)
+
+    def get_display_name(self, locale=None):
+        """Return the display name of the locale using the given locale.
+        
+        The display name will include the language, territory, script, and
+        variant, if those are specified.
+        
+        >>> Locale('zh', 'CN', script='Hans').get_display_name('en')
+        u'Chinese (Simplified Han, China)'
+        
+        :param locale: the locale to use
+        :return: the display name
+        """
+        if locale is None:
+            locale = self
+        locale = Locale.parse(locale)
+        retval = locale.languages.get(self.language)
+        if self.territory or self.script or self.variant:
+            details = []
+            if self.script:
+                details.append(locale.scripts.get(self.script))
+            if self.territory:
+                details.append(locale.territories.get(self.territory))
+            if self.variant:
+                details.append(locale.variants.get(self.variant))
+            details = filter(None, details)
+            if details:
+                retval += ' (%s)' % u', '.join(details)
+        return retval
+
+    display_name = property(get_display_name, doc="""\
+        The localized display name of the locale.
+        
+        >>> Locale('en').display_name
+        u'English'
+        >>> Locale('en', 'US').display_name
+        u'English (United States)'
+        >>> Locale('sv').display_name
+        u'svenska'
+        
+        :type: `unicode`
+        """)
+
+    def english_name(self):
+        return self.get_display_name(Locale('en'))
+    english_name = property(english_name, doc="""\
+        The english display name of the locale.
+        
+        >>> Locale('de').english_name
+        u'German'
+        >>> Locale('de', 'DE').english_name
+        u'German (Germany)'
+        
+        :type: `unicode`
+        """)
+
+    #{ General Locale Display Names
+
+    def languages(self):
+        return self._data['languages']
+    languages = property(languages, doc="""\
+        Mapping of language codes to translated language names.
+        
+        >>> Locale('de', 'DE').languages['ja']
+        u'Japanisch'
+        
+        :type: `dict`
+        :see: `ISO 639 <http://www.loc.gov/standards/iso639-2/>`_
+        """)
+
+    def scripts(self):
+        return self._data['scripts']
+    scripts = property(scripts, doc="""\
+        Mapping of script codes to translated script names.
+        
+        >>> Locale('en', 'US').scripts['Hira']
+        u'Hiragana'
+        
+        :type: `dict`
+        :see: `ISO 15924 <http://www.evertype.com/standards/iso15924/>`_
+        """)
+
+    def territories(self):
+        return self._data['territories']
+    territories = property(territories, doc="""\
+        Mapping of script codes to translated script names.
+        
+        >>> Locale('es', 'CO').territories['DE']
+        u'Alemania'
+        
+        :type: `dict`
+        :see: `ISO 3166 <http://www.iso.org/iso/en/prods-services/iso3166ma/>`_
+        """)
+
+    def variants(self):
+        return self._data['variants']
+    variants = property(variants, doc="""\
+        Mapping of script codes to translated script names.
+        
+        >>> Locale('de', 'DE').variants['1901']
+        u'Alte deutsche Rechtschreibung'
+        
+        :type: `dict`
+        """)
+
+    #{ Number Formatting
+
+    def currencies(self):
+        return self._data['currency_names']
+    currencies = property(currencies, doc="""\
+        Mapping of currency codes to translated currency names.
+        
+        >>> Locale('en').currencies['COP']
+        u'Colombian Peso'
+        >>> Locale('de', 'DE').currencies['COP']
+        u'Kolumbianischer Peso'
+        
+        :type: `dict`
+        """)
+
+    def currency_symbols(self):
+        return self._data['currency_symbols']
+    currency_symbols = property(currency_symbols, doc="""\
+        Mapping of currency codes to symbols.
+        
+        >>> Locale('en', 'US').currency_symbols['USD']
+        u'$'
+        >>> Locale('es', 'CO').currency_symbols['USD']
+        u'US$'
+        
+        :type: `dict`
+        """)
+
+    def number_symbols(self):
+        return self._data['number_symbols']
+    number_symbols = property(number_symbols, doc="""\
+        Symbols used in number formatting.
+        
+        >>> Locale('fr', 'FR').number_symbols['decimal']
+        u','
+        
+        :type: `dict`
+        """)
+
+    def decimal_formats(self):
+        return self._data['decimal_formats']
+    decimal_formats = property(decimal_formats, doc="""\
+        Locale patterns for decimal number formatting.
+        
+        >>> Locale('en', 'US').decimal_formats[None]
+        <NumberPattern u'#,##0.###'>
+        
+        :type: `dict`
+        """)
+
+    def currency_formats(self):
+        return self._data['currency_formats']
+    currency_formats = property(currency_formats, doc=r"""\
+        Locale patterns for currency number formatting.
+        
+        >>> print Locale('en', 'US').currency_formats[None]
+        <NumberPattern u'\xa4#,##0.00'>
+        
+        :type: `dict`
+        """)
+
+    def percent_formats(self):
+        return self._data['percent_formats']
+    percent_formats = property(percent_formats, doc="""\
+        Locale patterns for percent number formatting.
+        
+        >>> Locale('en', 'US').percent_formats[None]
+        <NumberPattern u'#,##0%'>
+        
+        :type: `dict`
+        """)
+
+    def scientific_formats(self):
+        return self._data['scientific_formats']
+    scientific_formats = property(scientific_formats, doc="""\
+        Locale patterns for scientific number formatting.
+        
+        >>> Locale('en', 'US').scientific_formats[None]
+        <NumberPattern u'#E0'>
+        
+        :type: `dict`
+        """)
+
+    #{ Calendar Information and Date Formatting
+
+    def periods(self):
+        return self._data['periods']
+    periods = property(periods, doc="""\
+        Locale display names for day periods (AM/PM).
+        
+        >>> Locale('en', 'US').periods['am']
+        u'AM'
+        
+        :type: `dict`
+        """)
+
+    def days(self):
+        return self._data['days']
+    days = property(days, doc="""\
+        Locale display names for weekdays.
+        
+        >>> Locale('de', 'DE').days['format']['wide'][3]
+        u'Donnerstag'
+        
+        :type: `dict`
+        """)
+
+    def months(self):
+        return self._data['months']
+    months = property(months, doc="""\
+        Locale display names for months.
+        
+        >>> Locale('de', 'DE').months['format']['wide'][10]
+        u'Oktober'
+        
+        :type: `dict`
+        """)
+
+    def quarters(self):
+        return self._data['quarters']
+    quarters = property(quarters, doc="""\
+        Locale display names for quarters.
+        
+        >>> Locale('de', 'DE').quarters['format']['wide'][1]
+        u'1. Quartal'
+        
+        :type: `dict`
+        """)
+
+    def eras(self):
+        return self._data['eras']
+    eras = property(eras, doc="""\
+        Locale display names for eras.
+        
+        >>> Locale('en', 'US').eras['wide'][1]
+        u'Anno Domini'
+        >>> Locale('en', 'US').eras['abbreviated'][0]
+        u'BC'
+        
+        :type: `dict`
+        """)
+
+    def time_zones(self):
+        return self._data['time_zones']
+    time_zones = property(time_zones, doc="""\
+        Locale display names for time zones.
+        
+        >>> Locale('en', 'US').time_zones['Europe/London']['long']['daylight']
+        u'British Summer Time'
+        >>> Locale('en', 'US').time_zones['America/St_Johns']['city']
+        u"St. John's"
+        
+        :type: `dict`
+        """)
+
+    def meta_zones(self):
+        return self._data['meta_zones']
+    meta_zones = property(meta_zones, doc="""\
+        Locale display names for meta time zones.
+        
+        Meta time zones are basically groups of different Olson time zones that
+        have the same GMT offset and daylight savings time.
+        
+        >>> Locale('en', 'US').meta_zones['Europe_Central']['long']['daylight']
+        u'Central European Summer Time'
+        
+        :type: `dict`
+        :since: version 0.9
+        """)
+
+    def zone_formats(self):
+        return self._data['zone_formats']
+    zone_formats = property(zone_formats, doc=r"""\
+        Patterns related to the formatting of time zones.
+        
+        >>> Locale('en', 'US').zone_formats['fallback']
+        u'%(1)s (%(0)s)'
+        >>> Locale('pt', 'BR').zone_formats['region']
+        u'Hor\xe1rio %s'
+        
+        :type: `dict`
+        :since: version 0.9
+        """)
+
+    def first_week_day(self):
+        return self._data['week_data']['first_day']
+    first_week_day = property(first_week_day, doc="""\
+        The first day of a week, with 0 being Monday.
+        
+        >>> Locale('de', 'DE').first_week_day
+        0
+        >>> Locale('en', 'US').first_week_day
+        6
+        
+        :type: `int`
+        """)
+
+    def weekend_start(self):
+        return self._data['week_data']['weekend_start']
+    weekend_start = property(weekend_start, doc="""\
+        The day the weekend starts, with 0 being Monday.
+        
+        >>> Locale('de', 'DE').weekend_start
+        5
+        
+        :type: `int`
+        """)
+
+    def weekend_end(self):
+        return self._data['week_data']['weekend_end']
+    weekend_end = property(weekend_end, doc="""\
+        The day the weekend ends, with 0 being Monday.
+        
+        >>> Locale('de', 'DE').weekend_end
+        6
+        
+        :type: `int`
+        """)
+
+    def min_week_days(self):
+        return self._data['week_data']['min_days']
+    min_week_days = property(min_week_days, doc="""\
+        The minimum number of days in a week so that the week is counted as the
+        first week of a year or month.
+        
+        >>> Locale('de', 'DE').min_week_days
+        4
+        
+        :type: `int`
+        """)
+
+    def date_formats(self):
+        return self._data['date_formats']
+    date_formats = property(date_formats, doc="""\
+        Locale patterns for date formatting.
+        
+        >>> Locale('en', 'US').date_formats['short']
+        <DateTimePattern u'M/d/yy'>
+        >>> Locale('fr', 'FR').date_formats['long']
+        <DateTimePattern u'd MMMM yyyy'>
+        
+        :type: `dict`
+        """)
+
+    def time_formats(self):
+        return self._data['time_formats']
+    time_formats = property(time_formats, doc="""\
+        Locale patterns for time formatting.
+        
+        >>> Locale('en', 'US').time_formats['short']
+        <DateTimePattern u'h:mm a'>
+        >>> Locale('fr', 'FR').time_formats['long']
+        <DateTimePattern u'HH:mm:ss z'>
+        
+        :type: `dict`
+        """)
+
+    def datetime_formats(self):
+        return self._data['datetime_formats']
+    datetime_formats = property(datetime_formats, doc="""\
+        Locale patterns for datetime formatting.
+        
+        >>> Locale('en').datetime_formats[None]
+        u'{1} {0}'
+        >>> Locale('th').datetime_formats[None]
+        u'{1}, {0}'
+        
+        :type: `dict`
+        """)
+
+
+def default_locale(category=None, aliases=LOCALE_ALIASES):
+    """Returns the system default locale for a given category, based on
+    environment variables.
+    
+    >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']:
+    ...     os.environ[name] = ''
+    >>> os.environ['LANG'] = 'fr_FR.UTF-8'
+    >>> default_locale('LC_MESSAGES')
+    'fr_FR'
+
+    The "C" or "POSIX" pseudo-locales are treated as aliases for the
+    "en_US_POSIX" locale:
+
+    >>> os.environ['LC_MESSAGES'] = 'POSIX'
+    >>> default_locale('LC_MESSAGES')
+    'en_US_POSIX'
+
+    :param category: one of the ``LC_XXX`` environment variable names
+    :param aliases: a dictionary of aliases for locale identifiers
+    :return: the value of the variable, or any of the fallbacks (``LANGUAGE``,
+             ``LC_ALL``, ``LC_CTYPE``, and ``LANG``)
+    :rtype: `str`
+    """
+    varnames = (category, 'LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG')
+    for name in filter(None, varnames):
+        locale = os.getenv(name)
+        if locale:
+            if name == 'LANGUAGE' and ':' in locale:
+                # the LANGUAGE variable may contain a colon-separated list of
+                # language codes; we just pick the language on the list
+                locale = locale.split(':')[0]
+            if locale in ('C', 'POSIX'):
+                locale = 'en_US_POSIX'
+            elif aliases and locale in aliases:
+                locale = aliases[locale]
+            try:
+                return '_'.join(filter(None, parse_locale(locale)))
+            except ValueError:
+                pass
+
+def negotiate_locale(preferred, available, sep='_', aliases=LOCALE_ALIASES):
+    """Find the best match between available and requested locale strings.
+    
+    >>> negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
+    'de_DE'
+    >>> negotiate_locale(['de_DE', 'en_US'], ['en', 'de'])
+    'de'
+    
+    Case is ignored by the algorithm, the result uses the case of the preferred
+    locale identifier:
+    
+    >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
+    'de_DE'
+    
+    >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
+    'de_DE'
+    
+    By default, some web browsers unfortunately do not include the territory
+    in the locale identifier for many locales, and some don't even allow the
+    user to easily add the territory. So while you may prefer using qualified
+    locale identifiers in your web-application, they would not normally match
+    the language-only locale sent by such browsers. To workaround that, this
+    function uses a default mapping of commonly used langauge-only locale
+    identifiers to identifiers including the territory:
+    
+    >>> negotiate_locale(['ja', 'en_US'], ['ja_JP', 'en_US'])
+    'ja_JP'
+    
+    Some browsers even use an incorrect or outdated language code, such as "no"
+    for Norwegian, where the correct locale identifier would actually be "nb_NO"
+    (Bokmål) or "nn_NO" (Nynorsk). The aliases are intended to take care of
+    such cases, too:
+    
+    >>> negotiate_locale(['no', 'sv'], ['nb_NO', 'sv_SE'])
+    'nb_NO'
+    
+    You can override this default mapping by passing a different `aliases`
+    dictionary to this function, or you can bypass the behavior althogher by
+    setting the `aliases` parameter to `None`.
+    
+    :param preferred: the list of locale strings preferred by the user
+    :param available: the list of locale strings available
+    :param sep: character that separates the different parts of the locale
+                strings
+    :param aliases: a dictionary of aliases for locale identifiers
+    :return: the locale identifier for the best match, or `None` if no match
+             was found
+    :rtype: `str`
+    """
+    available = [a.lower() for a in available if a]
+    for locale in preferred:
+        ll = locale.lower()
+        if ll in available:
+            return locale
+        if aliases:
+            alias = aliases.get(ll)
+            if alias:
+                alias = alias.replace('_', sep)
+                if alias.lower() in available:
+                    return alias
+        parts = locale.split(sep)
+        if len(parts) > 1 and parts[0].lower() in available:
+            return parts[0]
+    return None
+
+def parse_locale(identifier, sep='_'):
+    """Parse a locale identifier into a tuple of the form::
+    
+      ``(language, territory, script, variant)``
+    
+    >>> parse_locale('zh_CN')
+    ('zh', 'CN', None, None)
+    >>> parse_locale('zh_Hans_CN')
+    ('zh', 'CN', 'Hans', None)
+    
+    The default component separator is "_", but a different separator can be
+    specified using the `sep` parameter:
+    
+    >>> parse_locale('zh-CN', sep='-')
+    ('zh', 'CN', None, None)
+    
+    If the identifier cannot be parsed into a locale, a `ValueError` exception
+    is raised:
+    
+    >>> parse_locale('not_a_LOCALE_String')
+    Traceback (most recent call last):
+      ...
+    ValueError: 'not_a_LOCALE_String' is not a valid locale identifier
+    
+    Encoding information and locale modifiers are removed from the identifier:
+    
+    >>> parse_locale('it_IT@euro')
+    ('it', 'IT', None, None)
+    >>> parse_locale('en_US.UTF-8')
+    ('en', 'US', None, None)
+    >>> parse_locale('de_DE.iso885915@euro')
+    ('de', 'DE', None, None)
+    
+    :param identifier: the locale identifier string
+    :param sep: character that separates the different components of the locale
+                identifier
+    :return: the ``(language, territory, script, variant)`` tuple
+    :rtype: `tuple`
+    :raise `ValueError`: if the string does not appear to be a valid locale
+                         identifier
+    
+    :see: `IETF RFC 4646 <http://www.ietf.org/rfc/rfc4646.txt>`_
+    """
+    if '.' in identifier:
+        # this is probably the charset/encoding, which we don't care about
+        identifier = identifier.split('.', 1)[0]
+    if '@' in identifier:
+        # this is a locale modifier such as @euro, which we don't care about
+        # either
+        identifier = identifier.split('@', 1)[0]
+
+    parts = identifier.split(sep)
+    lang = parts.pop(0).lower()
+    if not lang.isalpha():
+        raise ValueError('expected only letters, got %r' % lang)
+
+    script = territory = variant = None
+    if parts:
+        if len(parts[0]) == 4 and parts[0].isalpha():
+            script = parts.pop(0).title()
+
+    if parts:
+        if len(parts[0]) == 2 and parts[0].isalpha():
+            territory = parts.pop(0).upper()
+        elif len(parts[0]) == 3 and parts[0].isdigit():
+            territory = parts.pop(0)
+
+    if parts:
+        if len(parts[0]) == 4 and parts[0][0].isdigit() or \
+                len(parts[0]) >= 5 and parts[0][0].isalpha():
+            variant = parts.pop()
+
+    if parts:
+        raise ValueError('%r is not a valid locale identifier' % identifier)
+
+    return lang, territory, script, variant

+ 991 - 0
desktop/core/ext-py/Babel-0.9.6/babel/dates.py

@@ -0,0 +1,991 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007 Edgewall Software
+# All rights reserved.
+#
+# This software is licensed as described in the file COPYING, which
+# you should have received as part of this distribution. The terms
+# are also available at http://babel.edgewall.org/wiki/License.
+#
+# This software consists of voluntary contributions made by many
+# individuals. For the exact contribution history, see the revision
+# history and logs, available at http://babel.edgewall.org/log/.
+
+"""Locale dependent formatting and parsing of dates and times.
+
+The default locale for the functions in this module is determined by the
+following environment variables, in that order:
+
+ * ``LC_TIME``,
+ * ``LC_ALL``, and
+ * ``LANG``
+"""
+
+from datetime import date, datetime, time, timedelta, tzinfo
+import re
+
+from babel.core import default_locale, get_global, Locale
+from babel.util import UTC
+
+__all__ = ['format_date', 'format_datetime', 'format_time',
+           'get_timezone_name', 'parse_date', 'parse_datetime', 'parse_time']
+__docformat__ = 'restructuredtext en'
+
+LC_TIME = default_locale('LC_TIME')
+
+# Aliases for use in scopes where the modules are shadowed by local variables
+date_ = date
+datetime_ = datetime
+time_ = time
+
+def get_period_names(locale=LC_TIME):
+    """Return the names for day periods (AM/PM) used by the locale.
+    
+    >>> get_period_names(locale='en_US')['am']
+    u'AM'
+    
+    :param locale: the `Locale` object, or a locale string
+    :return: the dictionary of period names
+    :rtype: `dict`
+    """
+    return Locale.parse(locale).periods
+
+def get_day_names(width='wide', context='format', locale=LC_TIME):
+    """Return the day names used by the locale for the specified format.
+    
+    >>> get_day_names('wide', locale='en_US')[1]
+    u'Tuesday'
+    >>> get_day_names('abbreviated', locale='es')[1]
+    u'mar'
+    >>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1]
+    u'D'
+    
+    :param width: the width to use, one of "wide", "abbreviated", or "narrow"
+    :param context: the context, either "format" or "stand-alone"
+    :param locale: the `Locale` object, or a locale string
+    :return: the dictionary of day names
+    :rtype: `dict`
+    """
+    return Locale.parse(locale).days[context][width]
+
+def get_month_names(width='wide', context='format', locale=LC_TIME):
+    """Return the month names used by the locale for the specified format.
+    
+    >>> get_month_names('wide', locale='en_US')[1]
+    u'January'
+    >>> get_month_names('abbreviated', locale='es')[1]
+    u'ene'
+    >>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1]
+    u'J'
+    
+    :param width: the width to use, one of "wide", "abbreviated", or "narrow"
+    :param context: the context, either "format" or "stand-alone"
+    :param locale: the `Locale` object, or a locale string
+    :return: the dictionary of month names
+    :rtype: `dict`
+    """
+    return Locale.parse(locale).months[context][width]
+
+def get_quarter_names(width='wide', context='format', locale=LC_TIME):
+    """Return the quarter names used by the locale for the specified format.
+    
+    >>> get_quarter_names('wide', locale='en_US')[1]
+    u'1st quarter'
+    >>> get_quarter_names('abbreviated', locale='de_DE')[1]
+    u'Q1'
+    
+    :param width: the width to use, one of "wide", "abbreviated", or "narrow"
+    :param context: the context, either "format" or "stand-alone"
+    :param locale: the `Locale` object, or a locale string
+    :return: the dictionary of quarter names
+    :rtype: `dict`
+    """
+    return Locale.parse(locale).quarters[context][width]
+
+def get_era_names(width='wide', locale=LC_TIME):
+    """Return the era names used by the locale for the specified format.
+    
+    >>> get_era_names('wide', locale='en_US')[1]
+    u'Anno Domini'
+    >>> get_era_names('abbreviated', locale='de_DE')[1]
+    u'n. Chr.'
+    
+    :param width: the width to use, either "wide", "abbreviated", or "narrow"
+    :param locale: the `Locale` object, or a locale string
+    :return: the dictionary of era names
+    :rtype: `dict`
+    """
+    return Locale.parse(locale).eras[width]
+
+def get_date_format(format='medium', locale=LC_TIME):
+    """Return the date formatting patterns used by the locale for the specified
+    format.
+    
+    >>> get_date_format(locale='en_US')
+    <DateTimePattern u'MMM d, yyyy'>
+    >>> get_date_format('full', locale='de_DE')
+    <DateTimePattern u'EEEE, d. MMMM yyyy'>
+    
+    :param format: the format to use, one of "full", "long", "medium", or
+                   "short"
+    :param locale: the `Locale` object, or a locale string
+    :return: the date format pattern
+    :rtype: `DateTimePattern`
+    """
+    return Locale.parse(locale).date_formats[format]
+
+def get_datetime_format(format='medium', locale=LC_TIME):
+    """Return the datetime formatting patterns used by the locale for the
+    specified format.
+    
+    >>> get_datetime_format(locale='en_US')
+    u'{1} {0}'
+    
+    :param format: the format to use, one of "full", "long", "medium", or
+                   "short"
+    :param locale: the `Locale` object, or a locale string
+    :return: the datetime format pattern
+    :rtype: `unicode`
+    """
+    patterns = Locale.parse(locale).datetime_formats
+    if format not in patterns:
+        format = None
+    return patterns[format]
+
+def get_time_format(format='medium', locale=LC_TIME):
+    """Return the time formatting patterns used by the locale for the specified
+    format.
+    
+    >>> get_time_format(locale='en_US')
+    <DateTimePattern u'h:mm:ss a'>
+    >>> get_time_format('full', locale='de_DE')
+    <DateTimePattern u'HH:mm:ss v'>
+    
+    :param format: the format to use, one of "full", "long", "medium", or
+                   "short"
+    :param locale: the `Locale` object, or a locale string
+    :return: the time format pattern
+    :rtype: `DateTimePattern`
+    """
+    return Locale.parse(locale).time_formats[format]
+
+def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
+    """Return the timezone associated with the given `datetime` object formatted
+    as string indicating the offset from GMT.
+    
+    >>> dt = datetime(2007, 4, 1, 15, 30)
+    >>> get_timezone_gmt(dt, locale='en')
+    u'GMT+00:00'
+    
+    >>> from pytz import timezone
+    >>> tz = timezone('America/Los_Angeles')
+    >>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz)
+    >>> get_timezone_gmt(dt, locale='en')
+    u'GMT-08:00'
+    >>> get_timezone_gmt(dt, 'short', locale='en')
+    u'-0800'
+    
+    The long format depends on the locale, for example in France the acronym
+    UTC string is used instead of GMT:
+    
+    >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
+    u'UTC-08:00'
+    
+    :param datetime: the ``datetime`` object; if `None`, the current date and
+                     time in UTC is used
+    :param width: either "long" or "short"
+    :param locale: the `Locale` object, or a locale string
+    :return: the GMT offset representation of the timezone
+    :rtype: `unicode`
+    :since: version 0.9
+    """
+    if datetime is None:
+        datetime = datetime_.utcnow()
+    elif isinstance(datetime, (int, long)):
+        datetime = datetime_.utcfromtimestamp(datetime).time()
+    if datetime.tzinfo is None:
+        datetime = datetime.replace(tzinfo=UTC)
+    locale = Locale.parse(locale)
+
+    offset = datetime.tzinfo.utcoffset(datetime)
+    seconds = offset.days * 24 * 60 * 60 + offset.seconds
+    hours, seconds = divmod(seconds, 3600)
+    if width == 'short':
+        pattern = u'%+03d%02d'
+    else:
+        pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
+    return pattern % (hours, seconds // 60)
+
+def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME):
+    """Return a representation of the given timezone using "location format".
+    
+    The result depends on both the local display name of the country and the
+    city associated with the time zone:
+    
+    >>> from pytz import timezone
+    >>> tz = timezone('America/St_Johns')
+    >>> get_timezone_location(tz, locale='de_DE')
+    u"Kanada (St. John's)"
+    >>> tz = timezone('America/Mexico_City')
+    >>> get_timezone_location(tz, locale='de_DE')
+    u'Mexiko (Mexiko-Stadt)'
+    
+    If the timezone is associated with a country that uses only a single
+    timezone, just the localized country name is returned:
+    
+    >>> tz = timezone('Europe/Berlin')
+    >>> get_timezone_name(tz, locale='de_DE')
+    u'Deutschland'
+    
+    :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
+                         the timezone; if `None`, the current date and time in
+                         UTC is assumed
+    :param locale: the `Locale` object, or a locale string
+    :return: the localized timezone name using location format
+    :rtype: `unicode`
+    :since: version 0.9
+    """
+    if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)):
+        dt = None
+        tzinfo = UTC
+    elif isinstance(dt_or_tzinfo, (datetime, time)):
+        dt = dt_or_tzinfo
+        if dt.tzinfo is not None:
+            tzinfo = dt.tzinfo
+        else:
+            tzinfo = UTC
+    else:
+        dt = None
+        tzinfo = dt_or_tzinfo
+    locale = Locale.parse(locale)
+
+    if hasattr(tzinfo, 'zone'):
+        zone = tzinfo.zone
+    else:
+        zone = tzinfo.tzname(dt or datetime.utcnow())
+
+    # Get the canonical time-zone code
+    zone = get_global('zone_aliases').get(zone, zone)
+
+    info = locale.time_zones.get(zone, {})
+
+    # Otherwise, if there is only one timezone for the country, return the
+    # localized country name
+    region_format = locale.zone_formats['region']
+    territory = get_global('zone_territories').get(zone)
+    if territory not in locale.territories:
+        territory = 'ZZ' # invalid/unknown
+    territory_name = locale.territories[territory]
+    if territory and len(get_global('territory_zones').get(territory, [])) == 1:
+        return region_format % (territory_name)
+
+    # Otherwise, include the city in the output
+    fallback_format = locale.zone_formats['fallback']
+    if 'city' in info:
+        city_name = info['city']
+    else:
+        metazone = get_global('meta_zones').get(zone)
+        metazone_info = locale.meta_zones.get(metazone, {})
+        if 'city' in metazone_info:
+            city_name = metainfo['city']
+        elif '/' in zone:
+            city_name = zone.split('/', 1)[1].replace('_', ' ')
+        else:
+            city_name = zone.replace('_', ' ')
+
+    return region_format % (fallback_format % {
+        '0': city_name,
+        '1': territory_name
+    })
+
+def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False,
+                      locale=LC_TIME):
+    r"""Return the localized display name for the given timezone. The timezone
+    may be specified using a ``datetime`` or `tzinfo` object.
+    
+    >>> from pytz import timezone
+    >>> dt = time(15, 30, tzinfo=timezone('America/Los_Angeles'))
+    >>> get_timezone_name(dt, locale='en_US')
+    u'Pacific Standard Time'
+    >>> get_timezone_name(dt, width='short', locale='en_US')
+    u'PST'
+    
+    If this function gets passed only a `tzinfo` object and no concrete
+    `datetime`,  the returned display name is indenpendent of daylight savings
+    time. This can be used for example for selecting timezones, or to set the
+    time of events that recur across DST changes:
+    
+    >>> tz = timezone('America/Los_Angeles')
+    >>> get_timezone_name(tz, locale='en_US')
+    u'Pacific Time'
+    >>> get_timezone_name(tz, 'short', locale='en_US')
+    u'PT'
+    
+    If no localized display name for the timezone is available, and the timezone
+    is associated with a country that uses only a single timezone, the name of
+    that country is returned, formatted according to the locale:
+    
+    >>> tz = timezone('Europe/Berlin')
+    >>> get_timezone_name(tz, locale='de_DE')
+    u'Deutschland'
+    >>> get_timezone_name(tz, locale='pt_BR')
+    u'Hor\xe1rio Alemanha'
+    
+    On the other hand, if the country uses multiple timezones, the city is also
+    included in the representation:
+    
+    >>> tz = timezone('America/St_Johns')
+    >>> get_timezone_name(tz, locale='de_DE')
+    u"Kanada (St. John's)"
+    
+    The `uncommon` parameter can be set to `True` to enable the use of timezone
+    representations that are not commonly used by the requested locale. For
+    example, while in French the central European timezone is usually
+    abbreviated as "HEC", in Canadian French, this abbreviation is not in
+    common use, so a generic name would be chosen by default:
+    
+    >>> tz = timezone('Europe/Paris')
+    >>> get_timezone_name(tz, 'short', locale='fr_CA')
+    u'France'
+    >>> get_timezone_name(tz, 'short', uncommon=True, locale='fr_CA')
+    u'HEC'
+    
+    :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
+                         the timezone; if a ``tzinfo`` object is used, the
+                         resulting display name will be generic, i.e.
+                         independent of daylight savings time; if `None`, the
+                         current date in UTC is assumed
+    :param width: either "long" or "short"
+    :param uncommon: whether even uncommon timezone abbreviations should be used
+    :param locale: the `Locale` object, or a locale string
+    :return: the timezone display name
+    :rtype: `unicode`
+    :since: version 0.9
+    :see:  `LDML Appendix J: Time Zone Display Names
+            <http://www.unicode.org/reports/tr35/#Time_Zone_Fallback>`_
+    """
+    if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)):
+        dt = None
+        tzinfo = UTC
+    elif isinstance(dt_or_tzinfo, (datetime, time)):
+        dt = dt_or_tzinfo
+        if dt.tzinfo is not None:
+            tzinfo = dt.tzinfo
+        else:
+            tzinfo = UTC
+    else:
+        dt = None
+        tzinfo = dt_or_tzinfo
+    locale = Locale.parse(locale)
+
+    if hasattr(tzinfo, 'zone'):
+        zone = tzinfo.zone
+    else:
+        zone = tzinfo.tzname(dt)
+
+    # Get the canonical time-zone code
+    zone = get_global('zone_aliases').get(zone, zone)
+
+    info = locale.time_zones.get(zone, {})
+    # Try explicitly translated zone names first
+    if width in info:
+        if dt is None:
+            field = 'generic'
+        else:
+            dst = tzinfo.dst(dt)
+            if dst is None:
+                field = 'generic'
+            elif dst == 0:
+                field = 'standard'
+            else:
+                field = 'daylight'
+        if field in info[width]:
+            return info[width][field]
+
+    metazone = get_global('meta_zones').get(zone)
+    if metazone:
+        metazone_info = locale.meta_zones.get(metazone, {})
+        if width in metazone_info and (uncommon or metazone_info.get('common')):
+            if dt is None:
+                field = 'generic'
+            else:
+                field = tzinfo.dst(dt) and 'daylight' or 'standard'
+            if field in metazone_info[width]:
+                return metazone_info[width][field]
+
+    # If we have a concrete datetime, we assume that the result can't be
+    # independent of daylight savings time, so we return the GMT offset
+    if dt is not None:
+        return get_timezone_gmt(dt, width=width, locale=locale)
+
+    return get_timezone_location(dt_or_tzinfo, locale=locale)
+
+def format_date(date=None, format='medium', locale=LC_TIME):
+    """Return a date formatted according to the given pattern.
+    
+    >>> d = date(2007, 04, 01)
+    >>> format_date(d, locale='en_US')
+    u'Apr 1, 2007'
+    >>> format_date(d, format='full', locale='de_DE')
+    u'Sonntag, 1. April 2007'
+    
+    If you don't want to use the locale default formats, you can specify a
+    custom date pattern:
+    
+    >>> format_date(d, "EEE, MMM d, ''yy", locale='en')
+    u"Sun, Apr 1, '07"
+    
+    :param date: the ``date`` or ``datetime`` object; if `None`, the current
+                 date is used
+    :param format: one of "full", "long", "medium", or "short", or a custom
+                   date/time pattern
+    :param locale: a `Locale` object or a locale identifier
+    :rtype: `unicode`
+    
+    :note: If the pattern contains time fields, an `AttributeError` will be
+           raised when trying to apply the formatting. This is also true if
+           the value of ``date`` parameter is actually a ``datetime`` object,
+           as this function automatically converts that to a ``date``.
+    """
+    if date is None:
+        date = date_.today()
+    elif isinstance(date, datetime):
+        date = date.date()
+
+    locale = Locale.parse(locale)
+    if format in ('full', 'long', 'medium', 'short'):
+        format = get_date_format(format, locale=locale)
+    pattern = parse_pattern(format)
+    return pattern.apply(date, locale)
+
+def format_datetime(datetime=None, format='medium', tzinfo=None,
+                    locale=LC_TIME):
+    """Return a date formatted according to the given pattern.
+    
+    >>> dt = datetime(2007, 04, 01, 15, 30)
+    >>> format_datetime(dt, locale='en_US')
+    u'Apr 1, 2007 3:30:00 PM'
+    
+    For any pattern requiring the display of the time-zone, the third-party
+    ``pytz`` package is needed to explicitly specify the time-zone:
+    
+    >>> from pytz import timezone
+    >>> format_datetime(dt, 'full', tzinfo=timezone('Europe/Paris'),
+    ...                 locale='fr_FR')
+    u'dimanche 1 avril 2007 17:30:00 HEC'
+    >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
+    ...                 tzinfo=timezone('US/Eastern'), locale='en')
+    u'2007.04.01 AD at 11:30:00 EDT'
+    
+    :param datetime: the `datetime` object; if `None`, the current date and
+                     time is used
+    :param format: one of "full", "long", "medium", or "short", or a custom
+                   date/time pattern
+    :param tzinfo: the timezone to apply to the time for display
+    :param locale: a `Locale` object or a locale identifier
+    :rtype: `unicode`
+    """
+    if datetime is None:
+        datetime = datetime_.utcnow()
+    elif isinstance(datetime, (int, long)):
+        datetime = datetime_.utcfromtimestamp(datetime)
+    elif isinstance(datetime, time):
+        datetime = datetime_.combine(date.today(), datetime)
+    if datetime.tzinfo is None:
+        datetime = datetime.replace(tzinfo=UTC)
+    if tzinfo is not None:
+        datetime = datetime.astimezone(tzinfo)
+        if hasattr(tzinfo, 'normalize'): # pytz
+            datetime = tzinfo.normalize(datetime)
+
+    locale = Locale.parse(locale)
+    if format in ('full', 'long', 'medium', 'short'):
+        return get_datetime_format(format, locale=locale) \
+            .replace('{0}', format_time(datetime, format, tzinfo=None,
+                                        locale=locale)) \
+            .replace('{1}', format_date(datetime, format, locale=locale))
+    else:
+        return parse_pattern(format).apply(datetime, locale)
+
+def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME):
+    """Return a time formatted according to the given pattern.
+    
+    >>> t = time(15, 30)
+    >>> format_time(t, locale='en_US')
+    u'3:30:00 PM'
+    >>> format_time(t, format='short', locale='de_DE')
+    u'15:30'
+    
+    If you don't want to use the locale default formats, you can specify a
+    custom time pattern:
+    
+    >>> format_time(t, "hh 'o''clock' a", locale='en')
+    u"03 o'clock PM"
+    
+    For any pattern requiring the display of the time-zone, the third-party
+    ``pytz`` package is needed to explicitly specify the time-zone:
+    
+    >>> from pytz import timezone
+    >>> t = datetime(2007, 4, 1, 15, 30)
+    >>> tzinfo = timezone('Europe/Paris')
+    >>> t = tzinfo.localize(t)
+    >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR')
+    u'15:30:00 HEC'
+    >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=timezone('US/Eastern'),
+    ...             locale='en')
+    u"09 o'clock AM, Eastern Daylight Time"
+    
+    As that example shows, when this function gets passed a
+    ``datetime.datetime`` value, the actual time in the formatted string is
+    adjusted to the timezone specified by the `tzinfo` parameter. If the
+    ``datetime`` is "naive" (i.e. it has no associated timezone information),
+    it is assumed to be in UTC.
+    
+    These timezone calculations are **not** performed if the value is of type
+    ``datetime.time``, as without date information there's no way to determine
+    what a given time would translate to in a different timezone without
+    information about whether daylight savings time is in effect or not. This
+    means that time values are left as-is, and the value of the `tzinfo`
+    parameter is only used to display the timezone name if needed:
+    
+    >>> t = time(15, 30)
+    >>> format_time(t, format='full', tzinfo=timezone('Europe/Paris'),
+    ...             locale='fr_FR')
+    u'15:30:00 HEC'
+    >>> format_time(t, format='full', tzinfo=timezone('US/Eastern'),
+    ...             locale='en_US')
+    u'3:30:00 PM ET'
+    
+    :param time: the ``time`` or ``datetime`` object; if `None`, the current
+                 time in UTC is used
+    :param format: one of "full", "long", "medium", or "short", or a custom
+                   date/time pattern
+    :param tzinfo: the time-zone to apply to the time for display
+    :param locale: a `Locale` object or a locale identifier
+    :rtype: `unicode`
+    
+    :note: If the pattern contains date fields, an `AttributeError` will be
+           raised when trying to apply the formatting. This is also true if
+           the value of ``time`` parameter is actually a ``datetime`` object,
+           as this function automatically converts that to a ``time``.
+    """
+    if time is None:
+        time = datetime.utcnow()
+    elif isinstance(time, (int, long)):
+        time = datetime.utcfromtimestamp(time)
+    if time.tzinfo is None:
+        time = time.replace(tzinfo=UTC)
+    if isinstance(time, datetime):
+        if tzinfo is not None:
+            time = time.astimezone(tzinfo)
+            if hasattr(tzinfo, 'normalize'): # pytz
+                time = tzinfo.normalize(time)
+        time = time.timetz()
+    elif tzinfo is not None:
+        time = time.replace(tzinfo=tzinfo)
+
+    locale = Locale.parse(locale)
+    if format in ('full', 'long', 'medium', 'short'):
+        format = get_time_format(format, locale=locale)
+    return parse_pattern(format).apply(time, locale)
+
+def parse_date(string, locale=LC_TIME):
+    """Parse a date from a string.
+    
+    This function uses the date format for the locale as a hint to determine
+    the order in which the date fields appear in the string.
+    
+    >>> parse_date('4/1/04', locale='en_US')
+    datetime.date(2004, 4, 1)
+    >>> parse_date('01.04.2004', locale='de_DE')
+    datetime.date(2004, 4, 1)
+    
+    :param string: the string containing the date
+    :param locale: a `Locale` object or a locale identifier
+    :return: the parsed date
+    :rtype: `date`
+    """
+    # TODO: try ISO format first?
+    format = get_date_format(locale=locale).pattern.lower()
+    year_idx = format.index('y')
+    month_idx = format.index('m')
+    if month_idx < 0:
+        month_idx = format.index('l')
+    day_idx = format.index('d')
+
+    indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]
+    indexes.sort()
+    indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)])
+
+    # FIXME: this currently only supports numbers, but should also support month
+    #        names, both in the requested locale, and english
+
+    numbers = re.findall('(\d+)', string)
+    year = numbers[indexes['Y']]
+    if len(year) == 2:
+        year = 2000 + int(year)
+    else:
+        year = int(year)
+    month = int(numbers[indexes['M']])
+    day = int(numbers[indexes['D']])
+    if month > 12:
+        month, day = day, month
+    return date(year, month, day)
+
+def parse_datetime(string, locale=LC_TIME):
+    """Parse a date and time from a string.
+    
+    This function uses the date and time formats for the locale as a hint to
+    determine the order in which the time fields appear in the string.
+    
+    :param string: the string containing the date and time
+    :param locale: a `Locale` object or a locale identifier
+    :return: the parsed date/time
+    :rtype: `datetime`
+    """
+    raise NotImplementedError
+
+def parse_time(string, locale=LC_TIME):
+    """Parse a time from a string.
+    
+    This function uses the time format for the locale as a hint to determine
+    the order in which the time fields appear in the string.
+    
+    >>> parse_time('15:30:00', locale='en_US')
+    datetime.time(15, 30)
+    
+    :param string: the string containing the time
+    :param locale: a `Locale` object or a locale identifier
+    :return: the parsed time
+    :rtype: `time`
+    """
+    # TODO: try ISO format first?
+    format = get_time_format(locale=locale).pattern.lower()
+    hour_idx = format.index('h')
+    if hour_idx < 0:
+        hour_idx = format.index('k')
+    min_idx = format.index('m')
+    sec_idx = format.index('s')
+
+    indexes = [(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')]
+    indexes.sort()
+    indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)])
+
+    # FIXME: support 12 hour clock, and 0-based hour specification
+    #        and seconds should be optional, maybe minutes too
+    #        oh, and time-zones, of course
+
+    numbers = re.findall('(\d+)', string)
+    hour = int(numbers[indexes['H']])
+    minute = int(numbers[indexes['M']])
+    second = int(numbers[indexes['S']])
+    return time(hour, minute, second)
+
+
+class DateTimePattern(object):
+
+    def __init__(self, pattern, format):
+        self.pattern = pattern
+        self.format = format
+
+    def __repr__(self):
+        return '<%s %r>' % (type(self).__name__, self.pattern)
+
+    def __unicode__(self):
+        return self.pattern
+
+    def __mod__(self, other):
+        assert type(other) is DateTimeFormat
+        return self.format % other
+
+    def apply(self, datetime, locale):
+        return self % DateTimeFormat(datetime, locale)
+
+
+class DateTimeFormat(object):
+
+    def __init__(self, value, locale):
+        assert isinstance(value, (date, datetime, time))
+        if isinstance(value, (datetime, time)) and value.tzinfo is None:
+            value = value.replace(tzinfo=UTC)
+        self.value = value
+        self.locale = Locale.parse(locale)
+
+    def __getitem__(self, name):
+        char = name[0]
+        num = len(name)
+        if char == 'G':
+            return self.format_era(char, num)
+        elif char in ('y', 'Y', 'u'):
+            return self.format_year(char, num)
+        elif char in ('Q', 'q'):
+            return self.format_quarter(char, num)
+        elif char in ('M', 'L'):
+            return self.format_month(char, num)
+        elif char in ('w', 'W'):
+            return self.format_week(char, num)
+        elif char == 'd':
+            return self.format(self.value.day, num)
+        elif char == 'D':
+            return self.format_day_of_year(num)
+        elif char == 'F':
+            return self.format_day_of_week_in_month()
+        elif char in ('E', 'e', 'c'):
+            return self.format_weekday(char, num)
+        elif char == 'a':
+            return self.format_period(char)
+        elif char == 'h':
+            if self.value.hour % 12 == 0:
+                return self.format(12, num)
+            else:
+                return self.format(self.value.hour % 12, num)
+        elif char == 'H':
+            return self.format(self.value.hour, num)
+        elif char == 'K':
+            return self.format(self.value.hour % 12, num)
+        elif char == 'k':
+            if self.value.hour == 0:
+                return self.format(24, num)
+            else:
+                return self.format(self.value.hour, num)
+        elif char == 'm':
+            return self.format(self.value.minute, num)
+        elif char == 's':
+            return self.format(self.value.second, num)
+        elif char == 'S':
+            return self.format_frac_seconds(num)
+        elif char == 'A':
+            return self.format_milliseconds_in_day(num)
+        elif char in ('z', 'Z', 'v', 'V'):
+            return self.format_timezone(char, num)
+        else:
+            raise KeyError('Unsupported date/time field %r' % char)
+
+    def format_era(self, char, num):
+        width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[max(3, num)]
+        era = int(self.value.year >= 0)
+        return get_era_names(width, self.locale)[era]
+
+    def format_year(self, char, num):
+        value = self.value.year
+        if char.isupper():
+            week = self.get_week_number(self.get_day_of_year())
+            if week == 0:
+                value -= 1
+        year = self.format(value, num)
+        if num == 2:
+            year = year[-2:]
+        return year
+
+    def format_quarter(self, char, num):
+        quarter = (self.value.month - 1) // 3 + 1
+        if num <= 2:
+            return ('%%0%dd' % num) % quarter
+        width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
+        context = {'Q': 'format', 'q': 'stand-alone'}[char]
+        return get_quarter_names(width, context, self.locale)[quarter]
+
+    def format_month(self, char, num):
+        if num <= 2:
+            return ('%%0%dd' % num) % self.value.month
+        width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
+        context = {'M': 'format', 'L': 'stand-alone'}[char]
+        return get_month_names(width, context, self.locale)[self.value.month]
+
+    def format_week(self, char, num):
+        if char.islower(): # week of year
+            day_of_year = self.get_day_of_year()
+            week = self.get_week_number(day_of_year)
+            if week == 0:
+                date = self.value - timedelta(days=day_of_year)
+                week = self.get_week_number(self.get_day_of_year(date),
+                                            date.weekday())
+            return self.format(week, num)
+        else: # week of month
+            week = self.get_week_number(self.value.day)
+            if week == 0:
+                date = self.value - timedelta(days=self.value.day)
+                week = self.get_week_number(date.day, date.weekday())
+                pass
+            return '%d' % week
+
+    def format_weekday(self, char, num):
+        if num < 3:
+            if char.islower():
+                value = 7 - self.locale.first_week_day + self.value.weekday()
+                return self.format(value % 7 + 1, num)
+            num = 3
+        weekday = self.value.weekday()
+        width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
+        context = {3: 'format', 4: 'format', 5: 'stand-alone'}[num]
+        return get_day_names(width, context, self.locale)[weekday]
+
+    def format_day_of_year(self, num):
+        return self.format(self.get_day_of_year(), num)
+
+    def format_day_of_week_in_month(self):
+        return '%d' % ((self.value.day - 1) / 7 + 1)
+
+    def format_period(self, char):
+        period = {0: 'am', 1: 'pm'}[int(self.value.hour >= 12)]
+        return get_period_names(locale=self.locale)[period]
+
+    def format_frac_seconds(self, num):
+        value = str(self.value.microsecond)
+        return self.format(round(float('.%s' % value), num) * 10**num, num)
+
+    def format_milliseconds_in_day(self, num):
+        msecs = self.value.microsecond // 1000 + self.value.second * 1000 + \
+                self.value.minute * 60000 + self.value.hour * 3600000
+        return self.format(msecs, num)
+
+    def format_timezone(self, char, num):
+        width = {3: 'short', 4: 'long'}[max(3, num)]
+        if char == 'z':
+            return get_timezone_name(self.value, width, locale=self.locale)
+        elif char == 'Z':
+            return get_timezone_gmt(self.value, width, locale=self.locale)
+        elif char == 'v':
+            return get_timezone_name(self.value.tzinfo, width,
+                                     locale=self.locale)
+        elif char == 'V':
+            if num == 1:
+                return get_timezone_name(self.value.tzinfo, width,
+                                         uncommon=True, locale=self.locale)
+            return get_timezone_location(self.value.tzinfo, locale=self.locale)
+
+    def format(self, value, length):
+        return ('%%0%dd' % length) % value
+
+    def get_day_of_year(self, date=None):
+        if date is None:
+            date = self.value
+        return (date - date_(date.year, 1, 1)).days + 1
+
+    def get_week_number(self, day_of_period, day_of_week=None):
+        """Return the number of the week of a day within a period. This may be
+        the week number in a year or the week number in a month.
+        
+        Usually this will return a value equal to or greater than 1, but if the
+        first week of the period is so short that it actually counts as the last
+        week of the previous period, this function will return 0.
+        
+        >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE'))
+        >>> format.get_week_number(6)
+        1
+        
+        >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('en_US'))
+        >>> format.get_week_number(6)
+        2
+        
+        :param day_of_period: the number of the day in the period (usually
+                              either the day of month or the day of year)
+        :param day_of_week: the week day; if ommitted, the week day of the
+                            current date is assumed
+        """
+        if day_of_week is None:
+            day_of_week = self.value.weekday()
+        first_day = (day_of_week - self.locale.first_week_day -
+                     day_of_period + 1) % 7
+        if first_day < 0:
+            first_day += 7
+        week_number = (day_of_period + first_day - 1) / 7
+        if 7 - first_day >= self.locale.min_week_days:
+            week_number += 1
+        return week_number
+
+
+PATTERN_CHARS = {
+    'G': [1, 2, 3, 4, 5],                                           # era
+    'y': None, 'Y': None, 'u': None,                                # year
+    'Q': [1, 2, 3, 4], 'q': [1, 2, 3, 4],                           # quarter
+    'M': [1, 2, 3, 4, 5], 'L': [1, 2, 3, 4, 5],                     # month
+    'w': [1, 2], 'W': [1],                                          # week
+    'd': [1, 2], 'D': [1, 2, 3], 'F': [1], 'g': None,               # day
+    'E': [1, 2, 3, 4, 5], 'e': [1, 2, 3, 4, 5], 'c': [1, 3, 4, 5],  # week day
+    'a': [1],                                                       # period
+    'h': [1, 2], 'H': [1, 2], 'K': [1, 2], 'k': [1, 2],             # hour
+    'm': [1, 2],                                                    # minute
+    's': [1, 2], 'S': None, 'A': None,                              # second
+    'z': [1, 2, 3, 4], 'Z': [1, 2, 3, 4], 'v': [1, 4], 'V': [1, 4]  # zone
+}
+
+def parse_pattern(pattern):
+    """Parse date, time, and datetime format patterns.
+    
+    >>> parse_pattern("MMMMd").format
+    u'%(MMMM)s%(d)s'
+    >>> parse_pattern("MMM d, yyyy").format
+    u'%(MMM)s %(d)s, %(yyyy)s'
+    
+    Pattern can contain literal strings in single quotes:
+    
+    >>> parse_pattern("H:mm' Uhr 'z").format
+    u'%(H)s:%(mm)s Uhr %(z)s'
+    
+    An actual single quote can be used by using two adjacent single quote
+    characters:
+    
+    >>> parse_pattern("hh' o''clock'").format
+    u"%(hh)s o'clock"
+    
+    :param pattern: the formatting pattern to parse
+    """
+    if type(pattern) is DateTimePattern:
+        return pattern
+
+    result = []
+    quotebuf = None
+    charbuf = []
+    fieldchar = ['']
+    fieldnum = [0]
+
+    def append_chars():
+        result.append(''.join(charbuf).replace('%', '%%'))
+        del charbuf[:]
+
+    def append_field():
+        limit = PATTERN_CHARS[fieldchar[0]]
+        if limit and fieldnum[0] not in limit:
+            raise ValueError('Invalid length for field: %r'
+                             % (fieldchar[0] * fieldnum[0]))
+        result.append('%%(%s)s' % (fieldchar[0] * fieldnum[0]))
+        fieldchar[0] = ''
+        fieldnum[0] = 0
+
+    for idx, char in enumerate(pattern.replace("''", '\0')):
+        if quotebuf is None:
+            if char == "'": # quote started
+                if fieldchar[0]:
+                    append_field()
+                elif charbuf:
+                    append_chars()
+                quotebuf = []
+            elif char in PATTERN_CHARS:
+                if charbuf:
+                    append_chars()
+                if char == fieldchar[0]:
+                    fieldnum[0] += 1
+                else:
+                    if fieldchar[0]:
+                        append_field()
+                    fieldchar[0] = char
+                    fieldnum[0] = 1
+            else:
+                if fieldchar[0]:
+                    append_field()
+                charbuf.append(char)
+
+        elif quotebuf is not None:
+            if char == "'": # end of quote
+                charbuf.extend(quotebuf)
+                quotebuf = None
+            else: # inside quote
+                quotebuf.append(char)
+
+    if fieldchar[0]:
+        append_field()
+    elif charbuf:
+        append_chars()
+
+    return DateTimePattern(pattern, u''.join(result).replace('\0', "'"))

BIN
desktop/core/ext-py/Babel-0.9.6/babel/global.dat


+ 209 - 0
desktop/core/ext-py/Babel-0.9.6/babel/localedata.py

@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2007 Edgewall Software
+# All rights reserved.
+#
+# This software is licensed as described in the file COPYING, which
+# you should have received as part of this distribution. The terms
+# are also available at http://babel.edgewall.org/wiki/License.
+#
+# This software consists of voluntary contributions made by many
+# individuals. For the exact contribution history, see the revision
+# history and logs, available at http://babel.edgewall.org/log/.
+
+"""Low-level locale data access.
+
+:note: The `Locale` class, which uses this module under the hood, provides a
+       more convenient interface for accessing the locale data.
+"""
+
+import os
+import pickle
+try:
+    import threading
+except ImportError:
+    import dummy_threading as threading
+from UserDict import DictMixin
+
+__all__ = ['exists', 'list', 'load']
+__docformat__ = 'restructuredtext en'
+
+_cache = {}
+_cache_lock = threading.RLock()
+_dirname = os.path.join(os.path.dirname(__file__), 'localedata')
+
+
+def exists(name):
+    """Check whether locale data is available for the given locale.
+    
+    :param name: the locale identifier string
+    :return: `True` if the locale data exists, `False` otherwise
+    :rtype: `bool`
+    """
+    if name in _cache:
+        return True
+    return os.path.exists(os.path.join(_dirname, '%s.dat' % name))
+
+
+def list():
+    """Return a list of all locale identifiers for which locale data is
+    available.
+    
+    :return: a list of locale identifiers (strings)
+    :rtype: `list`
+    :since: version 0.8.1
+    """
+    return [stem for stem, extension in [
+        os.path.splitext(filename) for filename in os.listdir(_dirname)
+    ] if extension == '.dat' and stem != 'root']
+
+
+def load(name, merge_inherited=True):
+    """Load the locale data for the given locale.
+    
+    The locale data is a dictionary that contains much of the data defined by
+    the Common Locale Data Repository (CLDR). This data is stored as a
+    collection of pickle files inside the ``babel`` package.
+    
+    >>> d = load('en_US')
+    >>> d['languages']['sv']
+    u'Swedish'
+    
+    Note that the results are cached, and subsequent requests for the same
+    locale return the same dictionary:
+    
+    >>> d1 = load('en_US')
+    >>> d2 = load('en_US')
+    >>> d1 is d2
+    True
+    
+    :param name: the locale identifier string (or "root")
+    :param merge_inherited: whether the inherited data should be merged into
+                            the data of the requested locale
+    :return: the locale data
+    :rtype: `dict`
+    :raise `IOError`: if no locale data file is found for the given locale
+                      identifer, or one of the locales it inherits from
+    """
+    _cache_lock.acquire()
+    try:
+        data = _cache.get(name)
+        if not data:
+            # Load inherited data
+            if name == 'root' or not merge_inherited:
+                data = {}
+            else:
+                parts = name.split('_')
+                if len(parts) == 1:
+                    parent = 'root'
+                else:
+                    parent = '_'.join(parts[:-1])
+                data = load(parent).copy()
+            filename = os.path.join(_dirname, '%s.dat' % name)
+            fileobj = open(filename, 'rb')
+            try:
+                if name != 'root' and merge_inherited:
+                    merge(data, pickle.load(fileobj))
+                else:
+                    data = pickle.load(fileobj)
+                _cache[name] = data
+            finally:
+                fileobj.close()
+        return data
+    finally:
+        _cache_lock.release()
+
+
+def merge(dict1, dict2):
+    """Merge the data from `dict2` into the `dict1` dictionary, making copies
+    of nested dictionaries.
+    
+    >>> d = {1: 'foo', 3: 'baz'}
+    >>> merge(d, {1: 'Foo', 2: 'Bar'})
+    >>> items = d.items(); items.sort(); items
+    [(1, 'Foo'), (2, 'Bar'), (3, 'baz')]
+    
+    :param dict1: the dictionary to merge into
+    :param dict2: the dictionary containing the data that should be merged
+    """
+    for key, val2 in dict2.items():
+        if val2 is not None:
+            val1 = dict1.get(key)
+            if isinstance(val2, dict):
+                if val1 is None:
+                    val1 = {}
+                if isinstance(val1, Alias):
+                    val1 = (val1, val2)
+                elif isinstance(val1, tuple):
+                    alias, others = val1
+                    others = others.copy()
+                    merge(others, val2)
+                    val1 = (alias, others)
+                else:
+                    val1 = val1.copy()
+                    merge(val1, val2)
+            else:
+                val1 = val2
+            dict1[key] = val1
+
+
+class Alias(object):
+    """Representation of an alias in the locale data.
+    
+    An alias is a value that refers to some other part of the locale data,
+    as specified by the `keys`.
+    """
+
+    def __init__(self, keys):
+        self.keys = tuple(keys)
+
+    def __repr__(self):
+        return '<%s %r>' % (type(self).__name__, self.keys)
+
+    def resolve(self, data):
+        """Resolve the alias based on the given data.
+        
+        This is done recursively, so if one alias resolves to a second alias,
+        that second alias will also be resolved.
+        
+        :param data: the locale data
+        :type data: `dict`
+        """
+        base = data
+        for key in self.keys:
+            data = data[key]
+        if isinstance(data, Alias):
+            data = data.resolve(base)
+        elif isinstance(data, tuple):
+            alias, others = data
+            data = alias.resolve(base)
+        return data
+
+
+class LocaleDataDict(DictMixin, dict):
+    """Dictionary wrapper that automatically resolves aliases to the actual
+    values.
+    """
+
+    def __init__(self, data, base=None):
+        dict.__init__(self, data)
+        if base is None:
+            base = data
+        self.base = base
+
+    def __getitem__(self, key):
+        orig = val = dict.__getitem__(self, key)
+        if isinstance(val, Alias): # resolve an alias
+            val = val.resolve(self.base)
+        if isinstance(val, tuple): # Merge a partial dict with an alias
+            alias, others = val
+            val = alias.resolve(self.base).copy()
+            merge(val, others)
+        if type(val) is dict: # Return a nested alias-resolving dict
+            val = LocaleDataDict(val, base=self.base)
+        if val is not orig:
+            self[key] = val
+        return val
+
+    def copy(self):
+        return LocaleDataDict(dict.copy(self), base=self.base)

BIN
desktop/core/ext-py/Babel-0.9.6/babel/localedata/aa.dat


Some files were not shown because too many files changed in this diff