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