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