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