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