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