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