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