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