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