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