query dynamically for relationship types 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         var typedefpath = getTextURL( 'definitions' );
206     $.getJSON( typedefpath, function(data) {
207         var rel_types = data.types.sort();
208         // Add the relationship types to our document data so that we don't have
209         // to call again
210         $('#keymap').data( 'relations', rel_types );
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( evt ) {
637         $(evt.target).button("disable");
638         $('#status').empty();
639         form_values = $('#collapse_node_form').serialize();
640         ncpath = getTextURL( 'relationships' );
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                 var relation_found = $.inArray( source_target[2], $('#keymap').data('relations') );
646                 if( source_found.size() && target_found.size() && relation_found > -1 ) {
647                     var relation = relation_manager.create( source_target[0], source_target[1], relation_found );
648                                         relation.data( 'type', source_target[2]  );
649                                         relation.data( 'scope', $('#scope :selected').text()  );
650                                         relation.data( 'note', $('#note').val()  );
651                                         relation_manager.toggle_active( relation.attr('id') );
652                                 }
653                                 $(evt.target).button("enable");
654            });
655             $( "#dialog-form" ).dialog( "close" );
656         }, 'json' );
657       },
658       Cancel: function() {
659           $( this ).dialog( "close" );
660       }
661     },
662     create: function(event, ui) { 
663         $(this).data( 'relation_drawn', false );
664         //TODO Check whether we have already retrieved the definitions
665                 var typedefpath = getTextURL( 'definitions' );
666         var jqjson = $.getJSON( typedefpath, function(data) {
667             var types = data.types.sort();
668             $.each( types, function(index, value) {   
669                  $('#rel_type').append( $('<option />').attr( "value", value ).text(value) ); 
670                  $('#keymaplist').append( $('<li>').css( "border-color", relation_manager.relation_colors[index] ).text(value) ); 
671             });
672             var scopes = data.scopes;
673             $.each( scopes, function(index, value) {   
674                  $('#scope').append( $('<option />').attr( "value", value ).text(value) ); 
675             });
676         });        
677     },
678     open: function() {
679         relation_manager.create_temporary( $('#source_node_id').val(), $('#target_node_id').val() );
680         $(".ui-widget-overlay").css("background", "none");
681         $("#dialog_overlay").show();
682         $("#dialog_overlay").height( $("#enlargement_container").height() );
683         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
684         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
685     },
686     close: function() {
687         relation_manager.remove_temporary();
688         $( '#status' ).empty();
689         $("#dialog_overlay").hide();
690     }
691   }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
692       if( ajaxSettings.url == getTextURL('relationships') 
693         && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
694           var errobj = jQuery.parseJSON( jqXHR.responseText );
695           $('#status').append( '<p class="error">Error: ' + errobj.error + '</br>The relationship cannot be made.</p>' );
696       }
697           $(event.target).parent().find('.ui-button').button("enable");
698   } );
699
700   $( "#delete-form" ).dialog({
701     autoOpen: false,
702     height: 135,
703     width: 160,
704     modal: false,
705     buttons: {
706         Cancel: function() {
707             $( this ).dialog( "close" );
708         },
709         Delete: function() {
710           form_values = $('#delete_relation_form').serialize();
711           ncpath = getTextURL( 'relationships' );
712           var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
713               $.each( data, function(item, source_target) { 
714                   relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
715               });
716               $( "#delete-form" ).dialog( "close" );
717           }, dataType: 'json', type: 'DELETE' });
718         }
719     },
720     create: function(event, ui) {
721         var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
722         buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
723         var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");  
724         dialog_aria.mouseenter( function() {
725             if( mouseWait != null ) { clearTimeout(mouseWait) };
726         })
727         dialog_aria.mouseleave( function() {
728             mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
729         })
730     },
731     open: function() {
732         mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
733     },
734     close: function() {
735     }
736   });
737
738   // function for reading form dialog should go here; 
739   // just hide the element for now if we don't have morphology
740   if( can_morphologize ) {
741           $('#reading-form').dialog({
742                 autoOpen: false,
743                 // height: 400,
744                 width: 450,
745                 modal: true,
746                 buttons: {
747                         Cancel: function() {
748                                 $( this ).dialog( "close" );
749                         },
750                         Update: function( evt ) {
751                                 // Disable the button
752                                 $(evt.target).button("disable");
753                                 $('#reading_status').empty();
754                                 var reading_id = $('#reading_id').val()
755                                 form_values = {
756                                         'id' : reading_id,
757                                         'is_nonsense': $('#reading_is_nonsense').is(':checked'),
758                                         'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
759                                         'normal_form': $('#reading_normal_form').val() };
760                                 // Add the morphology values
761                                 $('.reading_morphology').each( function() {
762                                         if( $(this).val() != '(Click to select)' ) {
763                                                 var rmid = $(this).attr('id');
764                                                 rmid = rmid.substring(8);
765                                                 form_values[rmid] = $(this).val();
766                                         }
767                                 });
768                                 // Make the JSON call
769                                 ncpath = getReadingURL( reading_id );
770                                 var reading_element = readingdata[reading_id];
771                                 // $(':button :contains("Update")').attr("disabled", true);
772                                 var jqjson = $.post( ncpath, form_values, function(data) {
773                                         $.each( data, function(key, value) { 
774                                                 reading_element[key] = value;
775                                         });
776                                         if( $('#update_workspace_button').data('locked') == false ) {
777                                                 color_inactive( get_ellipse( reading_id ) );
778                                         }
779                                         $(evt.target).button("enable");
780                                         $( "#reading-form" ).dialog( "close" );
781                                 });
782                                 // Re-color the node if necessary
783                                 return false;
784                         }
785                 },
786                 create: function() {
787                 },
788                 open: function() {
789                         $(".ui-widget-overlay").css("background", "none");
790                         $("#dialog_overlay").show();
791                         $('#reading_status').empty();
792                         $("#dialog_overlay").height( $("#enlargement_container").height() );
793                         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
794                         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
795                         $("#reading-form").parent().find('.ui-button').button("enable");
796                 },
797                 close: function() {
798                         $("#dialog_overlay").hide();
799                 }
800           }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
801                   if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
802                         && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
803                           var errobj = jQuery.parseJSON( jqXHR.responseText );
804                           $('#reading_status').append( '<p class="error">Error: ' + errobj.error + '</p>' );
805                   }
806                   $(event.target).parent().find('.ui-button').button("enable");
807           });
808         } else {
809                 $('#reading-form').hide();
810         }
811   
812
813   $('#update_workspace_button').click( function() {
814      var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
815      mouse_scale = svg_root_element.getScreenCTM().a;
816      if( $(this).data('locked') == true ) {
817          $('#svgenlargement ellipse' ).each( function( index ) {
818              if( $(this).data( 'node_obj' ) != null ) {
819                  $(this).data( 'node_obj' ).ungreyout_edges();
820                  $(this).data( 'node_obj' ).set_draggable( false );
821                  var node_id = $(this).data( 'node_obj' ).get_id();
822                  toggle_relation_active( node_id );
823                  $(this).data( 'node_obj', null );
824              }
825          })
826          $(this).data('locked', false);
827          $(this).css('background-position', '0px 44px');
828      } else {
829          var left = $('#enlargement').offset().left;
830          var right = left + $('#enlargement').width();
831          var tf = svg_root_element.getScreenCTM().inverse(); 
832          var p = svg_root.createSVGPoint();
833          p.x=left;
834          p.y=100;
835          var cx_min = p.matrixTransform(tf).x;
836          p.x=right;
837          var cx_max = p.matrixTransform(tf).x;
838          $('#svgenlargement ellipse').each( function( index ) {
839              var cx = parseInt( $(this).attr('cx') );
840              if( cx > cx_min && cx < cx_max) { 
841                  if( $(this).data( 'node_obj' ) == null ) {
842                      $(this).data( 'node_obj', new node_obj( $(this) ) );
843                  } else {
844                      $(this).data( 'node_obj' ).set_draggable( true );
845                  }
846                  $(this).data( 'node_obj' ).greyout_edges();
847                  var node_id = $(this).data( 'node_obj' ).get_id();
848                  toggle_relation_active( node_id );
849              }
850          });
851          $(this).css('background-position', '0px 0px');
852          $(this).data('locked', true );
853      }
854   });
855   
856   $('.helptag').popupWindow({ 
857           height:500, 
858           width:800, 
859           top:50, 
860           left:50,
861           scrollbars:1 
862   }); 
863
864   
865   function toggle_relation_active( node_id ) {
866       $('#svgenlargement .relation').find( "title:contains('" + node_id +  "')" ).each( function(index) {
867           matchid = new RegExp( "^" + node_id );
868           if( $(this).text().match( matchid ) != null ) {
869                   var relation_id = $(this).parent().attr('id');
870               relation_manager.toggle_active( relation_id );
871           };
872       });
873   }
874
875   expandFillPageClients();
876   $(window).resize(function() {
877     expandFillPageClients();
878   });
879
880 });
881
882
883 function expandFillPageClients() {
884         $('.fillPage').each(function () {
885                 $(this).height($(window).height() - $(this).offset().top - MARGIN);
886         });
887 }
888
889 function loadSVG(svgData) {
890         var svgElement = $('#svgenlargement');
891
892         $(svgElement).svg('destroy');
893
894         $(svgElement).svg({
895                 loadURL: svgData,
896                 onLoad : svgEnlargementLoaded
897         });
898 }
899
900
901 /*      OS Gadget stuff
902
903 function svg_select_callback(topic, data, subscriberData) {
904         svgData = data;
905         loadSVG(svgData);
906 }
907
908 function loaded() {
909         var prefs = new gadgets.Prefs();
910         var preferredHeight = parseInt(prefs.getString('height'));
911         if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
912         expandFillPageClients();
913 }
914
915 if (gadgets.util.hasFeature('pubsub-2')) {
916         gadgets.HubSettings.onConnect = function(hum, suc, err) {
917                 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
918                 loaded();
919         };
920 }
921 else gadgets.util.registerOnLoadHandler(loaded);
922 */