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