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