gracefully handle lack of morphological info / capability in rel mapper
[scpubgit/stemmaweb.git] / root / js / relationship-full.js
1 var MARGIN=30;
2 var svg_root = null;
3 var svg_root_element = null;
4 var start_element_height = 0;
5 var reltypes = {};
6 var readingdata = {};
7
8 function getTextURL( which ) {
9         return basepath + textid + '/' + which;
10 }
11
12 function getReadingURL( reading_id ) {
13         return basepath + textid + '/reading/' + reading_id;
14 }
15
16 // Make an XML ID into a valid selector
17 function jq(myid) { 
18         return '#' + myid.replace(/(:|\.)/g,'\\$1');
19 }
20
21 // Actions for opening the reading panel
22 function node_dblclick_listener( evt ) {
23         // Open the reading dialogue for the given node.
24         // First get the reading info
25         var reading_id = $(this).attr('id');
26         var reading_info = readingdata[reading_id];
27         // and then populate the dialog box with it.
28         // Set the easy properties first
29         $('#reading-form').dialog( 'option', 'title', 'Reading information for "' + reading_info['text'] + '"' );
30         $('#reading_id').val( reading_id );
31         toggle_checkbox( $('#reading_is_nonsense'), reading_info['is_nonsense'] );
32         toggle_checkbox( $('#reading_grammar_invalid'), reading_info['grammar_invalid'] );
33         // Use .text as a backup for .normal_form
34         var normal_form = reading_info['normal_form'];
35         if( !normal_form ) {
36                 normal_form = reading_info['text'];
37         }
38         var nfboxsize = 10;
39         if( normal_form.length > 9 ) {
40                 nfboxsize = normal_form.length + 1;
41         }
42         $('#reading_normal_form').attr( 'size', nfboxsize )
43         $('#reading_normal_form').val( normal_form );
44         // Now do the morphological properties.
45         morphology_form( reading_info['lexemes'] );
46         // and then open the dialog.
47         $('#reading-form').dialog("open");
48 }
49
50 function toggle_checkbox( box, value ) {
51         if( value == null ) {
52                 value = false;
53         }
54         box.attr('checked', value );
55 }
56
57 function morphology_form ( lexlist ) {
58         if( lexlist.length ) {
59                 $('#morph_outer').show();
60                 $('#morphology').empty();
61                 $.each( lexlist, function( idx, lex ) {
62                         var morphoptions = [];
63                         if( 'wordform_matchlist' in lex ) {
64                                 $.each( lex['wordform_matchlist'], function( tdx, tag ) {
65                                         var tagstr = stringify_wordform( tag );
66                                         morphoptions.push( tagstr );
67                                 });
68                         }
69                         var formtag = 'morphology_' + idx;
70                         var formstr = '';
71                         if( 'form' in lex ) {
72                                 formstr = stringify_wordform( lex['form'] );
73                         } 
74                         var form_morph_elements = morph_elements( 
75                                 formtag, lex['string'], formstr, morphoptions );
76                         $.each( form_morph_elements, function( idx, el ) {
77                                 $('#morphology').append( el );
78                         });
79                 });
80         } else {
81                 $('#morph_outer').hide();
82         }
83 }
84
85 function stringify_wordform ( tag ) {
86         if( tag ) {
87                 var elements = tag.split(' // ');
88                 return elements[1] + ' // ' + elements[2];
89         }
90         return ''
91 }
92
93 function morph_elements ( formtag, formtxt, currform, morphoptions ) {
94         var clicktag = '(Click to select)';
95         if ( !currform ) {
96                 currform = clicktag;
97         }
98         var formlabel = $('<label/>').attr( 'id', 'label_' + formtag ).attr( 
99                 'for', 'reading_' + formtag ).text( formtxt + ': ' );
100         var forminput = $('<input/>').attr( 'id', 'reading_' + formtag ).attr( 
101                 'name', 'reading_' + formtag ).attr( 'size', '50' ).attr(
102                 'class', 'reading_morphology' ).val( currform );
103         forminput.autocomplete({ source: morphoptions, minLength: 0     });
104         forminput.focus( function() { 
105                 if( $(this).val() == clicktag ) {
106                         $(this).val('');
107                 }
108                 $(this).autocomplete('search', '') 
109         });
110         var morphel = [ formlabel, forminput, $('<br/>') ];
111         return morphel;
112 }
113
114 function color_inactive ( el ) {
115         var reading_id = $(el).parent().attr('id');
116         var reading_info = readingdata[reading_id];
117         // If the reading info has any non-disambiguated lexemes, color it yellow;
118         // otherwise color it green.
119         $(el).attr( {stroke:'green', fill:'#b3f36d'} );
120         if( reading_info ) {
121                 $.each( reading_info['lexemes'], function ( idx, lex ) {
122                         if( !lex['is_disambiguated'] || lex['is_disambiguated'] == 0 ) {
123                                 $(el).attr( {stroke:'orange', fill:'#fee233'} );
124                         }
125                 });
126         }
127 }
128
129 function relemmatize () {
130         // Send the reading for a new lemmatization and reopen the form.
131         $('#relemmatize_pending').show();
132         var reading_id = $('#reading_id').val()
133         ncpath = getReadingURL( reading_id );
134         form_values = { 
135                 'normal_form': $('#reading_normal_form').val(), 
136                 'relemmatize': 1 };
137         var jqjson = $.post( ncpath, form_values, function( data ) {
138                 // Update the form with the return
139                 if( 'id' in data ) {
140                         // We got back a good answer. Stash it
141                         readingdata[reading_id] = data;
142                         // and regenerate the morphology form.
143                         morphology_form( data['lexemes'] );
144                 } else {
145                         alert("Could not relemmatize as requested: " + data['error']);
146                 }
147                 $('#relemmatize_pending').hide();
148         });
149 }
150
151 // Initialize the SVG once it exists
152 function svgEnlargementLoaded() {
153         //Give some visual evidence that we are working
154         $('#loading_overlay').show();
155         lo_height = $("#enlargement_container").outerHeight();
156         lo_width = $("#enlargement_container").outerWidth();
157         $("#loading_overlay").height( lo_height );
158         $("#loading_overlay").width( lo_width );
159         $("#loading_overlay").offset( $("#enlargement_container").offset() );
160         $("#loading_message").offset(
161                 { 'top': lo_height / 2 - $("#loading_message").height() / 2,
162                   'left': lo_width / 2 - $("#loading_message").width() / 2 });
163     //Set viewbox widht and height to widht and height of $('#svgenlargement svg').
164     $('#update_workspace_button').data('locked', false);
165     $('#update_workspace_button').css('background-position', '0px 44px');
166     //This is essential to make sure zooming and panning works properly.
167         var rdgpath = getTextURL( 'readings' );
168                 $.getJSON( rdgpath, function( data ) {
169                 readingdata = data;
170             $('#svgenlargement ellipse').each( function( i, el ) { color_inactive( el ) });
171         });
172     $('#svgenlargement ellipse').parent().dblclick( node_dblclick_listener );
173     var graph_svg = $('#svgenlargement svg');
174     var svg_g = $('#svgenlargement svg g')[0];
175     if (!svg_g) return;
176     svg_root = graph_svg.svg().svg('get').root();
177
178     // Find the real root and ignore any text nodes
179     for (i = 0; i < svg_root.childNodes.length; ++i) {
180         if (svg_root.childNodes[i].nodeName != '#text') {
181                 svg_root_element = svg_root.childNodes[i];
182                 break;
183            }
184     }
185
186     svg_root.viewBox.baseVal.width = graph_svg.attr( 'width' );
187     svg_root.viewBox.baseVal.height = graph_svg.attr( 'height' );
188     //Now set scale and translate so svg height is about 150px and vertically centered in viewbox.
189     //This is just to create a nice starting enlargement.
190     var initial_svg_height = 250;
191     var scale = initial_svg_height/graph_svg.attr( 'height' );
192     var additional_translate = (graph_svg.attr( 'height' ) - initial_svg_height)/(2*scale);
193     var transform = svg_g.getAttribute('transform');
194     var translate = parseFloat( transform.match( /translate\([^\)]*\)/ )[0].split('(')[1].split(' ')[1].split(')')[0] );
195     translate += additional_translate;
196     var transform = 'rotate(0) scale(' + scale + ') translate(4 ' + translate + ')';
197     svg_g.setAttribute('transform', transform);
198     //used to calculate min and max zoom level:
199     start_element_height = $('#__START__').children('ellipse')[0].getBBox().height;
200     add_relations( function() { $('#loading_overlay').hide(); });
201 }
202
203 function add_relations( callback_fn ) {
204         var textrelpath = getTextURL( 'relationships' );
205     $.getJSON( basepath + 'definitions', function(data) {
206         var rel_types = data.types.sort();
207         $.getJSON( textrelpath,
208         function(data) {
209             $.each(data, function( index, rel_info ) {
210                 var type_index = $.inArray(rel_info.type, rel_types);
211                 var source_found = get_ellipse( rel_info.source );
212                 var target_found = get_ellipse( rel_info.target );
213                 if( type_index != -1 && source_found.size() && target_found.size() ) {
214                     var relation = relation_manager.create( rel_info.source, rel_info.target, type_index );
215                     relation.data( 'type', rel_info.type );
216                     relation.data( 'scope', rel_info.scope );
217                     relation.data( 'note', rel_info.note );
218                     var node_obj = get_node_obj(rel_info.source);
219                     node_obj.set_draggable( false );
220                     node_obj.ellipse.data( 'node_obj', null );
221                     node_obj = get_node_obj(rel_info.target);
222                     node_obj.set_draggable( false );
223                     node_obj.ellipse.data( 'node_obj', null );
224                 }
225             });
226             callback_fn.call();
227         });
228     });
229 }
230
231 function get_ellipse( node_id ) {
232         return $( jq( node_id ) + ' ellipse');
233 }
234
235 function get_node_obj( node_id ) {
236     var node_ellipse = get_ellipse( node_id );
237     if( node_ellipse.data( 'node_obj' ) == null ) {
238         node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
239     };
240     return node_ellipse.data( 'node_obj' );
241 }
242
243 function node_obj(ellipse) {
244   this.ellipse = ellipse;
245   var self = this;
246   
247   this.x = 0;
248   this.y = 0;
249   this.dx = 0;
250   this.dy = 0;
251   this.node_elements = node_elements_for(self.ellipse);
252
253   this.get_id = function() {
254     return $(self.ellipse).parent().attr('id')
255   }
256   
257   this.set_draggable = function( draggable ) {
258     if( draggable ) {
259       $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
260       $(self.ellipse).parent().mousedown( this.mousedown_listener );
261       $(self.ellipse).parent().hover( this.enter_node, this.leave_node ); 
262       self.ellipse.siblings('text').attr('class', 'noselect draggable');
263     } else {
264       self.ellipse.siblings('text').attr('class', '');
265           $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' ).unbind( 'mousedown' );     
266       color_inactive( self.ellipse );
267     }
268   }
269
270   this.mousedown_listener = function(evt) {
271     evt.stopPropagation();
272     self.x = evt.clientX;
273     self.y = evt.clientY;
274     $('body').mousemove( self.mousemove_listener );
275     $('body').mouseup( self.mouseup_listener );
276     $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
277     self.ellipse.attr( 'fill', '#ff66ff' );
278     first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
279     if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
280   }
281
282   this.mousemove_listener = function(evt) {
283     self.dx = (evt.clientX - self.x) / mouse_scale;
284     self.dy = (evt.clientY - self.y) / mouse_scale;
285     self.move_elements();
286     evt.returnValue = false;
287     evt.preventDefault();
288     return false;
289   }
290
291   this.mouseup_listener = function(evt) {    
292     if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
293         var source_node_id = $(self.ellipse).parent().attr('id');
294         var source_node_text = self.ellipse.siblings('text').text();
295         var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
296         var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
297         $('#source_node_id').val( source_node_id );
298         $('#source_node_text').val( source_node_text );
299         $('#target_node_id').val( target_node_id );
300         $('#target_node_text').val( target_node_text );
301         $('#dialog-form').dialog( 'open' );
302     };
303     $('body').unbind('mousemove');
304     $('body').unbind('mouseup');
305     self.ellipse.attr( 'fill', '#fff' );
306     $(self.ellipse).parent().hover( self.enter_node, self.leave_node );
307     self.reset_elements();
308   }
309   
310   this.cpos = function() {
311     return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
312   }
313
314   this.get_g = function() {
315     return self.ellipse.parent('g');
316   }
317
318   this.enter_node = function(evt) {
319     self.ellipse.attr( 'fill', '#ffccff' );
320   }
321
322   this.leave_node = function(evt) {
323     self.ellipse.attr( 'fill', '#fff' );
324   }
325
326   this.greyout_edges = function() {
327       $.each( self.node_elements, function(index, value) {
328         value.grey_out('.edge');
329       });
330   }
331
332   this.ungreyout_edges = function() {
333       $.each( self.node_elements, function(index, value) {
334         value.un_grey_out('.edge');
335       });
336   }
337
338   this.move_elements = function() {
339     $.each( self.node_elements, function(index, value) {
340       value.move(self.dx,self.dy);
341     });
342   }
343
344   this.reset_elements = function() {
345     $.each( self.node_elements, function(index, value) {
346       value.reset();
347     });
348   }
349
350   this.update_elements = function() {
351       self.node_elements = node_elements_for(self.ellipse);
352   }
353
354   self.set_draggable( true );
355 }
356
357 function svgshape( shape_element ) {
358   this.shape = shape_element;
359   this.move = function(dx,dy) {
360     this.shape.attr( "transform", "translate(" + dx + " " + dy + ")" );
361   }
362   this.reset = function() {
363     this.shape.attr( "transform", "translate( 0, 0 )" );
364   }
365   this.grey_out = function(filter) {
366       if( this.shape.parent(filter).size() != 0 ) {
367           this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
368       }
369   }
370   this.un_grey_out = function(filter) {
371       if( this.shape.parent(filter).size() != 0 ) {
372         this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
373       }
374   }
375 }
376
377 function svgpath( path_element, svg_element ) {
378   this.svg_element = svg_element;
379   this.path = path_element;
380   this.x = this.path.x;
381   this.y = this.path.y;
382   this.move = function(dx,dy) {
383     this.path.x = this.x + dx;
384     this.path.y = this.y + dy;
385   }
386   this.reset = function() {
387     this.path.x = this.x;
388     this.path.y = this.y;
389   }
390   this.grey_out = function(filter) {
391       if( this.svg_element.parent(filter).size() != 0 ) {
392           this.svg_element.attr('stroke', '#e5e5e5');
393           this.svg_element.siblings('text').attr('fill', '#e5e5e5');
394           this.svg_element.siblings('text').attr('class', 'noselect');
395       }
396   }
397   this.un_grey_out = function(filter) {
398       if( this.svg_element.parent(filter).size() != 0 ) {
399           this.svg_element.attr('stroke', '#000000');
400           this.svg_element.siblings('text').attr('fill', '#000000');
401           this.svg_element.siblings('text').attr('class', '');
402       }
403   }
404 }
405
406 function node_elements_for( ellipse ) {
407   node_elements = get_edge_elements_for( ellipse );
408   node_elements.push( new svgshape( ellipse.siblings('text') ) );
409   node_elements.push( new svgshape( ellipse ) );
410   return node_elements;
411 }
412
413 function get_edge_elements_for( ellipse ) {
414   edge_elements = new Array();
415   node_id = ellipse.parent().attr('id');
416   edge_in_pattern = new RegExp( node_id + '$' );
417   edge_out_pattern = new RegExp( '^' + node_id );
418   $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
419     title = $(this).text();
420     if( edge_in_pattern.test(title) ) {
421         polygon = $(this).siblings('polygon');
422         if( polygon.size() > 0 ) {
423             edge_elements.push( new svgshape( polygon ) );
424         }
425         path_segments = $(this).siblings('path')[0].pathSegList;
426         edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
427     }
428     if( edge_out_pattern.test(title) ) {
429       path_segments = $(this).siblings('path')[0].pathSegList;
430       edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
431     }
432   });
433   return edge_elements;
434
435
436 function relation_factory() {
437     var self = this;
438     this.color_memo = null;
439     //TODO: colors hard coded for now
440     this.temp_color = '#FFA14F';
441     this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
442
443     this.create_temporary = function( source_node_id, target_node_id ) {
444         var relation_id = get_relation_id( source_node_id, target_node_id );
445         var relation = $( jq( relation_id ) );
446         if( relation.size() == 0 ) { 
447             draw_relation( source_node_id, target_node_id, self.temp_color );
448         } else {
449             self.color_memo = relation.children('path').attr( 'stroke' );
450             relation.children('path').attr( 'stroke', self.temp_color );
451         }
452     }
453     this.remove_temporary = function() {
454         var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
455         if( self.color_memo != null ) {
456             path_element.attr( 'stroke', self.color_memo );
457             self.color_memo = null;
458         } else {
459             var temporary = path_element.parent('g').remove();
460             temporary.empty();
461             temporary = null; 
462         }
463     }
464     this.create = function( source_node_id, target_node_id, color_index ) {
465         //TODO: Protect from (color_)index out of bound..
466         var relation_color = self.relation_colors[ color_index ];
467         var relation = draw_relation( source_node_id, target_node_id, relation_color );
468         get_node_obj( source_node_id ).update_elements();
469         get_node_obj( target_node_id ).update_elements();
470         return relation;
471     }
472     this.toggle_active = function( relation_id ) {
473         var relation = $( jq( relation_id ) );
474         var relation_path = relation.children('path');
475         if( !relation.data( 'active' ) ) {
476             relation_path.css( {'cursor':'pointer'} );
477             relation_path.mouseenter( function(event) { 
478                 outerTimer = setTimeout( function() { 
479                     timer = setTimeout( function() { 
480                         var related_nodes = get_related_nodes( relation_id );
481                         var source_node_id = related_nodes[0];
482                         var target_node_id = related_nodes[1];
483                         $('#delete_source_node_id').val( source_node_id );
484                         $('#delete_target_node_id').val( target_node_id );
485                         self.showinfo(relation); 
486                     }, 500 ) 
487                 }, 1000 );
488             });
489             relation_path.mouseleave( function(event) {
490                 clearTimeout(outerTimer); 
491                 if( timer != null ) { clearTimeout(timer); } 
492             });
493             relation.data( 'active', true );
494         } else {
495             relation_path.unbind( 'mouseenter' );
496             relation_path.unbind( 'mouseleave' );
497             relation_path.css( {'cursor':'inherit'} );
498             relation.data( 'active', false );
499         }
500     }
501     this.showinfo = function(relation) {
502         var htmlstr = 'type: ' + relation.data( 'type' ) + '<br/>scope: ' + relation.data( 'scope' );
503         if( relation.data( 'note' ) ) {
504                 htmlstr = htmlstr + '<br/>note: ' + relation.data( 'note' );
505         }
506         $('#delete-form-text').html( htmlstr );
507         var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
508         var xs = parseFloat( points[0].split(',')[0] );
509         var xe = parseFloat( points[1].split(',')[0] );
510         var ys = parseFloat( points[0].split(',')[1] );
511         var ye = parseFloat( points[3].split(',')[1] );
512         var p = svg_root.createSVGPoint();
513         p.x = xs + ((xe-xs)*1.1);
514         p.y = ye - ((ye-ys)/2);
515         var ctm = svg_root_element.getScreenCTM();
516         var nx = p.matrixTransform(ctm).x;
517         var ny = p.matrixTransform(ctm).y;
518         var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
519         $('#delete-form').dialog( 'open' );
520         dialog_aria.offset({ left: nx, top: ny });
521     }
522     this.remove = function( relation_id ) {
523         var relation = $( jq( relation_id ) );
524         relation.remove();
525     }
526 }
527
528 // Utility function to create/return the ID of a relation link between
529 // a source and target.
530 function get_relation_id( source_id, target_id ) {
531         var idlist = [ source_id, target_id ];
532         idlist.sort();
533         return 'relation-' + idlist[0] + '-...-' + idlist[1];
534 }
535
536 function get_related_nodes( relation_id ) {
537         var srctotarg = relation_id.substr( 9 );
538         return srctotarg.split('-...-');
539 }
540
541 function draw_relation( source_id, target_id, relation_color ) {
542     var source_ellipse = get_ellipse( source_id );
543     var target_ellipse = get_ellipse( target_id );
544     var relation_id = get_relation_id( source_id, target_id );
545     var svg = $('#svgenlargement').children('svg').svg().svg('get');
546     var path = svg.createPath(); 
547     var sx = parseInt( source_ellipse.attr('cx') );
548     var rx = parseInt( source_ellipse.attr('rx') );
549     var sy = parseInt( source_ellipse.attr('cy') );
550     var ex = parseInt( target_ellipse.attr('cx') );
551     var ey = parseInt( target_ellipse.attr('cy') );
552     var relation = svg.group( $("#svgenlargement svg g"), 
553         { 'class':'relation', 'id':relation_id } );
554     svg.title( relation, source_id + '->' + target_id );
555     svg.path( relation, path.move( sx, sy ).curveC( sx + (2*rx), sy, ex + (2*rx), ey, ex, ey ), {fill: 'none', stroke: relation_color, strokeWidth: 4});
556     var relation_element = $('#svgenlargement .relation').filter( ':last' );
557     relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
558     return relation_element;
559 }
560
561
562 $(document).ready(function () {
563     
564   timer = null;
565   relation_manager = new relation_factory();
566   $('#update_workspace_button').data('locked', false);
567   
568   $('#enlargement').mousedown(function (event) {
569     $(this)
570         .data('down', true)
571         .data('x', event.clientX)
572         .data('y', event.clientY)
573         .data('scrollLeft', this.scrollLeft)
574         stateTf = svg_root_element.getCTM().inverse();
575         var p = svg_root.createSVGPoint();
576         p.x = event.clientX;
577         p.y = event.clientY;
578         stateOrigin = p.matrixTransform(stateTf);
579         event.returnValue = false;
580         event.preventDefault();
581         return false;
582   }).mouseup(function (event) {
583         $(this).data('down', false);
584   }).mousemove(function (event) {
585     if( timer != null ) { clearTimeout(timer); } 
586     if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
587         var p = svg_root.createSVGPoint();
588         p.x = event.clientX;
589         p.y = event.clientY;
590         p = p.matrixTransform(stateTf);
591         var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
592         var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
593         svg_root_element.setAttribute("transform", s);
594     }
595     event.returnValue = false;
596     event.preventDefault();
597   }).mousewheel(function (event, delta) {
598     event.returnValue = false;
599     event.preventDefault();
600     if ( $('#update_workspace_button').data('locked') == false ) {
601         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
602         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
603         if( delta < -9 ) { delta = -9 }; 
604         var z = 1 + delta/10;
605         z = delta > 0 ? 1 : -1;
606         var g = svg_root_element;
607         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
608             var root = svg_root;
609             var p = root.createSVGPoint();
610             p.x = event.originalEvent.clientX;
611             p.y = event.originalEvent.clientY;
612             p = p.matrixTransform(g.getCTM().inverse());
613             var scaleLevel = 1+(z/20);
614             var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
615             var matrix = g.getCTM().multiply(k);
616             var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
617             g.setAttribute("transform", s);
618         }
619     }
620   }).css({
621     'overflow' : 'hidden',
622     'cursor' : '-moz-grab'
623   });
624   
625
626   $( "#dialog-form" ).dialog({
627     autoOpen: false,
628     height: 270,
629     width: 290,
630     modal: true,
631     buttons: {
632       "Ok": function( evt ) {
633         $(evt.target).button("disable");
634         $('#status').empty();
635         form_values = $('#collapse_node_form').serialize();
636         ncpath = getTextURL( 'relationships' );
637         var jqjson = $.post( ncpath, form_values, function(data) {
638             $.each( data, function(item, source_target) { 
639                 var source_found = get_ellipse( source_target[0] );
640                 var target_found = get_ellipse( source_target[1] );
641                 if( source_found.size() && target_found.size() ) {
642                     var relation = relation_manager.create( source_target[0], source_target[1], $('#rel_type')[0].selectedIndex-1 );
643                                         relation.data( 'type', $('#rel_type :selected').text()  );
644                                         relation.data( 'scope', $('#scope :selected').text()  );
645                                         relation.data( 'note', $('#note').val()  );
646                                         relation_manager.toggle_active( relation.attr('id') );
647                                 }
648                                 $(evt.target).button("enable");
649            });
650             $( "#dialog-form" ).dialog( "close" );
651         }, 'json' );
652       },
653       Cancel: function() {
654           $( this ).dialog( "close" );
655       }
656     },
657     create: function(event, ui) { 
658         $(this).data( 'relation_drawn', false );
659         //TODO? Err handling?
660         var jqjson = $.getJSON( basepath + 'definitions', function(data) {
661             var types = data.types.sort();
662             $.each( types, function(index, value) {   
663                  $('#rel_type').append( $('<option />').attr( "value", value ).text(value) ); 
664                  $('#keymaplist').append( $('<li>').css( "border-color", relation_manager.relation_colors[index] ).text(value) ); 
665             });
666             var scopes = data.scopes;
667             $.each( scopes, function(index, value) {   
668                  $('#scope').append( $('<option />').attr( "value", value ).text(value) ); 
669             });
670         });        
671     },
672     open: function() {
673         relation_manager.create_temporary( $('#source_node_id').val(), $('#target_node_id').val() );
674         $(".ui-widget-overlay").css("background", "none");
675         $("#dialog_overlay").show();
676         $("#dialog_overlay").height( $("#enlargement_container").height() );
677         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
678         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
679     },
680     close: function() {
681         relation_manager.remove_temporary();
682         $( '#status' ).empty();
683         $("#dialog_overlay").hide();
684     }
685   }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
686       if( ajaxSettings.url == getTextURL('relationships') 
687         && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
688           var errobj = jQuery.parseJSON( jqXHR.responseText );
689           $('#status').append( '<p class="error">Error: ' + errobj.error + '</br>The relationship cannot be made.</p>' );
690       }
691           $(event.target).parent().find('.ui-button').button("enable");
692   } );
693
694   $( "#delete-form" ).dialog({
695     autoOpen: false,
696     height: 135,
697     width: 160,
698     modal: false,
699     buttons: {
700         Cancel: function() {
701             $( this ).dialog( "close" );
702         },
703         Delete: function() {
704           form_values = $('#delete_relation_form').serialize();
705           ncpath = getTextURL( 'relationships' );
706           var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
707               $.each( data, function(item, source_target) { 
708                   relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
709               });
710               $( "#delete-form" ).dialog( "close" );
711           }, dataType: 'json', type: 'DELETE' });
712         }
713     },
714     create: function(event, ui) {
715         var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
716         buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
717         var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");  
718         dialog_aria.mouseenter( function() {
719             if( mouseWait != null ) { clearTimeout(mouseWait) };
720         })
721         dialog_aria.mouseleave( function() {
722             mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
723         })
724     },
725     open: function() {
726         mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
727     },
728     close: function() {
729     }
730   });
731
732   // function for reading form dialog should go here; 
733   // just hide the element for now if we don't have morphology
734   if( can_morphologize ) {
735           $('#reading-form').dialog({
736                 autoOpen: false,
737                 // height: 400,
738                 width: 450,
739                 modal: true,
740                 buttons: {
741                         Cancel: function() {
742                                 $( this ).dialog( "close" );
743                         },
744                         Update: function( evt ) {
745                                 // Disable the button
746                                 $(evt.target).button("disable");
747                                 $('#reading_status').empty();
748                                 var reading_id = $('#reading_id').val()
749                                 form_values = {
750                                         'id' : reading_id,
751                                         'is_nonsense': $('#reading_is_nonsense').is(':checked'),
752                                         'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
753                                         'normal_form': $('#reading_normal_form').val() };
754                                 // Add the morphology values
755                                 $('.reading_morphology').each( function() {
756                                         if( $(this).val() != '(Click to select)' ) {
757                                                 var rmid = $(this).attr('id');
758                                                 rmid = rmid.substring(8);
759                                                 form_values[rmid] = $(this).val();
760                                         }
761                                 });
762                                 // Make the JSON call
763                                 ncpath = getReadingURL( reading_id );
764                                 var reading_element = readingdata[reading_id];
765                                 // $(':button :contains("Update")').attr("disabled", true);
766                                 var jqjson = $.post( ncpath, form_values, function(data) {
767                                         $.each( data, function(key, value) { 
768                                                 reading_element[key] = value;
769                                         });
770                                         if( $('#update_workspace_button').data('locked') == false ) {
771                                                 color_inactive( get_ellipse( reading_id ) );
772                                         }
773                                         $(evt.target).button("enable");
774                                         $( "#reading-form" ).dialog( "close" );
775                                 });
776                                 // Re-color the node if necessary
777                                 return false;
778                         }
779                 },
780                 create: function() {
781                 },
782                 open: function() {
783                         $(".ui-widget-overlay").css("background", "none");
784                         $("#dialog_overlay").show();
785                         $('#reading_status').empty();
786                         $("#dialog_overlay").height( $("#enlargement_container").height() );
787                         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
788                         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
789                         $("#reading-form").parent().find('.ui-button').button("enable");
790                 },
791                 close: function() {
792                         $("#dialog_overlay").hide();
793                 }
794           }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
795                   if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
796                         && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
797                           var errobj = jQuery.parseJSON( jqXHR.responseText );
798                           $('#reading_status').append( '<p class="error">Error: ' + errobj.error + '</p>' );
799                   }
800                   $(event.target).parent().find('.ui-button').button("enable");
801           });
802         } else {
803                 $('#reading-form').hide();
804         }
805   
806
807   $('#update_workspace_button').click( function() {
808      var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
809      mouse_scale = svg_root_element.getScreenCTM().a;
810      if( $(this).data('locked') == true ) {
811          $('#svgenlargement ellipse' ).each( function( index ) {
812              if( $(this).data( 'node_obj' ) != null ) {
813                  $(this).data( 'node_obj' ).ungreyout_edges();
814                  $(this).data( 'node_obj' ).set_draggable( false );
815                  var node_id = $(this).data( 'node_obj' ).get_id();
816                  toggle_relation_active( node_id );
817                  $(this).data( 'node_obj', null );
818              }
819          })
820          $(this).data('locked', false);
821          $(this).css('background-position', '0px 44px');
822      } else {
823          var left = $('#enlargement').offset().left;
824          var right = left + $('#enlargement').width();
825          var tf = svg_root_element.getScreenCTM().inverse(); 
826          var p = svg_root.createSVGPoint();
827          p.x=left;
828          p.y=100;
829          var cx_min = p.matrixTransform(tf).x;
830          p.x=right;
831          var cx_max = p.matrixTransform(tf).x;
832          $('#svgenlargement ellipse').each( function( index ) {
833              var cx = parseInt( $(this).attr('cx') );
834              if( cx > cx_min && cx < cx_max) { 
835                  if( $(this).data( 'node_obj' ) == null ) {
836                      $(this).data( 'node_obj', new node_obj( $(this) ) );
837                  } else {
838                      $(this).data( 'node_obj' ).set_draggable( true );
839                  }
840                  $(this).data( 'node_obj' ).greyout_edges();
841                  var node_id = $(this).data( 'node_obj' ).get_id();
842                  toggle_relation_active( node_id );
843              }
844          });
845          $(this).css('background-position', '0px 0px');
846          $(this).data('locked', true );
847      }
848   });
849   
850   $('.helptag').popupWindow({ 
851           height:500, 
852           width:800, 
853           top:50, 
854           left:50,
855           scrollbars:1 
856   }); 
857
858   
859   function toggle_relation_active( node_id ) {
860       $('#svgenlargement .relation').find( "title:contains('" + node_id +  "')" ).each( function(index) {
861           matchid = new RegExp( "^" + node_id );
862           if( $(this).text().match( matchid ) != null ) {
863                   var relation_id = $(this).parent().attr('id');
864               relation_manager.toggle_active( relation_id );
865           };
866       });
867   }
868
869   expandFillPageClients();
870   $(window).resize(function() {
871     expandFillPageClients();
872   });
873
874 });
875
876
877 function expandFillPageClients() {
878         $('.fillPage').each(function () {
879                 $(this).height($(window).height() - $(this).offset().top - MARGIN);
880         });
881 }
882
883 function loadSVG(svgData) {
884         var svgElement = $('#svgenlargement');
885
886         $(svgElement).svg('destroy');
887
888         $(svgElement).svg({
889                 loadURL: svgData,
890                 onLoad : svgEnlargementLoaded
891         });
892 }
893
894
895 /*      OS Gadget stuff
896
897 function svg_select_callback(topic, data, subscriberData) {
898         svgData = data;
899         loadSVG(svgData);
900 }
901
902 function loaded() {
903         var prefs = new gadgets.Prefs();
904         var preferredHeight = parseInt(prefs.getString('height'));
905         if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
906         expandFillPageClients();
907 }
908
909 if (gadgets.util.hasFeature('pubsub-2')) {
910         gadgets.HubSettings.onConnect = function(hum, suc, err) {
911                 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
912                 loaded();
913         };
914 }
915 else gadgets.util.registerOnLoadHandler(loaded);
916 */