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