Merged out conflicts
[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 jQuery.removeFromArray = function(value, arr) {
9     return jQuery.grep(arr, function(elem, index) {
10         return elem !== value;
11     });
12 };
13
14 function arrayUnique(array) {
15     var a = array.concat();
16     for(var i=0; i<a.length; ++i) {
17         for(var j=i+1; j<a.length; ++j) {
18             if(a[i] === a[j])
19                 a.splice(j--, 1);
20         }
21     }
22     return a;
23 };
24
25 function getTextURL( which ) {
26         return basepath + textid + '/' + which;
27 }
28
29 function getReadingURL( reading_id ) {
30         return basepath + textid + '/reading/' + reading_id;
31 }
32
33 // Make an XML ID into a valid selector
34 function jq(myid) { 
35         return '#' + myid.replace(/(:|\.)/g,'\\$1');
36 }
37
38 // Actions for opening the reading panel
39 function node_dblclick_listener( evt ) {
40         // Open the reading dialogue for the given node.
41         // First get the reading info
42         var reading_id = $(this).attr('id');
43         var reading_info = readingdata[reading_id];
44         // and then populate the dialog box with it.
45         // Set the easy properties first
46         $('#reading-form').dialog( 'option', 'title', 'Reading information for "' + reading_info['text'] + '"' );
47         $('#reading_id').val( reading_id );
48         toggle_checkbox( $('#reading_is_nonsense'), reading_info['is_nonsense'] );
49         toggle_checkbox( $('#reading_grammar_invalid'), reading_info['grammar_invalid'] );
50         // Use .text as a backup for .normal_form
51         var normal_form = reading_info['normal_form'];
52         if( !normal_form ) {
53                 normal_form = reading_info['text'];
54         }
55         var nfboxsize = 10;
56         if( normal_form.length > 9 ) {
57                 nfboxsize = normal_form.length + 1;
58         }
59         $('#reading_normal_form').attr( 'size', nfboxsize )
60         $('#reading_normal_form').val( normal_form );
61         if( editable ) {
62                 // Fill in the witnesses for the de-collation box.
63                 $('#reading_decollate_witnesses').empty();
64                 $.each( reading_info['witnesses'], function( idx, wit ) {
65                         $('#reading_decollate_witnesses').append( $('<option/>').attr(
66                                 'value', wit ).text( wit ) );
67                 });
68         }
69         // Now do the morphological properties.
70         morphology_form( reading_info['lexemes'] );
71         // and then open the dialog.
72         $('#reading-form').dialog("open");
73 }
74
75 function toggle_checkbox( box, value ) {
76         if( value == null ) {
77                 value = false;
78         }
79         box.attr('checked', value );
80 }
81
82 function morphology_form ( lexlist ) {
83         if( lexlist.length ) {
84                 $('#morph_outer').show();
85                 $('#morphology').empty();
86                 $.each( lexlist, function( idx, lex ) {
87                         var morphoptions = [];
88                         if( 'wordform_matchlist' in lex ) {
89                                 $.each( lex['wordform_matchlist'], function( tdx, tag ) {
90                                         var tagstr = stringify_wordform( tag );
91                                         morphoptions.push( tagstr );
92                                 });
93                         }
94                         var formtag = 'morphology_' + idx;
95                         var formstr = '';
96                         if( 'form' in lex ) {
97                                 formstr = stringify_wordform( lex['form'] );
98                         } 
99                         var form_morph_elements = morph_elements( 
100                                 formtag, lex['string'], formstr, morphoptions );
101                         $.each( form_morph_elements, function( idx, el ) {
102                                 $('#morphology').append( el );
103                         });
104                 });
105         } else {
106                 $('#morph_outer').hide();
107         }
108 }
109
110 function stringify_wordform ( tag ) {
111         if( tag ) {
112                 var elements = tag.split(' // ');
113                 return elements[1] + ' // ' + elements[2];
114         }
115         return ''
116 }
117
118 function morph_elements ( formtag, formtxt, currform, morphoptions ) {
119         var clicktag = '(Click to select)';
120         if ( !currform ) {
121                 currform = clicktag;
122         }
123         var formlabel = $('<label/>').attr( 'id', 'label_' + formtag ).attr( 
124                 'for', 'reading_' + formtag ).text( formtxt + ': ' );
125         var forminput = $('<input/>').attr( 'id', 'reading_' + formtag ).attr( 
126                 'name', 'reading_' + formtag ).attr( 'size', '50' ).attr(
127                 'class', 'reading_morphology' ).val( currform );
128         forminput.autocomplete({ source: morphoptions, minLength: 0     });
129         forminput.focus( function() { 
130                 if( $(this).val() == clicktag ) {
131                         $(this).val('');
132                 }
133                 $(this).autocomplete('search', '') 
134         });
135         var morphel = [ formlabel, forminput, $('<br/>') ];
136         return morphel;
137 }
138
139 function color_inactive ( el ) {
140         var reading_id = $(el).parent().attr('id');
141         var reading_info = readingdata[reading_id];
142         // If the reading info has any non-disambiguated lexemes, color it yellow;
143         // otherwise color it green.
144         $(el).attr( {stroke:'green', fill:'#b3f36d'} );
145         if( reading_info ) {
146                 $.each( reading_info['lexemes'], function ( idx, lex ) {
147                         if( !lex['is_disambiguated'] || lex['is_disambiguated'] == 0 ) {
148                                 $(el).attr( {stroke:'orange', fill:'#fee233'} );
149                         }
150                 });
151         }
152 }
153
154 function relemmatize () {
155         // Send the reading for a new lemmatization and reopen the form.
156         $('#relemmatize_pending').show();
157         var reading_id = $('#reading_id').val()
158         ncpath = getReadingURL( reading_id );
159         form_values = { 
160                 'normal_form': $('#reading_normal_form').val(), 
161                 'relemmatize': 1 };
162         var jqjson = $.post( ncpath, form_values, function( data ) {
163                 // Update the form with the return
164                 if( 'id' in data ) {
165                         // We got back a good answer. Stash it
166                         readingdata[reading_id] = data;
167                         // and regenerate the morphology form.
168                         morphology_form( data['lexemes'] );
169                 } else {
170                         alert("Could not relemmatize as requested: " + data['error']);
171                 }
172                 $('#relemmatize_pending').hide();
173         });
174 }
175
176 // Initialize the SVG once it exists
177 function svgEnlargementLoaded() {
178         //Give some visual evidence that we are working
179         $('#loading_overlay').show();
180         lo_height = $("#enlargement_container").outerHeight();
181         lo_width = $("#enlargement_container").outerWidth();
182         $("#loading_overlay").height( lo_height );
183         $("#loading_overlay").width( lo_width );
184         $("#loading_overlay").offset( $("#enlargement_container").offset() );
185         $("#loading_message").offset(
186                 { 'top': lo_height / 2 - $("#loading_message").height() / 2,
187                   'left': lo_width / 2 - $("#loading_message").width() / 2 });
188     if( editable ) {
189         // Show the update toggle button.
190             $('#update_workspace_button').data('locked', false);
191         $('#update_workspace_button').css('background-position', '0px 44px');
192     }
193     $('#svgenlargement ellipse').parent().dblclick( node_dblclick_listener );
194     var graph_svg = $('#svgenlargement svg');
195     var svg_g = $('#svgenlargement svg g')[0];
196     if (!svg_g) return;
197     svg_root = graph_svg.svg().svg('get').root();
198
199     // Find the real root and ignore any text nodes
200     for (i = 0; i < svg_root.childNodes.length; ++i) {
201         if (svg_root.childNodes[i].nodeName != '#text') {
202                 svg_root_element = svg_root.childNodes[i];
203                 break;
204            }
205     }
206
207     //Set viewbox width and height to width and height of $('#svgenlargement svg').
208     //This is essential to make sure zooming and panning works properly.
209     svg_root.viewBox.baseVal.width = graph_svg.attr( 'width' );
210     svg_root.viewBox.baseVal.height = graph_svg.attr( 'height' );
211     //Now set scale and translate so svg height is about 150px and vertically centered in viewbox.
212     //This is just to create a nice starting enlargement.
213     var initial_svg_height = 250;
214     var scale = initial_svg_height/graph_svg.attr( 'height' );
215     var additional_translate = (graph_svg.attr( 'height' ) - initial_svg_height)/(2*scale);
216     var transform = svg_g.getAttribute('transform');
217     var translate = parseFloat( transform.match( /translate\([^\)]*\)/ )[0].split('(')[1].split(' ')[1].split(')')[0] );
218     translate += additional_translate;
219     var transform = 'rotate(0) scale(' + scale + ') translate(4 ' + translate + ')';
220     svg_g.setAttribute('transform', transform);
221     //used to calculate min and max zoom level:
222     start_element_height = $('#__START__').children('ellipse')[0].getBBox().height;
223     //some use of call backs to ensure succesive execution
224     add_relations( function() { 
225         var rdgpath = getTextURL( 'readings' );
226         $.getJSON( rdgpath, function( data ) {
227             readingdata = data;
228             $('#svgenlargement ellipse').each( function( i, el ) { color_inactive( el ) });
229             // detach_node(null);
230         });
231         $('#loading_overlay').hide(); 
232     });
233     
234     //initialize marquee
235     marquee = new Marquee();
236     
237 }
238
239 function add_relations( callback_fn ) {
240         // Add the relationship types to the keymap list
241         $.each( relationship_types, function(index, typedef) {   
242                  li_elm = $('<li class="key">').css( "border-color", 
243                         relation_manager.relation_colors[index] ).text(typedef.name);
244                  li_elm.append( $('<div>').attr('class', 'key_tip_container').append(
245                         $('<div>').attr('class', 'key_tip').text(typedef.description) ) );
246                  $('#keymaplist').append( li_elm ); 
247         });
248         // Now fetch the relationships themselves and add them to the graph
249         var rel_types = $.map( relationship_types, function(t) { return t.name });
250         // Save this list of names to the outer element data so that the relationship
251         // factory can access it
252         $('#keymap').data('relations', rel_types);
253         var textrelpath = getTextURL( 'relationships' );
254         $.getJSON( textrelpath, function(data) {
255                 $.each(data, function( index, rel_info ) {
256                         var type_index = $.inArray(rel_info.type, rel_types);
257                         var source_found = get_ellipse( rel_info.source );
258                         var target_found = get_ellipse( rel_info.target );
259                         if( type_index != -1 && source_found.size() && target_found.size() ) {
260                                 var relation = relation_manager.create( rel_info.source, rel_info.target, type_index );
261                                 relation.data( 'type', rel_info.type );
262                                 relation.data( 'scope', rel_info.scope );
263                                 relation.data( 'note', rel_info.note );
264                                 if( editable ) {
265                                         var node_obj = get_node_obj(rel_info.source);
266                                         node_obj.set_selectable( false );
267                                         node_obj.ellipse.data( 'node_obj', null );
268                                         node_obj = get_node_obj(rel_info.target);
269                                         node_obj.set_selectable( false );
270                                         node_obj.ellipse.data( 'node_obj', null );
271                                 }
272                         }
273                 });
274                 callback_fn.call();
275         });
276 }
277
278 function get_ellipse( node_id ) {
279         return $( jq( node_id ) + ' ellipse');
280 }
281
282 function get_node_obj( node_id ) {
283     var node_ellipse = get_ellipse( node_id );
284     if( node_ellipse.data( 'node_obj' ) == null ) {
285         node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
286     };
287     return node_ellipse.data( 'node_obj' );
288 }
289
290 function node_obj(ellipse) {
291   this.ellipse = ellipse;
292   var self = this;
293   
294   this.ox = 0;
295   this.oy = 0;
296   this.x = 0;
297   this.y = 0;
298   this.dx = 0;
299   this.dy = 0;
300   this.node_elements = node_elements_for(self.ellipse);
301
302   if( $(self.ellipse).data( 'org_translate' ) != null ) {
303       var org_translate = $(self.ellipse).data( 'org_translate' );
304       this.ox = org_translate[0];
305       this.oy = org_translate[1]; 
306   }
307   
308   this.get_id = function() {
309     return $(self.ellipse).parent().attr('id')
310   }
311   
312   this.set_selectable = function( clickable ) {
313       if( clickable && editable ) {
314           $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
315           $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
316           $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } ); 
317           $(self.ellipse).parent().click( function(evt) { 
318               evt.stopPropagation();              
319               if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
320                 $('ellipse[fill="#9999ff"]').each( function() { 
321                     $(this).data( 'node_obj' ).set_draggable( false );
322                 } );
323               }
324               self.set_draggable( true ) 
325           });
326       } else {
327           $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
328           self.ellipse.siblings('text').attr('class', '');
329           $(self.ellipse).parent().unbind(); 
330           $('body').unbind('mousemove');
331           $('body').unbind('mouseup');
332       }
333   }
334   
335   this.set_draggable = function( draggable ) {
336     if( draggable && editable ) {
337       $(self.ellipse).attr( {stroke:'black', fill:'#9999ff'} );
338       $(self.ellipse).parent().mousedown( this.mousedown_listener );
339       $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' );
340       self.ellipse.siblings('text').attr('class', 'noselect draggable');
341     } else {
342       $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
343       self.ellipse.siblings('text').attr('class', '');
344       $(self.ellipse).parent().unbind( 'mousedown ');
345       $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } ); 
346       $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
347     }
348   }
349
350   this.mousedown_listener = function(evt) {
351     evt.stopPropagation();
352     self.x = evt.clientX;
353     self.y = evt.clientY;
354     $('body').mousemove( self.mousemove_listener );
355     $('body').mouseup( self.mouseup_listener );
356     $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
357     self.ellipse.attr( 'fill', '#6b6bb2' );
358     first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
359     if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
360   }
361
362   this.mousemove_listener = function(evt) {
363     self.dx = (evt.clientX - self.x) / mouse_scale;
364     self.dy = (evt.clientY - self.y) / mouse_scale;
365     self.move_elements();
366     evt.returnValue = false;
367     evt.preventDefault();
368     return false;
369   }
370
371   this.mouseup_listener = function(evt) {    
372     if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
373         var source_node_id = $(self.ellipse).parent().attr('id');
374         var source_node_text = self.ellipse.siblings('text').text();
375         var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
376         var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
377         $('#source_node_id').val( source_node_id );
378         $('#source_node_text').val( source_node_text );
379         $('#target_node_id').val( target_node_id );
380         $('#target_node_text').val( target_node_text );
381         $('#dialog-form').dialog( 'open' );
382     };
383     $('body').unbind('mousemove');
384     $('body').unbind('mouseup');
385     self.ellipse.attr( 'fill', '#9999ff' );
386     self.reset_elements();
387   }
388   
389   this.cpos = function() {
390     return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
391   }
392
393   this.get_g = function() {
394     return self.ellipse.parent('g');
395   }
396
397   this.enter_node = function(evt) {
398     self.ellipse.attr( 'fill', '#ffccff' );
399   }
400
401   this.leave_node = function(evt) {
402     self.ellipse.attr( 'fill', '#fff' );
403   }
404
405   this.greyout_edges = function() {
406       $.each( self.node_elements, function(index, value) {
407         value.grey_out('.edge');
408       });
409   }
410
411   this.ungreyout_edges = function() {
412       $.each( self.node_elements, function(index, value) {
413         value.un_grey_out('.edge');
414       });
415   }
416
417   this.move_elements = function() {
418     $.each( self.node_elements, function(index, value) {
419       value.move( ( self.ox + self.dx ) , ( self.oy + self.dy ) );
420     } );
421   }
422
423   this.reset_elements = function() {
424     $.each( self.node_elements, function(index, value) {
425       value.move( self.ox, self.oy );
426     } );
427   }
428
429   this.update_elements = function() {
430       self.node_elements = node_elements_for(self.ellipse);
431   }
432
433   this.get_witnesses = function() {
434       return readingdata[self.get_id()].witnesses
435   }
436   
437   this.relocate = function( dx, dy ) {
438       self.ox = self.ox + dx;
439       self.oy = self.oy + dy;
440       $(self.ellipse).data( 'org_translate', [self.ox, self.oy] );
441       self.move_elements();
442   }
443   
444   self.set_selectable( true );
445 }
446
447 function svgshape( shape_element ) {
448   this.shape = shape_element;
449   this.move = function(dx,dy) {
450       this.shape.attr( "transform", "translate(" + dx + " " + dy + ")" );
451   }
452   this.reset = function() {
453     this.shape.attr( "transform", "translate( 0, 0 )" );
454   }
455   this.grey_out = function(filter) {
456       if( this.shape.parent(filter).size() != 0 ) {
457           this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
458       }
459   }
460   this.un_grey_out = function(filter) {
461       if( this.shape.parent(filter).size() != 0 ) {
462         this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
463       }
464   }
465 }
466
467 function svgpath( path_element, svg_element ) {
468   this.svg_element = svg_element;
469   this.path = path_element;
470   this.x = this.path.x;
471   this.y = this.path.y;
472   this.move = function(dx,dy) {
473     this.path.x = this.x + dx;
474     this.path.y = this.y + dy;
475   }
476   this.reset = function() {
477     this.path.x = this.x;
478     this.path.y = this.y;
479   }
480   this.grey_out = function(filter) {
481       if( this.svg_element.parent(filter).size() != 0 ) {
482           this.svg_element.attr('stroke', '#e5e5e5');
483           this.svg_element.siblings('text').attr('fill', '#e5e5e5');
484           this.svg_element.siblings('text').attr('class', 'noselect');
485       }
486   }
487   this.un_grey_out = function(filter) {
488       if( this.svg_element.parent(filter).size() != 0 ) {
489           this.svg_element.attr('stroke', '#000000');
490           this.svg_element.siblings('text').attr('fill', '#000000');
491           this.svg_element.siblings('text').attr('class', '');
492       }
493   }
494 }
495
496 function node_elements_for( ellipse ) {
497   node_elements = get_edge_elements_for( ellipse );
498   node_elements.push( new svgshape( ellipse.siblings('text') ) );
499   node_elements.push( new svgshape( ellipse ) );
500   return node_elements;
501 }
502
503 function get_edge_elements_for( ellipse ) {
504   edge_elements = new Array();
505   node_id = ellipse.parent().attr('id');
506   edge_in_pattern = new RegExp( node_id + '$' );
507   edge_out_pattern = new RegExp( '^' + node_id + '-' );
508   $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
509     title = $(this).text();
510     if( edge_in_pattern.test(title) ) {
511         polygon = $(this).siblings('polygon');
512         if( polygon.size() > 0 ) {
513             edge_elements.push( new svgshape( polygon ) );
514         }
515         path_segments = $(this).siblings('path')[0].pathSegList;
516         edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
517     }
518     if( edge_out_pattern.test(title) ) {
519       path_segments = $(this).siblings('path')[0].pathSegList;
520       edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
521     }
522   });
523   return edge_elements;
524
525
526 function relation_factory() {
527     var self = this;
528     this.color_memo = null;
529     //TODO: colors hard coded for now
530     this.temp_color = '#FFA14F';
531     this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
532
533     this.create_temporary = function( source_node_id, target_node_id ) {
534         var relation_id = get_relation_id( source_node_id, target_node_id );
535         var relation = $( jq( relation_id ) );
536         if( relation.size() == 0 ) { 
537             draw_relation( source_node_id, target_node_id, self.temp_color );
538         } else {
539             self.color_memo = relation.children('path').attr( 'stroke' );
540             relation.children('path').attr( 'stroke', self.temp_color );
541         }
542     }
543     this.remove_temporary = function() {
544         var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
545         if( self.color_memo != null ) {
546             path_element.attr( 'stroke', self.color_memo );
547             self.color_memo = null;
548         } else {
549             var temporary = path_element.parent('g').remove();
550             temporary.empty();
551             temporary = null; 
552         }
553     }
554     this.create = function( source_node_id, target_node_id, color_index ) {
555         //TODO: Protect from (color_)index out of bound..
556         var relation_color = self.relation_colors[ color_index ];
557         var relation = draw_relation( source_node_id, target_node_id, relation_color );
558         get_node_obj( source_node_id ).update_elements();
559         get_node_obj( target_node_id ).update_elements();
560         return relation;
561     }
562     this.toggle_active = function( relation_id ) {
563         var relation = $( jq( relation_id ) );
564         var relation_path = relation.children('path');
565         if( !relation.data( 'active' ) ) {
566             relation_path.css( {'cursor':'pointer'} );
567             relation_path.mouseenter( function(event) { 
568                 outerTimer = setTimeout( function() { 
569                     timer = setTimeout( function() { 
570                         var related_nodes = get_related_nodes( relation_id );
571                         var source_node_id = related_nodes[0];
572                         var target_node_id = related_nodes[1];
573                         $('#delete_source_node_id').val( source_node_id );
574                         $('#delete_target_node_id').val( target_node_id );
575                         self.showinfo(relation); 
576                     }, 500 ) 
577                 }, 1000 );
578             });
579             relation_path.mouseleave( function(event) {
580                 clearTimeout(outerTimer); 
581                 if( timer != null ) { clearTimeout(timer); } 
582             });
583             relation.data( 'active', true );
584         } else {
585             relation_path.unbind( 'mouseenter' );
586             relation_path.unbind( 'mouseleave' );
587             relation_path.css( {'cursor':'inherit'} );
588             relation.data( 'active', false );
589         }
590     }
591     this.showinfo = function(relation) {
592         $('#delete_relation_type').text( relation.data('type') );
593         $('#delete_relation_scope').text( relation.data('scope') );
594         if( relation.data( 'note' ) ) {
595                 $('#delete_relation_note').text('note: ' + relation.data( 'note' ) );
596         }
597         var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
598         var xs = parseFloat( points[0].split(',')[0] );
599         var xe = parseFloat( points[1].split(',')[0] );
600         var ys = parseFloat( points[0].split(',')[1] );
601         var ye = parseFloat( points[3].split(',')[1] );
602         var p = svg_root.createSVGPoint();
603         p.x = xs + ((xe-xs)*1.1);
604         p.y = ye - ((ye-ys)/2);
605         var ctm = svg_root_element.getScreenCTM();
606         var nx = p.matrixTransform(ctm).x;
607         var ny = p.matrixTransform(ctm).y;
608         var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
609         $('#delete-form').dialog( 'open' );
610         dialog_aria.offset({ left: nx, top: ny });
611     }
612     this.remove = function( relation_id ) {
613         if( !editable ) {
614                 return;
615         }
616         var relation = $( jq( relation_id ) );
617         relation.remove();
618     }
619 }
620
621 // Utility function to create/return the ID of a relation link between
622 // a source and target.
623 function get_relation_id( source_id, target_id ) {
624         var idlist = [ source_id, target_id ];
625         idlist.sort();
626         return 'relation-' + idlist[0] + '-...-' + idlist[1];
627 }
628
629 function get_related_nodes( relation_id ) {
630         var srctotarg = relation_id.substr( 9 );
631         return srctotarg.split('-...-');
632 }
633
634 function draw_relation( source_id, target_id, relation_color ) {
635     var source_ellipse = get_ellipse( source_id );
636     var target_ellipse = get_ellipse( target_id );
637     var relation_id = get_relation_id( source_id, target_id );
638     var svg = $('#svgenlargement').children('svg').svg().svg('get');
639     var path = svg.createPath(); 
640     var sx = parseInt( source_ellipse.attr('cx') );
641     var rx = parseInt( source_ellipse.attr('rx') );
642     var sy = parseInt( source_ellipse.attr('cy') );
643     var ex = parseInt( target_ellipse.attr('cx') );
644     var ey = parseInt( target_ellipse.attr('cy') );
645     var relation = svg.group( $("#svgenlargement svg g"), 
646         { 'class':'relation', 'id':relation_id } );
647     svg.title( relation, source_id + '->' + target_id );
648     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});
649     var relation_element = $('#svgenlargement .relation').filter( ':last' );
650     relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
651     return relation_element;
652 }
653
654 function detach_node( readings ) {
655     
656     // This method is work in progress
657     // Todos:
658     // 1) Unproven/untested: readings.each will get us in trouble most likely for
659     //    duplicating edges in a strand that both are incoming and outgoing
660     //    like b and c in -i-> a -ii-> b -iii-> c -iv->
661     // 2) Added edges and nodes look rough and unsmoothed, what the f.?
662     //
663     
664     // add new node(s)
665     $.extend( readingdata, readings );
666     // remove from existing readings the witnesses for the new nodes/readings
667     $.each( readings, function( node_id, reading ) {
668         $.each( reading.witnesses, function( index, witness ) {
669             var witnesses = readingdata[ reading.orig_rdg ].witnesses;
670             readingdata[ reading.orig_rdg ].witnesses = $.removeFromArray( witness, witnesses );
671         } );
672     } );    
673     
674     detached_edges = [];
675     
676     // here we detach witnesses from the existing edges accoring to what's being relayed by readings
677     $.each( readings, function( node_id, reading ) {
678         var edges = edges_of( get_ellipse( reading.orig_rdg ) );
679         incoming_remaining = [];
680         outgoing_remaining = [];
681         $.each( reading.witnesses, function( index, witness ) {
682             incoming_remaining.push( witness );
683             outgoing_remaining.push( witness );
684         } );
685         $.each( edges, function( index, edge ) {
686             detached_edge = edge.detach_witnesses( reading.witnesses );
687             if( detached_edge != null ) {
688                 detached_edges.push( detached_edge );
689                 $.each( detached_edge.witnesses, function( index, witness ) {
690                     if( detached_edge.is_incoming == true ) {
691                         incoming_remaining = $.removeFromArray( witness, incoming_remaining );
692                     } else {
693                         outgoing_remaining = $.removeFromArray( witness, outgoing_remaining );
694                     }
695                 } );
696             }
697         } );
698         
699         // After detaching we still need to check if for *all* readings
700         // an edge was detached. It may be that a witness was not
701         // explicitly named on an edge but was part of a 'majority' edge
702         // in which case we need to duplicate and name that edge after those
703         // remaining witnesses.
704         if( outgoing_remaining.length > 0 ) {
705             $.each( edges, function( index, edge ) {
706                 if( edge.get_label() == 'majority' && !edge.is_incoming ) {
707                     detached_edges.push( edge.clone_for( outgoing_remaining ) );
708                 }
709             } );
710         }
711         if( incoming_remaining.length > 0 ) {
712             $.each( edges, function( index, edge ) {
713                 if( edge.get_label() == 'majority' && edge.is_incoming ) {
714                     detached_edges.push( edge.clone_for( outgoing_remaining ) );
715                 }
716             } );
717         }
718         
719         // Finally multiple selected nodes may share edges
720         var copy_array = [];
721         $.each( detached_edges, function( index, edge ) {
722             var do_copy = true;
723             $.each( copy_array, function( index, copy_edge ) {
724                 if( copy_edge.g_elem.attr( 'id' ) == edge.g_elem.attr( 'id' ) ) { do_copy = false }
725             } );
726             if( do_copy == true ) {
727                 copy_array.push( edge );
728             }
729         } );
730         detached_edges = copy_array;
731         
732         // Lots of unabstracted knowledge down here :/
733         // Clone original node/reading, rename/id it..
734         duplicate_node = get_ellipse( reading.orig_rdg ).parent().clone();
735         duplicate_node.attr( 'id', node_id );
736         duplicate_node.children( 'title' ).text( node_id );
737         duplicate_node_data = get_ellipse( reading.orig_rdg ).data( 'org_translate' );
738         if( duplicate_node_data != null ) {
739             duplicate_node.children( 'ellipse' ).data( 'org_translate', duplicate_node_data );
740         }
741         
742         // Add the node and all new edges into the graph
743         var graph_root = $('#svgenlargement svg g.graph');
744         graph_root.append( duplicate_node );
745         $.each( detached_edges, function( index, edge ) {
746             edge.g_elem.attr( 'id', ( edge.g_elem.attr( 'id' ) + "_0" ) );
747             edge_title = edge.g_elem.children( 'title' ).text();
748             edge_weight = 0.8 + ( 0.2 * edge.witnesses.length );
749             edge_title = edge_title.replace( reading.orig_rdg, node_id );
750             edge.g_elem.children( 'title' ).text( edge_title );
751             edge.g_elem.children( 'path').attr( 'stroke-width', edge_weight );
752             // Reg unabstracted knowledge: isn't it more elegant to make 
753             // it edge.append_to( graph_root )?
754             graph_root.append( edge.g_elem );
755         } );
756                 
757         // Make the detached node a real node_obj
758         var ellipse_elem = get_ellipse( node_id );
759         var new_node = new node_obj( ellipse_elem );
760         ellipse_elem.data( 'node_obj', new_node );
761
762         // Move the node somewhat up for 'dramatic effect' :-p
763         new_node.relocate( 0, -150 );        
764         
765     } );
766     
767
768 }
769
770 function Marquee() {
771     
772     var self = this;
773     
774     this.x = 0;
775     this.y = 0;
776     this.dx = 0;
777     this.dy = 0;
778     this.enlargementOffset = $('#svgenlargement').offset();
779     this.svg_rect = $('#svgenlargement svg').svg('get');
780
781     this.show = function( event ) {
782         self.x = event.clientX;
783         self.y = event.clientY;
784         p = svg_root.createSVGPoint();
785         p.x = event.clientX - self.enlargementOffset.left;
786         p.y = event.clientY - self.enlargementOffset.top;
787         self.svg_rect.rect( p.x, p.y, 0, 0, { fill: 'black', 'fill-opacity': '0.1', stroke: 'black', 'stroke-dasharray': '4,2', strokeWidth: '0.02em', id: 'marquee' } );
788     };
789
790     this.expand = function( event ) {
791         self.dx = (event.clientX - self.x);
792         self.dy = (event.clientY - self.y);
793         var rect = $('#marquee');
794         if( rect.length != 0 ) {            
795             var rect_w =  Math.abs( self.dx );
796             var rect_h =  Math.abs( self.dy );
797             var rect_x = self.x - self.enlargementOffset.left;
798             var rect_y = self.y - self.enlargementOffset.top;
799             if( self.dx < 0 ) { rect_x = rect_x - rect_w }
800             if( self.dy < 0 ) { rect_y = rect_y - rect_h }
801             rect.attr("x", rect_x).attr("y", rect_y).attr("width", rect_w).attr("height", rect_h);
802         }
803     };
804     
805     this.select = function() {
806         var rect = $('#marquee');
807         if( rect.length != 0 ) {
808             //unselect any possible selected first
809             //TODO: unless SHIFT?
810             if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
811               $('ellipse[fill="#9999ff"]').each( function() { 
812                   $(this).data( 'node_obj' ).set_draggable( false );
813               } );
814             }
815             //compute dimension of marquee
816             var left = $('#marquee').offset().left;
817             var top = $('#marquee').offset().top;
818             var right = left + parseInt( $('#marquee').attr( 'width' ) );
819             var bottom = top + parseInt( $('#marquee').attr( 'height' ) );
820             var tf = svg_root_element.getScreenCTM().inverse(); 
821             var p = svg_root.createSVGPoint();
822             p.x=left;
823             p.y=top;
824             var cx_min = p.matrixTransform(tf).x;
825             var cy_min = p.matrixTransform(tf).y;
826             p.x=right;
827             p.y=bottom;
828             var cx_max = p.matrixTransform(tf).x;
829             var cy_max = p.matrixTransform(tf).y;
830             //select any node with its center inside the marquee
831             var readings = [];
832             //also merge witness sets from nodes
833             var witnesses = [];
834             $('#svgenlargement ellipse').each( function( index ) {
835                 var cx = parseInt( $(this).attr('cx') );
836                 var cy = parseInt( $(this).attr('cy') );
837                 var org_translate = $(this).data( 'org_translate' );
838                 if( org_translate != null ) {
839                     cx = cx + org_translate[0];
840                     cy = cy + org_translate[1];
841                 }
842                 if( cx > cx_min && cx < cx_max) {
843                     if( cy > cy_min && cy < cy_max) {
844                         // we actually heve no real 'selected' state for nodes, except coloring
845                         $(this).attr( 'fill', '#9999ff' );
846                         // Take note of the selected reading(s) and applicable witness(es)
847                         // so we can populate the multipleselect-form 
848                         readings.push( $(this).parent().attr('id') ); 
849                         var this_witnesses = $(this).data( 'node_obj' ).get_witnesses();
850                         witnesses = arrayUnique( witnesses.concat( this_witnesses ) );
851                     }
852                 }
853             });
854             if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
855                 //add intersection of witnesses sets to the multi select form and open it
856                 $('#detach_collated_form').empty();
857                 $.each( readings, function( index, value ) {
858                   $('#detach_collated_form').append( $('<input>').attr(
859                     "type", "hidden").attr("name", "readings[]").attr(
860                     "value", value ) );
861                 });
862                                 $.each( witnesses, function( index, value ) {
863                     $('#detach_collated_form').append( 
864                       '<input type="checkbox" name="witnesses[]" value="' + value 
865                       + '">' + value + '<br>' ); 
866                 });
867                 $('#multiple_selected_readings').attr('value', readings.join(',') ); 
868                 $('#multipleselect-form').dialog( 'open' );
869             }
870             self.svg_rect.remove( $('#marquee') );
871         }
872     };
873     
874     this.unselect = function() {
875         $('ellipse[fill="#9999ff"]').attr( 'fill', '#fff' );
876     }
877      
878 }
879
880 function readings_equivalent( source, target ) {
881         var sourcetext = readingdata[source].text;
882         var targettext = readingdata[target].text;
883         if( sourcetext === targettext ) {
884                 return true;
885         }
886         // Lowercase and strip punctuation from both and compare again
887         var stlc = sourcetext.toLowerCase().replace(/[^\w\s]|_/g, "");
888         var ttlc = targettext.toLowerCase().replace(/[^\w\s]|_/g, "");
889         if( stlc === ttlc ) {
890                 return true;
891         }       
892         return false;
893 }
894
895
896 $(document).ready(function () {
897     
898   timer = null;
899   relation_manager = new relation_factory();
900   
901   $('#update_workspace_button').data('locked', false);
902    
903   // Set up the mouse events on the SVG enlargement             
904   $('#enlargement').mousedown(function (event) {
905     $(this)
906         .data('down', true)
907         .data('x', event.clientX)
908         .data('y', event.clientY)
909         .data('scrollLeft', this.scrollLeft)
910     stateTf = svg_root_element.getCTM().inverse();
911     var p = svg_root.createSVGPoint();
912     p.x = event.clientX;
913     p.y = event.clientY;
914     stateOrigin = p.matrixTransform(stateTf);
915
916     // Activate marquee if in interaction mode
917     if( $('#update_workspace_button').data('locked') == true ) { marquee.show( event ) };
918         
919     event.returnValue = false;
920     event.preventDefault();
921     return false;
922   }).mouseup(function (event) {
923     marquee.select(); 
924     $(this).data('down', false);
925   }).mousemove(function (event) {
926     if( timer != null ) { clearTimeout(timer); } 
927     if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
928         var p = svg_root.createSVGPoint();
929         p.x = event.clientX;
930         p.y = event.clientY;
931         p = p.matrixTransform(stateTf);
932         var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
933         var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
934         svg_root_element.setAttribute("transform", s);
935     }
936     marquee.expand( event ); 
937     event.returnValue = false;
938     event.preventDefault();
939   }).mousewheel(function (event, delta) {
940     event.returnValue = false;
941     event.preventDefault();
942     if ( $('#update_workspace_button').data('locked') == false ) {
943         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
944         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
945         if( delta < -9 ) { delta = -9 }; 
946         var z = 1 + delta/10;
947         z = delta > 0 ? 1 : -1;
948         var g = svg_root_element;
949         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
950             var root = svg_root;
951             var p = root.createSVGPoint();
952             p.x = event.originalEvent.clientX;
953             p.y = event.originalEvent.clientY;
954             p = p.matrixTransform(g.getCTM().inverse());
955             var scaleLevel = 1+(z/20);
956             var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
957             var matrix = g.getCTM().multiply(k);
958             var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
959             g.setAttribute("transform", s);
960         }
961     }
962   }).css({
963     'overflow' : 'hidden',
964     'cursor' : '-moz-grab'
965   });
966   
967   
968   // Set up the relationship creation dialog. This also functions as the reading
969   // merge dialog where appropriate.
970                           
971   if( editable ) {
972         $( "#dialog-form" ).dialog({
973         autoOpen: false,
974         height: 270,
975         width: 290,
976         modal: true,
977         buttons: {
978           "Merge readings": function( evt ) {
979                   $(evt.target).button("disable");
980                   $('#status').empty();
981                   form_values = $('#collapse_node_form').serialize();
982                   ncpath = getTextURL( 'merge' );
983                   var jqjson = $.post( ncpath, form_values, function(data) {
984                           alert( "Did a node merge" );
985                   });
986           },
987           OK: function( evt ) {
988                 $(evt.target).button("disable");
989                 $('#status').empty();
990                 form_values = $('#collapse_node_form').serialize();
991                 ncpath = getTextURL( 'relationships' );
992                 var jqjson = $.post( ncpath, form_values, function(data) {
993                         $.each( data, function(item, source_target) { 
994                                 var source_found = get_ellipse( source_target[0] );
995                                 var target_found = get_ellipse( source_target[1] );
996                                 var relation_found = $.inArray( source_target[2], $('#keymap').data('relations') );
997                                 if( source_found.size() && target_found.size() && relation_found > -1 ) {
998                                         var relation = relation_manager.create( source_target[0], source_target[1], relation_found );
999                                         relation.data( 'type', source_target[2]  );
1000                                         relation.data( 'scope', $('#scope :selected').text()  );
1001                                         relation.data( 'note', $('#note').val()  );
1002                                         relation_manager.toggle_active( relation.attr('id') );
1003                                 }
1004                                 $(evt.target).button("enable");
1005                    });
1006                         $( "#dialog-form" ).dialog( "close" );
1007                 }, 'json' );
1008           },
1009           Cancel: function() {
1010                   $( this ).dialog( "close" );
1011           }
1012         },
1013         create: function(event, ui) { 
1014                 $(this).data( 'relation_drawn', false );
1015                 $('#rel_type').data( 'changed_after_open', false );
1016                 $.each( relationship_types, function(index, typedef) {   
1017                          $('#rel_type').append( $('<option />').attr( "value", typedef.name ).text(typedef.name) ); 
1018                 });
1019                 $.each( relationship_scopes, function(index, value) {   
1020                          $('#scope').append( $('<option />').attr( "value", value ).text(value) ); 
1021                 });
1022                 // Handler to clear the annotation field, the first time the relationship is
1023                 // changed after opening the form.
1024                 $('#rel_type').change( function () {
1025                         if( !$(this).data( 'changed_after_open' ) ) {
1026                                 $('#note').val('');
1027                         }
1028                         $(this).data( 'changed_after_open', true );
1029                 });
1030         },
1031         open: function() {
1032                 relation_manager.create_temporary( 
1033                         $('#source_node_id').val(), $('#target_node_id').val() );
1034                 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' )
1035                 if( readings_equivalent( $('#source_node_id').val(), 
1036                                 $('#target_node_id').val() ) ) {
1037                         buttonset.find( "button:contains('Merge readings')" ).show();
1038                 } else {
1039                         buttonset.find( "button:contains('Merge readings')" ).hide();
1040                 }
1041                 $(".ui-widget-overlay").css("background", "none");
1042                 $("#dialog_overlay").show();
1043                 $("#dialog_overlay").height( $("#enlargement_container").height() );
1044                 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1045                 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1046                 $('#rel_type').data( 'changed_after_open', false );
1047         },
1048         close: function() {
1049                 relation_manager.remove_temporary();
1050                 $( '#status' ).empty();
1051                 $("#dialog_overlay").hide();
1052         }
1053         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
1054                 if( ajaxSettings.url == getTextURL('relationships') 
1055                         && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1056                         var error;
1057                         if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1058                                 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1059                         } else {
1060                                 try {
1061                                         var errobj = jQuery.parseJSON( jqXHR.responseText );
1062                                         error = errobj.error + '</br>The relationship cannot be made.</p>';
1063                                 } catch(e) {
1064                                         error = jqXHR.responseText;
1065                                 }
1066                         }
1067                         $('#status').append( '<p class="error">Error: ' + error );
1068                 }
1069                 $(event.target).parent().find('.ui-button').button("enable");
1070         } );
1071   }
1072
1073   // Set up the relationship info display and deletion dialog.  
1074   $( "#delete-form" ).dialog({
1075     autoOpen: false,
1076     height: 135,
1077     width: 250,
1078     modal: false,
1079     buttons: {
1080         OK: function() { $( this ).dialog( "close" ); },
1081         "Delete all": function () { delete_relation( true ); },
1082         Delete: function() { delete_relation( false ); }
1083     },
1084     create: function(event, ui) {
1085         // TODO What is this logic doing?
1086         // This scales the buttons in the dialog and makes it look proper
1087         // Not sure how essential it is, does anything break if it's not here?
1088         var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
1089         buttonset.find( "button:contains('OK')" ).css( 'float', 'right' );
1090         // A: This makes sure that the pop up delete relation dialogue for a hovered over
1091         // relation auto closes if the user doesn't engage (mouseover) with it.
1092         var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");  
1093         dialog_aria.mouseenter( function() {
1094             if( mouseWait != null ) { clearTimeout(mouseWait) };
1095         })
1096         dialog_aria.mouseleave( function() {
1097             mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1098         })
1099     },
1100     open: function() {
1101         // Show the appropriate buttons...
1102                 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' )
1103                 // If the user can't edit, show only the OK button
1104         if( !editable ) {
1105                 buttonset.find( "button:contains('Delete')" ).hide();
1106         // If the relationship scope is local, show only OK and Delete
1107         } else if( $('#delete_relation_scope').text() === 'local' ) {
1108                 $( this ).dialog( "option", "width", 160 );
1109                 buttonset.find( "button:contains('Delete')" ).show();
1110                 buttonset.find( "button:contains('Delete all')" ).hide();
1111         // Otherwise, show all three
1112         } else {
1113                 $( this ).dialog( "option", "width", 200 );
1114                 buttonset.find( "button:contains('Delete')" ).show();
1115                 }       
1116         mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1117     },
1118     close: function() {}
1119   });
1120
1121   $( "#multipleselect-form" ).dialog({
1122     autoOpen: false,
1123     height: 150,
1124     width: 250,
1125     modal: true,
1126     buttons: {
1127         Cancel: function() { $( this ).dialog( "close" ); },
1128         Detach: function ( evt ) { 
1129             var self = $(this);
1130             $( evt.target ).button( "disable" );
1131             var form_values = $('#detach_collated_form').serialize();
1132             ncpath = getTextURL( 'duplicate' );
1133             var jqjson = $.post( ncpath, form_values, function(data) {
1134                 detach_node( data );
1135                 $(evt.target).button("enable");
1136                 self.dialog( "close" );
1137             } );
1138         }
1139     },
1140     create: function(event, ui) {
1141         var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
1142         buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
1143     },
1144     open: function() {
1145         $( this ).dialog( "option", "width", 200 );
1146         $(".ui-widget-overlay").css("background", "none");
1147         $('#multipleselect-form-status').empty();
1148         $("#dialog_overlay").show();
1149         $("#dialog_overlay").height( $("#enlargement_container").height() );
1150         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1151         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1152     },
1153     close: function() { 
1154         marquee.unselect();
1155         $("#dialog_overlay").hide();
1156     }
1157   }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
1158     if( ajaxSettings.url == getTextURL('duplicate') 
1159       && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1160       var error;
1161       if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1162         error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1163       } else {
1164         try {
1165           var errobj = jQuery.parseJSON( jqXHR.responseText );
1166           error = errobj.error + '</br>The relationship cannot be made.</p>';
1167         } catch(e) {
1168           error = jqXHR.responseText;
1169         }
1170       }
1171       $('#multipleselect-form-status').append( '<p class="error">Error: ' + error );
1172     }
1173     $(event.target).parent().find('.ui-button').button("enable");
1174   }); 
1175
1176
1177   // Helpers for relationship deletion
1178   
1179   function delete_relation( scopewide ) {
1180           form_values = $('#delete_relation_form').serialize();
1181           if( scopewide ) {
1182                 form_values += "&scopewide=true";
1183           }
1184           ncpath = getTextURL( 'relationships' );
1185           var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
1186                   $.each( data, function(item, source_target) { 
1187                           relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
1188                   });
1189                   $( "#delete-form" ).dialog( "close" );
1190           }, dataType: 'json', type: 'DELETE' });
1191   }
1192   
1193   function toggle_relation_active( node_id ) {
1194       $('#svgenlargement .relation').find( "title:contains('" + node_id +  "')" ).each( function(index) {
1195           matchid = new RegExp( "^" + node_id );
1196           if( $(this).text().match( matchid ) != null ) {
1197                   var relation_id = $(this).parent().attr('id');
1198               relation_manager.toggle_active( relation_id );
1199           };
1200       });
1201   }
1202
1203   // function for reading form dialog should go here; 
1204   // just hide the element for now if we don't have morphology
1205   if( can_morphologize ) {
1206           if( editable ) {
1207                   $('#reading_decollate_witnesses').multiselect();
1208           } else {
1209                   $('#decollation').hide();
1210           }
1211           $('#reading-form').dialog({
1212                 autoOpen: false,
1213                 // height: 400,
1214                 width: 450,
1215                 modal: true,
1216                 buttons: {
1217                         Cancel: function() {
1218                                 $( this ).dialog( "close" );
1219                         },
1220                         Update: function( evt ) {
1221                                 // Disable the button
1222                                 $(evt.target).button("disable");
1223                                 $('#reading_status').empty();
1224                                 var reading_id = $('#reading_id').val()
1225                                 form_values = {
1226                                         'id' : reading_id,
1227                                         'is_nonsense': $('#reading_is_nonsense').is(':checked'),
1228                                         'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
1229                                         'normal_form': $('#reading_normal_form').val() };
1230                                 // Add the morphology values
1231                                 $('.reading_morphology').each( function() {
1232                                         if( $(this).val() != '(Click to select)' ) {
1233                                                 var rmid = $(this).attr('id');
1234                                                 rmid = rmid.substring(8);
1235                                                 form_values[rmid] = $(this).val();
1236                                         }
1237                                 });
1238                                 // Make the JSON call
1239                                 ncpath = getReadingURL( reading_id );
1240                                 var reading_element = readingdata[reading_id];
1241                                 // $(':button :contains("Update")').attr("disabled", true);
1242                                 var jqjson = $.post( ncpath, form_values, function(data) {
1243                                         $.each( data, function(key, value) { 
1244                                                 reading_element[key] = value;
1245                                         });
1246                                         if( $('#update_workspace_button').data('locked') == false ) {
1247                                                 color_inactive( get_ellipse( reading_id ) );
1248                                         }
1249                                         $(evt.target).button("enable");
1250                                         $( "#reading-form" ).dialog( "close" );
1251                                 });
1252                                 // Re-color the node if necessary
1253                                 return false;
1254                         }
1255                 },
1256                 create: function() {
1257                         if( !editable ) {
1258                                 // Get rid of the disallowed editing UI bits
1259                                 $( this ).dialog( "option", "buttons", 
1260                                         [{ text: "OK", click: function() { $( this ).dialog( "close" ); }}] );
1261                                 $('#reading_relemmatize').hide();
1262                         }
1263                 },
1264                 open: function() {
1265                         $(".ui-widget-overlay").css("background", "none");
1266                         $('#reading_decollate_witnesses').multiselect("refresh");
1267                         $('#reading_decollate_witnesses').multiselect("uncheckAll");
1268                         $("#dialog_overlay").show();
1269                         $('#reading_status').empty();
1270                         $("#dialog_overlay").height( $("#enlargement_container").height() );
1271                         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1272                         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1273                         $("#reading-form").parent().find('.ui-button').button("enable");
1274                 },
1275                 close: function() {
1276                         $("#dialog_overlay").hide();
1277                 }
1278           }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
1279                 if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
1280                         && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1281                         var error;
1282                         if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1283                                 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1284                         } else {
1285                                 try {
1286                                         var errobj = jQuery.parseJSON( jqXHR.responseText );
1287                                         error = errobj.error + '</br>The relationship cannot be made.</p>';
1288                                 } catch(e) {
1289                                         error = jqXHR.responseText;
1290                                 }
1291                         }
1292                         $('#status').append( '<p class="error">Error: ' + error );
1293                 }
1294                 $(event.target).parent().find('.ui-button').button("enable");
1295           });
1296         } else {
1297                 $('#reading-form').hide();
1298         }
1299   
1300
1301   $('#update_workspace_button').click( function() {
1302          if( !editable ) {
1303                 return;
1304          }
1305      var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
1306      mouse_scale = svg_root_element.getScreenCTM().a;
1307      if( $(this).data('locked') == true ) {
1308          $('#svgenlargement ellipse' ).each( function( index ) {
1309              if( $(this).data( 'node_obj' ) != null ) {
1310                  $(this).data( 'node_obj' ).ungreyout_edges();
1311                  $(this).data( 'node_obj' ).set_selectable( false );
1312                  color_inactive( $(this) );
1313                  var node_id = $(this).data( 'node_obj' ).get_id();
1314                  toggle_relation_active( node_id );
1315                  $(this).data( 'node_obj', null );
1316              }
1317          })
1318          $(this).data('locked', false);
1319          $(this).css('background-position', '0px 44px');
1320      } else {
1321          var left = $('#enlargement').offset().left;
1322          var right = left + $('#enlargement').width();
1323          var tf = svg_root_element.getScreenCTM().inverse(); 
1324          var p = svg_root.createSVGPoint();
1325          p.x=left;
1326          p.y=100;
1327          var cx_min = p.matrixTransform(tf).x;
1328          p.x=right;
1329          var cx_max = p.matrixTransform(tf).x;
1330          $('#svgenlargement ellipse').each( function( index ) {
1331              var cx = parseInt( $(this).attr('cx') );
1332              if( cx > cx_min && cx < cx_max) { 
1333                  if( $(this).data( 'node_obj' ) == null ) {
1334                      $(this).data( 'node_obj', new node_obj( $(this) ) );
1335                  } else {
1336                      $(this).data( 'node_obj' ).set_selectable( true );
1337                  }
1338                  $(this).data( 'node_obj' ).greyout_edges();
1339                  var node_id = $(this).data( 'node_obj' ).get_id();
1340                  toggle_relation_active( node_id );
1341              }
1342          });
1343          $(this).css('background-position', '0px 0px');
1344          $(this).data('locked', true );
1345      }
1346   });
1347
1348   if( !editable ) {  
1349     // Hide the unused elements
1350     $('#dialog-form').hide();
1351     $('#update_workspace_button').hide();
1352   }
1353
1354   
1355   $('.helptag').popupWindow({ 
1356           height:500, 
1357           width:800, 
1358           top:50, 
1359           left:50,
1360           scrollbars:1 
1361   }); 
1362
1363   expandFillPageClients();
1364   $(window).resize(function() {
1365     expandFillPageClients();
1366   });
1367
1368 });
1369
1370
1371 function expandFillPageClients() {
1372         $('.fillPage').each(function () {
1373                 $(this).height($(window).height() - $(this).offset().top - MARGIN);
1374         });
1375 }
1376
1377 function loadSVG(svgData) {
1378         var svgElement = $('#svgenlargement');
1379
1380         $(svgElement).svg('destroy');
1381
1382         $(svgElement).svg({
1383                 loadURL: svgData,
1384                 onLoad : svgEnlargementLoaded
1385         });
1386 }
1387
1388
1389
1390 /*      OS Gadget stuff
1391
1392 function svg_select_callback(topic, data, subscriberData) {
1393         svgData = data;
1394         loadSVG(svgData);
1395 }
1396
1397 function loaded() {
1398         var prefs = new gadgets.Prefs();
1399         var preferredHeight = parseInt(prefs.getString('height'));
1400         if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
1401         expandFillPageClients();
1402 }
1403
1404 if (gadgets.util.hasFeature('pubsub-2')) {
1405         gadgets.HubSettings.onConnect = function(hum, suc, err) {
1406                 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
1407                 loaded();
1408         };
1409 }
1410 else gadgets.util.registerOnLoadHandler(loaded);
1411 */