8e9bed7a0bb2e41dfb78f45c18c2542f359c0a14
[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.ox = 0;
295   this.oy = 0;
296   this.x = 0;
297   this.y = 0;
298   this.dx = 0;
299   this.dy = 0;
300   this.node_elements = node_elements_for(self.ellipse);
301
302   if( $(self.ellipse).data( 'org_translate' ) != null ) {
303       var org_translate = $(self.ellipse).data( 'org_translate' );
304       this.ox = org_translate[0];
305       this.oy = org_translate[1]; 
306   }
307   
308   this.get_id = function() {
309     return $(self.ellipse).parent().attr('id')
310   }
311   
312   this.set_selectable = function( clickable ) {
313       if( clickable && editable ) {
314           $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
315           $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
316           $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } ); 
317           $(self.ellipse).parent().click( function(evt) { 
318               evt.stopPropagation();              
319               if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
320                 $('ellipse[fill="#9999ff"]').each( function() { 
321                     $(this).data( 'node_obj' ).set_draggable( false );
322                 } );
323               }
324               self.set_draggable( true ) 
325           });
326       } else {
327           $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
328           self.ellipse.siblings('text').attr('class', '');
329           $(self.ellipse).parent().unbind(); 
330           $('body').unbind('mousemove');
331           $('body').unbind('mouseup');
332       }
333   }
334   
335   this.set_draggable = function( draggable ) {
336     if( draggable && editable ) {
337       $(self.ellipse).attr( {stroke:'black', fill:'#9999ff'} );
338       $(self.ellipse).parent().mousedown( this.mousedown_listener );
339       $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' );
340       self.ellipse.siblings('text').attr('class', 'noselect draggable');
341     } else {
342       $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
343       self.ellipse.siblings('text').attr('class', '');
344       $(self.ellipse).parent().unbind( 'mousedown ');
345       $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } ); 
346       $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
347     }
348   }
349
350   this.mousedown_listener = function(evt) {
351     evt.stopPropagation();
352     self.x = evt.clientX;
353     self.y = evt.clientY;
354     $('body').mousemove( self.mousemove_listener );
355     $('body').mouseup( self.mouseup_listener );
356     $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
357     self.ellipse.attr( 'fill', '#6b6bb2' );
358     first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
359     if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
360   }
361
362   this.mousemove_listener = function(evt) {
363     self.dx = (evt.clientX - self.x) / mouse_scale;
364     self.dy = (evt.clientY - self.y) / mouse_scale;
365     self.move_elements();
366     evt.returnValue = false;
367     evt.preventDefault();
368     return false;
369   }
370
371   this.mouseup_listener = function(evt) {    
372     if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
373         var source_node_id = $(self.ellipse).parent().attr('id');
374         var source_node_text = self.ellipse.siblings('text').text();
375         var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
376         var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
377         $('#source_node_id').val( source_node_id );
378         $('#source_node_text').val( source_node_text );
379         $('#target_node_id').val( target_node_id );
380         $('#target_node_text').val( target_node_text );
381         $('#dialog-form').dialog( 'open' );
382     };
383     $('body').unbind('mousemove');
384     $('body').unbind('mouseup');
385     self.ellipse.attr( 'fill', '#9999ff' );
386     self.reset_elements();
387   }
388   
389   this.cpos = function() {
390     return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
391   }
392
393   this.get_g = function() {
394     return self.ellipse.parent('g');
395   }
396
397   this.enter_node = function(evt) {
398     self.ellipse.attr( 'fill', '#ffccff' );
399   }
400
401   this.leave_node = function(evt) {
402     self.ellipse.attr( 'fill', '#fff' );
403   }
404
405   this.greyout_edges = function() {
406       $.each( self.node_elements, function(index, value) {
407         value.grey_out('.edge');
408       });
409   }
410
411   this.ungreyout_edges = function() {
412       $.each( self.node_elements, function(index, value) {
413         value.un_grey_out('.edge');
414       });
415   }
416
417   this.move_elements = function() {
418     $.each( self.node_elements, function(index, value) {
419       value.move( ( self.ox + self.dx ) , ( self.oy + self.dy ) );
420     } );
421   }
422
423   this.reset_elements = function() {
424     $.each( self.node_elements, function(index, value) {
425       value.move( self.ox, self.oy );
426     } );
427   }
428
429   this.update_elements = function() {
430       self.node_elements = node_elements_for(self.ellipse);
431   }
432
433   this.get_witnesses = function() {
434       return readingdata[self.get_id()].witnesses
435   }
436   
437   this.relocate = function( dx, dy ) {
438       self.ox = self.ox + dx;
439       self.oy = self.oy + dy;
440       $(self.ellipse).data( 'org_translate', [self.ox, self.oy] );
441       self.move_elements();
442   }
443   
444   self.set_selectable( true );
445 }
446
447 function svgshape( shape_element ) {
448   this.shape = shape_element;
449   this.move = function(dx,dy) {
450       this.shape.attr( "transform", "translate(" + dx + " " + dy + ")" );
451   }
452   this.reset = function() {
453     this.shape.attr( "transform", "translate( 0, 0 )" );
454   }
455   this.grey_out = function(filter) {
456       if( this.shape.parent(filter).size() != 0 ) {
457           this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
458       }
459   }
460   this.un_grey_out = function(filter) {
461       if( this.shape.parent(filter).size() != 0 ) {
462         this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
463       }
464   }
465 }
466
467 function svgpath( path_element, svg_element ) {
468   this.svg_element = svg_element;
469   this.path = path_element;
470   this.x = this.path.x;
471   this.y = this.path.y;
472   this.move = function(dx,dy) {
473     this.path.x = this.x + dx;
474     this.path.y = this.y + dy;
475   }
476   this.reset = function() {
477     this.path.x = this.x;
478     this.path.y = this.y;
479   }
480   this.grey_out = function(filter) {
481       if( this.svg_element.parent(filter).size() != 0 ) {
482           this.svg_element.attr('stroke', '#e5e5e5');
483           this.svg_element.siblings('text').attr('fill', '#e5e5e5');
484           this.svg_element.siblings('text').attr('class', 'noselect');
485       }
486   }
487   this.un_grey_out = function(filter) {
488       if( this.svg_element.parent(filter).size() != 0 ) {
489           this.svg_element.attr('stroke', '#000000');
490           this.svg_element.siblings('text').attr('fill', '#000000');
491           this.svg_element.siblings('text').attr('class', '');
492       }
493   }
494 }
495
496 function node_elements_for( ellipse ) {
497   node_elements = get_edge_elements_for( ellipse );
498   node_elements.push( new svgshape( ellipse.siblings('text') ) );
499   node_elements.push( new svgshape( ellipse ) );
500   return node_elements;
501 }
502
503 function get_edge_elements_for( ellipse ) {
504   edge_elements = new Array();
505   node_id = ellipse.parent().attr('id');
506   edge_in_pattern = new RegExp( node_id + '$' );
507   edge_out_pattern = new RegExp( '^' + node_id + '-' );
508   $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
509     title = $(this).text();
510     if( edge_in_pattern.test(title) ) {
511         polygon = $(this).siblings('polygon');
512         if( polygon.size() > 0 ) {
513             edge_elements.push( new svgshape( polygon ) );
514         }
515         path_segments = $(this).siblings('path')[0].pathSegList;
516         edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
517     }
518     if( edge_out_pattern.test(title) ) {
519       path_segments = $(this).siblings('path')[0].pathSegList;
520       edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
521     }
522   });
523   return edge_elements;
524
525
526 function relation_factory() {
527     var self = this;
528     this.color_memo = null;
529     //TODO: colors hard coded for now
530     this.temp_color = '#FFA14F';
531     this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
532
533     this.create_temporary = function( source_node_id, target_node_id ) {
534         var relation_id = get_relation_id( source_node_id, target_node_id );
535         var relation = $( jq( relation_id ) );
536         if( relation.size() == 0 ) { 
537             draw_relation( source_node_id, target_node_id, self.temp_color );
538         } else {
539             self.color_memo = relation.children('path').attr( 'stroke' );
540             relation.children('path').attr( 'stroke', self.temp_color );
541         }
542     }
543     this.remove_temporary = function() {
544         var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
545         if( self.color_memo != null ) {
546             path_element.attr( 'stroke', self.color_memo );
547             self.color_memo = null;
548         } else {
549             var temporary = path_element.parent('g').remove();
550             temporary.empty();
551             temporary = null; 
552         }
553     }
554     this.create = function( source_node_id, target_node_id, color_index ) {
555         //TODO: Protect from (color_)index out of bound..
556         var relation_color = self.relation_colors[ color_index ];
557         var relation = draw_relation( source_node_id, target_node_id, relation_color );
558         get_node_obj( source_node_id ).update_elements();
559         get_node_obj( target_node_id ).update_elements();
560         return relation;
561     }
562     this.toggle_active = function( relation_id ) {
563         var relation = $( jq( relation_id ) );
564         var relation_path = relation.children('path');
565         if( !relation.data( 'active' ) ) {
566             relation_path.css( {'cursor':'pointer'} );
567             relation_path.mouseenter( function(event) { 
568                 outerTimer = setTimeout( function() { 
569                     timer = setTimeout( function() { 
570                         var related_nodes = get_related_nodes( relation_id );
571                         var source_node_id = related_nodes[0];
572                         var target_node_id = related_nodes[1];
573                         $('#delete_source_node_id').val( source_node_id );
574                         $('#delete_target_node_id').val( target_node_id );
575                         self.showinfo(relation); 
576                     }, 500 ) 
577                 }, 1000 );
578             });
579             relation_path.mouseleave( function(event) {
580                 clearTimeout(outerTimer); 
581                 if( timer != null ) { clearTimeout(timer); } 
582             });
583             relation.data( 'active', true );
584         } else {
585             relation_path.unbind( 'mouseenter' );
586             relation_path.unbind( 'mouseleave' );
587             relation_path.css( {'cursor':'inherit'} );
588             relation.data( 'active', false );
589         }
590     }
591     this.showinfo = function(relation) {
592         $('#delete_relation_type').text( relation.data('type') );
593         $('#delete_relation_scope').text( relation.data('scope') );
594         if( relation.data( 'note' ) ) {
595                 $('#delete_relation_note').text('note: ' + relation.data( 'note' ) );
596         }
597         var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
598         var xs = parseFloat( points[0].split(',')[0] );
599         var xe = parseFloat( points[1].split(',')[0] );
600         var ys = parseFloat( points[0].split(',')[1] );
601         var ye = parseFloat( points[3].split(',')[1] );
602         var p = svg_root.createSVGPoint();
603         p.x = xs + ((xe-xs)*1.1);
604         p.y = ye - ((ye-ys)/2);
605         var ctm = svg_root_element.getScreenCTM();
606         var nx = p.matrixTransform(ctm).x;
607         var ny = p.matrixTransform(ctm).y;
608         var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
609         $('#delete-form').dialog( 'open' );
610         dialog_aria.offset({ left: nx, top: ny });
611     }
612     this.remove = function( relation_id ) {
613         if( !editable ) {
614                 return;
615         }
616         var relation = $( jq( relation_id ) );
617         relation.remove();
618     }
619 }
620
621 // Utility function to create/return the ID of a relation link between
622 // a source and target.
623 function get_relation_id( source_id, target_id ) {
624         var idlist = [ source_id, target_id ];
625         idlist.sort();
626         return 'relation-' + idlist[0] + '-...-' + idlist[1];
627 }
628
629 function get_related_nodes( relation_id ) {
630         var srctotarg = relation_id.substr( 9 );
631         return srctotarg.split('-...-');
632 }
633
634 function draw_relation( source_id, target_id, relation_color ) {
635     var source_ellipse = get_ellipse( source_id );
636     var target_ellipse = get_ellipse( target_id );
637     var relation_id = get_relation_id( source_id, target_id );
638     var svg = $('#svgenlargement').children('svg').svg().svg('get');
639     var path = svg.createPath(); 
640     var sx = parseInt( source_ellipse.attr('cx') );
641     var rx = parseInt( source_ellipse.attr('rx') );
642     var sy = parseInt( source_ellipse.attr('cy') );
643     var ex = parseInt( target_ellipse.attr('cx') );
644     var ey = parseInt( target_ellipse.attr('cy') );
645     var relation = svg.group( $("#svgenlargement svg g"), 
646         { 'class':'relation', 'id':relation_id } );
647     svg.title( relation, source_id + '->' + target_id );
648     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});
649     var relation_element = $('#svgenlargement .relation').filter( ':last' );
650     relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
651     return relation_element;
652 }
653
654 function detach_node( readings ) {
655     
656     // This method is work in progress
657     // Todos:
658     // 1) Unproven/untested: readings.each will get us in trouble most likely for
659     //    duplicating edges in a strand that both are incoming and outgoing
660     //    like b and c in -i-> a -ii-> b -iii-> c -iv->
661     // 2) Added edges and nodes look rough and unsmoothed, what the f.?
662     //
663     
664     // add new node(s)
665     $.extend( readingdata, readings );
666     // remove from existing readings the witnesses for the new nodes/readings
667     $.each( readings, function( node_id, reading ) {
668         $.each( reading.witnesses, function( index, witness ) {
669             var witnesses = readingdata[ reading.orig_rdg ].witnesses;
670             readingdata[ reading.orig_rdg ].witnesses = $.removeFromArray( witness, witnesses );
671         } );
672     } );    
673     
674     detached_edges = [];
675     
676     // here we detach witnesses from the existing edges accoring to what's being relayed by readings
677     $.each( readings, function( node_id, reading ) {
678         var edges = edges_of( get_ellipse( reading.orig_rdg ) );
679         incoming_remaining = [];
680         outgoing_remaining = [];
681         $.each( reading.witnesses, function( index, witness ) {
682             incoming_remaining.push( witness );
683             outgoing_remaining.push( witness );
684         } );
685         $.each( edges, function( index, edge ) {
686             detached_edge = edge.detach_witnesses( reading.witnesses );
687             if( detached_edge != null ) {
688                 detached_edges.push( detached_edge );
689                 $.each( detached_edge.witnesses, function( index, witness ) {
690                     if( detached_edge.is_incoming == true ) {
691                         incoming_remaining = $.removeFromArray( witness, incoming_remaining );
692                     } else {
693                         outgoing_remaining = $.removeFromArray( witness, outgoing_remaining );
694                     }
695                 } );
696             }
697         } );
698         
699         // After detaching we still need to check if for *all* readings
700         // an edge was detached. It may be that a witness was not
701         // explicitly named on an edge but was part of a 'majority' edge
702         // in which case we need to duplicate and name that edge after those
703         // remaining witnesses.
704         if( outgoing_remaining.length > 0 ) {
705             $.each( edges, function( index, edge ) {
706                 if( edge.get_label() == 'majority' && !edge.is_incoming ) {
707                     detached_edges.push( edge.clone_for( outgoing_remaining ) );
708                 }
709             } );
710         }
711         if( incoming_remaining.length > 0 ) {
712             $.each( edges, function( index, edge ) {
713                 if( edge.get_label() == 'majority' && edge.is_incoming ) {
714                     detached_edges.push( edge.clone_for( outgoing_remaining ) );
715                 }
716             } );
717         }
718         
719         // Finally multiple selected nodes may share edges
720         var copy_array = [];
721         $.each( detached_edges, function( index, edge ) {
722             var do_copy = true;
723             $.each( copy_array, function( index, copy_edge ) {
724                 if( copy_edge.g_elem.attr( 'id' ) == edge.g_elem.attr( 'id' ) ) { do_copy = false }
725             } );
726             if( do_copy == true ) {
727                 copy_array.push( edge );
728             }
729         } );
730         detached_edges = copy_array;
731         
732         // Lots of unabstracted knowledge down here :/
733         // Clone original node/reading, rename/id it..
734         duplicate_node = get_ellipse( reading.orig_rdg ).parent().clone();
735         duplicate_node.attr( 'id', node_id );
736         duplicate_node.children( 'title' ).text( node_id );
737         duplicate_node_data = get_ellipse( reading.orig_rdg ).data( 'org_translate' );
738         if( duplicate_node_data != null ) {
739             duplicate_node.children( 'ellipse' ).data( 'org_translate', duplicate_node_data );
740         }
741         
742         // Add the node and all new edges into the graph
743         var graph_root = $('#svgenlargement svg g.graph');
744         graph_root.append( duplicate_node );
745         $.each( detached_edges, function( index, edge ) {
746             edge.g_elem.attr( 'id', ( edge.g_elem.attr( 'id' ) + "_0" ) );
747             edge_title = edge.g_elem.children( 'title' ).text();
748             edge_weight = 0.8 + ( 0.2 * edge.witnesses.length );
749             edge_title = edge_title.replace( reading.orig_rdg, node_id );
750             edge.g_elem.children( 'title' ).text( edge_title );
751             edge.g_elem.children( 'path').attr( 'stroke-width', edge_weight );
752             // Reg unabstracted knowledge: isn't it more elegant to make 
753             // it edge.append_to( graph_root )?
754             graph_root.append( edge.g_elem );
755         } );
756                 
757         // Make the detached node a real node_obj
758         var ellipse_elem = get_ellipse( node_id );
759         var new_node = new node_obj( ellipse_elem );
760         ellipse_elem.data( 'node_obj', new_node );
761
762         // Move the node somewhat up for 'dramatic effect' :-p
763         new_node.relocate( 0, -150 );        
764         
765     } );
766     
767
768 }
769
770 function Marquee() {
771     
772     var self = this;
773     
774     this.x = 0;
775     this.y = 0;
776     this.dx = 0;
777     this.dy = 0;
778     this.enlargementOffset = $('#svgenlargement').offset();
779     this.svg_rect = $('#svgenlargement svg').svg('get');
780
781     this.show = function( event ) {
782         self.x = event.clientX;
783         self.y = event.clientY;
784         p = svg_root.createSVGPoint();
785         p.x = event.clientX - self.enlargementOffset.left;
786         p.y = event.clientY - self.enlargementOffset.top;
787         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' } );
788     };
789
790     this.expand = function( event ) {
791         self.dx = (event.clientX - self.x);
792         self.dy = (event.clientY - self.y);
793         var rect = $('#marquee');
794         if( rect.length != 0 ) {            
795             var rect_w =  Math.abs( self.dx );
796             var rect_h =  Math.abs( self.dy );
797             var rect_x = self.x - self.enlargementOffset.left;
798             var rect_y = self.y - self.enlargementOffset.top;
799             if( self.dx < 0 ) { rect_x = rect_x - rect_w }
800             if( self.dy < 0 ) { rect_y = rect_y - rect_h }
801             rect.attr("x", rect_x).attr("y", rect_y).attr("width", rect_w).attr("height", rect_h);
802         }
803     };
804     
805     this.select = function() {
806         var rect = $('#marquee');
807         if( rect.length != 0 ) {
808             //unselect any possible selected first
809             //TODO: unless SHIFT?
810             if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
811               $('ellipse[fill="#9999ff"]').each( function() { 
812                   $(this).data( 'node_obj' ).set_draggable( false );
813               } );
814             }
815             //compute dimension of marquee
816             var left = $('#marquee').offset().left;
817             var top = $('#marquee').offset().top;
818             var right = left + parseInt( $('#marquee').attr( 'width' ) );
819             var bottom = top + parseInt( $('#marquee').attr( 'height' ) );
820             var tf = svg_root_element.getScreenCTM().inverse(); 
821             var p = svg_root.createSVGPoint();
822             p.x=left;
823             p.y=top;
824             var cx_min = p.matrixTransform(tf).x;
825             var cy_min = p.matrixTransform(tf).y;
826             p.x=right;
827             p.y=bottom;
828             var cx_max = p.matrixTransform(tf).x;
829             var cy_max = p.matrixTransform(tf).y;
830             //select any node with its center inside the marquee
831             var readings = [];
832             //also merge witness sets from nodes
833             var witnesses = [];
834             $('#svgenlargement ellipse').each( function( index ) {
835                 var cx = parseInt( $(this).attr('cx') );
836                 var cy = parseInt( $(this).attr('cy') );
837                 var org_translate = $(this).data( 'org_translate' );
838                 if( org_translate != null ) {
839                     cx = cx + org_translate[0];
840                     cy = cy + org_translate[1];
841                 }
842                 if( cx > cx_min && cx < cx_max) {
843                     if( cy > cy_min && cy < cy_max) {
844                         // we actually heve no real 'selected' state for nodes, except coloring
845                         $(this).attr( 'fill', '#9999ff' );
846                         // Take note of the selected reading(s) and applicable witness(es)
847                         // so we can populate the multipleselect-form 
848                         readings.push( $(this).parent().attr('id') ); 
849                         var this_witnesses = $(this).data( 'node_obj' ).get_witnesses();
850                         witnesses = arrayUnique( witnesses.concat( this_witnesses ) );
851                     }
852                 }
853             });
854             if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
855                 //add intersection of witnesses sets to the multi select form and open it
856                 $('#detach_collated_form').empty();
857                 $.each( readings, function( index, value ) {
858                   $('#detach_collated_form').append( $('<input>').attr(
859                     "type", "hidden").attr("name", "readings[]").attr(
860                     "value", value ) );
861                 });
862                                 $.each( witnesses, function( index, value ) {
863                     $('#detach_collated_form').append( 
864                       '<input type="checkbox" name="witnesses[]" value="' + value 
865                       + '">' + value + '<br>' ); 
866                 });
867                 $('#multiple_selected_readings').attr('value', readings.join(',') ); 
868                 $('#multipleselect-form').dialog( 'open' );
869             }
870             self.svg_rect.remove( $('#marquee') );
871         }
872     };
873     
874     this.unselect = function() {
875         $('ellipse[fill="#9999ff"]').attr( 'fill', '#fff' );
876     }
877      
878 }
879
880
881 $(document).ready(function () {
882     
883   timer = null;
884   relation_manager = new relation_factory();
885   
886   $('#update_workspace_button').data('locked', false);
887                 
888   $('#enlargement').mousedown(function (event) {
889     $(this)
890         .data('down', true)
891         .data('x', event.clientX)
892         .data('y', event.clientY)
893         .data('scrollLeft', this.scrollLeft)
894     stateTf = svg_root_element.getCTM().inverse();
895     var p = svg_root.createSVGPoint();
896     p.x = event.clientX;
897     p.y = event.clientY;
898     stateOrigin = p.matrixTransform(stateTf);
899
900     // Activate marquee if in interaction mode
901     if( $('#update_workspace_button').data('locked') == true ) { marquee.show( event ) };
902         
903     event.returnValue = false;
904     event.preventDefault();
905     return false;
906   }).mouseup(function (event) {
907     marquee.select(); 
908     $(this).data('down', false);
909   }).mousemove(function (event) {
910     if( timer != null ) { clearTimeout(timer); } 
911     if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
912         var p = svg_root.createSVGPoint();
913         p.x = event.clientX;
914         p.y = event.clientY;
915         p = p.matrixTransform(stateTf);
916         var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
917         var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
918         svg_root_element.setAttribute("transform", s);
919     }
920     marquee.expand( event ); 
921     event.returnValue = false;
922     event.preventDefault();
923   }).mousewheel(function (event, delta) {
924     event.returnValue = false;
925     event.preventDefault();
926     if ( $('#update_workspace_button').data('locked') == false ) {
927         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
928         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
929         if( delta < -9 ) { delta = -9 }; 
930         var z = 1 + delta/10;
931         z = delta > 0 ? 1 : -1;
932         var g = svg_root_element;
933         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
934             var root = svg_root;
935             var p = root.createSVGPoint();
936             p.x = event.originalEvent.clientX;
937             p.y = event.originalEvent.clientY;
938             p = p.matrixTransform(g.getCTM().inverse());
939             var scaleLevel = 1+(z/20);
940             var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
941             var matrix = g.getCTM().multiply(k);
942             var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
943             g.setAttribute("transform", s);
944         }
945     }
946   }).css({
947     'overflow' : 'hidden',
948     'cursor' : '-moz-grab'
949   });
950   
951   
952   if( editable ) {
953         $( "#dialog-form" ).dialog({
954         autoOpen: false,
955         height: 270,
956         width: 290,
957         modal: true,
958         buttons: {
959           "Ok": function( evt ) {
960                 $(evt.target).button("disable");
961                 $('#status').empty();
962                 form_values = $('#collapse_node_form').serialize();
963                 ncpath = getTextURL( 'relationships' );
964                 var jqjson = $.post( ncpath, form_values, function(data) {
965                         $.each( data, function(item, source_target) { 
966                                 var source_found = get_ellipse( source_target[0] );
967                                 var target_found = get_ellipse( source_target[1] );
968                                 var relation_found = $.inArray( source_target[2], $('#keymap').data('relations') );
969                                 if( source_found.size() && target_found.size() && relation_found > -1 ) {
970                                         var relation = relation_manager.create( source_target[0], source_target[1], relation_found );
971                                         relation.data( 'type', source_target[2]  );
972                                         relation.data( 'scope', $('#scope :selected').text()  );
973                                         relation.data( 'note', $('#note').val()  );
974                                         relation_manager.toggle_active( relation.attr('id') );
975                                 }
976                                 $(evt.target).button("enable");
977                    });
978                         $( "#dialog-form" ).dialog( "close" );
979                 }, 'json' );
980           },
981           Cancel: function() {
982                   $( this ).dialog( "close" );
983           }
984         },
985         create: function(event, ui) { 
986                 $(this).data( 'relation_drawn', false );
987                 $('#rel_type').data( 'changed_after_open', false );
988                 $.each( relationship_types, function(index, typedef) {   
989                          $('#rel_type').append( $('<option />').attr( "value", typedef.name ).text(typedef.name) ); 
990                 });
991                 $.each( relationship_scopes, function(index, value) {   
992                          $('#scope').append( $('<option />').attr( "value", value ).text(value) ); 
993                 });
994                 // Handler to clear the annotation field, the first time the relationship is
995                 // changed after opening the form.
996                 $('#rel_type').change( function () {
997                         if( !$(this).data( 'changed_after_open' ) ) {
998                                 $('#note').val('');
999                         }
1000                         $(this).data( 'changed_after_open', true );
1001                 });
1002         },
1003         open: function() {
1004                 relation_manager.create_temporary( $('#source_node_id').val(), $('#target_node_id').val() );
1005                 $(".ui-widget-overlay").css("background", "none");
1006                 $("#dialog_overlay").show();
1007                 $("#dialog_overlay").height( $("#enlargement_container").height() );
1008                 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1009                 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1010                 $('#rel_type').data( 'changed_after_open', false );
1011         },
1012         close: function() {
1013                 relation_manager.remove_temporary();
1014                 $( '#status' ).empty();
1015                 $("#dialog_overlay").hide();
1016         }
1017         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
1018                 if( ajaxSettings.url == getTextURL('relationships') 
1019                         && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1020                         var error;
1021                         if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1022                                 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1023                         } else {
1024                                 try {
1025                                         var errobj = jQuery.parseJSON( jqXHR.responseText );
1026                                         error = errobj.error + '</br>The relationship cannot be made.</p>';
1027                                 } catch(e) {
1028                                         error = jqXHR.responseText;
1029                                 }
1030                         }
1031                         $('#status').append( '<p class="error">Error: ' + error );
1032                 }
1033                 $(event.target).parent().find('.ui-button').button("enable");
1034         } );
1035   }
1036
1037   var deletion_buttonset = {
1038         cancel: function() { $( this ).dialog( "close" ); },
1039         global: function () { delete_relation( true ); },
1040         delete: function() { delete_relation( false ); }
1041   };    
1042   
1043   $( "#delete-form" ).dialog({
1044     autoOpen: false,
1045     height: 135,
1046     width: 250,
1047     modal: false,
1048     create: function(event, ui) {
1049         // TODO What is this logic doing?
1050         // This scales the buttons in the dialog and makes it look proper
1051         // Not sure how essential it is, does anything break if it's not here?
1052         var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
1053         buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
1054         // A: This makes sure that the pop up delete relation dialogue for a hovered over
1055         // relation auto closes if the user doesn't engage (mouseover) with it.
1056         var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");  
1057         dialog_aria.mouseenter( function() {
1058             if( mouseWait != null ) { clearTimeout(mouseWait) };
1059         })
1060         dialog_aria.mouseleave( function() {
1061             mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1062         })
1063     },
1064     open: function() {
1065         if( !editable ) {
1066                 $( this ).dialog( "option", "buttons", 
1067                         [{ text: "OK", click: deletion_buttonset['cancel'] }] );
1068         } else if( $('#delete_relation_scope').text() === 'local' ) {
1069                 $( this ).dialog( "option", "width", 160 );
1070                 $( this ).dialog( "option", "buttons",
1071                         [{ text: "Delete", click: deletion_buttonset['delete'] },
1072                          { text: "Cancel", click: deletion_buttonset['cancel'] }] );
1073         } else {
1074                 $( this ).dialog( "option", "width", 200 );
1075                 $( this ).dialog( "option", "buttons",
1076                         [{ text: "Delete", click: deletion_buttonset['delete'] },
1077                          { text: "Delete all", click: deletion_buttonset['global'] },
1078                          { text: "Cancel", click: deletion_buttonset['cancel'] }] );
1079                 }       
1080                         
1081         mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1082     },
1083     close: function() {}
1084   });
1085
1086   $( "#multipleselect-form" ).dialog({
1087     autoOpen: false,
1088     height: 150,
1089     width: 250,
1090     modal: true,
1091     buttons: {
1092         Cancel: function() { $( this ).dialog( "close" ); },
1093         Detach: function ( evt ) { 
1094             var self = $(this);
1095             $( evt.target ).button( "disable" );
1096             var form_values = $('#detach_collated_form').serialize();
1097             ncpath = getTextURL( 'duplicate' );
1098             var jqjson = $.post( ncpath, form_values, function(data) {
1099                 detach_node( data );
1100                 $(evt.target).button("enable");
1101                 self.dialog( "close" );
1102             } );
1103         }
1104     },
1105     create: function(event, ui) {
1106         var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
1107         buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
1108     },
1109     open: function() {
1110         $( this ).dialog( "option", "width", 200 );
1111         $(".ui-widget-overlay").css("background", "none");
1112         $('#multipleselect-form-status').empty();
1113         $("#dialog_overlay").show();
1114         $("#dialog_overlay").height( $("#enlargement_container").height() );
1115         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1116         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1117     },
1118     close: function() { 
1119         marquee.unselect();
1120         $("#dialog_overlay").hide();
1121     }
1122   }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
1123     if( ajaxSettings.url == getTextURL('duplicate') 
1124       && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1125       var error;
1126       if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1127         error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1128       } else {
1129         try {
1130           var errobj = jQuery.parseJSON( jqXHR.responseText );
1131           error = errobj.error + '</br>The relationship cannot be made.</p>';
1132         } catch(e) {
1133           error = jqXHR.responseText;
1134         }
1135       }
1136       $('#multipleselect-form-status').append( '<p class="error">Error: ' + error );
1137     }
1138     $(event.target).parent().find('.ui-button').button("enable");
1139   }); 
1140
1141
1142   // Helpers for relationship deletion
1143   
1144   function delete_relation( scopewide ) {
1145           form_values = $('#delete_relation_form').serialize();
1146           if( scopewide ) {
1147                 form_values += "&scopewide=true";
1148           }
1149           ncpath = getTextURL( 'relationships' );
1150           var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
1151                   $.each( data, function(item, source_target) { 
1152                           relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
1153                   });
1154                   $( "#delete-form" ).dialog( "close" );
1155           }, dataType: 'json', type: 'DELETE' });
1156   }
1157   
1158   function toggle_relation_active( node_id ) {
1159       $('#svgenlargement .relation').find( "title:contains('" + node_id +  "')" ).each( function(index) {
1160           matchid = new RegExp( "^" + node_id );
1161           if( $(this).text().match( matchid ) != null ) {
1162                   var relation_id = $(this).parent().attr('id');
1163               relation_manager.toggle_active( relation_id );
1164           };
1165       });
1166   }
1167
1168   // function for reading form dialog should go here; 
1169   // just hide the element for now if we don't have morphology
1170   if( can_morphologize ) {
1171           if( editable ) {
1172                   $('#reading_decollate_witnesses').multiselect();
1173           } else {
1174                   $('#decollation').hide();
1175           }
1176           $('#reading-form').dialog({
1177                 autoOpen: false,
1178                 // height: 400,
1179                 width: 450,
1180                 modal: true,
1181                 buttons: {
1182                         Cancel: function() {
1183                                 $( this ).dialog( "close" );
1184                         },
1185                         Update: function( evt ) {
1186                                 // Disable the button
1187                                 $(evt.target).button("disable");
1188                                 $('#reading_status').empty();
1189                                 var reading_id = $('#reading_id').val()
1190                                 form_values = {
1191                                         'id' : reading_id,
1192                                         'is_nonsense': $('#reading_is_nonsense').is(':checked'),
1193                                         'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
1194                                         'normal_form': $('#reading_normal_form').val() };
1195                                 // Add the morphology values
1196                                 $('.reading_morphology').each( function() {
1197                                         if( $(this).val() != '(Click to select)' ) {
1198                                                 var rmid = $(this).attr('id');
1199                                                 rmid = rmid.substring(8);
1200                                                 form_values[rmid] = $(this).val();
1201                                         }
1202                                 });
1203                                 // Make the JSON call
1204                                 ncpath = getReadingURL( reading_id );
1205                                 var reading_element = readingdata[reading_id];
1206                                 // $(':button :contains("Update")').attr("disabled", true);
1207                                 var jqjson = $.post( ncpath, form_values, function(data) {
1208                                         $.each( data, function(key, value) { 
1209                                                 reading_element[key] = value;
1210                                         });
1211                                         if( $('#update_workspace_button').data('locked') == false ) {
1212                                                 color_inactive( get_ellipse( reading_id ) );
1213                                         }
1214                                         $(evt.target).button("enable");
1215                                         $( "#reading-form" ).dialog( "close" );
1216                                 });
1217                                 // Re-color the node if necessary
1218                                 return false;
1219                         }
1220                 },
1221                 create: function() {
1222                         if( !editable ) {
1223                                 // Get rid of the disallowed editing UI bits
1224                                 $( this ).dialog( "option", "buttons", 
1225                                         [{ text: "OK", click: function() { $( this ).dialog( "close" ); }}] );
1226                                 $('#reading_relemmatize').hide();
1227                         }
1228                 },
1229                 open: function() {
1230                         $(".ui-widget-overlay").css("background", "none");
1231                         $('#reading_decollate_witnesses').multiselect("refresh");
1232                         $('#reading_decollate_witnesses').multiselect("uncheckAll");
1233                         $("#dialog_overlay").show();
1234                         $('#reading_status').empty();
1235                         $("#dialog_overlay").height( $("#enlargement_container").height() );
1236                         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1237                         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1238                         $("#reading-form").parent().find('.ui-button').button("enable");
1239                 },
1240                 close: function() {
1241                         $("#dialog_overlay").hide();
1242                 }
1243           }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
1244                 if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
1245                         && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1246                         var error;
1247                         if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1248                                 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1249                         } else {
1250                                 try {
1251                                         var errobj = jQuery.parseJSON( jqXHR.responseText );
1252                                         error = errobj.error + '</br>The relationship cannot be made.</p>';
1253                                 } catch(e) {
1254                                         error = jqXHR.responseText;
1255                                 }
1256                         }
1257                         $('#status').append( '<p class="error">Error: ' + error );
1258                 }
1259                 $(event.target).parent().find('.ui-button').button("enable");
1260           });
1261         } else {
1262                 $('#reading-form').hide();
1263         }
1264   
1265
1266   $('#update_workspace_button').click( function() {
1267          if( !editable ) {
1268                 return;
1269          }
1270      var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
1271      mouse_scale = svg_root_element.getScreenCTM().a;
1272      if( $(this).data('locked') == true ) {
1273          $('#svgenlargement ellipse' ).each( function( index ) {
1274              if( $(this).data( 'node_obj' ) != null ) {
1275                  $(this).data( 'node_obj' ).ungreyout_edges();
1276                  $(this).data( 'node_obj' ).set_selectable( false );
1277                  color_inactive( $(this) );
1278                  var node_id = $(this).data( 'node_obj' ).get_id();
1279                  toggle_relation_active( node_id );
1280                  $(this).data( 'node_obj', null );
1281              }
1282          })
1283          $(this).data('locked', false);
1284          $(this).css('background-position', '0px 44px');
1285      } else {
1286          var left = $('#enlargement').offset().left;
1287          var right = left + $('#enlargement').width();
1288          var tf = svg_root_element.getScreenCTM().inverse(); 
1289          var p = svg_root.createSVGPoint();
1290          p.x=left;
1291          p.y=100;
1292          var cx_min = p.matrixTransform(tf).x;
1293          p.x=right;
1294          var cx_max = p.matrixTransform(tf).x;
1295          $('#svgenlargement ellipse').each( function( index ) {
1296              var cx = parseInt( $(this).attr('cx') );
1297              if( cx > cx_min && cx < cx_max) { 
1298                  if( $(this).data( 'node_obj' ) == null ) {
1299                      $(this).data( 'node_obj', new node_obj( $(this) ) );
1300                  } else {
1301                      $(this).data( 'node_obj' ).set_selectable( true );
1302                  }
1303                  $(this).data( 'node_obj' ).greyout_edges();
1304                  var node_id = $(this).data( 'node_obj' ).get_id();
1305                  toggle_relation_active( node_id );
1306              }
1307          });
1308          $(this).css('background-position', '0px 0px');
1309          $(this).data('locked', true );
1310      }
1311   });
1312
1313   if( !editable ) {  
1314     // Hide the unused elements
1315     $('#dialog-form').hide();
1316     $('#update_workspace_button').hide();
1317   }
1318
1319   
1320   $('.helptag').popupWindow({ 
1321           height:500, 
1322           width:800, 
1323           top:50, 
1324           left:50,
1325           scrollbars:1 
1326   }); 
1327
1328   expandFillPageClients();
1329   $(window).resize(function() {
1330     expandFillPageClients();
1331   });
1332
1333 });
1334
1335
1336 function expandFillPageClients() {
1337         $('.fillPage').each(function () {
1338                 $(this).height($(window).height() - $(this).offset().top - MARGIN);
1339         });
1340 }
1341
1342 function loadSVG(svgData) {
1343         var svgElement = $('#svgenlargement');
1344
1345         $(svgElement).svg('destroy');
1346
1347         $(svgElement).svg({
1348                 loadURL: svgData,
1349                 onLoad : svgEnlargementLoaded
1350         });
1351 }
1352
1353
1354
1355 /*      OS Gadget stuff
1356
1357 function svg_select_callback(topic, data, subscriberData) {
1358         svgData = data;
1359         loadSVG(svgData);
1360 }
1361
1362 function loaded() {
1363         var prefs = new gadgets.Prefs();
1364         var preferredHeight = parseInt(prefs.getString('height'));
1365         if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
1366         expandFillPageClients();
1367 }
1368
1369 if (gadgets.util.hasFeature('pubsub-2')) {
1370         gadgets.HubSettings.onConnect = function(hum, suc, err) {
1371                 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
1372                 loaded();
1373         };
1374 }
1375 else gadgets.util.registerOnLoadHandler(loaded);
1376 */