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