24b692b0e32f5d06c1a9cbd375d248914cef9c3c
[scpubgit/stemmaweb.git] / root / js / componentload.js
1 // Global state variables
2 var selectedTextID;
3 var selectedTextInfo;
4 var selectedTextEditable;
5 var selectedStemmaID = -1;
6 var stemmata = [];
7
8 // Load the names of the appropriate traditions into the directory div.
9 function refreshDirectory () {
10         var lmesg = $('#loading_message').clone();
11         $('#directory').empty().append( lmesg.contents() );
12     $('#directory').load( _get_url(["directory"]), 
13         function(response, status, xhr) {
14                         if (status == "error") {
15                                 var msg = "An error occurred: ";
16                                 $("#directory").html(msg + xhr.status + " " + xhr.statusText);
17                         } else {
18                                 if( textOnLoad != "" ) {
19                                         // Call the click callback for the relevant text, if it is
20                                         // in the page.
21                                         $('#'+textOnLoad).click();
22                                         textOnLoad = "";
23                                 }
24                         }
25                 }
26         );
27 }
28
29 // Load a tradition with its information and stemmata into the tradition
30 // view pane. Calls load_textinfo.
31 function loadTradition( textid, textname, editable ) {
32         selectedTextID = textid;
33         selectedTextEditable = editable;
34     // First insert the placeholder image and register an error handler
35     $('#textinfo_load_status').empty();
36     $('#stemma_graph').empty();
37     $('#textinfo_waitbox').show();
38     $('#textinfo_container').hide().ajaxError( 
39         function(event, jqXHR, ajaxSettings, thrownError) {
40         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 && ajaxSettings.type == 'GET'  ) {
41                         $('#textinfo_waitbox').hide();
42                         $('#textinfo_container').show();
43                         display_error( jqXHR, $("#textinfo_load_status") );
44         }
45     });
46     
47     // Hide the functionality that is irrelevant
48     if( editable ) {
49         $('#open_stemma_add').show();
50         $('#open_textinfo_edit').show();
51         $('#relatebutton_label').text('View collation and edit relationships');
52     } else {
53         $('#open_stemma_add').hide();
54         $('#open_stemweb_ui').hide();
55         $('#query_stemweb_ui').hide();
56         $('#open_textinfo_edit').hide();
57         $('#relatebutton_label').text('View collation and relationships');
58     }
59
60     // Then get and load the actual content.
61     // TODO: scale #stemma_graph both horizontally and vertically
62     // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
63     $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
64         // Add the scalar data
65         selectedTextInfo = textdata;
66         load_textinfo();
67         // Add the stemma(ta)
68         stemmata = textdata.stemmata;
69         if( stemmata.length ) {
70                 selectedStemmaID = 0;
71         } else {
72                 selectedStemmaID = -1;
73                 }
74                 load_stemma( selectedStemmaID );
75         // Set up the relationship mapper button
76                 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
77                 // Set up the download button
78                 $('#dl_tradition').attr( 'href', _get_url([ "download", textid ]) );
79                 $('#dl_tradition').attr( 'download', selectedTextInfo.name + '.xml' );
80         });
81 }
82
83 // Load the metadata about a tradition into the appropriate div.
84 function load_textinfo() {
85         $('#textinfo_waitbox').hide();
86         $('#textinfo_load_status').empty();
87         $('#textinfo_container').show();
88         // The tradition name should appear here and should be identical in the
89         // corresponding directory span. In case the name was just changed...
90         $('.texttitle').empty().append( selectedTextInfo.name );
91         $('#' + selectedTextID).empty().append( selectedTextInfo.name );
92         // Witnesses
93         $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
94         $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
95         // Who the owner is
96         $('#owner_id').empty().append('no one');
97         if( selectedTextInfo.owner ) {
98                 var owneremail = selectedTextInfo.owner;
99                 var chop = owneremail.indexOf( '@' );
100                 if( chop > -1 ) {
101                         owneremail = owneremail.substr( 0, chop + 1 ) + '...';
102                 }
103                 $('#owner_id').empty().append( owneremail );
104         }
105         // Whether or not it is public
106         $('#not_public').empty();
107         if( selectedTextInfo['public'] == false ) {
108                 $('#not_public').append('NOT ');
109         }
110         // What language setting it has, if any
111         $('#marked_language').empty().append('no language set');
112         if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
113                 $('#marked_language').empty().append( selectedTextInfo.language );
114         }
115 }       
116
117 // Enable / disable the appropriate buttons for paging through the stemma.
118 function show_stemmapager () {
119       $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
120       $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
121       if( selectedStemmaID > 0 ) {
122               $('.pager_left_button').click( function () {
123                       load_stemma( selectedStemmaID - 1, selectedTextEditable );
124               }).removeClass( 'greyed_out' );
125       }       
126       if( selectedStemmaID + 1 < stemmata.length ) {
127               $('.pager_right_button').click( function () {
128                       load_stemma( selectedStemmaID + 1, selectedTextEditable );
129               }).removeClass( 'greyed_out' );
130       }
131 }
132
133 // Load a given stemma SVG into the stemmagraph box.
134 function load_stemma( idx ) {
135         // Load the stemma at idx
136         selectedStemmaID = idx;
137         show_stemmapager( selectedTextEditable );
138         $('#open_stemma_edit').hide();
139         $('#run_stexaminer').hide();
140         $('#stemma_identifier').empty();
141         // Add the relevant Stemweb functionality
142         if( selectedTextEditable ) {
143                 switch_stemweb_ui();
144         }
145         if( idx > -1 ) {
146                 // Load the stemma and its properties
147                 var stemmadata = stemmata[idx];
148                 if( selectedTextEditable ) {
149                         $('#open_stemma_edit').show();
150                 }
151                 if( stemmadata.directed ) {
152                         // Stexaminer submit action
153                         var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
154                         $('#run_stexaminer').attr( 'action', stexpath );
155                         $('#run_stexaminer').show();
156                 }
157                 loadSVG( stemmadata.svg );
158                 $('#stemma_identifier').text( stemmadata.name );
159         setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
160         }
161 }
162
163 function switch_stemweb_ui() {
164         if( selectedTextInfo.stemweb_jobid == 0 ) {
165                 // We want to run Stemweb.
166                 $('#open_stemweb_ui').show();
167                 $('#query_stemweb_ui').hide();
168                 if( ! $('#stemweb-ui-dialog').dialog('isOpen') ) {
169                         $('#call_stemweb').show()
170                         $('#stemweb_run_button').show();
171                 }
172         } else {
173                 $('#query_stemweb_ui').show();
174                 $('#open_stemweb_ui').hide();
175                 $('#call_stemweb').hide();
176                 $('#stemweb_run_button').hide();
177         }
178 }
179
180 function query_stemweb_progress() {
181         var requrl = _get_url([ "stemweb", "query", selectedTextInfo.stemweb_jobid ]);
182         $('#stemweb-ui-dialog').dialog('open');
183         $('#stemweb_run_status').empty().append( 
184                                 _make_message( 'notification', 'Querying Stemweb for calculation progress...') );
185         $.getJSON( requrl, function (data) {
186                 process_stemweb_result( data );
187         });
188 }
189
190 function process_stemweb_result(data) {
191         // Look for a status message, either success, running, or notfound.
192         if( data.status === 'success' ) {
193                 // Add the new stemmata to the textinfo and tell the user.
194                 selectedTextInfo.stemweb_jobid = 0;
195                 if( data.stemmata.length > 0 ) {
196                         stemmata = stemmata.concat( data.stemmata );
197                         if( selectedStemmaID == -1 ) {
198                                 // We have a stemma for the first time; load the first one.
199                                 load_stemma( 0, true );
200                         } else {
201                                 // Move to the index of the first added stemma.
202                                 var newIdx = stemmata.length - data.stemmata.length;
203                                 load_stemma( newIdx, true );
204                         } 
205                         // Hide the call dialog no matter how we got here
206                         $('#call_stemweb').hide()
207                         $('#stemweb_run_button').hide();
208                         $('#stemweb_run_status').empty().append( 
209                                 _make_message( 'notification', 'You have one or more new stemmata!' ) );
210                 } else {
211                         $('#stemweb_run_status').empty().append( 
212                                 _make_message( 'warning', 'Stemweb run finished with no stemmata...huh?!' ) );
213                 }
214         } else if( data.status === 'running' ) {
215                 // Just tell the user.
216                 $('#stemweb_run_status').empty().append( 
217                                 _make_message( 'warning', 'Your Stemweb query is still running!' ) );
218         } else if( data.status === 'notfound' ) {
219                 // Ask the user to refresh, for now.
220                 $('#stemweb_run_status').empty().append( 
221                                 _make_message( 'warning', 'Your Stemweb query probably finished and reported back. Please reload to check.' ) );
222         } else if( data.status === 'failed' ) {
223                 selectedTextInfo.stemweb_jobid = 0;
224                 failureMsg = 'Your stemweb query failed';
225                 if( data.message ) {
226                         failureMsg = failureMsg + ' with the following message: ' + data.message
227                 } else {
228                         failureMsg = failureMsg + ' without telling us why.'
229                 }
230                 $('#stemweb_run_status').empty().append( 
231                                 _make_message( 'error', failureMsg ) );
232         }
233 }
234
235 function _make_message( type, msg ) {
236         theMessage = $('<span>').attr( 'class', type );
237         theMessage.append( msg );
238         return theMessage;
239 }
240
241 // Load the SVG we are given
242 function loadSVG(svgData) {
243         var svgElement = $('#stemma_graph');
244
245         $(svgElement).svg('destroy');
246
247         $(svgElement).svg({
248                 loadURL: svgData,
249                 onLoad : function () {
250                         var theSVG = svgElement.find('svg');
251                         var svgoffset = theSVG.offset();
252                         var browseroffset = 1;
253                         // Firefox needs a different offset, stupidly enough
254                         if( navigator.userAgent.indexOf('Firefox') > -1 ) {
255                                 browseroffset = 3; // works for tall images
256                                 // ...but if the SVG is wider than it is tall, Firefox treats
257                                 // the top as being the top of the graph, loaded into the middle
258                                 // of the canvas, but then the margin at the top of the canvas
259                                 // extends upward. So we have to find the actual top of the canvas
260                                 // and correct for *that* instead.
261                                 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
262                                 if( vbdim.height < vbdim.width ) {
263                                         var vbscale = svgElement.width() / vbdim.width;
264                                         var vbrealheight = vbdim.height * vbscale;
265                                         browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
266                                 }
267                         }
268                         var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
269                         theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
270                         set_stemma_interactive( theSVG );
271                 }
272         });
273 }
274
275 function set_stemma_interactive( svg_element ) {
276         if( selectedTextEditable ) {
277                 $( "#root_tree_dialog_button_ok" ).click( function() {
278                         var requrl = _get_url([ "stemmaroot", selectedTextID, selectedStemmaID ]);
279                         var targetnode = $('#root_tree_dialog').data( 'selectedNode' );
280                         $.post( requrl, { root: targetnode }, function (data) {
281                                 // Reload the new stemma
282                                 stemmata[selectedStemmaID] = data;
283                                 load_stemma( selectedStemmaID );
284                                 // Put away the dialog
285                                 $('#root_tree_dialog').data( 'selectedNode', null ).hide();
286                         } );
287                 } ).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
288                         if( ajaxSettings.url.indexOf( 'stemmaroot' ) > -1 
289                                 && ajaxSettings.type == 'POST' ) {
290                                 display_error( jqXHR, $("#stemma_load_status") );
291                         }
292                 } );
293                 // TODO Clear error at some appropriate point
294                 $.each( $( 'ellipse', svg_element ), function(index) {
295                         var ellipse = $(this);
296                         var g = ellipse.parent( 'g' );
297                         g.click( function(evt) {
298                                 if( typeof root_tree_dialog_timeout !== 'undefined' ) { clearTimeout( root_tree_dialog_timeout ) };
299                                 g.unbind( 'mouseleave' );
300                                 var dialog = $( '#root_tree_dialog' );
301                                 // Note which node triggered the dialog
302                                 dialog.data( 'selectedNode', g.attr('id') );
303                                 // Position the dialog
304                                 dialog.hide();
305                                 dialog.css( 'top', evt.pageY + 3 );
306                                 dialog.css( 'left', evt.pageX + 3 );
307                                 dialog.show();
308                                 root_tree_dialog_timeout = setTimeout( function() {
309                                         $( '#root_tree_dialog' ).data( 'selectedNode', null ).hide();
310                                         ellipse.removeClass( 'stemma_node_highlight' );
311                                         g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
312                                 }, 3000 );
313                         } );
314                         g.mouseenter( function() { 
315                                 $( 'ellipse.stemma_node_highlight' ).removeClass( 'stemma_node_highlight' );
316                                 ellipse.addClass( 'stemma_node_highlight' ) 
317                         } );
318                         g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
319                 } );
320         }
321 }
322
323 // General-purpose error-handling function.
324 // TODO make sure this gets used throughout, where appropriate.
325 function display_error( jqXHR, el ) {
326         var errmsg;
327         if( jqXHR.responseText == "" ) {
328                 errmsg = "perhaps the server went down?"
329         } else {
330                 var errobj;
331                 try {
332                         errobj = jQuery.parseJSON( jqXHR.responseText );
333                         errmsg = errobj.error;
334                 } catch ( parse_err ) {
335                         errmsg = "something went wrong on the server."
336                 }
337         }
338         var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
339         $(el).empty().append( msghtml ).show();
340 }
341
342 // Event to enable the upload button when a file has been selected
343 function file_selected( e ) {
344         if( e.files.length == 1 ) {
345                 $('#upload_button').button('enable');
346                 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
347         } else {
348                 $('#upload_button').button('disable');
349                 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
350         }
351 }
352
353 // Implement our own AJAX method that uses the features of XMLHttpRequest2
354 // but try to let it have a similar interface to jquery.post
355 // The data var needs to be a FormData() object.
356 // The callback will be given a single argument, which is the response data
357 // of the given type.
358
359 function post_xhr2( url, data, cb, type ) {
360         if( !type ) {
361                 type = 'json';
362         }
363         var xhr = new XMLHttpRequest();
364         // Set the expected response type
365         if( type === 'data' ) {
366                 xhr.responseType = 'blob';
367         } else if( type === 'xml' ) {
368                 xhr.responseType = 'document';
369         } 
370         // Post the form
371         // Gin up an AJAX settings object
372         $.ajaxSetup({ url: url, type: 'POST' });
373         xhr.open( 'POST', url, true );
374         // Handle the results
375         xhr.onload = function( e ) {
376                 // Get the response and parse it
377                 // Call the callback with the response, whatever it was
378                 var xhrs = e.target;
379                 if( xhrs.status > 199 && xhrs.status < 300  ) { // Success
380                         var resp;
381                         if( type === 'json' ) {
382                                 resp = $.parseJSON( xhrs.responseText );
383                         } else if ( type === 'xml' ) {
384                                 resp = xhrs.responseXML;
385                         } else if ( type === 'text' ) {
386                                 resp = xhrs.responseText;
387                         } else {
388                                 resp = xhrs.response;
389                         }
390                         cb( resp );
391                 } else {
392                         // Trigger the ajaxError...
393                         _trigger_ajaxerror( e );
394                 }
395         };
396         xhr.onerror = _trigger_ajaxerror;
397         xhr.onabort = _trigger_ajaxerror;
398         xhr.send( data );
399 }
400
401 function _trigger_ajaxerror( e ) {
402         var xhr = e.target;
403         var thrown = xhr.statusText || 'Request error';
404         jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
405 }
406
407 function upload_new () {
408         // Serialize the upload form, get the file and attach it to the request,
409         // POST the lot and handle the response.
410         var newfile = $('#new_file').get(0).files[0];
411         var reader = new FileReader();
412         reader.onload = function( evt ) {
413                 var data = new FormData();
414                 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
415                                 data.append( o.name, o.value );
416                         });
417                 data.append( 'file', newfile );
418                 var upload_url = _get_url([ 'newtradition' ]);
419                 post_xhr2( upload_url, data, function( ret ) {
420                         if( ret.id ) {
421                                 $('#upload-collation-dialog').dialog('close');
422                                 refreshDirectory();
423                                 loadTradition( ret.id, ret.name, 1 );
424                         } else if( ret.error ) {
425                                 $('#upload_status').empty().append( 
426                                         $('<span>').attr('class', 'error').append( ret.error ) );
427                         }
428                 }, 'json' );
429         };
430         reader.onerror = function( evt ) {
431                 var err_resp = 'File read error';
432                 if( e.name == 'NotFoundError' ) {
433                         err_resp = 'File not found';
434                 } else if ( e.name == 'NotReadableError' ) {
435                         err_resp == 'File unreadable - is it yours?';
436                 } else if ( e.name == 'EncodingError' ) {
437                         err_resp == 'File cannot be encoded - is it too long?';
438                 } else if ( e.name == 'SecurityError' ) {
439                         err_resp == 'File read security error';
440                 }
441                 // Fake a jqXHR object that we can pass to our generic error handler.
442                 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
443                 display_error( jqxhr, $('#upload_status') );
444                 $('#upload_button').button('disable');
445         }
446         
447         reader.readAsBinaryString( newfile );
448 }
449
450 // Utility function to neatly construct an application URL
451 function _get_url( els ) {
452         return basepath + els.join('/');
453 }
454
455 // TODO Attach unified ajaxError handler to document
456 $(document).ready( function() {
457         // See if we have the browser functionality we need
458         // TODO Also think of a test for SVG readiness
459         if( !!window.FileReader && !!window.File ) {
460                 $('#compatibility_check').empty();
461         }
462
463     // hide dialog not yet in use
464     $('#root_tree_dialog').hide();
465         
466     // call out to load the directory div
467     $('#textinfo_container').hide();
468     $('#textinfo_waitbox').hide();
469         refreshDirectory();
470         
471         // Set up the textinfo edit dialog
472         $('#textinfo-edit-dialog').dialog({
473                 autoOpen: false,
474                 height: 200,
475                 width: 300,
476                 modal: true,
477                 buttons: {
478                         Save: function (evt) {
479                                 $("#edit_textinfo_status").empty();
480                                 var mybuttons = $(evt.target).closest('button').parent().find('button');
481                                 mybuttons.button( 'disable' );
482                                 var requrl = _get_url([ "textinfo", selectedTextID ]);
483                                 var reqparam = $('#edit_textinfo').serialize();
484                                 $.post( requrl, reqparam, function (data) {
485                                         // Reload the selected text fields
486                                         selectedTextInfo = data;
487                                         load_textinfo();
488                                         // Reenable the button and close the form
489                                         mybuttons.button("enable");
490                                         $('#textinfo-edit-dialog').dialog('close');
491                                 }, 'json' );
492                         },
493                         Cancel: function() {
494                                 $('#textinfo-edit-dialog').dialog('close');
495                         }
496                 },
497                 open: function() {
498                         $("#edit_textinfo_status").empty();
499                         // Populate the form fields with the current values
500                         // edit_(name, language, public, owner)
501                         $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
502                                 var fname = '#edit_' + k;
503                                 // Special case: language Default is basically language null
504                                 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
505                                         $(fname).val( "" );
506                                 } else {
507                                         $(fname).val( selectedTextInfo[k] );
508                                 }
509                         });
510                         if( selectedTextInfo['public'] == true ) {
511                                 $('#edit_public').attr('checked','true');
512                         } else {
513                                 $('#edit_public').removeAttr('checked');
514                         }
515                 },
516         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
517                 $(event.target).parent().find('.ui-button').button("enable");
518         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 
519                 && ajaxSettings.type == 'POST' ) {
520                         display_error( jqXHR, $("#edit_textinfo_status") );
521         }
522         });
523
524         
525         // Set up the stemma editor dialog
526         $('#stemma-edit-dialog').dialog({
527                 autoOpen: false,
528                 height: 700,
529                 width: 600,
530                 modal: true,
531                 buttons: {
532                         Save: function (evt) {
533                                 $("#edit_stemma_status").empty();
534                                 var mybuttons = $(evt.target).closest('button').parent().find('button');
535                                 mybuttons.button( 'disable' );
536                                 var stemmaseq = $('#stemmaseq').val();
537                                 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
538                                 var reqparam = { 'dot': $('#dot_field').val() };
539                                 // TODO We need to stash the literal SVG string in stemmata
540                                 // somehow. Implement accept header on server side to decide
541                                 // whether to send application/json or application/xml?
542                                 $.post( requrl, reqparam, function (data) {
543                                         // We received a stemma SVG string in return. 
544                                         // Update the current stemma sequence number
545                                         selectedStemmaID = data.stemmaid;
546                                         delete data.stemmaid;
547                                         // Stash the answer in the appropriate spot in our stemma array
548                                         stemmata[selectedStemmaID] = data;
549                                         // Display the new stemma
550                                         load_stemma( selectedStemmaID, true );
551                                         // Reenable the button and close the form
552                                         mybuttons.button("enable");
553                                         $('#stemma-edit-dialog').dialog('close');
554                                 }, 'json' );
555                         },
556                         Cancel: function() {
557                                 $('#stemma-edit-dialog').dialog('close');
558                         }
559                 },
560                 open: function(evt) {
561                         $("#edit_stemma_status").empty();
562                         var stemmaseq = $('#stemmaseq').val();
563                         if( stemmaseq == 'n' ) {
564                                 // If we are creating a new stemma, populate the textarea with a
565                                 // bare digraph.
566                                 $(evt.target).dialog('option', 'title', 'Add a new stemma')
567                                 $('#dot_field').val( "digraph \"NAME STEMMA HERE\" {\n\n}" );
568                         } else {
569                                 // If we are editing a stemma, grab its stemmadot and populate the
570                                 // textarea with that.
571                                 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
572                                 $('#dot_field').val( 'Loading, please wait...' );
573                                 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
574                                 $.getJSON( doturl, function (data) {
575                                         // Re-insert the line breaks
576                                         var dotstring = data.dot.replace(/\|n/gm, "\n");                                        
577                                         $('#dot_field').val( dotstring );
578                                 });
579                         }
580                 },
581         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
582                 $(event.target).parent().find('.ui-button').button("enable");
583         if( ajaxSettings.url.indexOf( 'stemma' ) > -1 
584                 && ajaxSettings.type == 'POST' ) {
585                         display_error( jqXHR, $("#edit_stemma_status") );
586         }
587         });
588
589         $('#stemweb-ui-dialog').dialog({
590                 autoOpen: false,
591                 height: 'auto',
592                 width: 520,
593                 modal: true,
594                 buttons: {
595                         Run: {
596                                 id: 'stemweb_run_button',
597                                 text: 'Run',
598                                 click: function (evt) {
599                                 $("#stemweb_run_status").empty();
600                                 var mybuttons = $(evt.target).closest('button').parent().find('button');
601                                 mybuttons.button( 'disable' );
602                                 var requrl = _get_url([ "stemweb", "request" ]);
603                                 var reqparam = $('#call_stemweb').serialize();
604                                 // TODO We need to stash the literal SVG string in stemmata
605                                 // somehow. Implement accept header on server side to decide
606                                 // whether to send application/json or application/xml?
607                                 $.getJSON( requrl, reqparam, function (data) {
608                                         mybuttons.button("enable");
609                                         if( 'jobid' in data ) {
610                                                 // There is a pending job.
611                                                 selectedTextInfo.stemweb_jobid = data.jobid;
612                                                 $('#stemweb_run_status').empty().append( 
613                                                         _make_message( 'notification', "Your request has been submitted to Stemweb.\nThe resulting tree will appear in due course." ) );
614                                                 // Reload the current stemma to rejigger the buttons
615                                                 switch_stemweb_ui();
616                                         } else {
617                                                 // We appear to have an answer; process it.
618                                                 process_stemweb_result( data );
619                                         }
620                                 }, 'json' );
621                                 },
622                         },
623                         Close: {
624                                 id: 'stemweb_close_button',
625                                 text: 'Close',
626                                 click: function() {
627                                         $('#stemweb-ui-dialog').dialog('close');
628                                         switch_stemweb_ui();
629                                 },
630                         },
631                 },
632                 create: function(evt) {
633                         // Call out to Stemweb to get the algorithm options, with which we
634                         // populate the form.
635                         var algorithmTypes = {};
636                         var algorithmArgs = {};
637                         var requrl = _get_url([ "stemweb", "available" ]);
638                         $.getJSON( requrl, function( data ) {
639                                 $.each( data, function( i, o ) {
640                                         if( o.model === 'algorithms.algorithm' ) {
641                                                 // it's an algorithm.
642                                                 algorithmTypes[ o.pk ] = o.fields;
643                                         } else if( o.model == 'algorithms.algorithmarg' && o.fields.external ) {
644                                                 // it's an option for an algorithm that we should display.
645                                                 algorithmArgs[ o.pk ] = o.fields;
646                                         }
647                                 });
648                                 // TODO if it is an empty object, disable Stemweb entirely.
649                                 if( !jQuery.isEmptyObject( algorithmTypes ) ) {
650                                         $.each( algorithmTypes, function( pk, fields ) {
651                                                 var algopt = $('<option>').attr( 'value', pk ).append( fields.name );
652                                                 $('#stemweb_algorithm').append( algopt );
653                                         });
654                                         // Set up the relevant options for whichever algorithm is chosen.
655                                         // "key" -> form name, option ID "stemweb_$key_opt"
656                                         // "name" -> form label
657                                         $('#stemweb_algorithm_help').click( function() {
658                                                 $('#stemweb_algorithm_desc_text').toggle( 'blind' );
659                                                 });
660                                         $('#stemweb_algorithm').change( function() {
661                                                 var pk = $(this).val();
662                                                 // Display a link to the popup description, and fill in
663                                                 // the description itself, if we have one.
664                                                 if( 'desc' in algorithmTypes[pk] ) {
665                                                         $('#stemweb_algorithm_desc_text').empty().append( algorithmTypes[pk].desc );
666                                                         $('#stemweb_algorithm_desc').show();
667                                                 } else {
668                                                         $('#stemweb_algorithm_desc').hide();
669                                                 }
670                                                 $('#stemweb_runtime_options').empty();
671                                                 $.each( algorithmTypes[pk].args, function( i, apk ) {
672                                                         var argInfo = algorithmArgs[apk];
673                                                         if( argInfo ) {
674                                                                 // Make the element ID
675                                                                 var optId = 'stemweb_' + argInfo.key + '_opt';
676                                                                 // Make the label
677                                                                 var optLabel = $('<label>').attr( 'for', optId )
678                                                                         .append( argInfo.name + ": " );
679                                                                 var optCtrl;
680                                                                 var argType = argInfo.value;
681                                                                 if( argType === 'positive_integer' ) {
682                                                                         // Make it an input field of smallish size.
683                                                                         optCtrl = $('<input>').attr( 'size', 4 );
684                                                                 } else if ( argType === 'boolean' ) {
685                                                                         // Make it a checkbox.
686                                                                         optCtrl = $('<checkbox>');
687                                                                 }
688                                                                 // Add the name and element ID
689                                                                 optCtrl.attr( 'name', argInfo.key ).attr( 'id', optId );
690                                                                 // Append the label and the option itself to the form.
691                                                                 $('#stemweb_runtime_options').append( optLabel )
692                                                                         .append( optCtrl ).append( $('<br>') );
693                                                         }
694                                                 });
695                                         });
696                                         $('#stemweb_algorithm').change();
697                                 }
698                         });
699                         // Prime the initial options
700                 },
701                 open: function(evt) {
702                         $('#stemweb_run_status').empty();
703                         $('#stemweb_tradition').attr('value', selectedTextID );
704                         if( selectedTextInfo.stemweb_jobid == 0 ) {
705                                 $('#stemweb_merge_reltypes').empty();
706                                 $.each( selectedTextInfo.reltypes, function( i, r ) {
707                                         var relation_opt = $('<option>').attr( 'value', r ).append( r );
708                                         $('#stemweb_merge_reltypes').append( relation_opt );
709                                 });
710                                 $('#stemweb_merge_reltypes').multiselect({ 
711                                         header: false,
712                                         selectedList: 3
713                                 });
714                         }
715                 },
716         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
717                 $(event.target).parent().find('.ui-button').button("enable");
718         if( ajaxSettings.url.indexOf( 'stemweb/' ) > -1 ) {
719                         display_error( jqXHR, $("#stemweb_run_status") );
720         }
721         });
722                 
723         // Set up the download dialog
724         $('#download-dialog').dialog({
725                 autoOpen: false,
726                 height: 150,
727                 width: 300,
728                 modal: true,
729                 buttons: {
730                         Download: function (evt) {
731                                 var dlurl = _get_url([ "download", $('#download_tradition').val(), $('#download_format').val() ]);
732                                 window.location = dlurl;
733                         },
734                         Done: function() {
735                                 $('#download-dialog').dialog('close');
736                         }
737                 },
738                 open: function() {
739                         $('#download_tradition').attr('value', selectedTextID );
740                 },
741         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
742                 $(event.target).parent().find('.ui-button').button("enable");
743         if( ajaxSettings.url.indexOf( 'download' ) > -1 
744                 && ajaxSettings.type == 'POST' ) {
745                         display_error( jqXHR, $("#download_status") );
746         }
747         });
748
749         $('#upload-collation-dialog').dialog({
750                 autoOpen: false,
751                 height: 360,
752                 width: 480,
753                 modal: true,
754                 buttons: {
755                   upload: {
756                     text: 'Upload',
757                     id: 'upload_button',
758                     click: function() {
759                             $('#upload_status').empty();
760                             $('#upload_button').button("disable");
761                 upload_new();
762             }
763                   },
764                   pick_file: {
765                     text: 'Pick File',
766                     id: 'pick_file_button',
767                     click: function() {
768                 $('#new_file').click();
769             }
770                   },
771                   Cancel: function() {
772                     $('#upload-collation-dialog').dialog('close');
773                   }
774                 },
775                 open: function() {
776                         // Set the upload button to its correct state based on
777                         // whether a file is loaded
778                         file_selected( $('#new_file').get(0) );
779                         $('#upload_status').empty();
780                 }
781         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
782                 // Reset button state
783                 file_selected( $('#new_file').get(0) );
784                 // Display error message if applicable
785         if( ajaxSettings.url.indexOf( 'newtradition' ) > -1 
786                 && ajaxSettings.type == 'POST' ) {
787                         display_error( jqXHR, $("#upload_status") );
788         }
789         });;
790         
791         $('#stemma_graph').mousedown( function(evt) {
792         evt.stopPropagation();
793         $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
794         $('body').mousemove( function(evt) {
795             mouse_scale = 1; // for now, was:  mouse_scale = svg_root_element.getScreenCTM().a;
796             dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
797             dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
798             $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
799             var svg_root = $('#stemma_graph svg').svg().svg('get').root();
800             var g = $('g.graph', svg_root).get(0);
801             current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
802             new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
803             g.setAttribute( 'transform', new_transform );
804             evt.returnValue = false;
805             evt.preventDefault();
806             return false;
807         });
808         $('body').mouseup( function(evt) {
809             $('body').unbind('mousemove');
810             $('body').unbind('mouseup');
811         });
812         });
813          
814         $('#stemma_graph').mousewheel(function (event, delta) {
815         event.returnValue = false;
816         event.preventDefault();
817         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
818         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
819         if( delta < -9 ) { delta = -9 }; 
820         var z = 1 + delta/10;
821         z = delta > 0 ? 1 : -1;
822         var svg_root = $('#stemma_graph svg').svg().svg('get').root();
823         var g = $('g.graph', svg_root).get(0);
824         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
825             var scaleLevel = z/10;
826             current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
827             new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
828             g.setAttribute( 'transform', new_transform );
829         }
830     });
831     
832 });