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