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