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