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