re-merge the full and readonly versions of relationship.js
[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
206 function add_relations( callback_fn ) {
207         // Add the relationship types to the keymap list
208         $.each( relationship_types, function(index, typedef) {   
209                  li_elm = $('<li class="key">').css( "border-color", 
210                         relation_manager.relation_colors[index] ).text(typedef.name);
211                  li_elm.append( $('<div>').attr('class', 'key_tip_container').append(
212                         $('<div>').attr('class', 'key_tip').text(typedef.description) ) );
213                  $('#keymaplist').append( li_elm ); 
214         });
215         // Now fetch the relationships themselves and add them to the graph
216         var rel_types = $.map( relationship_types, function(t) { return t.name });
217         // Save this list of names to the outer element data so that the relationship
218         // factory can access it
219         $('#keymap').data('relations', rel_types);
220         var textrelpath = getTextURL( 'relationships' );
221         $.getJSON( textrelpath, function(data) {
222                 $.each(data, function( index, rel_info ) {
223                         var type_index = $.inArray(rel_info.type, rel_types);
224                         var source_found = get_ellipse( rel_info.source );
225                         var target_found = get_ellipse( rel_info.target );
226                         if( type_index != -1 && source_found.size() && target_found.size() ) {
227                                 var relation = relation_manager.create( rel_info.source, rel_info.target, type_index );
228                                 relation.data( 'type', rel_info.type );
229                                 relation.data( 'scope', rel_info.scope );
230                                 relation.data( 'note', rel_info.note );
231                                 if( editable ) {
232                                         var node_obj = get_node_obj(rel_info.source);
233                                         node_obj.set_draggable( false );
234                                         node_obj.ellipse.data( 'node_obj', null );
235                                         node_obj = get_node_obj(rel_info.target);
236                                         node_obj.set_draggable( false );
237                                         node_obj.ellipse.data( 'node_obj', null );
238                                 }
239                         }
240                 });
241                 callback_fn.call();
242         });
243 }
244
245 function get_ellipse( node_id ) {
246         return $( jq( node_id ) + ' ellipse');
247 }
248
249 function get_node_obj( node_id ) {
250     var node_ellipse = get_ellipse( node_id );
251     if( node_ellipse.data( 'node_obj' ) == null ) {
252         node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
253     };
254     return node_ellipse.data( 'node_obj' );
255 }
256
257 function node_obj(ellipse) {
258   this.ellipse = ellipse;
259   var self = this;
260   
261   this.x = 0;
262   this.y = 0;
263   this.dx = 0;
264   this.dy = 0;
265   this.node_elements = node_elements_for(self.ellipse);
266
267   this.get_id = function() {
268     return $(self.ellipse).parent().attr('id')
269   }
270   
271   this.set_draggable = function( draggable ) {
272     if( draggable && editable ) {
273       $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
274       $(self.ellipse).parent().mousedown( this.mousedown_listener );
275       $(self.ellipse).parent().hover( this.enter_node, this.leave_node ); 
276       self.ellipse.siblings('text').attr('class', 'noselect draggable');
277     } else {
278       self.ellipse.siblings('text').attr('class', '');
279           $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' ).unbind( 'mousedown' );     
280       color_inactive( self.ellipse );
281     }
282   }
283
284   this.mousedown_listener = function(evt) {
285     evt.stopPropagation();
286     self.x = evt.clientX;
287     self.y = evt.clientY;
288     $('body').mousemove( self.mousemove_listener );
289     $('body').mouseup( self.mouseup_listener );
290     $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
291     self.ellipse.attr( 'fill', '#ff66ff' );
292     first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
293     if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
294   }
295
296   this.mousemove_listener = function(evt) {
297     self.dx = (evt.clientX - self.x) / mouse_scale;
298     self.dy = (evt.clientY - self.y) / mouse_scale;
299     self.move_elements();
300     evt.returnValue = false;
301     evt.preventDefault();
302     return false;
303   }
304
305   this.mouseup_listener = function(evt) {    
306     if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
307         var source_node_id = $(self.ellipse).parent().attr('id');
308         var source_node_text = self.ellipse.siblings('text').text();
309         var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
310         var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
311         $('#source_node_id').val( source_node_id );
312         $('#source_node_text').val( source_node_text );
313         $('#target_node_id').val( target_node_id );
314         $('#target_node_text').val( target_node_text );
315         $('#dialog-form').dialog( 'open' );
316     };
317     $('body').unbind('mousemove');
318     $('body').unbind('mouseup');
319     self.ellipse.attr( 'fill', '#fff' );
320     $(self.ellipse).parent().hover( self.enter_node, self.leave_node );
321     self.reset_elements();
322   }
323   
324   this.cpos = function() {
325     return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
326   }
327
328   this.get_g = function() {
329     return self.ellipse.parent('g');
330   }
331
332   this.enter_node = function(evt) {
333     self.ellipse.attr( 'fill', '#ffccff' );
334   }
335
336   this.leave_node = function(evt) {
337     self.ellipse.attr( 'fill', '#fff' );
338   }
339
340   this.greyout_edges = function() {
341       $.each( self.node_elements, function(index, value) {
342         value.grey_out('.edge');
343       });
344   }
345
346   this.ungreyout_edges = function() {
347       $.each( self.node_elements, function(index, value) {
348         value.un_grey_out('.edge');
349       });
350   }
351
352   this.move_elements = function() {
353     $.each( self.node_elements, function(index, value) {
354       value.move(self.dx,self.dy);
355     });
356   }
357
358   this.reset_elements = function() {
359     $.each( self.node_elements, function(index, value) {
360       value.reset();
361     });
362   }
363
364   this.update_elements = function() {
365       self.node_elements = node_elements_for(self.ellipse);
366   }
367
368   self.set_draggable( true );
369 }
370
371 function svgshape( shape_element ) {
372   this.shape = shape_element;
373   this.move = function(dx,dy) {
374     this.shape.attr( "transform", "translate(" + dx + " " + dy + ")" );
375   }
376   this.reset = function() {
377     this.shape.attr( "transform", "translate( 0, 0 )" );
378   }
379   this.grey_out = function(filter) {
380       if( this.shape.parent(filter).size() != 0 ) {
381           this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
382       }
383   }
384   this.un_grey_out = function(filter) {
385       if( this.shape.parent(filter).size() != 0 ) {
386         this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
387       }
388   }
389 }
390
391 function svgpath( path_element, svg_element ) {
392   this.svg_element = svg_element;
393   this.path = path_element;
394   this.x = this.path.x;
395   this.y = this.path.y;
396   this.move = function(dx,dy) {
397     this.path.x = this.x + dx;
398     this.path.y = this.y + dy;
399   }
400   this.reset = function() {
401     this.path.x = this.x;
402     this.path.y = this.y;
403   }
404   this.grey_out = function(filter) {
405       if( this.svg_element.parent(filter).size() != 0 ) {
406           this.svg_element.attr('stroke', '#e5e5e5');
407           this.svg_element.siblings('text').attr('fill', '#e5e5e5');
408           this.svg_element.siblings('text').attr('class', 'noselect');
409       }
410   }
411   this.un_grey_out = function(filter) {
412       if( this.svg_element.parent(filter).size() != 0 ) {
413           this.svg_element.attr('stroke', '#000000');
414           this.svg_element.siblings('text').attr('fill', '#000000');
415           this.svg_element.siblings('text').attr('class', '');
416       }
417   }
418 }
419
420 function node_elements_for( ellipse ) {
421   node_elements = get_edge_elements_for( ellipse );
422   node_elements.push( new svgshape( ellipse.siblings('text') ) );
423   node_elements.push( new svgshape( ellipse ) );
424   return node_elements;
425 }
426
427 function get_edge_elements_for( ellipse ) {
428   edge_elements = new Array();
429   node_id = ellipse.parent().attr('id');
430   edge_in_pattern = new RegExp( node_id + '$' );
431   edge_out_pattern = new RegExp( '^' + node_id );
432   $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
433     title = $(this).text();
434     if( edge_in_pattern.test(title) ) {
435         polygon = $(this).siblings('polygon');
436         if( polygon.size() > 0 ) {
437             edge_elements.push( new svgshape( polygon ) );
438         }
439         path_segments = $(this).siblings('path')[0].pathSegList;
440         edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
441     }
442     if( edge_out_pattern.test(title) ) {
443       path_segments = $(this).siblings('path')[0].pathSegList;
444       edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
445     }
446   });
447   return edge_elements;
448
449
450 function relation_factory() {
451     var self = this;
452     this.color_memo = null;
453     //TODO: colors hard coded for now
454     this.temp_color = '#FFA14F';
455     this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
456
457     this.create_temporary = function( source_node_id, target_node_id ) {
458         var relation_id = get_relation_id( source_node_id, target_node_id );
459         var relation = $( jq( relation_id ) );
460         if( relation.size() == 0 ) { 
461             draw_relation( source_node_id, target_node_id, self.temp_color );
462         } else {
463             self.color_memo = relation.children('path').attr( 'stroke' );
464             relation.children('path').attr( 'stroke', self.temp_color );
465         }
466     }
467     this.remove_temporary = function() {
468         var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
469         if( self.color_memo != null ) {
470             path_element.attr( 'stroke', self.color_memo );
471             self.color_memo = null;
472         } else {
473             var temporary = path_element.parent('g').remove();
474             temporary.empty();
475             temporary = null; 
476         }
477     }
478     this.create = function( source_node_id, target_node_id, color_index ) {
479         //TODO: Protect from (color_)index out of bound..
480         var relation_color = self.relation_colors[ color_index ];
481         var relation = draw_relation( source_node_id, target_node_id, relation_color );
482         get_node_obj( source_node_id ).update_elements();
483         get_node_obj( target_node_id ).update_elements();
484         return relation;
485     }
486     this.toggle_active = function( relation_id ) {
487         var relation = $( jq( relation_id ) );
488         var relation_path = relation.children('path');
489         if( !relation.data( 'active' ) ) {
490             relation_path.css( {'cursor':'pointer'} );
491             relation_path.mouseenter( function(event) { 
492                 outerTimer = setTimeout( function() { 
493                     timer = setTimeout( function() { 
494                         var related_nodes = get_related_nodes( relation_id );
495                         var source_node_id = related_nodes[0];
496                         var target_node_id = related_nodes[1];
497                         $('#delete_source_node_id').val( source_node_id );
498                         $('#delete_target_node_id').val( target_node_id );
499                         self.showinfo(relation); 
500                     }, 500 ) 
501                 }, 1000 );
502             });
503             relation_path.mouseleave( function(event) {
504                 clearTimeout(outerTimer); 
505                 if( timer != null ) { clearTimeout(timer); } 
506             });
507             relation.data( 'active', true );
508         } else {
509             relation_path.unbind( 'mouseenter' );
510             relation_path.unbind( 'mouseleave' );
511             relation_path.css( {'cursor':'inherit'} );
512             relation.data( 'active', false );
513         }
514     }
515     this.showinfo = function(relation) {
516         var htmlstr = 'type: ' + relation.data( 'type' ) + '<br/>scope: ' + relation.data( 'scope' );
517         if( relation.data( 'note' ) ) {
518                 htmlstr = htmlstr + '<br/>note: ' + relation.data( 'note' );
519         }
520         $('#delete-form-text').html( htmlstr );
521         var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
522         var xs = parseFloat( points[0].split(',')[0] );
523         var xe = parseFloat( points[1].split(',')[0] );
524         var ys = parseFloat( points[0].split(',')[1] );
525         var ye = parseFloat( points[3].split(',')[1] );
526         var p = svg_root.createSVGPoint();
527         p.x = xs + ((xe-xs)*1.1);
528         p.y = ye - ((ye-ys)/2);
529         var ctm = svg_root_element.getScreenCTM();
530         var nx = p.matrixTransform(ctm).x;
531         var ny = p.matrixTransform(ctm).y;
532         var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
533         $('#delete-form').dialog( 'open' );
534         dialog_aria.offset({ left: nx, top: ny });
535     }
536     this.remove = function( relation_id ) {
537         if( !editable ) {
538                 return;
539         }
540         var relation = $( jq( relation_id ) );
541         relation.remove();
542     }
543 }
544
545 // Utility function to create/return the ID of a relation link between
546 // a source and target.
547 function get_relation_id( source_id, target_id ) {
548         var idlist = [ source_id, target_id ];
549         idlist.sort();
550         return 'relation-' + idlist[0] + '-...-' + idlist[1];
551 }
552
553 function get_related_nodes( relation_id ) {
554         var srctotarg = relation_id.substr( 9 );
555         return srctotarg.split('-...-');
556 }
557
558 function draw_relation( source_id, target_id, relation_color ) {
559     var source_ellipse = get_ellipse( source_id );
560     var target_ellipse = get_ellipse( target_id );
561     var relation_id = get_relation_id( source_id, target_id );
562     var svg = $('#svgenlargement').children('svg').svg().svg('get');
563     var path = svg.createPath(); 
564     var sx = parseInt( source_ellipse.attr('cx') );
565     var rx = parseInt( source_ellipse.attr('rx') );
566     var sy = parseInt( source_ellipse.attr('cy') );
567     var ex = parseInt( target_ellipse.attr('cx') );
568     var ey = parseInt( target_ellipse.attr('cy') );
569     var relation = svg.group( $("#svgenlargement svg g"), 
570         { 'class':'relation', 'id':relation_id } );
571     svg.title( relation, source_id + '->' + target_id );
572     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});
573     var relation_element = $('#svgenlargement .relation').filter( ':last' );
574     relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
575     return relation_element;
576 }
577
578
579 $(document).ready(function () {
580     
581   timer = null;
582   relation_manager = new relation_factory();
583   $('#update_workspace_button').data('locked', false);
584   
585   $('#enlargement').mousedown(function (event) {
586     $(this)
587         .data('down', true)
588         .data('x', event.clientX)
589         .data('y', event.clientY)
590         .data('scrollLeft', this.scrollLeft)
591         stateTf = svg_root_element.getCTM().inverse();
592         var p = svg_root.createSVGPoint();
593         p.x = event.clientX;
594         p.y = event.clientY;
595         stateOrigin = p.matrixTransform(stateTf);
596         event.returnValue = false;
597         event.preventDefault();
598         return false;
599   }).mouseup(function (event) {
600         $(this).data('down', false);
601   }).mousemove(function (event) {
602     if( timer != null ) { clearTimeout(timer); } 
603     if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
604         var p = svg_root.createSVGPoint();
605         p.x = event.clientX;
606         p.y = event.clientY;
607         p = p.matrixTransform(stateTf);
608         var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
609         var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
610         svg_root_element.setAttribute("transform", s);
611     }
612     event.returnValue = false;
613     event.preventDefault();
614   }).mousewheel(function (event, delta) {
615     event.returnValue = false;
616     event.preventDefault();
617     if ( $('#update_workspace_button').data('locked') == false ) {
618         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
619         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
620         if( delta < -9 ) { delta = -9 }; 
621         var z = 1 + delta/10;
622         z = delta > 0 ? 1 : -1;
623         var g = svg_root_element;
624         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
625             var root = svg_root;
626             var p = root.createSVGPoint();
627             p.x = event.originalEvent.clientX;
628             p.y = event.originalEvent.clientY;
629             p = p.matrixTransform(g.getCTM().inverse());
630             var scaleLevel = 1+(z/20);
631             var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
632             var matrix = g.getCTM().multiply(k);
633             var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
634             g.setAttribute("transform", s);
635         }
636     }
637   }).css({
638     'overflow' : 'hidden',
639     'cursor' : '-moz-grab'
640   });
641   
642   if( editable ) {
643         $( "#dialog-form" ).dialog({
644         autoOpen: false,
645         height: 270,
646         width: 290,
647         modal: true,
648         buttons: {
649           "Ok": function( evt ) {
650                 $(evt.target).button("disable");
651                 $('#status').empty();
652                 form_values = $('#collapse_node_form').serialize();
653                 ncpath = getTextURL( 'relationships' );
654                 var jqjson = $.post( ncpath, form_values, function(data) {
655                         $.each( data, function(item, source_target) { 
656                                 var source_found = get_ellipse( source_target[0] );
657                                 var target_found = get_ellipse( source_target[1] );
658                                 var relation_found = $.inArray( source_target[2], $('#keymap').data('relations') );
659                                 if( source_found.size() && target_found.size() && relation_found > -1 ) {
660                                         var relation = relation_manager.create( source_target[0], source_target[1], relation_found );
661                                         relation.data( 'type', source_target[2]  );
662                                         relation.data( 'scope', $('#scope :selected').text()  );
663                                         relation.data( 'note', $('#note').val()  );
664                                         relation_manager.toggle_active( relation.attr('id') );
665                                 }
666                                 $(evt.target).button("enable");
667                    });
668                         $( "#dialog-form" ).dialog( "close" );
669                 }, 'json' );
670           },
671           Cancel: function() {
672                   $( this ).dialog( "close" );
673           }
674         },
675         create: function(event, ui) { 
676                 $(this).data( 'relation_drawn', false );
677                 $.each( relationship_types, function(index, typedef) {   
678                          $('#rel_type').append( $('<option />').attr( "value", typedef.name ).text(typedef.name) ); 
679                 });
680                 $.each( relationship_scopes, function(index, value) {   
681                          $('#scope').append( $('<option />').attr( "value", value ).text(value) ); 
682                 });        
683         },
684         open: function() {
685                 relation_manager.create_temporary( $('#source_node_id').val(), $('#target_node_id').val() );
686                 $(".ui-widget-overlay").css("background", "none");
687                 $("#dialog_overlay").show();
688                 $("#dialog_overlay").height( $("#enlargement_container").height() );
689                 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
690                 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
691         },
692         close: function() {
693                 relation_manager.remove_temporary();
694                 $( '#status' ).empty();
695                 $("#dialog_overlay").hide();
696         }
697         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
698           if( ajaxSettings.url == getTextURL('relationships') 
699                 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
700                   var errobj = jQuery.parseJSON( jqXHR.responseText );
701                   $('#status').append( '<p class="error">Error: ' + errobj.error + '</br>The relationship cannot be made.</p>' );
702           }
703           $(event.target).parent().find('.ui-button').button("enable");
704         } );
705   }
706
707   $( "#delete-form" ).dialog({
708     autoOpen: false,
709     height: 135,
710     width: 160,
711     modal: false,
712     buttons: {
713         Cancel: function() {
714             $( this ).dialog( "close" );
715         },
716         Delete: function() {
717           form_values = $('#delete_relation_form').serialize();
718           ncpath = getTextURL( 'relationships' );
719           var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
720               $.each( data, function(item, source_target) { 
721                   relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
722               });
723               $( "#delete-form" ).dialog( "close" );
724           }, dataType: 'json', type: 'DELETE' });
725         }
726     },
727     create: function(event, ui) {
728         // Swap out the buttons if we are in readonly mode
729         if( !editable ) {
730                 $( this ).dialog( "option", "buttons", 
731                         [{ text: "OK", click: function() { $( this ).dialog( "close" ); }}] );
732         }
733         
734         // TODO What is this logic doing?
735         var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
736         buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
737         var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");  
738         dialog_aria.mouseenter( function() {
739             if( mouseWait != null ) { clearTimeout(mouseWait) };
740         })
741         dialog_aria.mouseleave( function() {
742             mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
743         })
744     },
745     open: function() {
746         mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
747     },
748     close: function() {
749     }
750   });
751
752   // function for reading form dialog should go here; 
753   // just hide the element for now if we don't have morphology
754   if( can_morphologize ) {
755           $('#reading-form').dialog({
756                 autoOpen: false,
757                 // height: 400,
758                 width: 450,
759                 modal: true,
760                 buttons: {
761                         Cancel: function() {
762                                 $( this ).dialog( "close" );
763                         },
764                         Update: function( evt ) {
765                                 // Disable the button
766                                 $(evt.target).button("disable");
767                                 $('#reading_status').empty();
768                                 var reading_id = $('#reading_id').val()
769                                 form_values = {
770                                         'id' : reading_id,
771                                         'is_nonsense': $('#reading_is_nonsense').is(':checked'),
772                                         'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
773                                         'normal_form': $('#reading_normal_form').val() };
774                                 // Add the morphology values
775                                 $('.reading_morphology').each( function() {
776                                         if( $(this).val() != '(Click to select)' ) {
777                                                 var rmid = $(this).attr('id');
778                                                 rmid = rmid.substring(8);
779                                                 form_values[rmid] = $(this).val();
780                                         }
781                                 });
782                                 // Make the JSON call
783                                 ncpath = getReadingURL( reading_id );
784                                 var reading_element = readingdata[reading_id];
785                                 // $(':button :contains("Update")').attr("disabled", true);
786                                 var jqjson = $.post( ncpath, form_values, function(data) {
787                                         $.each( data, function(key, value) { 
788                                                 reading_element[key] = value;
789                                         });
790                                         if( $('#update_workspace_button').data('locked') == false ) {
791                                                 color_inactive( get_ellipse( reading_id ) );
792                                         }
793                                         $(evt.target).button("enable");
794                                         $( "#reading-form" ).dialog( "close" );
795                                 });
796                                 // Re-color the node if necessary
797                                 return false;
798                         }
799                 },
800                 create: function() {
801                         if( !editable ) {
802                                 // Get rid of the disallowed editing UI bits
803                                 $( this ).dialog( "option", "buttons", 
804                                         [{ text: "OK", click: function() { $( this ).dialog( "close" ); }}] );
805                                 $('#reading_relemmatize').hide();
806                         }
807                 },
808                 open: function() {
809                         $(".ui-widget-overlay").css("background", "none");
810                         $("#dialog_overlay").show();
811                         $('#reading_status').empty();
812                         $("#dialog_overlay").height( $("#enlargement_container").height() );
813                         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
814                         $("#dialog_overlay").offset( $("#enlargement_container").offset() );
815                         $("#reading-form").parent().find('.ui-button').button("enable");
816                 },
817                 close: function() {
818                         $("#dialog_overlay").hide();
819                 }
820           }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
821                   if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
822                         && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
823                           var errobj = jQuery.parseJSON( jqXHR.responseText );
824                           $('#reading_status').append( '<p class="error">Error: ' + errobj.error + '</p>' );
825                   }
826                   $(event.target).parent().find('.ui-button').button("enable");
827           });
828         } else {
829                 $('#reading-form').hide();
830         }
831   
832
833   $('#update_workspace_button').click( function() {
834          if( !editable ) {
835                 return;
836          }
837      var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
838      mouse_scale = svg_root_element.getScreenCTM().a;
839      if( $(this).data('locked') == true ) {
840          $('#svgenlargement ellipse' ).each( function( index ) {
841              if( $(this).data( 'node_obj' ) != null ) {
842                  $(this).data( 'node_obj' ).ungreyout_edges();
843                  $(this).data( 'node_obj' ).set_draggable( false );
844                  var node_id = $(this).data( 'node_obj' ).get_id();
845                  toggle_relation_active( node_id );
846                  $(this).data( 'node_obj', null );
847              }
848          })
849          $(this).data('locked', false);
850          $(this).css('background-position', '0px 44px');
851      } else {
852          var left = $('#enlargement').offset().left;
853          var right = left + $('#enlargement').width();
854          var tf = svg_root_element.getScreenCTM().inverse(); 
855          var p = svg_root.createSVGPoint();
856          p.x=left;
857          p.y=100;
858          var cx_min = p.matrixTransform(tf).x;
859          p.x=right;
860          var cx_max = p.matrixTransform(tf).x;
861          $('#svgenlargement ellipse').each( function( index ) {
862              var cx = parseInt( $(this).attr('cx') );
863              if( cx > cx_min && cx < cx_max) { 
864                  if( $(this).data( 'node_obj' ) == null ) {
865                      $(this).data( 'node_obj', new node_obj( $(this) ) );
866                  } else {
867                      $(this).data( 'node_obj' ).set_draggable( true );
868                  }
869                  $(this).data( 'node_obj' ).greyout_edges();
870                  var node_id = $(this).data( 'node_obj' ).get_id();
871                  toggle_relation_active( node_id );
872              }
873          });
874          $(this).css('background-position', '0px 0px');
875          $(this).data('locked', true );
876      }
877   });
878
879   if( !editable ) {  
880     // Hide the unused elements
881     $('#dialog-form').hide();
882     $('#update_workspace_button').hide();
883   }
884
885   
886   $('.helptag').popupWindow({ 
887           height:500, 
888           width:800, 
889           top:50, 
890           left:50,
891           scrollbars:1 
892   }); 
893
894   
895   function toggle_relation_active( node_id ) {
896       $('#svgenlargement .relation').find( "title:contains('" + node_id +  "')" ).each( function(index) {
897           matchid = new RegExp( "^" + node_id );
898           if( $(this).text().match( matchid ) != null ) {
899                   var relation_id = $(this).parent().attr('id');
900               relation_manager.toggle_active( relation_id );
901           };
902       });
903   }
904
905   expandFillPageClients();
906   $(window).resize(function() {
907     expandFillPageClients();
908   });
909
910 });
911
912
913 function expandFillPageClients() {
914         $('.fillPage').each(function () {
915                 $(this).height($(window).height() - $(this).offset().top - MARGIN);
916         });
917 }
918
919 function loadSVG(svgData) {
920         var svgElement = $('#svgenlargement');
921
922         $(svgElement).svg('destroy');
923
924         $(svgElement).svg({
925                 loadURL: svgData,
926                 onLoad : svgEnlargementLoaded
927         });
928 }
929
930
931 /*      OS Gadget stuff
932
933 function svg_select_callback(topic, data, subscriberData) {
934         svgData = data;
935         loadSVG(svgData);
936 }
937
938 function loaded() {
939         var prefs = new gadgets.Prefs();
940         var preferredHeight = parseInt(prefs.getString('height'));
941         if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
942         expandFillPageClients();
943 }
944
945 if (gadgets.util.hasFeature('pubsub-2')) {
946         gadgets.HubSettings.onConnect = function(hum, suc, err) {
947                 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
948                 loaded();
949         };
950 }
951 else gadgets.util.registerOnLoadHandler(loaded);
952 */