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